<?php 
/*************************************************
* Micro Photo Gallery
*
* Version: 1.5
* Date: 2012-08-19
*
* Usage:
* Just copy these files into your image folder
*
**************************************************/

// SETTINGS

$title = 'Tenasia';
$desc = ''; // Description
$keyw = ''; // Keywords

// Enable different background for new images since last visit
$enableVisit = true;

// Enable RSS and link to it
$enable_RSS = false;
$RSS_file = 'rss.php';

// Enable Image Viewer and file
$enable_viewer = true;
$viewer_file = 'viewer.php';

// Enable page navigation
$enablePages = true;
// Images per page
$ippage = 96;
// Page navigation position(s): 0 = top, 1 = bottom, 2 = both
$navigation = 2;

// Sort by: 0 = file name, 1 = date, 2 = file size, 3 = image resolution
$sort = 0;
// Order: 0 = ascending  / oldest / biggest first
//        1 = descending / newest / smallest first
$order = 1;

// Directory of the images
$directory = 'i';
$image_url = '';

// Thumb size
$thmb_width = 236;
$thmb_height = 188;

/*************************************************/

ini_set('display_errors', 0);
ini_set('log_errors', 0); 

// Page number
if($enablePages){
	if(isset($_GET['page']) && is_numeric((int)$_GET['page'])){
		if((int)$_GET['page'] < 1){ $page = 1; }
		else{ $page = (int)$_GET['page']; }
	}else{ $page = 1; }
}

// Cookies for last visit
if($enableVisit){
	if(isset($_COOKIE['LastImage'])){ $lastVisit = (int)$_COOKIE['LastImage']; }
	else{ $lastVisit = NULL; }
	
	$expire = time() + 60 * 24 * 60 * 60;
	setcookie('LastImage', time(), $expire);
	
	if(empty($lastVisit) || !is_numeric($lastVisit)){ $enableVisit = false; }
}

// RSS
if($enable_RSS && file_exists(dirname(__FILE__).'/'.$RSS_file)){
	$rss = '<link href="'.$RSS_file.'" rel="alternate" type="application/rss+xml" title="'.$title.' RSS" />'."\n";
}else{ $rss = ''; }

// Viewer
if($enable_viewer && file_exists(dirname(__FILE__).'/'.$viewer_file)){
	$viewer = '  <a href="'.$viewer_file.'" title="Image Viewer" id="viewer">Image viewer</a>'."\n";
}else{ $viewer = ''; }

// Fixing image directory strings
$directory = preg_replace('#/+$#','',$directory);
$directory = empty($directory) ? dirname(__FILE__) : $directory;
if(strlen($image_url) > 1 && !preg_match('#/$#',$image_url)){ $image_url .= '/'; }

function resizeImage($originalImage,$toWidth,$toHeight,$ext){
	// Get the original geometry and calculate scales
	list($width, $height) = getimagesize($originalImage);
	$xscale=$width/$toWidth;
	$yscale=$height/$toHeight;
	
	// Recalculate new size with default ratio
	if($yscale>$xscale){
		$new_width = round($width * (1/$yscale));
		$new_height = round($height * (1/$yscale));
	}
	else {
		$new_width = round($width * (1/$xscale));
		$new_height = round($height * (1/$xscale));
	}
	// Resize the original image
	$imageResized = imagecreatetruecolor($new_width, $new_height);
	if($ext === 'png'){     $imageTmp = imagecreatefrompng  ($originalImage); }
	elseif($ext === 'gif'){ $imageTmp = imagecreatefromgif  ($originalImage); }
	else{                  $imageTmp = imagecreatefromjpeg ($originalImage); }
	imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

	return $imageResized;
} 

function generateThumbnails(){
	global $thmb_width,$thmb_height,$directory;
	
	// Creates thumbs directory if it doesn't exists and an empty index.php inside
	if(!is_dir($directory.'/thumbs')){ mkdir($directory.'/thumbs',0755); }
	if(!file_exists($directory.'/thumbs/index.php')){
		file_put_contents($directory.'/thumbs/index.php','');
	}
	
	// Open the actual directory
	if($handle = opendir($directory)) {
		// Read all file from the actual directory
		while ($file = readdir($handle)) {
			// Check whether tha actual item is a valid file
			if(is_file($directory.'/'.$file)){
				// Check if the actual file is a image
				if(preg_match('#(.*?)\.(jpg|jpeg|png|gif)$#i',$file,$nameFile)){
					$thmbFile = $directory.'/thumbs/'.$nameFile[1].'_th.'.strtolower($nameFile[2]);
					// If the thumb is older than the image, delete the thumb
					if(file_exists($thmbFile)){
						$create = false;
						if(filemtime($thmbFile) < filemtime($file)){
							unlink($thmbFile);
							$create = true;
						}
					}else{ $create = true; }
					// If a thumbnail doesn't exist than create a new one
					if($create){
						imagejpeg(resizeImage($directory.'/'.$file,$thmb_width,$thmb_height,strtolower($nameFile[2])),$thmbFile,80);
					}
				}
			}
		}
	}
}

