<?php
/** Minimages : Automatic dual sizing images for PmWiki 2  rev. 1.0  8 jan. 2005
* @author Pierre Rouzeau <pierre  àt rouzeau döt net>  
* @license  http://www.gnu.org/licenses/gpl.html GNU General Public License
* part of the stuff derived from the PmWiki upload.php script 
**/

global $iptc_special, $iptc_copyright, $iptc_caption, $icop, $icap, $ispe; 

// Linking
SDV($LinkFunctions['Img:'],'LinkImg');
SDV($IMap['Img:'],'$1');

SDV($HandleActions['img'],'HandleImg');
SDV($HandleActions['postimg'],'HandlePostImg');
SDV($ActionTitleFmt['img'],'| $[Upload images]');

$PageImg1 =
"
<h2 class='wikiaction'>$[Image for] \$FullName</h2>
<form enctype='multipart/form-data' action='\$ScriptUrl' method='post'>
<input type='hidden' name='pagename' value='\$FullName' />
<input type='hidden' name='action' value='postimg' />
<input type='hidden' name='upr' value='\$upresult' /> 
<input type='hidden' name='upname' value='\$UploadName' />  
<table  width='740' border='0'>
	<tr><td align='right'>$[Image to upload:]</td>
	<td align='right' colspan='2'><input name='uploadfile' accept='image/jpeg, image/png, image/gif' type='file' />
	</td><td> $[Step 1]</td><td id='wikicmds' rowspan='3' width='150'>$[IMGreload]</td></tr>
	<tr><td align='right'>$[Image wiki name:]</td>
	<td align='right'><b>\$affupname</b></td>
	<td align='right'><input type='submit' name='upl' value=' $[Upload] ' /></td><td> $[Step 2]</td></tr>
	<tr><td align='center' colspan='4'><h3>\$UploadResult</h3></td></tr></table>
<table>
	<tr><td width='224' height='224' colspan='2'><img src='\$ThumbUrl' border='0' alt='' /></td>
	<td width='258'>_________________</td><td width='258'>_________________</td></tr>
</table>	
";
$PageImg2a = 
"
<table width='740'>	
	<tr><td colspan='3'>
	<input type='text' name='icap' value='\$iptc_caption' size='40' /> $[Image title]</td><td>-</td></tr>
    <tr><td colspan='3'>
	<input type='text' name='icop' value='\$iptc_copyright' size='40' /> $[Image copyright]</td><td>-</td></tr>
	<tr><td colspan='3'><textarea name='ispe' rows='3' cols='36'>\$iptc_special</textarea><br /> $[Image special instructions]</td>
	<td align='center'><input type='submit' name='valid' value='    $[Ok]    ' />
		<input type='submit' name='canc' value=' $[Cancel] ' />
	</td></tr>  
</table>
</form>
";

$PageImg2b = 
"
<table width='740'>	
	<tr><td><td align='right'><input type='submit' name='valid' value='    $[Ok]    ' />
		<input type='submit' name='canc' value=' $[Cancel] ' />&nbsp; &nbsp; 
		<input type='hidden' name='icap' value='\$iptc_caption' />
    	<input type='hidden' name='icop' value='\$iptc_copyright' /> 
   		<input type='hidden' name='ispe' value='\$iptc_special' />  
	</td></tr>  
</table>
</form>
";
  
XLSDV('en',array(
  'IMGbadtype' => '<font color="#FF0000"> - invalid file extension -</font>',
  'ULnotimage' => 'uploaded file is not an allowed format',
  'IMGreload' => 'If wrong image, reload a new one then hit browser reload'
 ));

