<?php
/************************************************************************
//
// DirectoryMediaIndex (dmi) 1.7
// 
// http://tjw.org/dmi/
//
// This PHP script draws a DirectoryIndex of thumbnails for the 
// following types of digital media files:
//
// JPEG
// PNG
// BMP
// GIF
// MPEG
// PDF
// PS
//
// For most uses you should just be able to place this script in a
// directory that contains the types of files listed above and is 
// readable and writable by the webserver.  You can do any custom 
// configuration below.
//  
// This script is for use with only PHP 4.0 and higher http://www.php.net  
// It also depends on the ImageMagick (http://www.imagemagick.org)
// If you want to support MPEG movies too, you'll also need the following:
//  mpgtx    (http://mpgtx.sourceforge.net)  
//  dumpmpeg (http://sourceforge.net/projects/dumpmpeg/)  
//  SDL      (http://www.libsdl.org/)  
//  SMPEG    (http://www.lokigames.com/development/smpeg.php3)  
//
//
// 2004-03-23 
//	Tony J. White <tjw@tjw.org>
//	Hoang Scott Nguyen <scott@mrNguyen.com>
//	Gary E. Miller <gem@rellim.com>
//	Cynick Young <cynick.young@utoronto.ca>
//	
//**********************************************************************/

/**** CONFIGURATION *****/

// By default, dmi will try to include "dmi_config.php" from the current
// directory after reading the configuration set in this file.  You can
// disable this behaviour by settting DMI_CONFIG_FILE to "".  You can
// also include the configuration file from somewhere else on the filesystem
// by specifing the full path to the file here.
$DMI_CONFIG_FILE = "dmi_config.php"; 

// these two files will be prepended and appended to the output of dmi 
// if they exist.  To disable this behaviour, set them to "" 
$DMI_HEADER_FILE = "header.php";
$DMI_FOOTER_FILE = "footer.php";

// This is the virutal path to this script.  LEAVE THIS BLANK unless you
// are using include() to call dmi.  If the dmi script can be accessed
// at http://your.server.com/yourdir/dmi.php, use "/yourdir/dmi.php" 
// If you leave this blank, PHP_SELF will be used.  If basename(__FILE__)
// doesn't match basename(PHP_SELF), then basename(__FILE__) will be used.
// This means that placing dmi-1.6.php in the same directory as the script
// that's including it should work automatically (without setting DMI_SELF).
$DMI_SELF = "";

// do you want ANYONE to be able to upload files throught this script?
// WARNING: If you plan on useing DMI_ALLOW_UPLOAD in combination with
//          DMI_PG_INDEX, you should also enable DMI_CRONOLOGIC_SORT
//          to avoid confusing behaviour.
$DMI_ALLOW_UPLOAD = 0; 

// do you want ANYONE to be able to delete files throught this script?
$DMI_ALLOW_DELETE = 0; 

// Should the text under the image thumbnail be a link to the actual image?
$DMI_TEXT_LINK = 1; 

// how many thumbnails per table_row?
$DMI_WIDTH = 2;

// do you allow page indexes?
$DMI_PG_INDEX = 0;
// number of pictures per page
$DMI_PICS_PER_PAGE = 16; 

// Optional directory sorting.  These are mutually exclusive, pick only 
// Alphabetic is used if both are turned on.  Use Cronologic if you wish
// to use DMI_PG_INDEX with DMI_ALLOW_UPLOAD.
$DMI_ALPHABETIC_SORT = 0;
$DMI_CRONOLOGIC_SORT = 0;

// what are the max dimensions for thumbnails? note that the aspect ratio
// of the images will NOT be changed.  Setting either height or width very
// large will cause the lesser dimension to be used, this is nice for
// providing consistency for a better looking table.
$DMI_THUMB_WIDTH = 600;
$DMI_THUMB_HEIGHT = 300;

// set this to 1 if you want to assume all icons should be DMI_THUMB_HEIGHT
// even if thumbnails have not been generated  Useful with DMI_SHOW_ALL_FILES
$DMI_FORCE_THUMB_HEIGHT = 0;

// set this to 1 if you want to assume all icons should be DMI_THUMB_WIDTH
// even if thumbnails have not been generated.  Useful with DMI_SHOW_ALL_FILES
$DMI_FORCE_THUMB_WIDTH = 0;

// you need the FULL path here if this file is not in the same dir as 
// your images, leave blank otherwise
$DMI_PHOTO_DIR = ""; 

// virtual path to the photos, leave blank if they are in the same virtual path 
// as this script is.
$DMI_WEB_PHOTO_DIR = "";

// this is the path to ImageMagick's convert program.  
$DMI_CONVERT_PROG = "/usr/bin/convert";