function displayPhotos($addon = 0){
	generateThumbnails();
	
	global $lastVisit,$enableVisit,$ippage,$page,$enablePages,$navigation,$sort,$order,$directory,$image_url;
	
	if($addon === 'mod' && isset($_GET['bin'])){
		$trash = 'trash/';
		$urlvar = 'view=bin&';
	}else{ $trash = $urlvar = ''; }
	
	if(!$dir = scandir($directory.'/thumbs/')){ $dir = array(); }
	$arr = array();
	foreach($dir as $file) {
		if(preg_match('#(.*?)_th\.(jpg|jpeg|png|gif)$#i',$file,$nameFile)){
			$orgFileLow = $nameFile[1].'.'.$nameFile[2];
			$orgFileUpp = $nameFile[1].'.'.strtoupper($nameFile[2]);
			
			// Deletes thumbs to non-existent images
			if(file_exists($directory.'/'.$orgFileLow)){ $orgFile = $orgFileLow; }
			elseif(file_exists($directory.'/'.$orgFileUpp)){ $orgFile = $orgFileUpp; }
			elseif(file_exists($directory.'/trash/'.$orgFileLow)){ $orgFile = $orgFileLow; }
			elseif(file_exists($directory.'/trash/'.$orgFileUpp)){ $orgFile = $orgFileUpp; }
			else{ unlink($directory.'/thumbs/'.$file); continue; }
			
			// Skips image if it doesnt exist in the right folder
			if(!file_exists($directory.'/'.$trash.$orgFile)){ continue; }
			
			// Time for the creation of the image
			$time = filemtime($directory.'/'.$trash.$orgFile);
			
			// Sort the images
			switch($sort){
				case(1): // Date Added
					$info = $time;
					while(!empty($arr[$info])){ $info++; }
					break;
				case(2): // File Size
					$info = filesize($directory.'/'.$trash.$orgFile);
					while(!empty($arr[$info])){ $info++; }
					break;
				case(3): // Image Resolution
					list($width, $height) = getimagesize($directory.'/'.$trash.$orgFile);
					$info = $width * $height;
					while(!empty($arr[$info])){ $info++; }
					break;
				default: // File Name
					$info = strtolower($orgFile);
					$w = 2;
					while(!empty($arr[$info])){
						$info .= '_'.$w;
						$w++;
					}
			}

			if($enableVisit && $time >= $lastVisit){
				$newimage[$file] = ' class="newimage"';
			}else{ $newimage[$file] = ''; }
			
			$arr[$info]['file'] = $file;
			$arr[$info]['orgf'] = $orgFile;
			$arr[$info]['time'] = $time;
		}
	}
	
	// Sorting the images
	if($order){ krsort($arr); }
	else{ ksort($arr); }
	
	// Making a new array for pages
	$newarr = array();
	$n = 1;
	if($addon === 'viewer' && isset($_GET['i']) && file_exists($directory.'/'.basename(base64_decode($_GET['i'])))){
		foreach($arr as $image){
			if(basename(base64_decode($_GET['i'])) === $image['orgf']){ $newarr['current'] = $n; }
			$newarr[$n]['thumb'] = $image['file'];
			$newarr[$n]['image'] = $image['orgf'];
			$newarr[$n]['time'] = $image['time'];
			$n++;
		}return $newarr;
	}else{
		foreach($arr as $image){
			$newarr[$n]['thumb'] = $image['file'];
			$newarr[$n]['image'] = $image['orgf'];
			$newarr[$n]['time'] = $image['time'];
			$n++;
		}
	}
	
	if($addon === 'viewer'){ return $newarr; }
	
	// Images
	$i = ($page - 1) * $ippage;
	$count = count($newarr);
	$lastpage = ceil($count/$ippage);
	if($lastpage < 1){ $lastpage = 1; }
	
	if($count <= $i){
		$i = ($lastpage - 1) * $ippage;
		$page = $lastpage;
	}
	
	$j = $i + $ippage;
	if($count < $j || !$enablePages){ $j = $count; }
	if($count <= $ippage){ $enablePages = false; }
	if(!$enablePages && $addon !== 'mod'){ $padding = 0; }
	else{ $padding = '33px'; }
	
	
	$i++;
	if($i < 1){ $i = 1; }
	
	$images = '  <div id="images">'."\n";

	if(empty($newarr)){
		$images .= '    <div style="height:30px;"></div>'."\n";
	}elseif($addon === 'mod'){
		for($k=$i;$k<=$j;$k++){
			$images .= '    <label for="'.$k.'"'.$newimage[$newarr[$k]['thumb']].'>'."\n".'      <a href="'.$image_url.$trash.rawurlencode($newarr[$k]['image']);
			$images .= '" style="background-image:url(\''.$image_url.'thumbs/'.rawurlencode($newarr[$k]['thumb']).'\');"></a>'."\n";
			$images .= '      <input type="checkbox" id="'.$k.'" name="images[]" value="'.base64_encode($newarr[$k]['image']).'" />'."\n".'    </label>'."\n";
		}
	}else{
		for($k=$i;$k<=$j;$k++){
			$images .= '    <a href="'.$image_url.rawurlencode($newarr[$k]['image']).'"'.$newimage[$newarr[$k]['thumb']];
			$images .= ' style="background-image:url(\''.$image_url.'thumbs/'.rawurlencode($newarr[$k]['thumb']).'\');"></a>'."\n";
		}
	}
	
	$images .= '    <div style="clear:both;height:'.$padding.";\"></div>\n  </div>\n";
	
	// Pages
	if($enablePages){
		$nPage = $page + 1; $pPage = $page - 1;
		$prev = '    <a href="?'.$urlvar.'page=1" title="First page">&lt;&lt;</a>'."\n".'    <a href="?'.$urlvar.'page='.$pPage.'" title="Previous page">&lt;</a>'."\n";
		$next = '    <a href="?'.$urlvar.'page='.$nPage.'" title="Next page">&gt;</a>'."\n".'    <a href="?'.$urlvar.'page='.$lastpage.'" title="Last page">&gt;&gt;</a>'."\n";
		
		if($page == 1){ $prev = ''; }
		if($page == $lastpage){ $next = ''; }
		
		//$current[$page] = ' class="current"';
		
		$topPages = '  <div class="pages" style="top:14px;">';
		$bottomPages = '  <div class="pages" style="bottom:14px;">';
		
		$pages = "\n".$prev;
		for($p=1;$p<=$lastpage;$p++){
			if($page > 4 && $lastpage > 6 && $p > 2 && $p < ($page - 1)){ $pages .= "    ..\n"; $p = $page - 1; }
			
			//if(!isset($current[$p])){ $current[$p] = ''; }
			if($p == $page){ $pages .= '    <span class="current">'.$p."</span>\n"; }
			else{ $pages .= '    <a href="?'.$urlvar.'page='.$p.'" title="Page '.$p.'">'.$p."</a>\n"; }
			
			if($lastpage > 6 && $p < ($lastpage - 2) && $p > $page){ $pages .= "    ..\n"; $p = $lastpage - 2; }
		}
		$pages .= $next."  </div>\n";
		
		$topPages .= $pages;
		$bottomPages .= $pages;
		
		if($navigation == 0){ $bottomPages = ''; }
		elseif($navigation == 1){ $topPages = ''; }
		
		echo $topPages.$images.$bottomPages;
	}else{ echo $images; }
}
if(!isset($addon) || $addon !== 'viewer'){

// Encodes the title
$title = htmlentities($title,ENT_QUOTES);

// Checks if moderation is used
if(isset($mod_title)){ $title = htmlentities($mod_title,ENT_QUOTES); }

?>
<!DOCTYPE HTML>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php echo $title; ?></title>
<meta name="description" content="<?php echo $desc; ?>" />
<meta name="keywords" content="<?php echo $keyw; ?>" />
<link href="style.css" rel="stylesheet" type="text/css" />
<?php echo $rss; ?>
<div id="main">
  <div id="caption"><?php echo $title; ?></div>
<?php echo $viewer; ?>
  <div id="source">Micro Photo Gallery 1.5</div>
<?php
if(isset($addon) && $addon === 'mod'){ displayMod(); }
else{ displayPhotos(); }
?>
</div>
<!-- Piwik -->
<script type="text/javascript">
  var _paq = _paq || [];
  _paq.push(['trackPageView']);
  _paq.push(['enableLinkTracking']);
  (function() {
    var u=(("https:" == document.location.protocol) ? "https" : "http") + "://kastden.org/piwik/";
    _paq.push(['setTrackerUrl', u+'piwik.php']);
    _paq.push(['setSiteId', 1]);
    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.type='text/javascript';
    g.defer=true; g.async=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
  })();
</script>
<noscript><p><img src="http://kastden.org/piwik/piwik.php?idsite=1" style="border:0;" alt="" /></p></noscript>
<!-- End Piwik Code -->
<?php } ?>
