<?php

//   -------------------------------------------------------------------------------
//  |                  jupload-FTP - upload to your FTP server                      |
//  |                                                                               |
//  |                  Based on net2ftp - a web based FTP client                    |
//  |                         http://www.net2ftp.com                                |
//  |                                                                               |
//  |              Copyright (c) 2003-2005 by David Gartner                         |
//  |                                                                               |
//  | This program is free software; you can redistribute it and/or                 |
//  | modify it under the terms of the GNU General Public License                   |
//  | as published by the Free Software Foundation; either version 2                |
//  | of the License, or (at your option) any later version.                        |
//  |                                                                               |
//   -------------------------------------------------------------------------------

// This script has 4 main parts:
// -----------------------------
// 1.1 Erase all variables which are not $_GET, $_POST, $_COOKIE, $_SERVER, ...
// 1.2 Initialization of script
// 2. Move uploaded file to net2ftp's /temp directory
// 2.1 PUT method
// 2.2 POST method
// 3. Move uploaded file from net2ftp's /temp directory to the FTP server
// 3.1 Open FTP connection
// 3.2 Create subdirectories if needed
// 3.3 Transfer files
// 3.4 Close connection
// 4. End of script

// -------------------------------------------------------------------------
// 1.1 Erase all variables which are not $_GET, $_POST, $_COOKIE, $_SERVER, ...
// This is to make the script safer on environments which have register_globals = On.
// -------------------------------------------------------------------------
 if (ini_get(register_globals) == 1) {
	$defined_vars = get_defined_vars();
	while (list($var_name, $var_value) = each($defined_vars)) {
		if ($var_name != "_GET" && $var_name != "_POST" && $var_name != "_COOKIE" && $var_name != "_SERVER" && $var_name != "_FILES" && $var_name != "_SESSION" && $var_name != "_ENV" && $var_name != "HTTP_AUTHORIZATION") {
//			echo "Variable " . $var_name . " has value " . $var_value . "<br />\n";
			unset($$var_name);
		}
	} // end while
}


// -------------------------------------------------------------------------
// 1.2 Basic settings
// -------------------------------------------------------------------------
// Run the script to the end, even if the user hits the stop button
ignore_user_abort(true);

// Execute function shutdown() if the script reaches the maximum execution time (usually 30 seconds)
register_shutdown_function("jupload_shutdown");

// Get settings files
require_once("settings.inc.php");
require_once("settings_authorizations.inc.php");
require_once("settings_screens.inc.php");

// Check if Java Uploads are enabled
if ($settings['functionuse_javaupload'] != "yes") {
	$errormessage = __("This function has been disabled by the Administrator of this website.");
	echo $errormessage;
	exit();
}

// The root directory cannot be determined from an include file,
// so this is the workaround
$application_rootdir = dirname(__FILE__);
$application_includesdir  = $application_rootdir . "/includes";
$application_languagesdir = $application_rootdir . "/languages";
$application_pluginsdir   = $application_rootdir . "/plugins";
$application_tempdir      = $application_rootdir . "/temp";         // Chmod this directory to 777 !

// Set the error reporting level
if ($settings['error_reporting'] == "ALL")  { error_reporting(E_ALL); }
if ($settings['error_reporting'] == "NONE") { error_reporting(0); }
else                                        { error_reporting(E_ERROR | E_WARNING | E_PARSE); }

// Set the execution control variables
$execution_success = true;        // true if everything is OK; is set to false on error
$execution_errormessage = "";     // contains error message on error
$execution_debug_backtrace = "";  // contains the debug_backtrace on error
$execution_output = "no";         // "no" while preliminary code is executed and headers are sent; is set to "yes" when output has started

// Timer: start
$starttime = microtime();
$execution_output = "yes";
echo "Please wait, the files are being transferred to the FTP server...<br />\n";
flush();


// -------------------------------------------------------------------------
// 1. Function libraries
// -------------------------------------------------------------------------
require_once($application_includesdir  . "/authorizations.inc.php");
require_once($application_includesdir  . "/consumption.inc.php");
require_once($application_includesdir  . "/database.inc.php");
require_once($application_includesdir  . "/errorhandling.inc.php");
require_once($application_includesdir  . "/filesystem.inc.php");
require_once($application_includesdir  . "/languages.inc.php");

