<?php
/*
Copyright (c) 2007 Ryan Seto

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

require_once('Cache/Lite/Output.php');
import_request_variables("cpg","vars");
clearstatcache();

$numPicOptions = array(25,50,75,100,0);

# Globals
$RootPath = "Gallery/"; #Must have a forward slash at the end
$Path = isset($varspath) ? $varspath : $RootPath;
$Size = isset($varssize) ? $varssize : "medium";
$Img = isset($varsimg) ? $varsimg : "";
$NumPics = isset($varsnumpics) ? $varsnumpics : $numPicOptions[0];
$Page = isset($varspage) ? $varspage : 1;

# Force the root path
if(strpos($Path, $RootPath) !== 0) $Path = "$RootPath$Path";
# Don't allow relative paths to parent
if(strpos($Path, "../") >= 0) $Path = str_replace("..", "", $Path);
# Don't allow root directory access
#if(strpos($Path, "/") === 0) $Path = ".$Path";

# The temporary directory where imgs are stored, php must have write permissions
$TmpDir = "tmp/";
# The directory where the image is stored
$ImgDir = ($Size != "original") ? "$TmpDir$Path$Size/" : "$Path";
# The directory where the thumbs are stored
$ThumbDir = "${TmpDir}${Path}thumb/";

# Max image dimensions to use when resizing.
$ThumbXY = "150";
$MediumXY = "450";
$LargeXY = "650";

if (isset($_GET['numpics'])) {
      setcookie("numpics", $_GET['numpics'], time() + 31536000);
}

# Caching options for pages that need to be cached
$CacheOptions = array(
        'cacheDir' => $TmpDir,
        'lifeTime' => 14400, # Keep cache for 4 hours
        'automaticCleaningFactor' => 20
);

# Determine if a file is an image
# Uses an array of known types and falls back to the default php mime type
function isImg($srcFile) {
        $knownMime = array(
                'png',
                'jpg',
                'jpeg',
                'gif',
        );

        $file = pathinfo($srcFile);

        foreach($knownMime as $mime) {
                if (strpos($file["extension"],$mime) === 0) return true;
        }

        return strpos(mime_content_type("$srcFile"),"image") === 0;
}

# Lists the directories in a directory excluding itself and the parent
function listDirs($path) {
        $dirList = array();
        $d = opendir($path);

        while(false !== ($f = readdir($d))) {
                if (is_dir("$path$f") && $f != ".." && $f != ".") {
                        $dirList[] = "$f/";
                }
        }
        closedir($d);
        sort($dirList);
        return $dirList;
}

# Lists all the images in a directory
function listImgs($path) {
        $imgList = array();
        $d = scandir($path, 0);

        foreach($d as $f) {
                if (is_file("$path$f") && isImg("$path$f")) {
                        $imgList[] = $f;
                }
        }
        return $imgList;
}

# Makes a new image of the srcImg in the max size specified
# srcImg and destImg must include path and image name
function mkImg($srcImg,$destImg,$size) {
        $destDir = substr($destImg, 0, strrpos($destImg, "/")+1);
        if (is_file("$srcImg")) {
                if (!is_dir($destDir)) exec("mkdir -p $destDir");
                exec("convert -size ${size}x${size} $srcImg -thumbnail ${size}x${size} $destImg");
        }
}

# Uses mkImg() to generate the thumbnail
function makeThumb($imgName) {
        global $Path, $ThumbDir,$ThumbXY;
        mkImg("$Path$imgName","$ThumbDir$imgName",$ThumbXY);
}

# Uses mkImg() to generate the image
function makeImg($imgName) {
        global $Path, $Size, $ImgDir, $MediumXY, $LargeXY;
        if ($Size != "original") {
                $size = ($Size == "medium") ? $MediumXY : $LargeXY;
                mkImg("$Path$imgName","$ImgDir$imgName",$size);
        }
}

# Helps create the directory tree
function dirTreeHlprHtml($path, & $str) {
	$str = "$str<ul>\n";
	$d = listDirs($path);

	if (!count($d) == 0) {
		foreach($d as $f) {
			$fname = str_replace("/","",$f); #Take out directory slashes
			$str ="$str<li><a href=\"?path=$path$f\">$fname</a></li>\n";
			dirTreeHlprHtml("$path$f", $str);
		}
	}
	$str = "$str</ul>\n";
}

# Provides the html code to display the directory tree
function dirTreeHtml($path) {
	global $RootPath;
	$str = "";
	if ($path !== $RootPath) {
		$parent = substr($path,0,strlen($path)-1);
		$parent = substr($parent,0,strrpos($parent, "/"));
		#$parentName = substr($parent,strrpos($parent,"/")+1);
		$parent = "$parent/";
		$str = "$str<ul>\n";
		$str = "$str<li><a href=\"?path=${parent}\">Up</a></li>\n";
		dirTreeHlprHtml($path, $str);
		$str = "$str</ul>\n";
	} else {
		dirTreeHlprHtml($path, $str);
	}
	return $str;
}

# Prints out the directory tree, will use cached version if it exists
function dirTree($path) {
	global $CacheOptions;
	$cache = new Cache_Lite_Output($CacheOptions);
	if (!($cache->start("${path}_DirTree"))) {
		print dirTreeHtml($path);
		$cache->end();
	}	
}

# Provides the html code to display an image, making the image if it has to
function imgHtml($imgName) {
        global $ImgDir, $Path, $Img, $Size, $Page;
        if (!file_exists("$ImgDir$imgName")) makeImg($imgName);
	$html = "<a href=\"?path=$Path&page=$Page&size=$Size\">";
        $html = "$html<img src=\"$ImgDir$imgName\" border=0 />";
	$html = "$html</a>\n";
        $html = "$html<br />\n";
        $html = "$html<a href=\"?path=$Path&img=$Img&page=$Page&size=medium\">Medium</a> |\n";
        $html = "$html<a href=\"?path=$Path&img=$Img&page=$Page&size=large\">Large</a> |\n";
        $html = "$html<a href=\"?path=$Path&img=$Img&page=$Page&size=original\">Original</a>\n";

        return $html;
}

# Prints out the img, will use cached version if it exists
function img($imgName) {
	global $CacheOptions, $Path, $Size;
	$cache = new Cache_Lite_Output($CacheOptions);
	if (!($cache->start("${Path}${imgName}${Size}_ImgView"))) {
		print imgHtml($imgName);
		$cache->end();
	}	
}

# Provides the html code to display a thumbnail, making it if it has to
function thumbHtml($imgName) {
        global $ThumbDir, $Path, $Size, $NumPics, $Page;
        if (!file_Exists("$ThumbDir$imgName")) makeThumb($imgName);
        return "<a href=\"?path=$Path&img=$imgName&numpics=$NumPics&page=$Page&size=$Size\"><img border=0 src=\"$ThumbDir$imgName\" /></a>\n";
}

# Prints out all the thumbs, will use cached version if it exists
function thumb() {
	global $CacheOptions, $Path, $Img, $NumPics, $Page, $Size;
	$cache = new Cache_Lite_Output($CacheOptions);
	if (!($cache->start("${Path}${Img}${NumPics}${Page}${Size}_ThumbView"))) {
		$listImgs = listImgs($Path);
		if($NumPics != 0 && count($listImgs) > $NumPics) {
			$listImgs = array_slice($listImgs, $NumPics * ($Page - 1),$NumPics);
		}

		foreach($listImgs as $img) {
			print thumbHtml($img);
		}
		$cache->end();
	}
}

# Prints out a page list, will use cached version if it exists
function pageListHtml() {
	global $CacheOptions, $numPicOptions, $Path, $NumPics, $Page, $Size;
	$cache = new Cache_Lite_Output($CacheOptions);
	if (!($cache->start("${Path}${NumPics}${Page}${Size}_PageView"))) {
		$listImgs = listImgs($Path);
		if($NumPics != 0 && count($listImgs) > $NumPics) {
			$FirstPage = 1;
		        $LastPage = (int)((count($listImgs) - 1) / $NumPics) + 1;
		        $PrevPage = ($Page != $FirstPage) ? $Page - 1 : $Page;
		        $NextPage = ($Page != $LastPage) ? $Page + 1 : $LastPage;

			#We want to display only ten pages at a time so we dont crowd the screen
			#first and last define the borders of what pages we display as for the user to click
			if ($LastPage > 10) {
				$first = $Page - 4;
				$last = $Page + 5;
				if ($first < $FirstPage) {
					$last = 10;
					$first = $FirstPage;
				} else if ($last > $LastPage) {
					$first = $LastPage - 9;
					$last = $LastPage;
				}
			} else {
				$first = $FirstPage;
				$last = $LastPage;
			}

			print "<center>\n";
			print "<a href=\"?path=$Path&numpics=$NumPics&page=$FirstPage&size=$Size\">First</a> | ";
			if($Page != $FirstPage) 
				print "<a href=\"?path=$Path&numpics=$NumPics&page=$PrevPage&size=$Size\">Prev</a> | ";
			#let the user know there are more pages
			if($first !== $FirstPage) print " ... | ";

			for ($i = $first; $i <= $last; ++$i) {
				if ($i == $Page) print $i;
				else
					print "<a href=\"?path=$Path&numpics=$NumPics&page=$i&size=$Size\">$i</a>";
				print " | ";
			}

			#let the user know there are more pages
			if($last !== $LastPage) print " ... | ";
			if($Page != $LastPage) 
				print "<a href=\"?path=$Path&numpics=$NumPics&page=$NextPage&size=$Size\">Next</a> | ";
			print "<a href=\"?path=$Path&numpics=$NumPics&page=$LastPage&size=$Size\">Last</a>\n";
			print "</center>\n";

			print "<br />\n";
		}
		if (count($listImgs) > $numPicOptions[0]) {
			print "Show: ";
			foreach($numPicOptions as $num) {
				$str = ($num === 0) ? "All" : $num;
				if($NumPics == $num) print $str;
				else print "<a href=\"?path=$Path&img=$Img&numpics=$num&page=$Page&size=$Size\">$str</a>";
				print " ";
			}	
			print "<br />\n";
			print "<br />\n";
		}
		$cache->end();
	}
}

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<title></title>
		<link rel="stylesheet" type="text/css" href="style.css" />
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
	</head>
	<body>
	<center>
	<table border=0 width="100%">
		<tr>
		<td valign="top">
<?php
dirTree($Path);
?>
		</td>
		<td valign="top">
<?php if(strlen($Img) !== 0) { ?>
<center>

<?php img($Img); ?>
		<br />
</center>

<?php } ?>
<?php
$ListImgs = listImgs($Path);
pageListHtml();
thumb();
?>
		</td>
		</tr>
	</table>
	<center>
	</body>
</html>
