<?php
/*
Extension Name: LightGallery
Extension Url: http://vanilla.baldursoft.de/LightGallery
Description: This extension will display a public light weight image gallery
Version: 0.0.1
Author: Alex Lanin
Author Url: http://www.baldursoft.de
*/


// --- BEGIN CONFIG ---
// WARNING: These options will be overwrtitten with every single update!

// this is what will appear in the address bar like extension.php?PostBackAction=LightGallery
// you can change it to anything unique in your vanilla installation
define('LightGalleryID', 'LightGallery');

// --- END CONFIG ---



// ---------------------------------------------------------------------------------------
// --- do not change anything below this line unless you really know what you're doing ---
// ---------------------------------------------------------------------------------------




// a little security
if (!defined('IN_VANILLA')) exit();

// no menu, as for example the login page. no need to have a gallery there :)
if(!isset($Menu)) return;


// do *NOT* change this!
define('galleryPath', $Configuration['EXTENSIONS_PATH'] . 'LightGallery');
define('imagePath', galleryPath . '/images');
define('thumbPath', galleryPath . '/thumbs'); // chmod might be required!


// --- BEGIN load settings ---

// set file
$SettingsFile = galleryPath . '/settings.php';
if(!is_readable($SettingsFile)) die("LightGallery's settings.php is not readable. try changing chmod on /extensions/LightGallery/settings.php (for changing settings it must also be writable)");

// create ConfigurationManager instance
$Config = $Context->ObjectFactory->NewContextObject($Context, 'ConfigurationManager');

// load settings
$Config->GetSettingsFromFile($SettingsFile);

// --- END load settings ---


// avoid friendly urls "support" of extension.php :D
function GetUrl2($url) {
	global $Configuration;
	return $Configuration['WEB_ROOT'] . $url;
}


// add 'Gallery' tab to menu
$Menu->AddTab(	$Config->GetSetting('String_Gallery'),
				LightGalleryID,
				GetUrl2('extension.php?PostBackAction=' . LightGalleryID),
				'', 15);



// ToDo: move (most of) this to Gallery.Constructor()
if ($Context->SelfUrl == 'extension.php' && ForceIncomingString('PostBackAction', '') == LightGalleryID) {

	error_reporting(E_ALL);

	if(!is_writable(thumbPath)) die("LightGallery's thumbs dir is not writable. try changing chmod on /extensions/LightGallery/thumbs/");

	// set tab
	$Menu->CurrentTab = LightGalleryID;

	$Context->PageTitle = $Config->GetSetting("String_Gallery");

	// add gallery to output
	// "LightGallery" is the class name below
	$Page->AddRenderControl($Context->ObjectFactory->NewContextObject($Context, "LightGallery"),
							$Configuration["CONTROL_POSITION_BODY_ITEM"]);


	// add style (new in 0.0.1)
	$Head->AddStylesheet('extensions/LightGallery/style.css');

	// include LightBox
	if(!defined('LIGHTBOX_EXTENSION') && !defined('BALDURSBOX_EXTENSION'))
		if(array_key_exists('LightBox', DefineExtensions($Context)))
			die('ADMIN: please make sure to include the LightBox extension BEFORE this one.<br>Simply uncheck and check LightGallery here:<br><a href="' . GetUrl2('settings.php?PostBackAction=Extensions') . '">Settings -&gt; Extensions</a>');
		elseif(array_key_exists('BaldursBox', DefineExtensions($Context)))
			die('ADMIN: please make sure to include the BaldursBox extension BEFORE this one.<br>Simply uncheck and check LightGallery here:<br><a href="' . GetUrl2('settings.php?PostBackAction=Extensions') . '">Settings -&gt; Extensions</a>');
		else
			die('ADMIN: you have to install either LightBox or BaldursBox extension');

		if(function_exists('includeBaldursBox'))	includeBaldursBox();
	elseif(function_exists('includeLightBox'))		includeLightBox();

	$counter = 0;
	
	// all categories, not cats :)
	// dir: images, directories only
	$cats = getCatList('', true);

	// some space
	$Panel->AddString('<br><br><br>', 100);
	

	foreach($cats as $cat) {
		// count images in each category
		$counter = 0;
		$images = getFileList($cat);
		foreach($images as $image) $counter++;

		$Panel->AddString("<a href='" .
							GetUrl2('extension.php?PostBackAction=' . LightGalleryID . "&cat=$cat") .
							"' class=catlink>$cat</a> ($counter)<br>", 100);
	}
	
	if(sizeof($cats) == 1 && empty($_GET['cat'])) $_GET['cat'] = $cats[0];
}