// this is the path to David Hedbor's dumpmpeg 
// http://sourceforge.net/projects/dumpmpeg/
#$DMI_DUMPMPEG_PROG = "/usr/local/bin/dumpmpeg";

// this is the path to mpgtx's mpginfo 
// http://sourceforge.net/projects/mpgtx/
#$DMI_MPGINFO_PROG = "/usr/local/bin/mpginfo";

// dump every N frames from the MPEG to be used in the animated GIF thumb.
// 30 means dump every 30th frame, good for full motion NTSC mpegs
// set it higher if your mpegs have alot of frames or you'll get huge 
// thumbnail GIF's
$DMI_MPEG_FRAME_FREQ = 30;

// number of 1/100ths of a second to wait between frames in GIF animation
// thumbmails.   
$DMI_ANIM_DELAY = 300;

// Do you want dmi to draw icons for ALL files in DMI_PHOTO_DIR?
// Of course, it won't be able to draw thumbnails for every type of
// file, and will use a built-in document icon instead.
$DMI_SHOW_ALL_FILES = 1;

// Do you want dmi to try to generate animated GIF thumbnails for PDF and 
// PostScript files using ImageMagick?
$DMI_THUMB_PDF = 0;
$DMI_THUMB_PS = 0; 

// Do you want dmi to allow uploading of files of unknown types?  This
// uploads will be allowed even if PHP's getImageSize() fails on the
// file and ImageMagick is unable to convert the file into a JPEG.
// WARNING: THIS IS DANGEROUS AND SHOULD ONLY BE USED IF ACCESS IS
//          RESTRICTED TO TRUSTED USERS!!!
$DMI_ALLOW_UPLOAD_OF_UNKNOWN_FILE_TYPES = 0;

// This is a list of file names that are not allowed to be used for
// new files when DMI_ALLOW_UPLOAD is enabled.  This list will be
// appended to a built in list of files that include this one as well
// as DMI_FOOTER_FILE, DMI_HEADER_FILE, and DMI_CONFIG_FILE.
// If an element begins with '/', then it will be treated as a 
// PCRE regular expression for use with the PHP preg_match() function.
$DMI_DISALLOW_FILE_NAMES = array(
	"index.html", 
	"index.htm",
	"default.htm",
	"default.html",
	"/.*\.php$/",
	"/.*\.php3$/",
	"/.*\.phtml$/",
	"/.*\.cgi$/"
); 

/*****  END CONFIG *****/

// now we stomp over configuration in this file with DMI_CONFIG_FILE if it
// exists and is readable
if(is_readable($DMI_CONFIG_FILE)) include($DMI_CONFIG_FILE);

// handles spaces and such
function dmi_shellWrap($in) {
	/*
	return str_replace("\n", "\\", preg_replace("/([ \'\"&;\`\(\)?!])/", 
			"\n\\1", $in));
	*/
	return escapeshellarg($in);
}

// gets filename without extension
function dmi_getFileName($in) {
	$out = basename($in);
	$out = substr(strrev(strstr(strrev($out), ".")), 0, -1);
	return $out;
}

function dmi_safeFileName($in) {
	return preg_replace("/[^a-z0-9\.]/i", "_", $in);
}

function dmi_stripExtension($in) {
	if(eregi("(.+)\.[a-z]{2,4}$", $in, $out)) {
		return $out[1];
	}
	else return $in; 
}

// helper function for interpreting dmi_getImageSize() return data
function dmi_extensionize($in, $type) {
	global $DMI_GIS_TYPES;
	return preg_replace("/\..{3,4}$/", "", $in).".".$DMI_GIS_TYPES[$type];
}

// helper function for interpreting dmi_getImageSize() return data
function dmi_getExtension($type) {
	global $DMI_GIS_TYPES;
	if($DMI_GIS_TYPES[$type]) return ".".$DMI_GIS_TYPES[$type];
	return "";
}

// helper function for interpreting getImageSize() return data
function dmi_getMimeType($type) {
	global $DMI_GIS_MIME;
	if($DMI_GIS_MIME[$type]) return $DMI_GIS_MIME[$type];
	return "application/unknown";
}


function dmi_is_mpeg_video($filename) {
	if(!is_executable($GLOBALS["DMI_MPGINFO_PROG"])) return 0;
	$img = @getImageSize($filename);
	// for some reason PHP 4.3.x thinks MPEG's are WBMP files
	if(is_array($img) && $img[2] != 15) return 0;
	$is_mpeg = 0;
	$cmd = $GLOBALS["DMI_MPGINFO_PROG"]."  ".dmi_shellWrap($filename);
	$out = `$cmd`;
	$out = str_replace("\r", "", $out);
	$lines = explode("\n", $out);
	while(list($num, $line) = each($lines)) {
		if(preg_match("/^  Mpeg .*Video/", $line)) $is_mpeg = 1;
	}
	return $is_mpeg;
}