// Load the language file
// includeLanguageFile();


// -------------------------------------------------------------------------
// 1. Preliminary checks
// -------------------------------------------------------------------------
if (function_exists("ftp_connect") == false) { 
	echo "ERROR: The FTP module of PHP is not installed on the webserver. Script halted: no directories have been created, and no files have been uploaded.<br />\n"; 
	exit();
}


// -------------------------------------------------------------------------
// 1. Register the global variables
// -------------------------------------------------------------------------
// FTP connection settings
$net2ftp_ftpserver          = $_GET['ftpserver'];
$net2ftp_ftpserverport      = $_GET['ftpserverport'];
$net2ftp_username           = $_GET['username'];
$net2ftp_password_encrypted = $_GET['password_encrypted'];
$net2ftp_language           = $_GET['language'];
$net2ftp_ftpmode            = $_GET['ftpmode'];
$net2ftp_passivemode        = $_GET['passivemode'];
$net2ftp_sslconnect         = $_GET['sslconnect'];
$directory                  = $_GET['directory'];

// Server variables
$PHP_SELF                    = $_SERVER["PHP_SELF"];
$HTTP_REFERER                = $_SERVER["HTTP_REFERER"];
$HTTP_USER_AGENT             = $_SERVER["HTTP_USER_AGENT"];
$REMOTE_ADDR                 = $_SERVER["REMOTE_ADDR"];
$REMOTE_PORT                 = $_SERVER["REMOTE_PORT"];

// Change the input array ($_FILES) into the net2ftp array ($uploadedFilesArray)
// The $_FILES superglobal variable is structured as follows:
// $_FILES["fieldname"]["name"]               contains the original filename on the client computer
// $_FILES["fieldname"]["tmp_name"]           contains the temporary name on the webserver
// $_FILES["fieldname"]["size"]               contains the filesize
// $_FILES["fieldname"]["error"]              contains the error code (PHP >= 4.2.0)
// $_FILES["fieldname"]["absolute_directory"] contains the absolute directory (added by the jupload Java applet)
// fieldname is the name of the HTML input box: <input type="file" name="fieldname" />

$file_counter = 0;
foreach($_FILES as $tagname=>$object) {
	if ($object['name'] != "") {
		$file_counter = $file_counter + 1;
		$uploadedFilesArray["$file_counter"]["name"]               = $object['name'];
		$uploadedFilesArray["$file_counter"]["tmp_name"]           = $object['tmp_name'];
		$uploadedFilesArray["$file_counter"]["size"]               = $object['size'];
		$uploadedFilesArray["$file_counter"]["error"]              = $object['error'];

// Look for special encoded jupload files
		$contentType = $object['type'];
		if (substr($contentType,0,7) == "jupload") {
			$base64_encoded_path = substr($contentType,8);
			$base64_decoded_path = base64_decode($base64_encoded_path);
			$uploadedFilesArray["$file_counter"]["absolute_directory"] = $base64_decoded_path;
		} // end if

	} // end if
} // end foreach


// -------------------------------------------------------------------------
// 1. Check authorizations
// -------------------------------------------------------------------------
if ($settings["check_authorization"] == "yes" && $net2ftp_ftpserver != "") {
	$result = checkAuthorization($net2ftp_ftpserver, $net2ftp_ftpserverport, $directory, $net2ftp_username);
	if ($execution_success == false) { echo "ERROR: Authorization check failed. Script halted.<br />\n"; exit(); }
}


// -------------------------------------------------------------------------
// 1. Log access
// -------------------------------------------------------------------------
$state  = "manage";
$state2 = "javaupload";
logAccess();
if ($execution_success == false) { echo "ERROR: Unable to log the access. Script halted.<br />\n"; exit(); }


// -------------------------------------------------------------------------
// 1. Get the consumption counter values from the database
// -------------------------------------------------------------------------
getConsumption();
if ($execution_success == false) { echo "ERROR: Unable to get consumption values from the database. Script halted.<br />\n"; exit(); }