function LinkImg($pagename,$imap,$path,$title,$txt,$fmt=NULL) {
	global $FmtV,$UploadFileFmt,$LinkUploadCreateFmt,$UploadUrlFmt,$UploadPrefixFmt;
	$path = str_replace(array('.JPG','.JPEG','.GIF','.PNG'),array('.jpg','.jpeg','.gif','.png'),$path);
	preg_match('/\\.([^.]+)$/',$path,$match); $ext=@$match[1];
	if (!(($ext == 'jpg') OR ($ext == 'jpeg') OR ($ext == 'gif') OR ($ext == 'png')))
		return FmtPageName("<i>".$path."</i>: $[IMGbadtype]",$pagename);
	$pathSmall = str_replace(array('.jpg','.jpeg','.gif','.png'),array('.s.jpg','.s.jpeg','.s.gif','.s.png'),$path);
	$upname = MakeUploadName($pagename,$path);
	$upnameSmall = MakeUploadName($pagename,$pathSmall);
	$filepath = FmtPageName("$UploadFileFmt/$upname",$pagename);
	$filepathSmall = FmtPageName("$UploadFileFmt/$upnameSmall",$pagename);
	if (!file_exists($filepathSmall)) {
		if (!file_exists($filepath)) {
			$FmtV['$LinkUpload'] = 
				FmtPageName("\$PageUrl?action=img&amp;upname=zw_$upname", $pagename);  
			$FmtV['$LinkText'] = $txt;
			return FmtPageName($LinkUploadCreateFmt,$pagename);
		} 
		if (!function_exists('imagecopyresampled')) return ('$[Image resizing not possible on your server]');
		store_images ($filepath); // to allow image upload via ftp
	}
	$smallimg = FmtPageName("$UploadUrlFmt$UploadPrefixFmt/$upnameSmall",$pagename);
	$smimg = preg_replace('/[\\x80-\\xff ]/e',"'%'.dechex(ord('$0'))", $smallimg); // for accented letters
	$plainimg = str_replace(array('.s.jpg','.s.jpeg','.s.gif','.s.png'),array('.p.jpg','.p.jpeg','.p.gif','.p.png'),$smimg);
	$out = "<a class='urllink' href='".$plainimg."'><img src='".$smimg."' border='0' alt='' /></a>";
	return $out;
}

function store_images ($filepath) {
	global $img_smallsize, $img_plainsize, $img_archsize;
	SDV($img_smallsize, 256); // displayed image size
	SDV($img_plainsize, 768); // linked image size
	SDV($img_archsize, 1280); // archived image size
    $filepathSmall = str_replace(array('.jpg','.jpeg','.gif','.png'),
								array('.s.jpg','.s.jpeg','.s.gif','.s.png'),$filepath);
    $filepathPlain = str_replace(array('.jpg','.jpeg','.gif','.png'),
								array('.p.jpg','.p.jpeg','.p.gif','.p.png'),$filepath);
    Get_IPTC ($filepath);
    $res = CreateSmallImage ($filepath, $filepathPlain, $img_plainsize); 
    CreateSmallImage ($filepath, $filepathSmall, $img_smallsize);
    CreateSmallImage ($filepath, $filepath, $img_archsize); // to add iptc tags
    if ($res != 0)
		if (filesize($filepath) == filesize($filepathPlain)) unlink ($filepath);
}

function HandleImg($pagename) {
	global $FmtV,$UploadExtMax,
		$HandleImgFmt,$PageStartFmt,$PageImgFmt,$upresult,$affupname,$UploadDir,
		$iptc_caption, $iptc_copyright, $iptc_special,$UploadUrlFmt,$ThumbUrl,
		$PageImg1,$PageImg2a,$PageImg2b,$DispIPTC;
	
	$page = RetrieveAuthPage($pagename,'upload');
	if (!$page) Abort("?cannot upload to $pagename");
	PCache($pagename,$page);
	$upname = @$_REQUEST['upname'];
	$affupname = str_replace('zw_','', $upname);
	$FmtV['$UploadName'] = MakeUploadName($pagename,$upname);
	$ThumbUrl = $UploadUrlFmt.'/'; // to have default
	$thb = @$_REQUEST['thb'];  
	$thbdir = $UploadDir.'/'.$thb;  
	if (file_exists($thbdir) and is_file($thbdir))
		$ThumbUrl .= $thb;
	$upresult = @$_REQUEST['upresult'];
	$FmtV['$upext'] = @$_REQUEST['upext'];
	$FmtV['$upmax'] = @$_REQUEST['upmax'];
	$FmtV['$UploadResult'] = ($upresult) ?
		FmtPageName("<i>\$affupname</i>: $[UL$upresult]",$pagename) : '';
	$GLOBALS['PageHeaderFmt']=''; // Remove header
	$GLOBALS['PageLeftFmt']='';
	$GLOBALS['PageTitleFmt']='';
	$iptc_caption = @$_REQUEST['icap'];
	$iptc_copyright = @$_REQUEST['icop'];
	$iptc_special = @$_REQUEST['ispe'];
	$endname = substr($upname,-2);
	SDV($DispIPTC, TRUE);
	if ((($endname == 'pg') OR ($endname == 'eg')) AND $DispIPTC)
		$PageImgFmt = $PageImg1.$PageImg2a;
	else
		$PageImgFmt = $PageImg1.$PageImg2b;
	PrintFmt($pagename,array($PageStartFmt,$PageImgFmt)); // send page to browser
}