function dmi_is_pdf($filename) {
	$fp = fopen($filename, "r");
	if(!$fp) return 0;
	$head = fread($fp, 4);
	fclose($fp);
	if($head == "%PDF") return 1;
}

function dmi_is_ps($filename) {
	$fp = fopen($filename, "r");
	if(!$fp) return 0;
	$head = fread($fp, 4);
	fclose($fp);
	if($head == "%!PS") return 1;
}

// this function is the replacement for /bin/find to make things a
// little safer and to possibly allow windows portability
function dmi_getListing($order = "") {
       if(!is_dir($GLOBALS["DMI_PHOTO_DIR"])) {
                        echo "ERROR: ".$GLOBALS["DMI_PHOTO_DIR"]." is not a "
                                ." directory!<br>";
                        return 0;
        }
        $dir_handle = opendir($GLOBALS["DMI_PHOTO_DIR"]);
        while($file = readdir($dir_handle)) {
		$skip = 0;
		while(list(,$f) = each($GLOBALS["DMI_DISALLOW_FILE_NAMES"])) {
			if(substr($f, 0, 1) == "/") {
				if(preg_match($f, 
					$file)) 
					$skip = 1;
			}
			elseif($f == $file) 
				$skip = 1;
		}
		reset($GLOBALS["DMI_DISALLOW_FILE_NAMES"]);
		if($skip) continue;
                $full_file = $GLOBALS["DMI_PHOTO_DIR"]."/".$file;
		if(!is_file($full_file) || !is_readable($full_file)) continue;
		if($file == basename(__FILE__)) continue;
		$usable = 0;
		if($GLOBALS["DMI_SHOW_ALL_FILES"]) 
			$usable = 1;
		elseif(dmi_is_mpeg_video($file)) 
			$usable = 1;
		elseif($GLOBALS["DMI_THUMB_PDF"] && dmi_is_pdf($file)) 
			$usable = 1;
		elseif($GLOBALS["DMI_THUMB_PS"] && dmi_is_ps($file)) 
			$usable = 1;
		else {	
			$img_info = @getImageSize($full_file);
			if(is_array($img_info)) $usable = 1;
		}
	
		if($usable) {
			$files[] = $file;
			if($order == "alph") 
				$sort[] = strtolower($file);
			elseif($order == "cron") 
				$sort[] = filemtime($full_file);
		}
	}
	switch($order) {
		case "alph":
			array_multisort($sort, SORT_STRING, SORT_ASC, $files); 
			break;
		case "cron": 
			array_multisort($sort, SORT_NUMERIC, SORT_ASC, $files); 
			break;
	}

	if(is_array($files)) while(list(,$file) = each($files)) {
		$full_file = $GLOBALS["DMI_PHOTO_DIR"]."/".$file;
		$img_info = @getImageSize($full_file);
		if(dmi_is_mpeg_video($file) 
			|| ($GLOBALS["DMI_THUMB_PDF"] && dmi_is_pdf($full_file))
			|| ($GLOBALS["DMI_THUMB_PS"] && dmi_is_ps($full_file))){
			$thumb_info =  
				@getImageSize($GLOBALS["PHOTO_DIR"]
				."/thumbs/".dmi_stripExtension($file)
				."_thumb.gif");
			if(is_array($thumb_info)) 
				$thumb_infos[] = $thumb_info;
			else $thumb_infos[] = "";
		}
                elseif(is_array($img_info)) {
			$thumb_info =  @getImageSize($GLOBALS["PHOTO_DIR"]
				."/thumbs/".dmi_stripExtension($file)."_thumb"
				.dmi_getExtension($img_info[2]));
			if(is_array($thumb_info)) 
				$thumb_infos[] = $thumb_info;
			else $thumb_infos[] = "";
		}
		$img_info = "";
		$thumb_info = "";
        }
	return array($files, $thumb_infos);
}

function dmi_clearBitmaps($dump_dir) {
        if(!is_dir($GLOBALS["DMI_PHOTO_DIR"]."/thumbs/".$dump_dir)) {
                        return 0;
        }
	$full_dump_dir = $GLOBALS["DMI_PHOTO_DIR"]."/thumbs/".$dump_dir;	
	$bmp_dir_handle = opendir($full_dump_dir);
	while($file = readdir($bmp_dir_handle)) {
		if($file == ".." || $file == ".") continue;
		$full_file = $GLOBALS["DMI_PHOTO_DIR"]
			."/thumbs/".$dump_dir."/".$file;
		if(eregi("\.bmp$", $full_file)) 
			$deleted = unlink($full_file);
	}
	$success = @rmdir($full_dump_dir);
	return $success;
}