// -------------------------------------------------------------------------
// 2.1 PUT METHOD: Move files from the *webserver's* temporary directory to *net2ftp's*
// temporary directory.
// 
// http://jupload.biz/forum/static_read_206.html
// In Apache's httpd.conf file, set "Script PUT /put.php"
// -------------------------------------------------------------------------

/* ---------- The PUT method is not yet used ----------

if ($_SERVER["REQUEST_METHOD"] == "PUT" && ($_SERVER['PATH_TRANSLATED'] != "" || $_ENV['PATH_TRANSLATED'] != "") && $_SERVER['HTTP_CONTENT_RANGE'] != "") {

// Input file = stream
// Output file needs the following data
//		$file_name               = last part of $_SERVER['PATH_TRANSLATED']) or $_ENV['PATH_TRANSLATED']
//		$file_tmp_name           = $tempfilename
//		$file_size               = part of $_SERVER['HTTP_CONTENT_RANGE'], see $total
//		$file_error              = not used in PUT, only in POST
//		$file_absolute_directory = $_SERVER['PATH_TRANSLATED']) or $_ENV['PATH_TRANSLATED']
		
	if     ($_SERVER['PATH_TRANSLATED'] != "") { $file_absolute_directory = $_SERVER['PATH_TRANSLATED']; $file_name = get_filename_name($_SERVER['PATH_TRANSLATED']); }
	elseif ($_ENV['PATH_TRANSLATED'] != "")    { $file_absolute_directory = $_ENV['PATH_TRANSLATED'];    $file_name = get_filename_name($_ENV['PATH_TRANSLATED']);    }
	else { 
		echo "ERROR: Unable to determine the filename. Script halted: no directories have been created, and no files have been uploaded.<br />\n"; 
		exit();
	}

// Create the temporary filename as follows: (from left to right)
// - Use prefix "upload__", to be able to identify from where this temporary file comes from
// - Create a random filename
// - Add the original filename extension, to be able to identify the filetype
// - Add suffix ".txt" to avoid that the file would be executed on the webserver
		$extension = get_filename_extension($file_name);
		if (substr($file_name, -6) == "tar.gz") { $extension = "tar.gz"; }
		$tempfilename = mytempnam($application_tempdir, "upload__", "." . $extension . ".txt");
		if ($tempfilename == false) { 
			// If you get this warning message, you've probably forgotten to chmod 777 the /temp directory
			echo "WARNING: File <b>$file_name</b> skipped: unable to create a temporary file on the webserver.<br />\n"; 
			//@unlink($file_tmp_name); // Not needed for PUT, only for POST
		}

// Open input stream in read-only mode
	if     (php_sapi_name() == "apache") { $puthandle = fopen("php://input","r"); }
	elseif (php_sapi_name() == "cgi")    { $puthandle = fopen("php://stdin","r"); }
	else                                 {
		// In other cases, try both options: input and stdin
		$puthandle = @fopen("php://input","r"); 
		if ($puthandle == false) { @fopen("php://stdin","r"); }
	}

	if ($puthandle == false) { echo "ERROR: Unable to open the input stream. Script halted.<br />\n"; exit(); }
	
// Open temporary file in read+write mode
// r+ option: Open for reading and writing; place the file pointer at the beginning of the file.
	$temphandle = fopen($tempfilename,'r+b');
	if ($temphandle == false) { echo "ERROR: Unable to open the temporary file. Script halted.<br />\n"; exit(); }

// Read the content-range HTTP header to know which data has been sent
// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html paragraph 14.16
// Example: "bytes 2543-4532/7898". 
	$cr = $_SERVER['HTTP_CONTENT_RANGE'];
	if (substr($cr,0,6) == 'bytes ') {
		$pos1    = strpos($cr,'-');
		$pos2    = strpos($cr,'/');
		$start   = substr($cr,6,$pos1-6);             // 2543 start of chunk of data - first chunk starts with 0
		$end     = substr($cr,$pos1+1,$pos2-$pos1-1); // 4532 end   of chunk of data - last chunk ends with 7897
		$size    = substr($cr,$pos2+1);               // 7898 total size of data
		if (is_numeric($start) == false) { echo "ERROR: HTTP_CONTENT_RANGE variable start is not numeric. Script halted.<br />\n"; exit(); }
		if (is_numeric($end) == false)   { echo "ERROR: HTTP_CONTENT_RANGE variable end is not numeric. Script halted.<br />\n"; exit(); }
		if (is_numeric($size) == false)  { echo "ERROR: HTTP_CONTENT_RANGE variable size is not numeric. Script halted.<br />\n"; exit(); }
		$percent = round($end/$size, 2) * 100;        // (4532/7898)*100 = 57%
	} // end if

// Read the stream and write it to the temporary file
	$fseek_result = fseek($temphandle, $start);
	if ($fseek_result == -1) { echo "ERROR: Unable to execute the fseek command. Script halted.<br />\n"; exit(); }
	
	$i=0;
	while ($data = fread($puthandle, 1024)) {
		$i += strlen($data);
		fwrite($temphandle, $data, strlen($data));
	} // end while

// Close the files
	$fclose_result1 = fclose($puthandle);
	if ($fclose_result1 == false) { echo "WARNING: Unable to close the handle of the stream.<br />\n"; }
	
	$fclose_result2 = fclose($temphandle);
	if ($fclose_result2 == false) { echo "WARNING: Unable to close the handle of the temporary file.<br />\n"; }

// Store the values in $acceptedFilesArray
	echo "File $outfile: received $end of $size ($percent%).<br />\n";
	if (sizeof($tempfilename) >= $total) { 
		echo "File $outfile: HTTP transmission completed, starting FTP transmission.<br />\n"; 
		$acceptedFilesArray["1"]["name"]               = $file_name;               // Contains the original filename (client)
		$acceptedFilesArray["1"]["tmp_name"]           = $tempfilename;            // Contains the temporary filename (webserver)
		$acceptedFilesArray["1"]["size"]               = $size;                    // Contains the filesize in Bytes
		$acceptedFilesArray["1"]["absolute_directory"] = $file_absolute_directory; // Contains the original directory + filename (client)
	}
	else { 
		// Do not continue the script until the whole file has been received.
		exit(); 
	}
	
} // end if

---------- The PUT method is not yet used ---------- */