function HandlePostImg($pagename) {
	global $UploadVerifyFunction,$UploadFileFmt,$LastModFile,$ThumbUrl,$UploadDir,
		$iptc_caption, $iptc_copyright, $iptc_special;

	foreach (glob($UploadDir.'/zw_*') as $killfile) unlink ($killfile); // remove thumbnail
	$page = RetrieveAuthPage($pagename,'upload');
	if (!$page) Abort("?cannot upload to $pagename");
	$uploadfile = $_FILES['uploadfile'];
	$upname = $_REQUEST['upname'];
	if ($upname=='') $upname=$uploadfile['name'];
	$upname = MakeUploadName($pagename,$upname);
	$filepath = FmtPageName("$UploadFileFmt/$upname",$pagename);
	$result = ImgVerifyBasic($uploadfile,$filepath);
	if ($result=='') {
		$filedir = preg_replace('#/[^/]*$#','',$filepath);
		mkdirp($filedir);
		if (!move_uploaded_file($uploadfile['tmp_name'],$filepath))
			{ Abort("?cannot move uploaded file to $filepath"); return; }
		fixperms($filepath);
		if ($LastModFile) { touch($LastModFile); fixperms($LastModFile); }
		$result = "upresult=success";
	}
	if (isset($_POST["upl"])){ // After the upload
		$iptc_special = '';
		Get_IPTC ($filepath);
        $thb = 'zw_'.time().'.jpg'; // Always changing thumb name
		if (CreateSmallImage ($filepath, $UploadDir.'/'.$thb, 224, 1) == 0) {
			$result = 'upresult=notimage'; 
			$thb='';
		}	
		Redirect($pagename,"\$PageUrl?action=img&upname=$upname&$result&thb=$thb&icap=$iptc_caption&icop=$iptc_copyright&ispe=$iptc_special");
	}	
	if (isset($_POST["valid"])) {
		if ($_POST['upr']=="success") { 
			$finalfile = str_replace('zw_','',$filepath);
			rename ($filepath, $finalfile);
    	    $iptc_caption = $_REQUEST['icap'];
        	$iptc_copyright = $_REQUEST['icop'];
			$iptc_special = $_REQUEST['ispe'];
			Embed_IPTC ($finalfile);
			store_images ($finalfile);
		}	
	}
	// remove files in uploaddir groups and pages
	foreach (glob($UploadDir.'/*/zw_*') as $killfile) unlink ($killfile); 
	// files in Uploaddir root removed by thumbnail remover
	Redirect($pagename,"\$PageUrl");
}

function ImgVerifyBasic($uploadfile,$filepath) {
  global $UploadExtSize,$UploadPrefixQuota,$UploadDirQuota,$UploadDir;
  
  if (!is_uploaded_file($uploadfile['tmp_name'])) return 'upresult=nofile';
  switch ($uploadfile['error']) {
    case 1: return 'upresult=toobig';
    case 2: return 'upresult=toobig';
    case 3: return 'upresult=partial';
    case 4: return 'upresult=nofile';
  }
  $filedir = preg_replace('#/[^/]*$#','',$filepath);
  if ($UploadPrefixQuota && 
      (dirsize($filedir)-@filesize($filepath)+$uploadfile['size']) >
        $UploadPrefixQuota) return 'upresult=pquota';
  if ($UploadDirQuota && 
      (dirsize($UploadDir)-@filesize($filepath)+$uploadfile['size']) >
        $UploadDirQuota) return 'upresult=tquota';
  return '';
}