function dmi_getThumbFullPath($name) {
	$file_path =  $GLOBALS["DMI_PHOTO_DIR"]."/".$name;
	$thumb_path = $GLOBALS["DMI_PHOTO_DIR"]."/thumbs/";
	if(dmi_is_mpeg_video($file_path) ||
		 dmi_is_ps($file_path) || dmi_is_pdf($file_path)) {
		$thumb_name = $thumb_path.dmi_getFileName($name)
				."_thumb.gif";
	}
	else {
		$image_info = @getImageSize($file_path);
		$thumb_name = $thumb_path.dmi_getFileName($name)
                                ."_thumb".dmi_getExtension($image_info[2]);
	}
	return $thumb_name;
}

function dmi_deleteThumb($name) {
	$thumb_name = dmi_getThumbFullPath($name);
	if(is_writable($thumb_name)) {
		unlink($thumb_name);
	}
}

function dmi_deleteImage($name) {
	$full_name = $GLOBALS["DMI_PHOTO_DIR"]."/".$name;
	if(is_writable($full_name)) unlink($full_name);
}

function dmi_errorImage() {
	header("Content-type: image/gif");
	// this image is alert.red.png blatently ripped off from the 
	// apache icons directory
	$image = "iVBORw0KGgoAAAANSUhEUgAAABQAAAAWBAMAAAAyb6E1AAAAGFBMVEXM"
	."////mZn/MzP///+ZmZlmAAAzMzMAAAAN2u9lAAAAAWJLR0QHFmGI6wAAAF5JREFU"
	."eNpjSAODBAYgSDYGAjMzBNM4AcIMDTUzNoMwg5TMjEHCYKZ5eno6jFleXg5lGru4"
	."uMOYJgimsTEGU0gRzjRSxsYEA3eoG7CZgMREUgtjprlAANCRDOVQwAAAFqIxwNdK"
	."LXkAAABWdEVYdENvbW1lbnQAVGhpcyBhcnQgaXMgaW4gdGhlIHB1YmxpYyBkb21h"
	."aW4uIEtldmluIEh1Z2hlcywga2V2aW5oQGVpdC5jb20sIFNlcHRlbWJlciAxOTk1"
	."TOj0xAAAAABJRU5ErkJggg==";
	echo base64_decode($image);
	exit();
}

function dmi_genericImage() {
	header("Content-type: image/png");
	// this image is generic.png blatently ripped off from the 
	// apache icons directory
	$image = "iVBORw0KGgoAAAANSUhEUgAAABQAAAAWBAMAAAAyb6E1AAAAD1BMVEXM"
	."//////+ZmZkzMzMAAADr3BzJAAAAAWJLR0QEj2jZUQAAAEFJREFUeNpjMAYDAwYg"
	."MBQEAmFhBFPQAMEURjBBwmCmiImJCYzp4uICZQoKKanAmIJITEG6M42VIADoSAYX"
	."KGAAAGVEFLsJDEXQAAAAVnRFWHRDb21tZW50AFRoaXMgYXJ0IGlzIGluIHRoZSBw"
	."dWJsaWMgZG9tYWluLiBLZXZpbiBIdWdoZXMsIGtldmluaEBlaXQuY29tLCBTZXB0"
	."ZW1iZXIgMTk5NUzo9MQAAAAASUVORK5CYII=";
	echo base64_decode($image);
	exit();
}

function dmi_getNumOfMedia() {
	$listing = dmi_getListing();
	return sizeof($listing[0]);
}

function dmi_getPageIndex($pindex) {
	$pics_per_pg = $GLOBALS["DMI_PICS_PER_PAGE"];
	$num_of_pics = dmi_getNumOfMedia();	
	$num_of_index_pg = $num_of_pics / $pics_per_pg;
	if ( $num_of_pics % $pics_per_pg != 0 ) { 
		$num_of_index_pg = intval($num_of_index_pg) + 1; 
	}
	if ($pindex != 1) { 
		$pindex--; 
		?>
		<a href="<?php echo $_SERVER["PHP_SELF"];
		?>?dmi_pindex=<?php echo $pindex;
		?>">&lt;&lt;</a>&nbsp;
		<?php
		$pindex++;
	}
	else {
		?>&lt;&lt;<?php
	}
	if ($num_of_pics >= $pics_per_pg) {
		for ($i = 1 ; $i <= $num_of_index_pg ; $i++) {
			if ($pindex != $i) {
				?>
				<a href="<?php echo $_SERVER["PHP_SELF"];
					?>?dmi_pindex=<?php
				echo $i;?>">[<?php echo $i;?>]</a>
				<?php
			} 
			else { 
				?>	
				<b>[<?php echo $i;?>]</b>
				<?php
			}
		}
	}
	?>&nbsp;<?php
	if ($pindex != $num_of_index_pg) { 
		$pindex++; 
		?>
		<a href="<?php echo $_SERVER["PHP_SELF"];
			?>?dmi_pindex=<?php echo $pindex;?>">&gt;&gt;</a>
		<?php
		$pindex--;  
	}
	else {
		?>
		&gt;&gt;
		<?php
	}
}

