<!--
File Sharing Script (Jon Rifkin - 2005)

2005         Created
2011-06-03   Added ability to upload and download from non-secure directory,
             although the script itself must reside in a secure directory.
2012-01-03   Added ability to delete files.

This script allows users to upload/download/delete files into one directory on
your site. 

The script will refuse to run unless it is placed in a secure directory.

The directory where files are written and read is set in the variable ROOT_DIR
below (in the 'Configuration' section).  If for example, you want to upload and
download files from the directory 'my_dir' on your web site 'my_site', then set
ROOT_DIR to '/export/www/sites/my_site/my_dir'.

NOTE: The script checks whether it is running from a secure directory directory
by testing for existance of a non-blank user name in the Apache's environmental
variable REMOTE_USER.
-->


<!-- 
------------------------------------------------------------------------
  Configuration
------------------------------------------------------------------------
Set value of ROOT_DIR if you want this script to operate in a different
directory from the one it is placed in.  If left blank, i.e. if 
   $ROOTODIR = "";
then the ROOT_DIR is set to the directory where this script is.
-->

<?php
$ROOT_DIR = "/export/www/sites/testsite/sharestore";
?>

<!-- 
------------------------------------------------------------------------
  PHP Functions
------------------------------------------------------------------------
-->
<?php
function get_relative_path($src,$dst) {
    $srcs = explode("/",$src);
    $dsts = explode("/",$dst);
    #  Remove common top directories from both paths.
    while (count($srcs) && count($dsts) && $srcs[0]==$dsts[0]) {
        array_shift($srcs);
        array_shift($dsts);
    }
    $relpath = "";
    #  Go up directory tree (omit the filename part of the path)
    for ($i=1;$i<count($srcs);$i++) {
        $relpath .= "../";
    }
    #  Go back down to new destination
    $relpath .= implode("/",$dsts);
    return $relpath;
}
?>

<!-- 
------------------------------------------------------------------------
  Initialization
------------------------------------------------------------------------
-->

<?php

#  Make sure this script has been placed in a secured directory
#  by checking for existence of a logon name.
if (getenv("REMOTE_USER")=="") {
	print "<br><b style='color: red'>Webmaster ERROR:    This script must be placed in a secure directory.</b>";
	exit;
}

#  If ROOT_DIR is not set, set it to the current directory.
if (! $ROOT_DIR) {
    $ROOT_DIR = getcwd();
}

#  Get name of this script so we can ignore it when reading
#  list of files.
$THIS_SCRIPT_URL  = getenv("SCRIPT_NAME");
$THIS_SCRIPT_NAME = getenv("SCRIPT_FILENAME");

#  Web page title
$TITLE = "File Sharing Web Application";

#  Maximum filesize.  Note that the setting upload_max_filesize in the
#  /etc/php.ini file has the final say on the maximum file size.  This setting
#  affects the message shown to the user and the MAX_FILE_SIZE parameter to the
#  upload form which is a *suggestion* to browser and to php, but which a savvy
#  user can easily work around.
$MAX_FILE_SIZE=4000000;
$MAX_FILE_SIZE_LABEL = "4 megabytes";
?>



<!-- 
------------------------------------------------------------------------
  Main
------------------------------------------------------------------------
-->

