<?php

/*

IMAGE SETS
Author:		Robert Saunders
Contact:	chojin at internode.on.net
Version:	0.2

CHANGELOG:
0.2:
- fixed uppercase file extensions not showing in thumbs view
- added crossloading
- added file size display

*/



// prevent this page from running outside pmwiki
if (!defined('PmWiki')) exit();

// add a macro inside wiki pages for (:imgset name:) which calls the function imgset(name);
Markup('imgset','style','/\\(:imgset( (\\S+?)):\\)/e','imgset(\'$1\')');

// Set the default value of the editset handler (when it is passed as an action in the url eg. Group.Page?action=editset) to the EditImageSet function.
SDV($HandleActions['editset'], 'EditImageSet');
SDV($HandleActions['imgsetpost'], 'HandlePostImageSet');
SDV($HandleActions['delimg'], 'HandleDeleteImage');

// IMGSET:
// displays thumbnails for a given set in a wiki page
function imgset($IMGSET_Name)
{
	global $pagename, $directory, $UploadDir;

	// remove spaces from the imageset name
	$IMGSET_Name = explode(" ", $IMGSET_Name);
	$IMGSET_Name = implode("", $IMGSET_Name);

	$output = "<p class='vspace'>ImageSet: $IMGSET_Name</p><p><div style='text-align:center'>";

	// test for the existence of the upload directories, and if they're not there, create them.
	if (!file_exists("uploads/ImageSets/"))
	{
		mkdir("uploads/ImageSets/");
		chmod("uploads/ImageSets/", 0777);
	}

	if (!file_exists("uploads/ImageSets/$IMGSET_Name"))
	{
		mkdir("uploads/ImageSets/$IMGSET_Name");
		chmod("uploads/ImageSets/$IMGSET_Name", 0777);
	}
	
	// create a quick gallery of thumbs (without the editing options).
	$imagelist = ReadImageDir($IMGSET_Name);
	foreach($imagelist as $imagename)
	{
		if (substr($imagename, 0, 6) == "thumb_")
		{
			$output .= "<a href='$UploadDir/ImageSets/$IMGSET_Name/". substr($imagename, 6) ."'>";
			$output .= "<img src='$UploadDir/ImageSets/$IMGSET_Name/$imagename'>";
			$output .= "</a>\n";
		}
	}

	$output .= "</div><div style='text-align:right'>";
	$output .= "<a href='index.php?n=$pagename?action=editset&amp;setname=$IMGSET_Name' title='Edit Imageset'>Edit ImageSet</a></div>";
	return $output;
}

function EditImageSet($pagename)
{
	global $IsPagePosted,$EditFields,$EditFunctions,$FmtV,$Now, $HandleEditFmt,$PageStartFmt,$PageEditFmt,$PagePreviewFmt,$PageEndFmt;
	global $pagename, $directory, $UploadDir;

	// grab the environment variables passed in the url
	$IMGSET_Name = $_GET["setname"];

	// Test for correct authentication (uses permissions for the edit action).
	$page = RetrieveAuthPage($pagename,'edit');
	if (!$page) Abort("?cannot edit $pagename"); 


	$output .= DrawThumbs($IMGSET_Name);
	
	// put the page into the HandleEditFmt variable.
	SDV($HandleEditFmt, array(&$PageStartFmt, $output, &$PageEndFmt));
	PrintFmt($pagename,$HandleEditFmt);

	//print "Username: ". $_SERVER['PHP_AUTH_USER'] ."<BR>Pass: $PHP_AUTH_PW";
}


