<?php if (!defined('PmWiki')) exit();
/**
	Very simple thumbnail generator for PmWiki
	Written by (c) Petko Yotov 2006

	This script is POSTCARDWARE, if you like it, please send me
	a postcard. Details at
	http://galleries.accent-bg.com/index.php/Main/ThumbList#terms

	This file is written for PmWiki; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published
	by the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version. See pmwiki.php for full details
	and lack of warranty.

	Copyright 2007 Aidin Abedi
	Copyright 2006 Petko Yotov http://5ko.free.fr
	Copyright 2004-2006 Patrick R. Michaud http://www.pmwiki.org
	Copyright 2006 Hagan Fox (haganfoxATusersDOTsourceforge.net)
*/

# Version date
$RecipeInfo['ThumbList']['Version'] = '2007-10-31b';


SDV($ThumbPx, 128);
SDV($ThumbTableCols, 0);
SDV($ThumbTitleFormat, "%f: %wx%h, %kk (%t)");
SDV($ThumbBgColor, "#ffffff");//for transparent pictures
SDV($AlwaysRedoThumbs, 0);// for debugging: 1 always, -1:never; 0:when needed
SDV($ThumbQuality, 80);
SDV($ThumbLimit, 0);
SDV($ThumbMaxArea, 0);
SDV($ThumbLinkAdd, '');
SDV($ThumbAdd, '');
SDV($AlwaysLinkOriginal, 0); // if the original is small and allready displayed
SDV($ImageTemplateFmt, '(:include {$FullName}-ImageTemplate {$Group}.ImageTemplate {$SiteGroup}.ImageTemplate:)') ;
SDV($ThumbListUseTmpl, 0);
SDV($HandleActions['imgtpl'], 'HandleImageTemplate');
SDV($HandleActions['purgethumbs'], "PurgeThumbnails");

Markup('thumblist', '>{$var}',
  '/\\(:thumb(list)?\\s*(.*?):\\)/ei',
  "FmtThumbList(\$pagename,PSS('$2'),'$1')");