// -------------------------------------------------------------------------
// 2.2 POST METHOD: Move files from the *webserver's* temporary directory to *net2ftp's*
// temporary directory (move_uploaded_files).
// -------------------------------------------------------------------------

//elseif ($_SERVER["REQUEST_METHOD"] == "POST" && sizeof($uploadedFilesArray) > 0) {
if ($_SERVER["REQUEST_METHOD"] == "POST" && sizeof($uploadedFilesArray) > 0) {

	$moved_counter = 0;
	for ($j=1; $j<=sizeof($uploadedFilesArray); $j++) {
		$file_name               = $uploadedFilesArray["$j"]["name"];
		$file_tmp_name           = $uploadedFilesArray["$j"]["tmp_name"];
		$file_size               = $uploadedFilesArray["$j"]["size"];
		$file_error              = $uploadedFilesArray["$j"]["error"];
		$file_absolute_directory = $uploadedFilesArray["$j"]["absolute_directory"];
		
		if (($file_name != "" && $file_tmp_name == "") || $file_size > $settings['max_upload_filesize']) {
// The case ($file_name != "" && $file_tmp_name == "") occurs when the file is bigger than the directives set in php.ini
// In that case, only $uploadedFilesArray["$j"]["name"] is filled in.
			echo "WARNING: File <b>$file_name</b> skipped: this file is too big.<br />\n"; 
			@unlink($file_tmp_name); 
			continue;
		}
// Create the temporary filename as follows: (from left to right)
// - Use prefix "upload__", to be able to identify from where this temporary file comes from
// - Create a random filename
// - Add the original filename extension, to be able to identify the filetype
// - Add suffix ".txt" to avoid that the file would be executed on the webserver
		$extension = get_filename_extension($file_name);
		if (substr($file_name, -6) == "tar.gz") { $extension = "tar.gz"; }
		$tempfilename = mytempnam($application_tempdir, "upload__", "." . $extension . ".txt");
		if ($tempfilename == false) { 
			// If you get this warning message, you've probably forgotten to chmod 777 the /temp directory
			echo "WARNING: File <b>$file_name</b> skipped: unable to create a temporary file on the webserver.<br />\n"; 
			@unlink($file_tmp_name); 
			continue;
		}

// Move the uploaded file
		$move_uploaded_file_result = move_uploaded_file($uploadedFilesArray["$j"]["tmp_name"], $tempfilename);
		if ($move_uploaded_file_result == false) { 
			echo "WARNING: File <b>$file_name</b> skipped: unable to move the uploaded file to the webserver's temporary directory.<br />\n"; 
			@unlink($file_tmp_name); 
			@unlink($tempfilename); 
			continue;
		}
		else {
			$moved_counter = $moved_counter + 1;
			$acceptedFilesArray["$moved_counter"] = $uploadedFilesArray["$j"]; // Copy all parameters for this file from the $uploadedFilesArray to the $acceptedFilesArray
			$acceptedFilesArray["$moved_counter"]["tmp_name"] = $tempfilename; // Overwrite the old temporary name by the new one
		}
	
	} // end for j

	flush();

} // end if elseif

