<?
// this file will be called if there is no thumbnail for an image
// it will create the thumbnail and show it with header('Content-type: image/jpeg')

include 'settings.php';

function createThumb($src, $dst) {
	$size = getimagesize($src);
	$size['mime'] = explode('/', $size['mime']);
	
	// images only :)
	if($size['mime'][0] != 'image') return;
	
	switch($size['mime'][1]) {
		case 'jpeg':	$img = imagecreatefromjpeg($src);	break;
		case 'png':		$img = imagecreatefrompng($src);	break;
		case 'gif':		$img = imagecreatefromgif($src);	break;
		default:		readfile('notimage.jpg');			exit();
	}
	
	global $Configuration;
	
	// ToDo: move this to config somehow
	$height = min(intval($Configuration['Thumb_Height']), $size[1]);
	$width = $height / $size[1] * $size[0];

	$out = imagecreatetruecolor($width, $height);

	// resize and remove 10% of the border - nothing interesting there :-)
	$crop = doubleval($Configuration['Thumb_Cut']) / 100;
	imagecopyresampled($out, $img, 0, 0, $size[0] * $crop, $size[1] * $crop, $width, $height, $size[0] * (1-2*$crop), $size[1] * (1-2*$crop));
	
	imagedestroy($img);
	
	// ToDo: quality => config
	imagejpeg($out, $dst, intval($Configuration['Thumb_Quality']));
	return $out;
}

if(empty($_GET['img'])) return;

$img = $_GET['img'];
if(strpos($img, '..') || !strpos($img, '/')) die ('DENIED');

$thumb = filesize("images/$img") . '.' .
		filemtime("images/$img") . '.jpg';


header('Content-type: image/jpeg');

if(file_exists("thumbs/$thumb"))
	readfile("thumbs/$thumb");
else
	imagejpeg(createThumb("images/$img", "thumbs/$thumb"));
?>