function getCatList() {
	$arr = array();

	$d = @opendir(imagePath)
	// ToDo: change to vanilla error handler
			or die("error opening '" . imagePath . "' dir");

	while (($file = readdir($d)) !== false) {
		if($file[0] == ".") 				continue;
		if(!is_dir(imagePath . "/$file"))	continue;

		$arr[] = $file;
	}
	closedir($d);
	natsort($arr);
	return $arr;
}


// file list starting with LightGallery/images/
// separated into two functions because the time stuff is really slowing things down
function getFileList($dir) {

	$arr = array();

	$d = @opendir(imagePath . "/$dir/")
	// ToDo: change to vanilla error handler
			or die("error opening '" . imagePath . "/$dir' dir");

	while (($file = readdir($d)) !== false) {
		if($file[0] == ".") 					continue;
		if(is_dir(imagePath . "/$dir/$file"))	continue;

		$arr[] = $file;
	}
	closedir($d);
	natsort($arr);
	return $arr;
}


// this will be applied only to selected category
function getFileListSortedByTime($dir) {

	$arr = array();

	$d = @opendir(imagePath . "/$dir/")
	// ToDo: change to vanilla error handler
			or die("error opening '" . imagePath . "/$dir' dir");

	while (($file = readdir($d)) !== false) {
		if($file[0] == ".") 					continue;
		if(is_dir(imagePath . "/$dir/$file"))	continue;

		$arr[] = array('filename' => $file, 'filemtime' => filemtime(imagePath . "/$dir/$file"));
	}
	closedir($d);
	
	// array_multisort
	// http://de.php.net/manual/en/function.array-multisort.php
	// Example 261. Sorting database results
	foreach ($arr as $key => $row) {
		$filename[$key]  = $row['filename'];
		$filemtime[$key] = $row['filemtime'];
	}

	array_multisort($filemtime, SORT_ASC, $filename, SORT_ASC, $arr);

	return $arr;
}


class LightGallery extends PostBackControl 
{
	var $Context;
	function LightGallery(&$Context) {
		$this->ValidActions = array(LightGalleryID);
		$this->Constructor($Context);
		$this->Context = &$Context;
	}
	
	
	function Render() {
	
		if (ForceIncomingString('PostBackAction', '') != LightGalleryID) return;

		// gonna need the config here
		global $Config;

		$this->PostBackParams->Clear();
		
		// for counting whatever we need counted :)
		$counter = 0;
		
		// all categories, not cats :)
		//$cats = getCatList();
		global $cats;

		if(!isset($_GET['cat'])) {
			echo $Config->GetSetting('String_DefaultText');
			return;
		}
			
		// requested
		$cat = $_GET['cat'];

		// valid?
		// ToDo: use vanilla error handler
		if(!in_array($cat, $cats)) die('ACCESS DENIED');

		// ToDo: config, template, whatever
		echo "<br><br><h1 class=catname>$cat</h1>";

		// vanilla is using ob_ functions :-(
		// flush();

	
		$counter = 0;
		$page = ForceIncomingString('page', 0);
		$perPage = $Config->GetSetting('Gallery_FotosPerPage');
		if(empty($perPage)) {
			echo ("<hr>you just updated 0.0.0 to 0.0.1? Please go to Settings -&gt; ExtensionOptions -&gt; LightGallery<hr>");
			$perPage = 50;

			$Config->Settings['Gallery_SortBy'] = '----';
			$Config->Settings['Gallery_FotosPerPage'] = '----';

			$Config->DefineSetting('Gallery_SortBy', 'name', true);
			$Config->DefineSetting('Gallery_FotosPerPage', $perPage, true);

			global $SettingsFile;
			$Config->SaveSettingsToFile($SettingsFile);
			$Config->GetSettingsFromFile($SettingsFile);
		}

		$images = $Config->GetSetting('Gallery_SortBy') == 'time' ? getFileListSortedByTime($cat) : getFileList($cat);

		echo '<span class=thumbs>';

		foreach($images as $image) {

			if(is_array($image)) {
				$filemtime = $image['filemtime'];
				$image = $image['filename'];
			} else
				$filemtime = NULL;

			$counter++;

//echo "<hr>$counter < $perPage * $page + 1 || $counter > $perPage * ($page+1)<br>";

			if($counter < $perPage * $page + 1 || $counter > $perPage * ($page + 1))
				continue;

			$thumb = filesize(imagePath . "/$cat/$image") . '.' .
					 ($filemtime ? $filemtime : filemtime(imagePath . "/$cat/$image")) . '.jpg';
			
			echo " <a href='" .
					GetUrl2("extensions/LightGallery/images/$cat/$image") .
					"' rel='lightbox[$cat]'><img src='" .
					GetUrl2("extensions/LightGallery/" . (file_exists(thumbPath . "/$thumb") ? "thumbs/$thumb" : "thumb.php?img=$cat/$image")) .
					"' border=0></a> ";
					
		}

		echo '</span>';

		$pages = ceil(sizeof($images) / $perPage);
		
		if($pages > 1) {
			echo '<div class=pagination>';
	
			if($page > 0) for($p = 0; $p <= $page-1 && $p <= $pages; $p++)
				echo "<a href='" . GetUrl2('extension.php?PostBackAction=' . LightGalleryID . "&cat=$cat" . ($p > 0 ? "&page=$p" : "")) . "' class=prev>$p</a> ";
	
			echo "<span class=current>$page</span> ";
	
			if($pages > $page) for($p = $page+1; $p < $pages; $p++)
				echo "<a href='" . GetUrl2('extension.php?PostBackAction=' . LightGalleryID . "&cat=$cat&page=$p") . "' class=next>$p</a> ";
	
			echo '</div>';
		}
	}
}