function dmi_executable_path($name) {
	global $DMI_PATH;
	reset($DMI_PATH);
	while(list(,$p) = each($DMI_PATH)) {
		if(is_executable($p."/".$name)) 
			return $p."/".$name;
	}
	return $name; 
}

// defines	
$DMI_GIS_TYPES = array(
	1 => "gif", 2 => "jpg", 3 => "png", 4 => "swf", 5 => "psd", 
	6 => "bmp", 7 => "tiff", 8 => "tiff", 9 => "jpc", 10 => "jp2", 
	11 => "jpx", 12 => "jb2", 13 => "swc", 14 => "iff",  
	15 => "wbmp", 16 => "xbm"
	);

$DMI_GIS_MIME = array(
	1 => "image/gif", 2 => "image/jpg", 3 => "image/png", 
	4 => "application/x-shockwave-flash", 
	5 => "application/adobe-photoshop", 
	6 => "image/bmp", 7 => "image/tiff", 8 => "image/tiff", 
	9 => "image/jpc", 10 => "image/jp2", 
	11 => "image/jpx", 12 => "image/jb2", 13 => "image/swc", 
	14 => "image/iff",  15 => "image/vnd.wap.wbmp", 
	16 => "image/x-xbitmap"
	);

$DMI_PATH = array("/usr/local/bin", "/usr/bin", "/bin", "/usr/X11R6/bin");

// auto config
if(!trim($DMI_SELF)) {
	if(trim(__FILE__) 
		&& basename($_SERVER["PHP_SELF"]) != basename(__FILE__)) 
		$DMI_SELF = basename(__FILE__);
	else
		$DMI_SELF = $_SERVER["PHP_SELF"];
}
if(isset($path)) $GLOBALS["DMI_PHOTO_DIR"] = $path;
if($DMI_WIDTH < 1) $DMI_WIDTH = 4;
if($DMI_PICS_PER_PAGE < 1) $DMI_PICS_PER_PAGE = 16;
if($DMI_THUMB_WIDTH < 1) $DMI_THUMB_WIDTH = 200;
if($DMI_THUMB_HEIGHT < 1) $DMI_THUMB_HEIGHT = 60;
if($DMI_PHOTO_DIR == "") 
	$DMI_PHOTO_DIR = dirname($_SERVER["SCRIPT_FILENAME"]);
if($DMI_WEB_PHOTO_DIR == "") 
	$DMI_WEB_PHOTO_DIR = dirname($_SERVER["SCRIPT_NAME"]);
if($DMI_CONVERT_PROG == "") 
	$DMI_CONVERT_PROG = dmi_executable_path("convert");
if($DMI_DUMPMPEG_PROG == "") 
	$DMI_DUMPMPEG_PROG = dmi_executable_path("dumpmpeg");
if($DMI_MPGINFO_PROG == "") 
	$DMI_MPGINFO_PROG = dmi_executable_path("mpginfo");
if($DMI_MPEG_FRAME_FREQ == "") $DMI_MPEG_FRAME_FREQ = 30;
if($DMI_ANIM_DELAY == "") $DMI_ANIM_DELAY = 100;
$DMI_DISALLOW_FILE_NAMES[] = basename(__FILE__);
$DMI_DISALLOW_FILE_NAMES[] = basename($DMI_CONFIG_FILE);
$DMI_DISALLOW_FILE_NAMES[] = basename($DMI_HEADER_FILE);
$DMI_DISALLOW_FILE_NAMES[] = basename($DMI_FOOTER_FILE);