function CreateSmallImage ($imgfile, $smallimgfile, $lsize, $thjpg = 0) {
  global $WriteGif,$OverSize;
  SDV($OverSize, 1.15);
  // Get infos of images
  $size = getimagesize($imgfile);
  $width = $size[0];
  $height = $size[1];
  $type = $size[2];
  $imgsize = max ($height, $width);
  // Empty images creation
  if ($type == 1) $new = imagecreatefromgif($imgfile);
  elseif ($type == 2) $new = imagecreatefromjpeg($imgfile);
  elseif ($type == 3) $new = imagecreatefrompng($imgfile);
  else return (0);
  if (($lsize*$OverSize < $imgsize) OR ($thjpg == 1)) { // Do *not* resize images 15% larger 
    if ($height > $width) {
      $newheight = $lsize;
      $newwidth = $width*($newheight/$height);
    }
    else {
      $newwidth = $lsize;
      $newheight = $height*($newwidth/$width);
    }
    $newimage = imagecreatetruecolor($newwidth, $newheight);
    imagecopyresampled($newimage, $new, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    $typeout=$type;
    if ($thjpg != 0) $typeout = 2; 
    SDV($WriteGif,TRUE); 
    if ($typeout == 1) {
      if (function_exists("imagegif") AND ($WriteGif == TRUE))
        imagegif($newimage, $smallimgfile);
      else
        $typeout = 2;
    }
    if ($typeout == 2) imagejpeg($newimage, $smallimgfile);
      elseif ($typeout == 3) imagepng($newimage, $smallimgfile);
  }
  else {
    if ($imgfile != $smallimgfile) copy ($imgfile, $smallimgfile); // don't copy on itself	  
  }
  if ($thjpg == 0)  Embed_IPTC ($smallimgfile); 
  return ($type);  
}

function Get_IPTC ($imgfile) { // Get IPTC informations or set defaults
	global $iptc_caption,$iptc_copyright,$iptc_special,$Author,
	$def_iptc_caption,$def_iptc_copyright,$def_iptc_special;
	// Default iptc values
	SDV($def_iptc_caption, 'Image collected on a PmWiki');
	SDV($def_iptc_copyright, '');
	SDV($def_iptc_special, '');
	$size = getimagesize($imgfile, $info);	 
	if ($size[2] == 2) { // image is jpeg
		$cpr= (($Author == '') ? $def_iptc_copyright : $Author);
		if (isset($info["APP13"])) { // IPTC tags are present
			$iptc = iptcparse($info['APP13']);
			$iptc_caption = (isset($iptc['2#120'][0]) ? substr(htmlentities($iptc['2#120'][0]),0,64): '');
			$iptc_copyright = (isset($iptc['2#116'][0]) ? substr(htmlentities($iptc['2#116'][0]),0,64): '');
			$iptc_special = (isset($iptc['2#040'][0]) ? substr(htmlentities($iptc['2#040'][0]),0,128): '');
			if ($iptc_caption == '')  $iptc_caption = $def_iptc_caption;
			if ($iptc_copyright == '') $iptc_copyright = $cpr;
			$iptc_special .= $def_iptc_special;
		} else { // if IPTC not present, default values
			$iptc_caption = $def_iptc_caption;
			$iptc_copyright = $cpr;
			$iptc_special = $def_iptc_special;
		}
	}	
}

function Embed_IPTC ($imgfile) {
	global $iptc_caption, $iptc_copyright, $iptc_special;
	$size = getimagesize($imgfile, $info);
	if ($size[2] == 2) { // image is jpeg
		if(!isset($info["APP13"])) { // Embed against existing IPTC dont work, so left 'as is'
			$iptc["2#120"][0] = $iptc_caption;
			$iptc["2#116"][0] = $iptc_copyright;
			$iptc["2#040"][0] = $iptc_special;     
			$iptc_new = '';
			foreach (array_keys($iptc) as $s){
				$tag = str_replace("2#", "", $s); // Finds the IPTC numbers
				$c = count ($iptc[$s]);
				for ($i=0; $i <$c; $i++)  { // Creating the string
					$iptc_new .= iptc_maketag(2, $tag, $iptc[$s][$i]);
				}
			}
			$content = iptcembed($iptc_new, $imgfile, 0);
			$fp = fopen($imgfile, "w+b");
			fwrite($fp, $content);
			fclose($fp);
		}	
	}	
}

// Function to format the new IPTC text, (thanks to Thies C. Arntzen)
function iptc_maketag($rec,$dat,$val){
	$len = strlen($val);
	if ($len < 0x8000)
		return chr(0x1c).chr($rec).chr($dat).
		chr($len >> 8).
		chr($len & 0xff).
		$val;
	else
	return chr(0x1c).chr($rec).chr($dat).
		chr(0x80).chr(0x04).
		chr(($len >> 24) & 0xff).
		chr(($len >> 16) & 0xff).
		chr(($len >> 8 ) & 0xff).
		chr(($len ) & 0xff).
		$val;
}

// debug function 
function db($par) {
	$fp = fopen('errorimg.txt', "a+b");
	fwrite($fp, "\n".$par);
	fclose($fp);
}