<!-- Start html page  -->
<html>
<head>
<title>
<?php print "$TITLE\n"; ?>
</title>
<style type="text/css">
body      { font-family: Arial, Helvetica, sans-serif; }
img       { border: 0; padding: 0 2px; vertical-align: text-bottom;
margin-bottom: 2px;}
a         { font-family: monospace; text-decoration: none;
margin-bottom: 2px;}
a:link    { color: blue; }
a:visited { color: blue; }
a:hover   { background-color: #dddddd; }
.indent   { margin-left: 3em; margin-right: 6em; background-color: #dddddd; padding: 1em; }
td        { padding: 1em; }
</style>
</head>
<body>
<h2>
<?php print "$TITLE\n"; ?>
</h2>
<hr noshade>


<!-- Draw upload form -->
<h3>
To upload a file
</h3>
<form action='' method='post' enctype='multipart/form-data' name='uploadForm'>
<input type="hidden" name="MAX_FILE_SIZE" value="<?php print $MAX_FILE_SIZE ?>" >
<div class="indent">
<table>
<tr>
<td>
<b>Step 1:  Enter a filename</b>.
</td>
<td>
<input type="file" name="userfile" size="32">
</td>
</tr>
<tr>
<td>
<b>Step 2:  Push the button</b>.
</td>
<td>
<input type="submit" name="Submit" value="Upload File">
</td>
</tr>
</table>
</form>
<br>
<i>
Note that the <b>maximum allowed file size</b> for uploading is 
<?php print $MAX_FILE_SIZE_LABEL ?>.
</i>
</div>

<!-- Delete files if reqeusted -->
<?php
$flash = "";

if ($_POST['mode']=='delete') {
	//  Get list of files
	$files = array();
	foreach ($_POST["delete"] as $filename) {
		$files[] = $filename;
	}
	//  Delete files
	if ($files) {
		if ($_POST['sure']=='on') {
			$flash = "<h3>The following files have been deleted.</h3>\n<ul>\n";
			foreach ($_POST["delete"] as $filename) {
				//  Get filesystem path to file
				$path = get_relative_path($THIS_SCRIPT_NAME,"$ROOT_DIR/$filename");
				//  Delete file
				unlink($path);
				//  Update message
				$flash .= "<li>$filename</li>\n";
			}
			$flash .= "</ul>\n";
		//  "Yes I'm Sure!"  not checked.
		} else {
			$flash .= "<br/><span style='color: red'><b>ERROR</b>:   Click   <i>Yes I'm sure!</i>   if you want to delete files.</span><br/>\n";
		}
	//  No files selected
	} else {
		$flash .= "<br/><span style='color: red'><b>ERROR</b>:   Select one or more files and click   <i>Yes I'm sure!</i>   if you want to delete files.</span><br/>\n";
	}
}
?>

<!-- Upload file if present  -->
<?php
if ( isset($_FILES['userfile']['name']) ) {

	$fileName   = $_FILES['userfile']['name'];
	//  Don't upload .php files
	$lcfileName = strtolower($fileName);
	if ( 
		substr($lcfileName,-4)==".php"  ||
		substr($lcfileName,-5)==".php4" ||
		substr($lcfileName,-5)==".php5" ||
		substr($lcfileName,-5)==".phps"
	) {
		print "<p><strong>Sorry.  Uploading of PHP files is not allowed.</strong></p>\n";
	// Upload file
	} else {
		$uploadPath = "$ROOT_DIR/$fileName";
		if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadPath)) {
			print "<p>Your file <b>$fileName</b> uploaded successfully.</p><br/>\n";
		} else {
			print "<p>There was a problem uploading your file <b>$fileName</b>.</p><br/>\n";
		}
	}
}

?>


<!-- List files available for download -->
<hr noshade>

<?php

#  Refresh PHP's (OS's ?) file and directory list cache
clearstatcache();

#  Read directories and files in current directory
$handle  = opendir($ROOT_DIR);
$files = array();
while (false !== ($filename = readdir($handle))) {   
	#  Add file to list (omit this script)
	$filepath = "$ROOT_DIR/$filename";
	if (is_dir($filepath)==false && $filepath!=$THIS_SCRIPT_NAME) {
		$files[] = $filename; 
	}
}

#  List files if present
if ($files) {
	#  Print download message
	print "<h3>To download a file, right-click on the name.</h3>";
	print "<h3>To delete   a file, check the delete box(es) and the Yes box.</h3>";
	print "<div class='indent'>\n\n";

	#  Sort file list
	if ($files) { sort($files); }

	#  Start delete form
	print "<form action='' method='post'>\n";
	print "<input type='hidden' name='mode' value='delete'>\n";

	#  List files if present
	foreach($files as $name) {
		#  Get relative path from this script's directory to files directory.
		$path = get_relative_path($THIS_SCRIPT_NAME,"$ROOT_DIR/$name");
		#  Display delete check box
		print "<input type='checkbox' name='delete[]' value='$name'>\n";
		#  Display link
		print "<a href='$path'>";
		print "<img src='http://web.uconn.edu/file.gif'>$name</a><br/>\n";
	}

	#  End delete form
	print "<br/><br/>\n";
	print "<input type='submit' value='DELETE checked files'>\n";
	print "   ";
	print "   ";
	print "<input id='sure' type='checkbox' name='sure'><label for='sure'><i>Yes, I'm sure!</i></label><br/>\n";
	print "</form>\n";

	print '</div>';

#  No files to list
} else {
	print "<h3> No files are available for download. </h3><br>\n";
}

#  Print flash messagse
if ($flash) {
	print "<hr noshade>\n";
	print $flash;
}

?> 

<!-- End html page -->
</body>
</html>