if ($Context->SelfUrl == "settings.php" && $Context->Session->User->Permission('PERMISSION_CHANGE_APPLICATION_SETTINGS')) {

	// doesn't do anything for me :-(
	error_reporting(E_ALL);

	class LightGallerySettings extends PostBackControl
	{
		function LightGallerySettings(&$Context) 
		{
			if (ForceIncomingString('PostBackAction', '') != 'LightGallerySettings') return;

			$this->Name = 'LightGallerySettings';
			$this->ValidActions = array('LightGallerySettings');
			$this->Constructor($Context);
			
			global $SettingsFile, $Config;

			if(isset($_POST['save'])) {
			
				// force settings.php update 0.0.0 to 0.0.1
//				$Config->Settings['Gallery_FotosPerPage'] = '----';
//				$Config->Settings['Gallery_SortBy'] = '----';
				
				// save new settings
				$Config->DefineSetting('String_Gallery', $_POST['String_Gallery'], true);
				$Config->DefineSetting('String_DefaultText', $_POST['String_DefaultText'], true);
				$Config->DefineSetting('Thumb_Height', max(intval($_POST['Thumb_Height']), 20), true);
				$Config->DefineSetting('Thumb_Cut', min(intval($_POST['Thumb_Cut']), 30), true);
				$Config->DefineSetting('Thumb_Quality', intval($_POST['Thumb_Quality']), true);
				$Config->DefineSetting('Gallery_FotosPerPage', max(intval($_POST['Gallery_FotosPerPage']), 1), true);
				$Config->DefineSetting('Gallery_SortBy', $_POST['Gallery_SortBy'], true);

				// yeah it's not clean coded using $_GET, but it's easy ;)
				// $_GET['saved'] is boolean whether saving was succuessfull
				$_GET['saved'] = $Config->SaveSettingsToFile($SettingsFile);

				// reload settings, since $Config doesn't contain what was just saved....
				// bug or feature? ;-)
				$Config->GetSettingsFromFile($SettingsFile);
			}
		}

		function Render() {
			if (ForceIncomingString('PostBackAction', '') != 'LightGallerySettings') return;

			// no idea what this does
			$this->PostBackParams->Clear();


			if (isset($_GET['saved']))
				if($_GET['saved'])
					echo	'<div id="Success">Settings saved</div>';
				else
					echo	'<div class="ErrorContainer">Error: Settings NOT saved</div>';


			global $SettingsFile, $Config;
			
			
			if($Config->GetSetting('Gallery_ThumbVersion') < 2) {
				// delete 0.0.0 thumbs
				echo "<hr>UPDATING, please stand by....<br>Deleting old thumbnails....<br>";
				global $cats;
				$images = getFileList('../thumbs/');
				$counter = 0;
				foreach($images as $image) {
					$i = explode('.', $image);
					if(strlen($i[1]) == 32) {
						unlink(thumbPath . "/$image");
						$counter++;
					}
				}
	
				echo "$counter old files deleted!<br><br>sorry, but this step was required. new thumbnails will load much faster!<br>For details see changelog<hr>if any errors appeared, go to /extensions/LightGallery/thumbs and delete all files!<hr>";
				
				$Config->Settings['Gallery_ThumbVersion'] = '-';
				$Config->DefineSetting('Gallery_ThumbVersion', '2', true);
	
				$Config->SaveSettingsToFile($SettingsFile);
				$Config->GetSettingsFromFile($SettingsFile);
			}
			
			?>
			<div id="Form">
				<fieldset>
					<legend>LightGallery Settings</legend>
					<?= $this->Get_Warnings() /* no idea what this might output, never used this warning/error system */ ?>

					<form id="f" method="post" action="settings.php?PostBackAction=LightGallerySettings" enctype="multipart/form-data" >
						<!-- not yet implemented -->
						<input type="submit" name="thumbs_delete" value="Delete old thumbnails" disabled="disabled" /> [ToDo]<br />
						<br />
						<hr />
						<br />
						<table border=0 cellspacing=10>
						<tr><td colspan="2"><strong>Strings:</strong><br />

						<tr><td width="100">Gallery
							<td><input type="text" name="String_Gallery" value="<?=$Config->GetSetting('String_Gallery')?>" /><br />
							
						<tr><td>DefaultText
							<td><textarea name="String_DefaultText" cols="60" rows="10"><?=$Config->GetSetting('String_DefaultText')?></textarea><br />

						<tr><td colspan="2"><br /><strong>Gallery:</strong><br />

						<tr><td>Fotos per page:
							<td><input type="text" name="Gallery_FotosPerPage" value="<?=$Config->GetSetting('Gallery_FotosPerPage')?>" size="3" maxlength="3" /><br />
								default: 50<br />
								
						<tr><td>Sort Fotos By:
							<td><input type="radio" name="Gallery_SortBy" value="name" <? if($Config->GetSetting('Gallery_SortBy') == 'name') echo 'checked="checked"';?> /> name<br />
								<input type="radio" name="Gallery_SortBy" value="time" <? if($Config->GetSetting('Gallery_SortBy') == 'time') echo 'checked="checked"';?> /> time<br />
								default: name<br />
								
						<tr><td colspan="2"><br /><strong>Thumbs:</strong><br />

						<tr><td>Height:
							<td><input type="text" name="Thumb_Height" value="<?=$Config->GetSetting('Thumb_Height')?>" size="3" maxlength="3" />px<br />
								default: 70px<br />
							
						<tr><td>Cut:
							<td><input type="text" name="Thumb_Cut" value="<?=$Config->GetSetting('Thumb_Cut')?>" size="2" maxlength="2" />%<br />
								default: 10%<br />
							
						<tr><td>JPEG-Quality:
							<td><input type="text" name="Thumb_Quality" value="<?=$Config->GetSetting('Thumb_Quality')?>" size="2" maxlength="2" /><br />
								default: 90<br />

						</table>
						<br />
						<input type="submit" name="save" value="save" />
					</form>
				</fieldset><br />
			</div>
			<?
		}
	}

	$Page->AddRenderControl($Context->ObjectFactory->NewContextObject($Context, 'LightGallerySettings'),
							$Configuration["CONTROL_POSITION_BODY_ITEM"] + 1);

	$Context->SetDefinition('ExtensionOptions', 'Extension Options');
	$Panel->AddList($Context->GetDefinition('ExtensionOptions'), 10);
	
	$Panel->AddListItem($Context->GetDefinition('ExtensionOptions'),
						'LightGallery',
						GetUrl($Context->Configuration, 'settings.php', '', '', '', '', 'PostBackAction=LightGallerySettings'));
}
?>