// -------------------------------------------------------------------------
// If neither PUT nor POST is used, print error message
// -------------------------------------------------------------------------
else {
// Debugging info
	echo "No files were uploaded. Script halted.<br />\n";	
//	echo "_SERVER['PATH_TRANSLATED: "      . $_SERVER['PATH_TRANSLATED'] . "<br />\n";
//	echo "_ENV['PATH_TRANSLATED']: "       . $_ENV['PATH_TRANSLATED'] . "<br />\n";
//	echo "_SERVER['HTTP_CONTENT_RANGE']: " . $_SERVER['HTTP_CONTENT_RANGE'] . "<br />\n";
	exit();
}





// -------------------------------------------------------------------------
// 3. Move the files from net2ftp's temporary directory to the FTP server.
// -------------------------------------------------------------------------
if     (sizeof($acceptedFilesArray) == 0 && sizeof($uploadedFilesArray) != 0) { echo "WARNING: No files were accepted (see messages above), so nothing will be transferred to the FTP server.<br />\n"; }
elseif (sizeof($acceptedFilesArray) > 0) {

// ------------------------------
// 3.1 Open connection
// ------------------------------

// Decrypt password
	$net2ftp_password = decryptPassword($net2ftp_password_encrypted);

// Check if port nr is filled in
	if ($net2ftp_ftpserverport < 1 || $net2ftp_ftpserverport > 65535 || $net2ftp_ftpserverport == "") { $net2ftp_ftpserverport = 21; }

// Set up basic connection
	$ftp_connect = "ftp_connect";
	if ($net2ftp_sslconnect == "yes" && function_exists("ftp_ssl_connect")) { $ftp_connect = "ftp_ssl_connect"; }
	$conn_id = $ftp_connect("$net2ftp_ftpserver", $net2ftp_ftpserverport);
	if ($conn_id == false) {
		echo "ERROR: Unable to connect to FTP server $net2ftp_ftpserver on port $net2ftp_ftpserverport. Script halted: no directories have been created, and no files have been uploaded.<br />\n"; 
		exit();
	}

// Login with username and password
	$login_result = ftp_login($conn_id, $net2ftp_username, $net2ftp_password);
	if ($login_result == false) { 
		echo "ERROR: Unable to login to FTP server $net2ftp_ftpserver with username $net2ftp_username. Script halted: no directories have been created, and no files have been uploaded.<br />\n";
		exit();
	}

// Log the login
	logLogin($net2ftp_ftpserver, $net2ftp_username);
	if ($execution_success == false) { echo "ERROR: Unable to log the login. Script halted.<br />\n"; exit(); }

// Set passive mode
	if ($net2ftp_passivemode == "yes") { 
		$ftp_pasv_result = ftp_pasv($conn_id, TRUE); 
		if ($ftp_pasv_result == false) { 
			echo "WARNING: Unable to switch to the passive mode on FTP server $net2ftp_ftpserver. Script will try to continue...<br />\n"; 
			// Do not exit. Try to go on.
		}	
	}

// ------------------------------
// For loop (loop over all the files)
// ------------------------------
	for ($k=1; $k<=sizeof($acceptedFilesArray); $k++)  {
		$file_name               = $acceptedFilesArray["$k"]["name"];
		$file_tmp_name           = $acceptedFilesArray["$k"]["tmp_name"];
		$file_size               = $acceptedFilesArray["$k"]["size"];
		$file_error              = $acceptedFilesArray["$k"]["error"];
		$file_absolute_directory = $acceptedFilesArray["$k"]["absolute_directory"];
		
// Determine which FTP mode should be used
		$ftpmode = ftpAsciiBinary($file_name);

		if ($ftpmode == FTP_ASCII)      { $printftpmode = "FTP_ASCII"; }
		elseif ($ftpmode == FTP_BINARY) { $printftpmode = "FTP_BINARY"; }

// Add the filesize to the global consumption variables
		addConsumption(filesize($file_tmp_name), 0);
	
// Check the consumption
		if(checkConsumption() == false) {
			echo "The daily limit has been reached. File <b>$file_name</b> skipped. Script halted.<br />\n";
			$endtime = microtime();
			$time_taken = timer();
			addConsumption(0, $time_taken);
			exit();
		} // end if

// ------------------------------
// 3.2 Within the for loop: create the subdirectory if needed
// ------------------------------
// Replace Windows-style backslashes \ by Unix-style slashes /
		$file_absolute_directory = str_replace("\\", "/", trim($file_absolute_directory));
				
// Get the names of the subdirectories by splitting the string using slashes /
		$file_subdirectories = explode("/", $file_absolute_directory);
				
// $targetdirectory contains the successive directories to be created
		$targetdirectory = $directory;

// Loop over sizeof()-1 because the last part is the filename itself:
		for ($m=0; $m<sizeof($file_subdirectories)-1; $m++) {
// Create the targetdirectory string
			$targetdirectory = glueDirectories($targetdirectory, $file_subdirectories[$m]);
// Check if the subdirectories exist
			$result = @ftp_chdir($conn_id, $targetdirectory);
			if ($result == false) {
				$ftp_mkdir_result = ftp_mkdir($conn_id, $targetdirectory);
				if ($ftp_mkdir_result == false) { 
					echo "WARNING: Unable to create the directory <b>$targetdirectory</b>. The script will try to continue...<br />\n";
					continue;
				}
				echo "Directory $targetdirectory created.<br />\n";
			} // end if

			flush();

		} // end for m

// Store the $targetdirectory in the $acceptedFilesArray
		if ($targetdirectory != "" && $targetdirectory != "/") { 
			$acceptedFilesArray["$k"]["targetdirectory"] = "/" . $targetdirectory; 
		}

// ------------------------------
// 3.3 Within the for loop: put local file to remote file
// ------------------------------
		$localsource  = $acceptedFilesArray["$k"]["tmp_name"];
		$remotetarget = $acceptedFilesArray["$k"]["targetdirectory"] . "/" . $acceptedFilesArray["$k"]["name"];

// int ftp_put (int ftp_stream, string remote_file, string local_file, int mode)
		$ftp_put_result = ftp_put($conn_id, $remotetarget, $localsource, $ftpmode);
		if ($ftp_put_result == false) { 
			echo "WARNING: File <b>$file_name</b> skipped: unable put this file to the FTP target <b>$remotetarget</b> using FTP mode <b>$printftpmode</b>.<br />\n"; 
			continue;
		} // end if
		else { echo "File <b>$file_name</b> transferred.<br />\n"; }
	
// Delete the temporary file
		$unlink_result = unlink($localsource);
		if ($unlink_result == false) { 
			echo "WARNING: unable to delete the temporary file on the webserver. The script will try to continue...<br />\n"; 
			continue;
		} // end if

		flush();

	} // End for k

// ------------------------------
// 3.4 Close connection
// ------------------------------
	ftp_quit($conn_id);

} // end if