// main actions
if(!empty($_POST["dmi_upload"]) 
	&& $DMI_ALLOW_UPLOAD 
	&& is_uploaded_file($_FILES["dmi_new_file"]["tmp_name"])) {
	while(list(,$f) = each($GLOBALS["DMI_DISALLOW_FILE_NAMES"])) {
		if(substr($f, 0, 1) == "/") {
			if(preg_match($f, $_FILES["dmi_new_file"]["name"])) 
				die("ERROR: bad file name");
		}
		elseif($f == $_FILES["dmi_new_file"]["name"]) 
			die("ERROR: bad file name.");
	}
	$new_file = $_FILES["dmi_new_file"];
	$success = 0;
	$img = @getImageSize($new_file["tmp_name"]);
	if(dmi_is_pdf($new_file["tmp_name"])) {
		$new_name = basename($new_file["name"]);
		$new_name = dmi_stripExtension($new_name);
		$new_name = dmi_safeFileName($new_name);
		$new_name = $new_name.".pdf";
		$success = move_uploaded_file($new_file["tmp_name"], 
			$DMI_PHOTO_DIR."/".$new_name);
	}
	elseif(dmi_is_ps($new_file["tmp_name"])) {
		$new_name = basename($new_file["name"]);
		$new_name = dmi_stripExtension($new_name);
		$new_name = dmi_safeFileName($new_name);
		$new_name = $new_name.".ps";
		$success = move_uploaded_file($new_file["tmp_name"], 
			$DMI_PHOTO_DIR."/".$new_name);
	}
	elseif(dmi_is_mpeg_video($new_file["tmp_name"])) {
		$new_name = basename($new_file["name"]);
		$new_name = dmi_stripExtension($new_name);
		$new_name = dmi_safeFileName($new_name);
		$new_name = $new_name.".mpg";
		$success = move_uploaded_file($new_file["tmp_name"], 
			$DMI_PHOTO_DIR."/".$new_name);
	}
	elseif(!is_array($img)) {
		$tmp_name = basename($new_file["name"]);
		$tmp_name = dmi_safeFileName($tmp_name);
		$new_name = dmi_stripExtension($tmp_name).".jpg";
		move_uploaded_file($new_file["tmp_name"], 
			$DMI_PHOTO_DIR."/".$tmp_name);
		$cmd = "$DMI_CONVERT_PROG $DMI_PHOTO_DIR/"
			.dmi_shellWrap($tmp_name)
			." $DMI_PHOTO_DIR/".dmi_shellWrap($new_name);
		//echo $cmd;
		`$cmd`;
		//unlink($tmp_name);
		if(is_readable($DMI_PHOTO_DIR."/".$new_name)) 
			$success = ($img = getImageSize($new_name)); 
		else 
			$img = "";
	}
	else {
		$new_name = basename($new_file["name"]);
		$new_name = dmi_stripExtension($new_name);
		$new_name = dmi_safeFileName($new_name);
		$new_name = dmi_extensionize($new_name, $img[2]);	
		$success = move_uploaded_file($new_file["tmp_name"], 
				$DMI_PHOTO_DIR."/".$new_name);
	}

	if(!$success) {
		if($GLOBALS["DMI_ALLOW_UPLOAD_OF_UNKNOWN_FILE_TYPES"]) {
			$new_name = basename($new_file["name"]);
			$new_name = dmi_safeFileName($new_name);
			$success = move_uploaded_file($new_file["tmp_name"], 
				$DMI_PHOTO_DIR."/".$new_name);
		}
		else
			echo "ERROR: uploaded file is not a recoginzied "
				." image file format!";
	}
}
elseif(!empty($_POST["dmi_delete_confirmed"]) && $DMI_ALLOW_DELETE && 
	is_writable($GLOBALS["DMI_PHOTO_DIR"]."/".$_POST["dmi_name"])) {
	dmi_deleteThumb($_POST["dmi_name"]);
	dmi_deleteImage($_POST["dmi_name"]);
}