// an image has been uploaded, so save it to the relevant directory and add a thumbnail
function HandlePostImageSet()
{
	global $IsPagePosted,$EditFields,$EditFunctions,$FmtV,$Now, $HandleEditFmt,$PageStartFmt,$PageEditFmt,$PagePreviewFmt,$PageEndFmt;
	global $uploadfile, $uploadfile_name, $crossloadfile, $pagename, $UploadDir;

	// copy the POSTed file into the uploads directory
	$IMGSET_Name = $_GET["setname"];
	$IMGSET_CrossloadFile = $_POST["crossloadfile"];

	// recieve an uploaded file
	if(!empty($uploadfile))
	{
		if(copy($uploadfile, "$UploadDir/ImageSets/$IMGSET_Name/".$uploadfile_name))
		{
			$output = "Successfully uploaded $uploadfile_name.";
			CreateThumb($uploadfile_name);
		}
		else
		{
			$output = "<B>error uploading $uploadfile_name!</B>";
		}
	}

	// download a file from an URL
	if(!empty($IMGSET_CrossloadFile))
	{
		$IMGSET_NewImageName = "";

		//try to generate a filename for the image
		$ext = substr($IMGSET_CrossloadFile, -3);
		if(strtolower($ext) == "jpg" || strtolower($ext) == "gif" || strtolower($ext) == "png")
		{	
			// file has an image extension, so try use the filename out of the url.
			$crossload_filename = explode("/", $IMGSET_CrossloadFile);
			$IMGSET_NewImageName = $crossload_filename[count($crossload_filename) - 1];
		}
		else
		{
			// image might not have a filename, so generate a random one.
			list($width, $height, $type, $attr) = getimagesize($IMGSET_CrossloadFile);
			if($type == 1) $IMGSET_NewImageName = rand().".gif";
			if($type == 2) $IMGSET_NewImageName = rand().".jpg";
			if($type == 3) $IMGSET_NewImageName = rand().".png";
		}

		$fp = @fopen("$UploadDir/ImageSets/$IMGSET_Name/$IMGSET_NewImageName","w");
		fwrite($fp,file_get_contents($IMGSET_CrossloadFile) );
		fclose($fp);

		CreateThumb("$IMGSET_NewImageName");


		$output .= "Crossloaded $IMGSET_CrossloadFile to $UploadDir/ImageSets/$IMGSET_Name/$IMGSET_NewImageName";
		// get the file extension
		/*
		$ext = substr($IMGSET_CrossloadFile, -3);
		if($ext == "jpg" || $ext == "gif" || $ext == "png")
		{
			//file_put_contents(file_get_contents());
			$crossload_filename = explode("/"
		}
		else
		{
			$output .= "The crossload URL does not appear to be an image file, trying anyway...";
		}*/

		//file_put_contents("$UploadDir/ImageSets/$IMGSET_Name/test.jpg", file_get_contents($IMGSET_CrossloadFile));

		//file_get_contents();
	}

	$output .= DrawThumbs($IMGSET_Name);

	// put the page into the HandleEditFmt variable.
	SDV($HandleEditFmt, array(&$PageStartFmt, $output, &$PageEndFmt));
	PrintFmt($pagename,$HandleEditFmt);
}

function HandleDeleteImage()
{
	global $IsPagePosted,$EditFields,$EditFunctions,$FmtV,$Now, $HandleEditFmt,$PageStartFmt,$PageEditFmt,$PagePreviewFmt,$PageEndFmt;
	global $pagename, $UploadDir;

	$IMGSET_Name = $_GET["setname"];
	$IMGSET_ImageFile = $_GET["imgname"];

	// try to delete the file and its thumbnail
	if(unlink("$UploadDir/ImageSets/$IMGSET_Name/$IMGSET_ImageFile"))
	{
		$output = "<B>Successfully deleted $UploadDir/ImageSets/$IMGSET_Name/$IMGSET_ImageFile.</B><BR />";
		if(unlink("$UploadDir/ImageSets/$IMGSET_Name/thumb_$IMGSET_ImageFile"))
		{
			$output = "<B>Successfully deleted $UploadDir/ImageSets/$IMGSET_Name/thumb_$IMGSET_ImageFile.</B><BR />";
		}
	}
	else
	{
		$output = "<B>error deleting $UploadDir/ImageSets/$IMGSET_Name/$IMGSET_ImageFile!</B>";
	}

	$output .= DrawThumbs($IMGSET_Name);

	SDV($HandleEditFmt, array(&$PageStartFmt, $output, &$PageEndFmt));
	PrintFmt($pagename,$HandleEditFmt);
}