// -------------------------------------------------------------------------
// 4. Timer: stop
// -------------------------------------------------------------------------
$endtime = microtime();
$time_taken = timer();
addConsumption(0, $time_taken);


// -------------------------------------------------------------------------
// 4. Store the consumption counter values in the database
// -------------------------------------------------------------------------
putConsumption();
if ($execution_success == false) { echo "ERROR: Unable to store consumption values in the database. Script halted.<br />\n"; exit(); }


// -------------------------------------------------------------------------
// 4. Ending message
// -------------------------------------------------------------------------
echo "Script finished in <b>$time_taken seconds</b>.\n";


// -------------------------------------------------------------------------
// 4. Print debug code
// -------------------------------------------------------------------------

//echo "<br />\n<b>\$_SERVER:</b>\n<br /><br />\n";
//print_r($_SERVER);

//echo "<br />\n<b>\$_ENV:</b>\n<br /><br />\n";
//print_r($_ENV);

//echo "<br />\n<b>\$_FILES:</b>\n<br /><br />\n";
//print_r($_FILES);
//
//echo "<br />\n<b>\$uploadedFilesArray:</b>\n<br /><br />\n";
//print_r($uploadedFilesArray);
//
//echo "<br />\n<b>\$acceptedFilesArray:</b>\n<br /><br />\n";
//print_r($acceptedFilesArray);





