<?php

/*
This script requires the directory in which it lives to have an ACP allowing the apache user (www) to have permission to create subdirectories and delete children.  For some reason the deletion of the files directory fails.
*/


$MB = 1024 * 1024;
$KB = 1024;
$my_max_file_size   = 10 * $MB;
set_time_limit(60*10);	// 10 minutes
$scriptDebug = false;	// if set to true, then the print statements will go into the downloaded file!
$filesDir        = "/Users/dave/WebsiteSupport/shrinkerFiles/";
//$the_path        = "/Users/dave/WebsiteSupport/shrinkerFiles/";
//$the_new_dir	= $the_path. "files/";

$registered_types = array(
    "application/x-gzip-compressed"     => ".tar.gz, .tgz",
    "application/x-zip-compressed"         => ".zip",
    "application/x-tar"            => ".tar",
    "text/plain"                => ".html, .php, .txt, .inc (etc)",
    "image/bmp"                 => ".bmp, .ico",
    "image/gif"                 => ".gif",
    "image/pjpeg"                => ".jpg, .jpeg",
    "image/jpeg"                => ".jpg, .jpeg",
    "image/png"                => ".png",
    "image/tiff"                => ".tif, .tiff",
    "image/jp2"                => ".jp2",
    "application/x-shockwave-flash"     => ".swf",
    "application/msword"            => ".doc",
    "application/vnd.ms-excel"        => ".xls",
    "application/octet-stream"        => ".exe, .fla (etc)"
);


$allowed_types = array("image/jpeg","image/gif", "image/png", "image/jp2", "image/tiff");


function form($error=false) {

	global $my_max_file_size, $scriptDebug, $maxSizeStr, $MB, $KB;

	print "<html>\n<head>\n<title>Dave's Image shrinker</title>\n";
	print "</head>\n<body>";
	print "<table border=1 align=center width=60%>\n<tr><td><h2>Dave's Image Shrinker/Converter</h2>\n";
	print "This page will allow you to upload an image and have it download at an altered size, type and/or quality.  Files are currently limited to: <ul><li>Files under $maxSizeStr in size.<li>JPG, JP2, TIFF, PNG, or GIF files</ul>";
	echo "Note that if your file is large, then the upload may take quite a while.  Be patient.<br>";
	
    if ($error) print "<font color=\"#e00000\"><strong>$error</strong></font><br><br>";

	if ($scriptDebug) print "PHP_Self: <b>".$_SERVER['PHP_SELF']."</b><br>\n";

    print "\n<form ENCTYPE=\"multipart/form-data\"  action=\"" . $_SERVER['PHP_SELF'] . "?task=upload\" method=\"post\">";
    print "\n<INPUT TYPE=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"" . $my_max_file_size . "\">";
    print "\n<INPUT TYPE=\"hidden\" name=\"task\" value=\"upload\">";
	print "\n<label>Scale factor <input type='text' name='scalefactor' size='5' value='0.5'/></label>"; 
	print "\n<label>JPEG Quality <input type='text' name='quality' size='5' value='50'/></label>"; 
    print "\n<br><INPUT NAME=\"the_file\" TYPE=\"file\" SIZE=\"30\"><br><br>";
    print "\n<input type=\"submit\" Value=\"Upload\">";
    print "\n</form></table>";
    print "\n<br><br>Note that the Converter uses <a href=http://netpbm.sourceforge.net/>NetPBM</a> on the server to do the work.";
	print "\n<script src='http://www.google-analytics.com/urchin.js' type='text/javascript'></script>";
	print "\n<script type='text/javascript'>";
	print "\n_uacct = 'UA-1133088-1';";
	print "\nurchinTracker();";
	print "\n</script>";
	print "\n</body></html>";

}


function validate_upload($the_file) {

	global $my_max_file_size, $image_max_width, $image_max_height, $allowed_types, $registered_types, $scriptDebug;
    $the_file_name = $_FILES['the_file']['name'];
    $the_file_type = $_FILES['the_file']['type'];
	if ($scriptDebug) print "Name: <b>".$the_file_name."</b><br>\n";
	if ($scriptDebug) print "Type: <b>".$the_file_type."</b><br>\n";

	$start_error = "\n<b>Error:</b>\n<ul>";
    
    if ($the_file == "none") { // do we even have a file?
    
        $error .= "\n<li>You did not upload anything!</li>";
    
    } else { // check if we are allowed to upload this file_type
    
		$the_file_name = $_FILES['the_file']['name'];
		$ext = explode(".", $the_file_name);
		$ext = array_pop($ext);
		$ext = strtolower($ext);
		$baseName = basename($the_file_name, "." . $ext);
		
		if (!(($ext == "jpg") || ($ext == "jpeg") || ($ext == "gif") || ($ext == "tif") || ($ext == "tiff") || ($ext == "jp2") || ($ext == "png"))) {
			$error = "<br>Only JPG, JP2, TIFF, GIF, and PNG files may be uploaded to the shrinker.<br>\n";
			return $error;
		}

		if ($_FILES['the_file']['size'] > $my_max_file_size) {
			$error = "<br>Your file is too large.  Please try to reduce the size before uploading.<br>\n";
			return $error;
		}

		if (!is_uploaded_file($_FILES['the_file']['tmp_name'])) {
			$error = "Possible file upload attack: " . "filename '". $_FILES['the_file']['tmp_name'] . "'.";
			return $error;
		}

        if ($error) {
            $error = $start_error . $error . "\n</ul>";
            return $error;
        } else {
            return false;
        }
    }
}