function FmtThumbList($pagename, $args, $list='')
{
	global $UploadDir, $UploadPrefixFmt, $UploadUrlFmt, $AlwaysRedoThumbs,
		$ThumbTableCols,$ThumbBgColor, $TimeFmt, $EnableDirectDownload,
		$ThumbPx, $ThumbTitleFormat, $ThumbLimit, $AlwaysLinkOriginal,
		$ThumbListUseTmpl, $ThumbMaxArea, $ThumbLinkAdd, $ThumbAdd;
	static $ThumbGalNum = 0;
	$ThumbGalNum++;

	$opt = ParseArgs($args);

	$currentpage = $pagename = MakePageName($pagename, $pagename);

	if($list)//usual "thumblist"
	{
		if (@$opt[''][0]) $pagename = MakePageName($pagename, $opt[''][0]);
	}
	else// "thumb" was used
	{
		if (! @$opt[''][0]) return;
		if(preg_match("!^(.*)\\/([^\\/]+)$!", $opt[''][0], $m) )
		{
			$pagename = MakePageName($pagename, $m[1]);
			$opt['image'] = $m[2];
		}
		else	$opt['image'] = $opt[''][0];
		$opt['cols'] = 0;
	}
	$page = RetrieveAuthPage($pagename,"read");
	if (!$page) { return; }
	
	if(!$_POST['preview'] && !$AlwaysRedoThumbs && intval(@$opt['supercache']))
	{
		$output = ThumbGetCache($currentpage, $pagename, $ThumbGalNum);
		if($output) return '<:block>'. Keep($output);
	}
	if (@$opt['skip'])
		$skipmatch = '/^' . str_replace(array("\\*", "\\?", "\\|"), array(".*", ".", "|"), preg_quote($opt['skip'])) . '$/i';
	if (@$opt['name'])
		$pattern = '/^' . str_replace(array("\\*", "\\?", "\\|"), array(".*", ".", "|"), preg_quote($opt['name'])) . '$/i';

	$titlefmt =(@$opt['titlefmt'])? $opt['titlefmt'] : $ThumbTitleFormat;
	if (@$opt['px'] && intval($opt['px']) > 0 )
			$Px = intval($opt['px']);
	elseif(@intval(@$opt['width']))$Px = $Width = intval($opt['width']);
	else $Px = $ThumbPx;
	$atarget = (@$opt['target'])? ' target="'.htmlspecialchars($opt['target']).'"' : '';
	$usetpl = isset($opt['usetemplate'])?$opt['usetemplate'] : $ThumbListUseTmpl;

	$thumbcols = isset($opt['cols'])? intval($opt['cols']) : $ThumbTableCols;
	$caption = @$opt['caption'];

	if (@floatval(@$opt['maxarea']))
		$maxarea = floatval($opt['maxarea']);
	else $maxarea = $ThumbMaxArea;
	$maxarea *= 1000000;
	$start = intval(@$opt['start']);
	if(!$start)$start = 1;
	$limit = isset($opt['limit'])? intval(@$opt['limit']) : $ThumbLimit;

	$tableattributes = array("border", "cellpadding", "cellspacing", "rules", "style", "bgcolor", "align");
	$mytabattr = "";
	foreach($tableattributes as $k) { if(isset($opt[$k])) $mytabattr .= " $k=\"".htmlspecialchars($opt[$k])."\""; }
	$mybgcolor = preg_match("/^#[0-9a-f]{6}$/i", @$opt['bgcolor'])? $opt['bgcolor'] : $ThumbBgColor;

	$uploaddir = FmtPageName("$UploadDir$UploadPrefixFmt", $pagename);
	$uploadurl = FmtPageName(IsEnabled($EnableDirectDownload, 1)
					? "$UploadUrlFmt$UploadPrefixFmt/"
					: "\$PageUrl?action=download&amp;upname=",
				$pagename);

	$dirp = @opendir($uploaddir);
	if (!$dirp) return '';
	$filelist = array();
	while (($file=readdir($dirp)) !== false)
	{
		if ($file{0} == '.') continue;
		if (@$opt['image'] && $file != $opt['image']) continue;
		if (!preg_match("/\\.(jpe?g|png|gif)$/i", $file)) continue;
		if (preg_match("/^th\\d+---/", $file)) continue;
		if (@$skipmatch && preg_match(@$skipmatch, $file)) continue;
		if (@$pattern && !preg_match($pattern, $file)) continue;
		
		$LastModified = filemtime("$uploaddir/$file");
		$filelist[$file] = $LastModified;
	}
	closedir($dirp);
	if(!count($filelist) ) return;

	asort($filelist);
	$filelist=array_keys($filelist);

	if($thumbcols)
	{
		$Px4 = $Px+4;
		$outputstart = "<table class='thumbtable'$mytabattr>";
		if($caption)$outputstart .= "<caption>$caption</caption>";
		$td1 = "<td class='thumbtd' align='center' valign='middle' height='$Px4' width='$Px4'>";
		$td2 = "</td>\n";
	}
	else {$td1 = " "; $td2 = '';}

	$td=0;	$i=1;	$output = '';
	foreach($filelist as $x=>$file)
	{
		$filepath = "$uploaddir/$file";
		$info = @getimagesize($filepath);
		if(! $info) continue;
		if($maxarea > $info[0]*$info[1]) continue;

		if($start>1 && $i<$start) { $i++; continue; }
		if($limit>0 && $i>=$limit+$start) { break; }
		
		$stat = stat($filepath);
		$replArr = array(
			"%%" => "%",
			"%G" => $ThumbGalNum,
			"%f" => $file,
			"%w" => $info[0],
			"%h" => $info[1],
			"%b" => $stat['size'],
			"%k" => round($stat['size']/1024),
			"%t" => strftime($TimeFmt, $stat['mtime'])
		);
		$title = htmlspecialchars(strtr($titlefmt, $replArr));
		$thumbadd = strtr($ThumbAdd, $replArr);
		$thumblinkadd = strtr($ThumbLinkAdd, $replArr);

		$name = PUE("$uploadurl$file");

		if($thumbcols && $td%$thumbcols == 0)$output .= "<tr class='thumbtr'>\n";

		if(($thumbcols && $info[0] > $info[1]) || @$Width) // w > h
		{
			$imgh = round($Px * $info[1] / $info[0]);
			$imgw = $Px;
		}
		else { $imgh = $Px; $imgw = round($Px * $info[0] / $info[1]);}

		if($imgh>=$info[1] || $AlwaysRedoThumbs==-1)// the picture is not bigger than the thumb, display it
		{
			if($imgh>=$info[1])list($imgw, $imgh)= $info;
			$thumbname = $name;
		}
		else
		{
			$thumbprefix = "th$imgh---".substr($mybgcolor, 1). "--";
			$thumbpath = "$uploaddir/$thumbprefix$file.jpg";
			$thumbname = PUE("$uploadurl$thumbprefix$file.jpg");
			if($AlwaysRedoThumbs || !file_exists($thumbpath) || filemtime($thumbpath)<$stat['mtime'] )
			{
				CreateThumb($filepath, $thumbpath, $imgh, $info, $mybgcolor);
			}
		}
		if($usetpl)$name = FmtPageName("\$PageUrl?action=imgtpl&amp;updir=$pagename&amp;upname=$file", $currentpage);
		if($AlwaysLinkOriginal || $thumbname != $name || $AlwaysRedoThumbs==-1)
		{
			$a1 = "<a href='$name' class='thumblink'$atarget $thumblinkadd>";
			$a2 = "</a>";
		}
		else {$a1=$a2="";}
		$output .= "$td1$a1<img border='0' src='$thumbname' alt=\"$title\" title=\"$title\" class='thumbs' width='$imgw' height='$imgh' $thumbadd/>$a2$td2";

		$i++;$td++;
		if($thumbcols && $td%$thumbcols==0) $output .= "</tr>\n";
	}
	if($thumbcols && $td%$thumbcols) $output .=  "</tr>\n";
	if($thumbcols && $output) $output = "$outputstart$output\n</table>\n";

	if(!$_POST['preview'] && !$AlwaysRedoThumbs && intval(@$opt['supercache']))
		ThumbSetCache($currentpage, $pagename, $ThumbGalNum, $output);
	return '<:block>'. Keep($output);
}
function CreateThumb($filepath, $thumbpath, $nh, $info, $bgc)
{
	global $ThumbQuality;
	$rr = hexdec(substr($bgc, 1, 2) );
	$gg = hexdec(substr($bgc, 3, 2) );
	$bb = hexdec(substr($bgc, 5, 2) );
	
	list($imgw, $imgh, $t) = $info;
	switch ($t)
	{
		case 1:
			$img = @imagecreatefromgif($filepath);
			break;
		case 2:
			$img = @imagecreatefromjpeg($filepath);
			break;
		case 3:
			$img = @imagecreatefrompng($filepath);
			break;
	}
	if (!@$img) {return;}

	$nw = round($imgw * $nh / $imgh);

	$nimg = imagecreatetruecolor($nw,$nh);
	$back = imagecolorallocate($nimg, $rr, $gg, $bb);
	imagefill($nimg, 0, 0, $back);
	imagecopyresampled($nimg,$img,0,0,0,0,$nw,$nh,$imgw,$imgh);
	imagedestroy($img);
	imagejpeg($nimg,$thumbpath,$ThumbQuality);
	imagedestroy($nimg);
}

