<?php

function smarty_cms_function_microgal($params, &$smarty)
{
	$max_width = ($params['max_width']);
	$max_height = ($params['max_height']);
	$directory = ($params['directory']);
	$coppermine = isset($params['coppermine']) ? $params['coppermine'] : 'false';
	$takendate = isset($params['takendate']) ? $params['takendate'] : 'all';
	$gpsdata = isset($params['gpsdata']) ? $params['gpsdata'] : 'false';
	$kmlfile = ($params['kmlfile']);
	
	if ($gpsdata == 'true')
	{
		$kmlfilehandle = fopen($kmlfile,'w');
		fwrite($kmlfilehandle,'<?xml version="1.0" encoding="UTF-8"?>' . chr(13));
		fwrite($kmlfilehandle,'<kml xmlns="http://www.opengis.net/kml/2.2">' . chr(13));
		fwrite($kmlfilehandle,'<Document>' . chr(13));
	}

	echo '<div class="microgal">';
	echo "\n";
	

	loadFilesFromDir($directory,$max_width,$max_height,$coppermine,$takendate,$gpsdata,$kmlfilehandle);
	echo '</div>';

	if ($gpsdata == 'true')
	{
		fwrite($kmlfilehandle,'</Document>' . chr(13));
		fwrite($kmlfilehandle,'</kml>' . chr(13));
		fclose($kmlfilehandle);
	}
	
}

function loadFilesFromDir($directory,$max_width,$max_height,$coppermine,$takendate,$gpsdata,$kmlfilehandle)
{
	//get a random number for grouping pictures in fancybox
	$fancygroup = $directory . rand();
	
	//get all image files with a .jpg extension
	$images = glob($directory . "*.[jJ][pP][gG]");

	foreach($images as $image)
	{
		$path_parts = pathinfo($image);
		if ($coppermine == 'true')
		{
			if ( left($path_parts["filename"],7) == "normal_" or left($path_parts["filename"],6) == "thumb_" )
			{
			}
			else
			{
				createThumbnail($directory,$image,$max_width,$max_height);
				writeHTML($directory,$image,$fancygroup,$takendate,$gpsdata,$kmlfilehandle);
			}
		}
		else
		{

			createThumbnail($directory,$image,$max_width,$max_height);
			writeHTML($directory,$image,$fancygroup,$takendate,$gpsdata,$kmlfilehandle);
		}
	}
}

function writeHTML($directory,$image,$fancygroup,$takendate,$gpsdata,$kmlfilehandle)
{

	$path_parts = pathinfo($image);
	$filename = $path_parts["filename"] . "." . $path_parts["extension"];
//	$thumbnail = $directory . 'thumbs/tn_' . $filename;
	
//	echo '<h1>Test H1</h1>';
//	echo ("<img src=\"$thumbnail\" />\n");
	
//	$title=get_IPTC_title($image);
//	echo '<h1>' . $image . '</h1>';

	$iptc_date=get_IPTC_date($image);

	if ($takendate == $iptc_date or $takendate == "all")
	{
		$title=get_IPTC_title($image);
		if (!isset($title))
		{
			$title=$filename;
		}

		if ($gpsdata == 'true')
		{
			$coord=readGPS($image);
			
			KMLwriter($kmlfilehandle,$title,$coord,$image,$directory . 'thumbs/tn_' . $filename);
			
			$title = $title . chr(13) . 'Breddegrad: ' . $coord[1] . chr(13) . 'L&aelig;ngdegrad: ' . $coord[0];
			
			
			
		}
		


	
	//	echo $title;
		echo '<a class="fancybox" href="' . $image .'"';
		echo ' title="' . $title . '"';
		echo ' alt="' . $title . '"';
		echo ' data-fancybox-group="' . $fancygroup . '">';
		echo '<img src="' . $directory . 'thumbs/tn_' . $filename . '" />';
		echo '</a>';
		echo "\n";
	}
}