function upload($the_file) {

	global $filesDir, $scriptDebug;

    $the_file_name = $_FILES['the_file']['name'];
    $ext = explode(".", $the_file_name);
	$ext = array_pop($ext);
	$baseName = basename($the_file_name, "." . $ext);
	$uploadfile = $filesDir . $baseName . "Sm." . $ext;
	if ($scriptDebug) print "Basename: <b>".$baseName."</b><br>\n";
	if ($scriptDebug) print "Extension: <b>".$ext."</b><br>\n";
	if ($scriptDebug) print "UploadFile: <b>".$uploadfile."</b><br>\n";
	if ($scriptDebug) { echo "Debugging info:<br>"; print_r($_FILES); echo "<br>\n"; }

    $error = validate_upload($the_file);

    if ($error) {
		if ($scriptDebug) print "Error: <b>".$error."</b><br>\n";
        form($error);
    } else { // cool, we can continue
		if ($scriptDebug) print "<font color='green'>Upload validated successfully.</font><br>\n";
	   	$tempName = $_FILES['the_file']['tmp_name'];
	 	if ($scriptDebug) print "Temp Name: <b>".$tempName."</b><br>\n";
    	$num = 1;
		if ($scriptDebug) print "New UploadFile: <b>".$uploadfile."</b><br>\n";
		if (move_uploaded_file($tempName, $uploadfile)) {
			if ($scriptDebug) print "<font color='green'>File Moved Successfully.</font><br>\n";
			
			
			shrink_file($uploadfile);
			
			send_shrunken_file($uploadfile);
			
			if (!$scriptDebug) {
				unlink($uploadfile);
			}
			
			if (!is_file($uploadfile)) {
				if ($scriptDebug) print "<font color='green'>File deleted successfully.</font><br>\n";
			}
		} else {
		   echo "Possible file upload attack!\n";
		}
    } 
}

function shrink_file($uploadfile) {
	global $scriptDebug, $_POST;

	$tempfile = "/tmp/DMH".time()."temp.ppm";
	$scalefactor = $_POST["scalefactor"];
    $ext = explode(".", $uploadfile);
	$ext = array_pop($ext);
	$quality = $_POST["quality"];
	if ($scriptDebug) print "Here we are, shrinking the file.<br>\n";
	switch (strtolower($ext)) {
		case 'jpg':
		case 'jpeg':
			$converter = "jpegtopnm";
			break;
		case 'jp2':
			$converter = "jpeg2ktopam";
			break;
		case 'tif':
		case 'tiff':
			$converter = "tifftopnm";
			break;
		case 'gif':
			$converter = "giftopnm";
			break;
		case 'png':
			$converter = "pngtopnm";
			break;
	}
	$cmd = "/opt/local/bin/$converter '$uploadfile' | /opt/local/bin/pamscale $scalefactor | /opt/local/bin/pnmtojpeg -quality=$quality >  $tempfile";
	system($cmd,$return_value);
	if ($return_value != 0) {
		unlink($uploadfile);
		die("returned an error: $cmd");
	}
	
	unlink($uploadfile);
	
	copy($tempfile, $uploadfile);

	unlink($tempfile);
}

function send_shrunken_file($uploadfile) {
	global $scriptDebug;
	
	if ($scriptDebug) print "Here we are, sending the shrunken file.<br>\n";
	$len = filesize($uploadfile);
	$name = explode("/", $uploadfile);
	$name = array_pop($name);
	$name = explode(".", $name);
	$ext = array_pop($name);
	$name = $name[0].".jpg";

	if ($scriptDebug) {
		print "<a href='files/$name'>Link to file</a><br>\n";
	} else {
		header("Content-type: image/jpeg");
		header("Content-Length: $len");
		header("Content-Transfer-Encoding: binary");
		header("Content-Disposition: attachment; filename=$name");
		
		readfile($uploadfile);
	}
}


if ($my_max_file_size/$KB > 3000) {
	$maxSizeStr = ($my_max_file_size / $MB) ." MB";
} else {
	$maxSizeStr = ($my_max_file_size / $KB) ." KB";
}


if ($scriptDebug) print "Task: <b>".$_POST['task']."</b><br>\n";
if ($scriptDebug) print "Scale factor: <b>".$_POST['scalefactor']."</b><br>\n";
if ($scriptDebug) print "Quality: <b>".$_POST['quality']."</b><br>\n";

switch($_POST["task"]) {
    case 'upload':
        upload($the_file);
    break;
    default:
        form();
}

echo "</td></tr></table>\n";

?>