function PurgeThumbnails($pagename)
{
	global $UploadDir, $UploadPrefixFmt;
	$page = RetrieveAuthPage($pagename,"edit");
	if (!$page) { Abort("?Not enough permissions to purge all thumbs for $UploadPrefixFmt"); return; }
	$uploaddir = FmtPageName("$UploadDir$UploadPrefixFmt", $pagename);
	if ($dirp = @opendir($uploaddir))
	{
		while (($file=readdir($dirp)) !== false)
		{
			if (!preg_match("/^(th\\d+---|\\.thumblist\\.)/", $file)) continue;
			unlink("$uploaddir/$file");
		}
		closedir($dirp);
	}
	Redirect($pagename,"{\$PageUrl}?action=upload");
}


function ThumbGetCache($currentpage, $uploadpage, $n)
{
	global $UploadDir, $UploadPrefixFmt, $PCache, $MessagesFmt;
	$ptime = $PCache[$currentpage]['time'];
	$cachefile = FmtPageName("$UploadDir$UploadPrefixFmt/.thumblist.$currentpage.$n.cache", $uploadpage);
	if(file_exists($cachefile) && filemtime($cachefile) >= $ptime)
	{
		if($handle = @fopen($cachefile, "r"))
		{
			$contents = @fread($handle, filesize($cachefile));
			fclose($handle);
		}
		$MessagesFmt[] = "Got cache for $currentpage, gallery $n<br />\n";
		return @$contents;
	}
	else return "";
}
function ThumbSetCache($currentpage, $uploadpage, $n, $html)
{
	global $UploadDir, $UploadPrefixFmt, $MessagesFmt;
	$MessagesFmt[] = "Caching gallery $n for $currentpage<br />\n";
	$cachefile = FmtPageName("$UploadDir$UploadPrefixFmt/.thumblist.$currentpage.$n.cache", $uploadpage);
	if ($handle = fopen($cachefile, 'w+'))
	{
		@fwrite($handle, $html);
		fclose($handle);
	}
}

## based on Hagan Fox's "HandleImageLink" from thumblink.php
function HandleImageTemplate($pagename)
{
	global $FmtV, $FmtPV, $ImageTemplateFmt, $PageStartFmt,	$PageEndFmt, $HandleImageTplFmt;
	SDV($HandleImageTplFmt,array(&$PageStartFmt, '$PageText', &$PageEndFmt));
	PCache($pagename, RetrieveAuthPage($pagename, 'read'));
	$uname=htmlspecialchars(@$_REQUEST['upname'], ENT_QUOTES);
	$pname=preg_replace("/^.*[\\.\\/]/", '', MakePageName($pagename, str_replace(".", "", $uname)));
	$udir =htmlspecialchars(@$_REQUEST['updir'], ENT_QUOTES);
	$FmtPV['$UpFile'] = "'$uname'";
	$FmtPV['$UpFilePage'] = "'$pname'";
	$FmtPV['$UpDir'] = "'$udir'";
	$FmtPV['$UpDirUpFile'] = "'$udir/$uname'";
	$FmtV['$PageText'] = MarkupToHTML($pagename,$ImageTemplateFmt);
	if(!trim($FmtV['$PageText']))
		$FmtV['$PageText'] = MarkupToHTML($pagename,"[[$pagename| $[Back to gallery] ]]\\\\\nAttach:{\$UpDirUpFile}");
	PrintFmt($pagename, $HandleImageTplFmt);
}