//IPTC functions
function get_IPTC_title($path)
{
	$size=GetImageSize($path,&$info);
	if (isset($info["APP13"]))
	{
		$iptc=iptcparse($info["APP13"]);
		return $iptc["2#005"][0];
	}
}

function get_IPTC_date($path)
{
	$size=GetImageSize($path,&$info);
	if (isset($info["APP13"]))
	{
		$iptc=iptcparse($info["APP13"]);
		return $iptc["2#055"][0];
	}
}

//GPS coordinate functions

function readGPS($path) {
	$exif = exif_read_data($path);
	$lon = getGps($exif["GPSLongitude"], $exif['GPSLongitudeRef']);
	$lat = getGps($exif["GPSLatitude"], $exif['GPSLatitudeRef']);
	return array($lon, $lat);
}

function getGps ($exifCoord, $hemi) {
	$degrees = count($exifCoord) > 0 ? gps2Num($exifCoord[0]) : 0;
	$minutes = count($exifCoord) > 1 ? gps2Num($exifCoord[1]) : 0;
	$seconds = count($exifCoord) > 2 ? gps2Num($exifCoord[2]) : 0;
	
	$flip = ($hemi == 'W' or $hemi == 'S') ? -1 : 1;
	return $flip * ($degrees + $minutes / 60 + $seconds / 3600);
}

function gps2Num($coordPart) {

	$parts = explode('/', $coordPart);

	if (count($parts) <= 0)
		return 0;

	if (count($parts) == 1)
		return $parts[0];

	return floatval($parts[0]) / floatval($parts[1]);
}


function KMLwriter($kmlfilehandle,$title,$coord,$image,$thumbnail) {
	fwrite($kmlfilehandle,'<Placemark>' . chr(13));
	fwrite($kmlfilehandle,'<description>' . chr(13));
	fwrite($kmlfilehandle,'<![CDATA[<img src="http://miljokemi.dk/' . $thumbnail . '"></img><br>' . $title . ']]>' . chr(13));
	fwrite($kmlfilehandle,'</description>' . chr(13));
	fwrite($kmlfilehandle,'<name>' . $title . '</name>'  . chr(13));
	fwrite($kmlfilehandle,'<Style>' . chr(13));
	fwrite($kmlfilehandle,'<IconStyle>' . chr(13));
	fwrite($kmlfilehandle,'<Icon>' . chr(13));
	fwrite($kmlfilehandle,'<href>http://miljokemi.dk/' . $thumbnail . '</href>' . chr(13));
	fwrite($kmlfilehandle,'</Icon>' . chr(13));
	fwrite($kmlfilehandle,'</IconStyle>' . chr(13));
	fwrite($kmlfilehandle,'</Style>' . chr(13));
	fwrite($kmlfilehandle,'<Point>' . chr(13));
	fwrite($kmlfilehandle,'<coordinates>' . $coord[0] . ',' . $coord[1] . '</coordinates>' . chr(13));
	fwrite($kmlfilehandle,'</Point>' . chr(13));
	fwrite($kmlfilehandle,'</Placemark>' . chr(13));
}