if(!empty($_GET["dmi_delete"])) {
	if(is_readable($DMI_HEADER_FILE)) include($DMI_HEADER_FILE);
	?>
	<form method=post action="<?php echo $_SERVER["PHP_SELF"];?>">
	Are you sure you want to delete the file &quot;<?php
	echo htmlspecialchars($_GET["dmi_name"]);?>&quot;?  
	<input type=submit value="No">
	<input type=submit name="dmi_delete_confirmed" value="Yes">
	<input type=hidden name="dmi_name" value="<?php 
		echo htmlspecialchars($_GET["dmi_name"]);
		?>">
	</form>
	<img src="<?php echo $GLOBALS["DMI_SELF"];?>?dmi_thumb=1&dmi_name=<?php
		echo str_replace("+", "%20", urlencode($_GET["dmi_name"]));?>">
	<?php
	if(is_readable($DMI_FOOTER_FILE)) include($DMI_FOOTER_FILE);
}
elseif(empty($_GET["dmi_thumb"])) {
	if(is_readable($DMI_HEADER_FILE)) include($DMI_HEADER_FILE);

	if($DMI_ALPHABETIC_SORT) $listing = dmi_getListing("alph");
	elseif($DMI_CRONOLOGIC_SORT) $listing = dmi_getListing("cron");
	else  $listing = dmi_getListing(); 

	$files = $listing[0];
	$thumb_infos = $listing[1];
	$i = 0;
	if ($DMI_PG_INDEX) { 
		$pindex = $_GET["dmi_pindex"];
		if (empty($pindex)) $pindex = 1;
		dmi_getPageIndex($pindex);
		if ($pindex != 1) $from = $DMI_PICS_PER_PAGE * ($pindex - 1);
		else $from = 0;
		$to = $DMI_PICS_PER_PAGE * $pindex;
		$num_of_pics = dmi_getNumOfMedia();
		if ($to >= $num_of_pics) { 
			$to = $num_of_pics;
		}
		$i = $from;
	}
	?>
	<table border=0>
	<?php
	if(is_array($files)) while(list($key, $val) = each($files)) {
		if(empty($cell_count) || $cell_count >= $DMI_WIDTH) {
			// first row case
			if(!empty($cell_count)) {
				?>
				</tr>
				<?php
			}
			?>
			<tr>	
			<?php
			$cell_count = 0;
		} 
		?>
		<td align="center">
		<a href="<?php echo $DMI_WEB_PHOTO_DIR."/"
			.str_replace("+", "%20", urlencode($files[$i]));?>">
		<img 
		<?php
		if(is_array($thumb_infos[$i])) {
			echo $thumb_infos[$i][3];
		}
		elseif($GLOBALS["DMI_FORCE_THUMB_HEIGHT"])
			 echo " height=\"".$GLOBALS["DMI_THUMB_HEIGHT"]."\" ";
		elseif($GLOBALS["DMI_FORCE_THUMB_WIDTH"]) 
			 echo " width=\"".$GLOBALS["DMI_THUMB_WIDTH"]."\" ";
		?>
		src="<?php echo $GLOBALS["DMI_SELF"];
			?>?dmi_thumb=true&dmi_name=<?php 
			echo urlencode($files[$i]);
			?>" alt="<?php echo htmlspecialchars($files[$i]);
			?>" border="1"></a><BR><font size="-1"><?php
			if($DMI_TEXT_LINK) {
				?>
				<a href="<?php
				echo $DMI_WEB_PHOTO_DIR."/"
					.str_replace("+", "%20", 
						urlencode($files[$i]));?>">
				<?php
			}
			echo ucwords(
				str_replace("_", " ", 
					dmi_getFileName($files[$i])));
			if($DMI_TEXT_LINK) {
				?>
				</a>
				<?php
			}
			if($DMI_ALLOW_DELETE) {
				?>
				<a href="<?php 
				echo $_SERVER["PHP_SELF"];
				?>?dmi_delete=1&dmi_name=<?php
				echo htmlspecialchars($files[$i]);
				?>">[Delete]</a>
				<?php
			}
			?></font>

		</td>
		<?php
		$cell_count++;
		$i++;
		if ($DMI_PG_INDEX && $i >= $to) break;
	}

	// fill up all the empty sells
	for($i=$cell_count;$i<$DMI_WIDTH;$i++) {
		?>
		<td>
		&nbsp;
		</td>
		<?php
	}
	?>
	</tr>
	</table>
	<?php
	if($DMI_ALLOW_UPLOAD) {
		?>
		<form enctype="multipart/form-data" 
		method="post" action="<?php echo $_SERVER["PHP_SELF"]; 
		?>?dmi_pindex=<?php echo 
		ceil((dmi_getNumOfMedia() + 1)/$DMI_PICS_PER_PAGE); ?>">
		<input type=file name="dmi_new_file">
		<input type=submit name="dmi_upload" value="Upload">
		</form>
		<?php
	}
	if(is_readable($DMI_FOOTER_FILE)) include($DMI_FOOTER_FILE);
}

