<?php
	
	$url = @$_REQUEST['url'];
	$maxW = 100;
	$maxH = 80;
	
	$tmpfilename = "thumbnails/" . sha1($url . $maxW . $maxH) . md5($url) . ".png";
	
	if (empty($url)) { 
		header("Content-Type: image/png");
		readfile('thumboverlay_origdc.png');
		die();
	}
	if (file_exists($tmpfilename)) {
		header("Content-Type: image/png");
		readfile($tmpfilename);
		die();
	}
	
	if (substr_count($url, 'http://') == 1 || substr_count($url, 'https://') == 1) {
		
		if (substr(strtolower($url), -3) == 'png') {
			$timg = @imagecreatefrompng($url);
		}
		if (substr(strtolower($url), -3) == 'jpg') {
			$timg = @imagecreatefromjpeg($url);
		}
		
		if (!$timg) { 
			header("location: " . $url);
		}	else { 
			
			list($ow, $oh) = getimagesize($url);
						
			$resizeScale = $ow / $maxW;
			$newW = $ow / $resizeScale;
			$newH = $oh / $resizeScale;
			
			if ($newH > $maxH) {
				$resizeScale = $oh / $maxH;
				$newW = $ow / $resizeScale;
				$newH = $oh / $resizeScale;
			}
			
			
			$imgPosX = ceil(($maxW - $newW) / 2);
			$imgPosY = ceil(($maxH - $newH) / 2);
			$thumb = imagecreatetruecolor($maxW, $maxH);
			imagesavealpha($thumb, true);
			$trans_colour = imagecolorallocatealpha($thumb, 0, 0, 0, 127);
			imagefill($thumb, 0, 0, $trans_colour);
			
			imagecopyresampled($thumb, $timg, $imgPosX, $imgPosY, 0, 0, $newW, $newH, $ow, $oh);
			
			if ($oimg = @imagecreatefrompng('thumboverlay_origdc.png')) {
				imagecopy($thumb, $oimg, 0, 0, 0, 0, $maxW, $maxH);
			}
			
			
			
			header("Content-Type: image/png");
			
			imagepng($thumb, $tmpfilename);
			readfile($tmpfilename);
			
		}
		
	}
	
?>