//Thumbnail creation
function createThumbnail($directory,$image,$max_width,$max_height)
{
	
//	echo "Thumbnail generation\n";
	
	if ( ! is_dir($directory . "thumbs") )
	{
//		echo "Directory created\n";
		mkdir($directory . "thumbs");
	}
	
	$path_parts = pathinfo($image);
	$filename = $path_parts["filename"] . "." . $path_parts["extension"];
//	echo $filename . "\n";
//	echo $directory . "thumbs/" . $filename . "\n";
	
	if ( ! file_exists($directory . "thumbs/tn_" . $filename) )
	{
//		echo "Nu laves der thumbnails\n";
		if ($path_parts["extension"] == "jpg")
		{
			$src = imagecreatefromjpeg($directory . $filename);
		}
		
		$old_x=imageSX($src);
		$old_y=imageSY($src);
		
		if ( $old_x > $old_y )
		{
			$thumb_w=$max_width;
			$thumb_h=$old_y*($max_height/$old_x);
		}
		if ($old_x < $old_y)
		{
			$thumb_w=$old_x*($max_width/$old_y);
			$thumb_h=$max_height;
		}
		if ($old_x == $old_y)
		{
			$thumb_w=$max_width;
			$thumb_h=$max_height;
		}
//		echo "Højde og bredde";
//		echo $thumb_w;
//		echo $thumb_h;
		
		$new = ImageCreateTrueColor($thumb_w,$thumb_h);
		imagecopyresampled($new, $src, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y);
		
		if ( $path_parts["extension"] == 'jpg' )
		{
//			echo "writing image\n";
			imagejpeg($new, $directory . "thumbs/tn_" . $filename);
		}
		imagedestroy($new);
		imagedestroy($src);
	}
//	echo "Færdig!\n";

}

//A helper function returning the x left characters of a string
function left($str, $length)
{
	if ( $length <= strlen($str) )
	{
		return substr($str, 0, $length);
	}
	else
	{
		return substr($str, 0, strlen($str));
	}
}

function smarty_cms_help_function_microgal()
{
?>
<h3>MicroGal1.3</h3>
<br/><br/>
<h3>What does this do?</h3>
<p>
	This adds a simple gallery on your page with support for the Fancybox lightbox and possibility of creation of KML files (geotagged pictures only). KML files can be shown using my <a href="http://dev.cmsmadesimple.org/projects/gmapskml" target="_blank">gMapsKML plugin.</a>
</p>
<h3>How do I use it?</h3>
<p>
	Just insert the tag into your template/page like:<br />
	<code>
		{microgal max_width="100" max_height="100" directory="pictures"}<br />
		{microgal max_width="100" max_height="100" directory="pictures" $takendate="YYYYMMDD"}<br />
		{microgal max_width="100" max_height="100" directory="pictures" gpsdata="true" kmlfile="pictures/pictures.kml"}
	</code>
</p>
<h3>What parameters does it take?</h3>
<p></p>
<ul>
	<li>
		<em><strong>(required)</strong> </em>
		<tt>max_width </tt> - Maximum width of the thumbnails generated.
	</li>
	<li>
		<em><strong>(required)</strong> </em>
		<tt>max_height </tt> - Maximium height of the thumbnails generated..
	</li>
	<li>
		<em><strong>(required)</strong> </em>
		<tt>directory </tt> - Directory containing the pictures for the gallery.
	</li>
	<li>
		<em><strong>(optional)</strong> </em>
		<tt>takendate </tt> - Defaults to show all pictures in the directory given. To only show pictures for a specific date input the date as "YYYYMMDD".
	</li>
	<li>
		<em>(optional) </em>
		<tt>Coppermine </tt> - If using the Coppermine Gallery software set this to "true" to avoid showing Coppermine thumbnails in the gallery.
	</li>
	<li>
		<em>(optional) </em>
		<tt>gpsdata </tt> - Set this to true for geotagged pictures.
	</li>
	<li>
		<em>(optional - required if gpsdata is set to true) </em>
		<tt>kmlfile </tt> - Path and filename for KML file generation.
	</li>
</ul>
<h3>Other requirements?</h3>
<p>
	The Fancybox script can be download from <a href="http://fancyapps.com/fancybox/" target="_blank">FancyApps</a>.
</p>
<?php
}
function smarty_cms_about_function_microgal()
{
?>
<p>
	Author:	Morten Bjergstr&oslash;m <a href="http://www.miljokemi.dk" target="_blank">www.miljokemi.dk</a>
	<br/ ><br/ >
CMSMadesimple is in a serious need of a proper gallery module supporting e.g. EXIF, IPTC and XMP tags. I have created this plugin mainly to support my needs and is still work in progress.
</p>
<p>
	Version: 1.3
</p>
<?php
}
?>