else {
	$success = 0;
	$name = stripslashes($_GET["dmi_name"]);
	$full_filename = $GLOBALS["DMI_PHOTO_DIR"]."/".$name;
	$image_info = @getImageSize($full_filename);
	if(dmi_is_mpeg_video($full_filename)) {
		$success = 1;
		$is_mpeg_video = 1;
	}
	elseif(dmi_is_pdf($full_filename)) {
		$success = 1;
		$is_pdf = 1;
	}
	elseif(dmi_is_ps($full_filename)) {
		$success = 1;
		$is_ps = 1;
	}
	elseif(is_array($image_info)) $success = 1;

	if(!is_dir($DMI_PHOTO_DIR."/thumbs")) 
		$success = @mkdir($DMI_PHOTO_DIR."/thumbs", 0755);
	
	if(!$success) {
		if($GLOBALS["DMI_SHOW_ALL_FILES"]) dmi_genericImage();
		else dmi_errorImage();
	}
	if(!empty($is_mpeg_video)) {
		$thumb_name = dmi_getThumbFullPath($name);
		$dump_dir = $DMI_PHOTO_DIR."/thumbs/".dmi_getFileName($name);
		if(!($thumb_info = @getImageSize($thumb_name))) {
			// clean up any old bitmaps that might be laying
			// around	
			dmi_clearBitmaps(dmi_getFileName($name));

			if(!@mkdir($dump_dir, 0755)) dmi_errorImage();
			putenv("SDL_VIDEODRIVER=dummy");
			putenv("SDL_AUDIODRIVER=disk");
			putenv("SDL_DISKAUDIOFILE=/dev/null");
		

			// dumpmpeg dumps bitmaps to the current dir
			if(!chdir($dump_dir)) dmi_errorImage();
			// dump out the bitmaps
			$command = "$DMI_DUMPMPEG_PROG --dump "
					.dmi_shellWrap($DMI_MPEG_FRAME_FREQ)
					." ../../"
					.dmi_shellWrap($name);
			//echo $command;
			`$command`;
			chdir("../../../");

			// create an animated gif of the bitmaps
			$command = $DMI_CONVERT_PROG
				." -loop 100 -delay "
				.dmi_shellWrap($DMI_ANIM_DELAY)
				." -size ".dmi_shellWrap($DMI_THUMB_WIDTH)
				."x".dmi_shellWrap($DMI_THUMB_HEIGHT)
				." -geometry ".dmi_shellWrap($DMI_THUMB_WIDTH)
				."x".dmi_shellWrap($DMI_THUMB_HEIGHT)." " 
				.$dump_dir."/*.bmp "
				.$thumb_name;
			//echo $command;
			`$command`;
			dmi_clearBitmaps(dmi_getFileName($name));
			if(!($thumb_info = @getImageSize($thumb_name))) 	
				dmi_errorImage();
		}
		header("Content-type: image/gif");
		readfile($thumb_name);
	}
	elseif($is_pdf || $is_ps) {
		$thumb_name = dmi_getThumbFullPath($name);
		$dump_dir = $DMI_PHOTO_DIR."/thumbs/".dmi_getFileName($name);
		if(!($thumb_info = @getImageSize($thumb_name))) {
			// clean up any old bitmaps that might be laying
			// around	
			dmi_clearBitmaps(dmi_getFileName($name));
			if(!@mkdir($dump_dir, 0755)) dmi_errorImage();
			//if(!chdir($dump_dir)) dmi_errorImage();
			// dump out the bitmaps
			$cmd = $GLOBALS["DMI_CONVERT_PROG"]
				." -size "
				.$GLOBALS["DMI_THUMB_WIDTH"]."x"
				.$GLOBALS["DMI_THUMB_HEIGHT"]." "
				.dmi_shellWrap($full_filename)." "
				." -scale "
				.$GLOBALS["DMI_THUMB_WIDTH"]."x"
				.$GLOBALS["DMI_THUMB_HEIGHT"]." "
				."BMP:"
				.dmi_shellWrap($dump_dir."/tmp".".%03d.bmp");
			//echo $cmd;
			`$cmd`;
			//chdir("../../../");

			// create an animated gif of the bitmaps
			$command = $DMI_CONVERT_PROG
				." -loop 100 -delay "
				.dmi_shellWrap($DMI_ANIM_DELAY)
				." -size ".dmi_shellWrap($DMI_THUMB_WIDTH)
				."x".dmi_shellWrap($DMI_THUMB_HEIGHT)
				." -geometry ".dmi_shellWrap($DMI_THUMB_WIDTH)
				."x".dmi_shellWrap($DMI_THUMB_HEIGHT)." " 
				.$dump_dir."/*.bmp "
				.$thumb_name;
			//echo $command;
			`$command`;
			dmi_clearBitmaps(dmi_getFileName($name));
			if(!($thumb_info = @getImageSize($thumb_name))) 	
				dmi_errorImage();
		}
		header("Content-type: image/gif");
		readfile($thumb_name);
	}
	else {
		$thumb_name = dmi_getThumbFullPath($name);
		if(!($thumb_info = @getImageSize($thumb_name))) {
			$command = dmi_shellWrap($DMI_CONVERT_PROG)
				." -size ".dmi_shellWrap($DMI_THUMB_WIDTH)
				."x".dmi_shellWrap($DMI_THUMB_HEIGHT) 
				." ".dmi_shellWrap($DMI_PHOTO_DIR)
				."/".dmi_shellWrap($name)
				." -scale ".dmi_shellWrap($DMI_THUMB_WIDTH)
				."x".dmi_shellWrap($DMI_THUMB_HEIGHT) 
				." ".dmi_shellWrap($thumb_name);
			//echo $command;
			`$command`;
			if(!($thumb_info = @getImageSize($thumb_name))) 	
				dmi_errorImage();
		}
		header("Content-type: ".dmi_getMimeType($thumb_info[2]));
		readfile($thumb_name);
	}
}
?>