//UTILITY FUNCTIONS:------------------------------------------------------------------------------------

function ReadImageDir($IMGSET_Name)
{
	$output = array();


	// traverse directory
	$dir = @opendir("uploads/ImageSets/$IMGSET_Name");
		//if (!$dir) $output = "This ImageSet is empty";
		while (($file=readdir($dir)) !== false)
		{
			if ($file{0} == '.') continue;
			// grab the last 3 characters of the filename (ie. the extension)
			$ext = substr($file, -3, 3);
			if(strtolower($ext) == "jpg" || strtolower($ext) == "gif" || strtolower($ext) == "png")
				array_push($output, $file);
		}
	closedir($dir);

	return $output;
}

// Draw the gallery of thumbnails.
function DrawThumbs($IMGSET_Name)
{
	global $UploadDir, $pagename;
	$output = "<h1>Editing ImageSet: $IMGSET_Name</h1>[<a href='index.php?n=$pagename'>Return to $pagename</a>] [Delete This ImageSet]<HR>"; 

	$imagelist = ReadImageDir($IMGSET_Name);
	foreach($imagelist as $imagename)
	{
		if (substr($imagename, 0, 6) == "thumb_")
		{
			$output .= "<table><a href='$UploadDir/ImageSets/$IMGSET_Name/". substr($imagename, 6) ."'>";
			$output .= "<img src='$UploadDir/ImageSets/$IMGSET_Name/$imagename' align=left></a>";
			$output .= "<B>". substr($imagename, 6) ."</B><BR>".round((filesize("$UploadDir/ImageSets/$IMGSET_Name/".substr($imagename,6))/1024),0)."KB";
			$output .= "<BR>[Change] [<a href='?n=$pagename&amp;action=delimg&amp;setname=$IMGSET_Name&amp;imgname=".substr($imagename, 6)."'>Delete</a>]</table><br />";
		}
	}

	$output .= "<hr><div style='text-align:left'>
	<form enctype='multipart/form-data' action='".$_SERVER['PHP_SELF']."?n=$pagename&amp;action=imgsetpost&amp;setname=$IMGSET_Name' method='post'>
	Upload a new file:<BR /><input name='uploadfile' type='file' /><input type='submit' value=' Upload ' />
	<BR />Crossload a file from an URL:<BR /><input name='crossloadfile' /><input type='submit' value=' Crossload ' />
	</form>
	</div>";

	return $output;
}

// Create a thumbnail from an image, with max dimensions 100x100.
function CreateThumb($image)
{
	global $UploadDir;
	$IMGSET_Name = $_GET["setname"];
	$imagepath = "$UploadDir/ImageSets/$IMGSET_Name/$image";	// full path to the image

	$info = getimagesize($imagepath);
	$width = $info[0];
	$height = $info[1];
	$type = $info[2];

	if ($type == 1) $new = imagecreatefromgif($imagepath);
	elseif ($type == 2) $new = imagecreatefromjpeg($imagepath);
	elseif ($type == 3) $new = imagecreatefrompng($imagepath);

	if ($height > $width)
	{
		$newheight = 100; 
		$newwidth = $width/($height/$newheight);
	}
	else
	{
		$newwidth = 100; 
		$newheight = $height/($width/$newwidth);
	}

	$newimage = imagecreatetruecolor($newwidth, $newheight);
	imagecopyresampled($newimage, $new, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

	if ($type == 1) imagegif($newimage, "$UploadDir/ImageSets/$IMGSET_Name/thumb_$image");
	elseif ($type == 2) imagejpeg($newimage, "$UploadDir/ImageSets/$IMGSET_Name/thumb_$image");
	elseif ($type == 3) imagepng($newimage, "$UploadDir/ImageSets/$IMGSET_Name/thumb_$image");
}


?>