// **************************************************************************************
// **************************************************************************************
// **                                                                                  **
// **                                                                                  **

function jupload_shutdown() {

// --------------
// This function is registered through register_shutdown_function, so that it would be
// executed when the script reaches the maximum execution time.
//
// The function displays a warning message, and deletes temporary files.
// --------------

// -------------------------------------------------------------------------
// Global variables and settings
// -------------------------------------------------------------------------
	global $execution_success;
	$max_execution_time = ini_get("max_execution_time");
	$time_taken = timer();

// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// Check the time taken versus the maximum execution time, because on Windows + Apache
// servers, the shutdown function is always called, even if the maximum execution time
// was not reached.
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------

	if ($time_taken > $max_execution_time - 1) {

// -------------------------------------------------------------------------
// Delete the temporary files which were not deleted automatically
// -------------------------------------------------------------------------
		for ($i=1; $i<=sizeof($uploadedFilesArray); $i++) {
			@unlink($uploadedFilesArray["$i"]["tmp_name"]);	
		}
		for ($k=1; $k<=sizeof($acceptedFilesArray); $k++)  {
			@unlink($acceptedFilesArray["$k"]["tmp_name"]);	
		}
		@unlink($tempfilename);
	
// -------------------------------------------------------------------------
// Store the consumption counter values in the database
// -------------------------------------------------------------------------
		putConsumption();
		if ($execution_success == false) { echo "ERROR: Unable to store consumption values in the database. Script halted.<br />\n"; exit(); }


// -------------------------------------------------------------------------
// Print a message to tell the user that the script was halted
// -------------------------------------------------------------------------
		echo "Script halted - maximum execution time of $max_execution_time seconds exceeded.<br />\n";
	}

} // end jupload_shutdown

// **                                                                                  **
// **                                                                                  **
// **************************************************************************************
// **************************************************************************************





// **************************************************************************************
// **************************************************************************************
// **                                                                                  **
// **                                                                                  **

function timer() {

// --------------
// This function calculates the time between starttime and endtime in milliseconds
// --------------

	global $starttime, $endtime; // the value is set in index.php

	list($start_usec, $start_sec) = explode(' ', $starttime);
	$starttime  = ((float)$start_usec + (float)$start_sec);
	list($end_usec, $end_sec) = explode(' ', $endtime);
	$endtime    = ((float)$end_usec + (float)$end_sec);
	$time_taken = ($endtime - $starttime);   // to convert from microsec to sec
	$time_taken = number_format($time_taken, 2);     // optional

	return $time_taken;

} // End function timer

// **                                                                                  **
// **                                                                                  **
// **************************************************************************************
// **************************************************************************************


?>