<?php

//   -------------------------------------------------------------------------------
//  |                  net2ftp: a web based FTP client                              |
//  |              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.                        |
//  |                                                                               |
//   -------------------------------------------------------------------------------




/*

	The consumption of server and network resources is logged per client IP 
	address, and per target FTP server. The 2 database tables which contain 
	the logs are:
		net2ftp_logConsumptionIpaddress: date, ipaddress, dataTransfer, executionTime
		net2ftp_logConsumptionFtpserver: date, ftpserver, dataTransfer, executionTime
	
	The database is read at the beginning of the script, and updated at the end 
	of the script. There are 6 global variables:
	
	These variables
		$consumption_ipaddress_dataTransfer, $consumption_ipaddress_executionTime, 
		$consumption_ftpserver_dataTransfer, $consumption_ftpserver_executionTime; 
	contain the data transfer volume and script execution time. They are inititialized
	at the beginning of the script and updated each time data is read/written from/to the
	FTP server. 
	
	The variable 
		$consumption_dataTransfer_changeflag;
	is initialized as 0 and changed to 1 if data was transferred. 
	This is to avoid having to	run an SQL query if no data was transferred, e.g. when
	logging in, browsing the FTP server, when confirming an action or even for some 
	actions like delete or chmod.
	
	The variable 
		$consumption_database_updated;
	is initialized as 0 and changed to 1 when the database is updated with the consumption
	in putConsumption(). This is to avoid updating the database twice. The putConsumption()
	function is called from index.php and from shutdown() in filesystem.inc.php. On Windows
	the shutdown() function is called after *every* script execution.

*/


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

function getConsumption() {

// --------------
// This function reads the consumption from the database.
// It is run at the beginning of the script.
// --------------

// -------------------------------------------------------------------------
// Global variables
// -------------------------------------------------------------------------
	global $execution_success;
	global $settings;
	global $net2ftp_ftpserver, $REMOTE_ADDR;
	global $consumption_ipaddress_dataTransfer, $consumption_ipaddress_executionTime;
	global $consumption_ftpserver_dataTransfer, $consumption_ftpserver_executionTime;
	global $consumption_dataTransfer_changeflag, $consumption_database_updated;


// -------------------------------------------------------------------------
// Initial checks
// -------------------------------------------------------------------------

// Verify if a database is used, and if consumption checking is turned on. If not: don't continue.
	if ($settings["use_database"] != "yes" || $settings["check_consumption"] != "yes") { return true; }

// When user is not logged in, the FTP server is not set
	if ($net2ftp_ftpserver == "") { return true; }

// If the REMOTE_ADDR is not filled in, then there is a problem (IP spoofing), so return an error
	if ($REMOTE_ADDR == "") { 
		setErrorVars(false, __("Unable to determine your IP address."), debug_backtrace());
		return false; 
	}

// Add slashes to variables which are used in a SQL query, and which are
// potentially unsafe (supplied by the user).
	// $date is calculated in this function
	// $time is calculated in this function
	$REMOTE_ADDR_safe       = addslashes($REMOTE_ADDR);
	$net2ftp_ftpserver_safe = addslashes($net2ftp_ftpserver);
	
// -------------------------------------------------------------------------
// Set the change flags to the initial value
// -------------------------------------------------------------------------
	$consumption_dataTransfer_changeflag = 0;
	$consumption_database_updated = 0;

// -------------------------------------------------------------------------
// Get date
// -------------------------------------------------------------------------
	$date = date("Y-m-d");

// -------------------------------------------------------------------------
// Connect
// -------------------------------------------------------------------------
	$mydb = connect2db();
	if ($execution_success == false) { return false; }

// -------------------------------------------------------------------------
// Get consumed data volume and execution time by the current IP address
// -------------------------------------------------------------------------
	$sqlquery1 = "SELECT dataTransfer, executionTime FROM net2ftp_logConsumptionIpaddress WHERE date = '$date' AND ipaddress = '$REMOTE_ADDR_safe';";
	$result1   = mysql_query("$sqlquery1") or die("Unable to execute SQL SELECT query (getConsumption > sqlquery1) <br /> $sqlquery1");
	$nrofrows1 = mysql_num_rows($result1);

	if     ($nrofrows1 == 0) { 
		$consumption_ipaddress_dataTransfer = 0;
		$consumption_ipaddress_executionTime = 0; 
	}
	elseif ($nrofrows1 == 1) { 
		$resultRow1 = mysql_fetch_row($result1); 
		$consumption_ipaddress_dataTransfer = $resultRow1[0];
		$consumption_ipaddress_executionTime = $resultRow1[1]; 
	}
	else { 
		setErrorVars(false, __("Table net2ftp_logConsumptionIpaddress contains duplicate rows."), debug_backtrace());
		return false; 
	}

// -------------------------------------------------------------------------
// Get consumed data volume and execution time to the current FTP server
// -------------------------------------------------------------------------
	$sqlquery2 = "SELECT dataTransfer, executionTime FROM net2ftp_logConsumptionFtpserver WHERE date = '$date' AND ftpserver = '$net2ftp_ftpserver_safe';";
	$result2   = mysql_query("$sqlquery2") or die("Unable to execute SQL SELECT query (getConsumption > sqlquery2) <br /> $sqlquery2");
	$nrofrows2 = mysql_num_rows($result2);

	if     ($nrofrows2 == 0) { 
		$consumption_ftpserver_dataTransfer = 0;
		$consumption_ftpserver_executionTime = 0; 
	}
	elseif ($nrofrows2 == 1) { 
		$resultRow2 = mysql_fetch_row($result2); 
		$consumption_ftpserver_dataTransfer = $resultRow2[0];
		$consumption_ftpserver_executionTime = $resultRow2[1]; 
	}
	else { 
		setErrorVars(false, __("Table net2ftp_logConsumptionFtpserver contains duplicate rows."), debug_backtrace());
		return false; 
	}


// Return true
	return true;

} // End getConsumption

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





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

function putConsumption() {

// --------------
// This function writes the consumption to the database.
// It is run at the end of the script.
// --------------

// -------------------------------------------------------------------------
// Global variables
// -------------------------------------------------------------------------
	global $execution_success;
	global $settings;
	global $net2ftp_ftpserver, $REMOTE_ADDR;
	global $consumption_ipaddress_dataTransfer, $consumption_ipaddress_executionTime;
	global $consumption_ftpserver_dataTransfer, $consumption_ftpserver_executionTime;
	global $consumption_dataTransfer_changeflag, $consumption_database_updated;


// -------------------------------------------------------------------------
// Initial checks
// -------------------------------------------------------------------------

// Verify if a database is used, and if consumption checking is turned on. If not: don't continue.
	if ($settings["use_database"] != "yes" || $settings["check_consumption"] != "yes") { return true; }

// When user is not logged in, the FTP server is not set
	if ($net2ftp_ftpserver == "") { return true; }

// If the REMOTE_ADDR is not filled in, then there is a problem (IP spoofing), so return an error
	if ($REMOTE_ADDR == "") { 
		setErrorVars(false, __("Unable to determine your IP address."), debug_backtrace());
		return false; 
	}

// If the database has already been updated, don't do it a second time.
// This is to avoid updating the database twice. The putConsumption() function
// is called from index.php and from shutdown() in filesystem.inc.php. On Windows
// the shutdown() function is called after *every* script execution.
	if ($consumption_database_updated == 1) { return true; }

// Add slashes to variables which are used in a SQL query, and which are
// potentially unsafe (supplied by the user).
	// $date is calculated in this function
	// $time is calculated in this function
	$REMOTE_ADDR_safe       = addslashes($REMOTE_ADDR);
	$net2ftp_ftpserver_safe = addslashes($net2ftp_ftpserver);
	
// -------------------------------------------------------------------------
// Check the input
// -------------------------------------------------------------------------

//	if (preg_match("/^[0-9]+$/", $consumption_ipaddress_dataTransfer) == FALSE) { 
//			setErrorVars(false, __("The variable <b>consumption_ipaddress_dataTransfer</b> is not numeric."), debug_backtrace());
//			return false;
//	}


// -------------------------------------------------------------------------
// Connect
// -------------------------------------------------------------------------
	$mydb = connect2db();
	if ($execution_success == false) { return false; }

// -------------------------------------------------------------------------
// Get date
// -------------------------------------------------------------------------
	$date = date("Y-m-d");

// -------------------------------------------------------------------------
// Put consumed data volume and execution time by the current IP address
// -------------------------------------------------------------------------
	$sqlquery1 = "SELECT * FROM net2ftp_logConsumptionIpaddress WHERE date = '$date' AND ipaddress = '$REMOTE_ADDR_safe';";
	$result1   = mysql_query("$sqlquery1");
	$nrofrows1 = mysql_num_rows($result1);

	if ($nrofrows1 == 1) { 
		$sqlquery2 = "UPDATE net2ftp_logConsumptionIpaddress SET dataTransfer = '$consumption_ipaddress_dataTransfer', executionTime = '$consumption_ipaddress_executionTime' WHERE date = '$date' AND ipaddress = '$REMOTE_ADDR_safe';";
		$result2   = mysql_query("$sqlquery2");
		$nrofrows2 = mysql_affected_rows($mydb);
// Don't check on the UPDATE nr of rows, because when the values in the variables and in the table are the same,
// the $nrofrows2 is set to 0. (This happens on the Browse screen, when the loading is fast: the dataTransfer is 0
// and the executionTime is the same as in the table.)
//		if ($nrofrows2 != 1) { 
//			setErrorVars(false, __("Table net2ftp_logConsumptionIpaddress could not be updated."), debug_backtrace());
//			return false; 
//		}
	}
	elseif ($nrofrows1 == 0) { 
		$sqlquery3 = "INSERT INTO net2ftp_logConsumptionIpaddress VALUES('$date', '$REMOTE_ADDR_safe', '$consumption_ipaddress_dataTransfer', '$consumption_ipaddress_executionTime');";
		$result3   = mysql_query("$sqlquery3");
		$nrofrows3 = mysql_affected_rows($mydb);
		if ($nrofrows3 != 1) { 
			setErrorVars(false, __("Table net2ftp_logConsumptionIpaddress could not be updated."), debug_backtrace());
			return false; 
		}
	}
	else {
		setErrorVars(false, __("Table net2ftp_logConsumptionIpaddress contains duplicate entries."), debug_backtrace());
		return false; 
	}

// MySQL > 4.1.0
//	$sqlquery1 = "INSERT INTO net2ftp_logConsumptionIpaddress VALUES('$date', '$REMOTE_ADDR_safe', '$consumption_ipaddress_dataTransfer', '$consumption_ipaddress_executionTime') ON DUPLICATE KEY UPDATE dataTransfer = '$consumption_ipaddress_dataTransfer', executionTime = '$consumption_ipaddress_executionTime';";

	
// -------------------------------------------------------------------------
// Put consumed data volume and execution time to the current FTP server
// -------------------------------------------------------------------------
	$sqlquery4 = "SELECT * FROM net2ftp_logConsumptionFtpserver WHERE date = '$date' AND ftpserver = '$net2ftp_ftpserver_safe';";
	$result4   = mysql_query("$sqlquery4");
	$nrofrows4 = mysql_num_rows($result4);

	if ($nrofrows4 == 1) { 
		$sqlquery5 = "UPDATE net2ftp_logConsumptionFtpserver SET dataTransfer = '$consumption_ftpserver_dataTransfer', executionTime = '$consumption_ftpserver_executionTime' WHERE date = '$date' AND ftpserver = '$net2ftp_ftpserver_safe';";
		$result5   = mysql_query("$sqlquery5");
		$nrofrows5 = mysql_affected_rows($mydb);
// Don't check on the UPDATE nr of rows, because when the values in the variables and in the table are the same,
// the $nrofrows2 is set to 0. (This happens on the Browse screen, when the loading is fast: the dataTransfer is 0
// and the executionTime is the same as in the table.)
//		if ($nrofrows5 != 1) { 
//			setErrorVars(false, __("Table net2ftp_logConsumptionFtpserver could not be updated."), debug_backtrace());
//			return false; 
//		}
	}
	elseif ($nrofrows4 == 0) { 
		$sqlquery6 = "INSERT INTO net2ftp_logConsumptionFtpserver VALUES('$date', '$net2ftp_ftpserver_safe', '$consumption_ftpserver_dataTransfer', '$consumption_ftpserver_executionTime');";
		$result6   = mysql_query("$sqlquery6");
		$nrofrows6 = mysql_affected_rows($mydb);
		if ($nrofrows6 != 1) { 
			setErrorVars(false, __("Table net2ftp_logConsumptionFtpserver could not be updated."), debug_backtrace());
			return false; 
		}
	}
	else {
		setErrorVars(false, __("Table net2ftp_logConsumptionFtpserver contains duplicate entries."), debug_backtrace());
		return false; 
	}

// -------------------------------------------------------------------------
// If both tables have been updated, set the flag to 1
// -------------------------------------------------------------------------
	$consumption_database_updated = 1;

// Return true
	return true;

} // End putConsumption

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





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

function addConsumption($data, $time) {

// --------------
// This function adds the $data and $time given in the argument of the function
// to the global variables
// --------------

// -------------------------------------------------------------------------
// Global variables
// -------------------------------------------------------------------------
	global $settings;
	global $consumption_ipaddress_dataTransfer, $consumption_ipaddress_executionTime;
	global $consumption_ftpserver_dataTransfer, $consumption_ftpserver_executionTime;
	global $consumption_dataTransfer_changeflag, $consumption_database_updated;


// -------------------------------------------------------------------------
// Initial checks
// -------------------------------------------------------------------------

// Verify if a database is used, and if consumption checking is turned on. If not: don't continue.
	if ($settings["use_database"] != "yes" || $settings["check_consumption"] != "yes") { return true; }

// -------------------------------------------------------------------------
// Add the consumption to the global variables
// -------------------------------------------------------------------------
	if ($data != "" && $data > 0) {
		$consumption_dataTransfer_changeflag = 1;
		$consumption_ipaddress_dataTransfer = $consumption_ipaddress_dataTransfer + $data;
		$consumption_ftpserver_dataTransfer = $consumption_ftpserver_dataTransfer + $data;
	}

	if ($time != "" && $time > 0) {
		$consumption_ipaddress_executionTime = $consumption_ipaddress_executionTime + $time;
		$consumption_ftpserver_executionTime = $consumption_ftpserver_executionTime + $time;
	}

// Return true
	return true;

} // End addConsumption

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




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

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

function printConsumption() {

// --------------
// This function prints the global consumption variables.
// It is only used for debugging.
// --------------

// -------------------------------------------------------------------------
// Global variables
// -------------------------------------------------------------------------
	global $net2ftp_ftpserver, $REMOTE_ADDR;
	global $consumption_ipaddress_dataTransfer, $consumption_ipaddress_executionTime;
	global $consumption_ftpserver_dataTransfer, $consumption_ftpserver_executionTime;
	global $consumption_dataTransfer_changeflag, $consumption_database_updated;

// -------------------------------------------------------------------------
// Print the variables
// -------------------------------------------------------------------------
	echo "net2ftp_ftpserver: " . $net2ftp_ftpserver . "<br />\n";
	echo "REMOTE_ADDR: "       . $REMOTE_ADDR . "<br />\n";

	echo "consumption_ipaddress_dataTransfer: "  . $consumption_ipaddress_dataTransfer  . "<br />\n";
	echo "consumption_ipaddress_executionTime: " . $consumption_ipaddress_executionTime . "<br />\n";

	echo "consumption_ftpserver_dataTransfer: "  . $consumption_ftpserver_dataTransfer  . "<br />\n";
	echo "consumption_ftpserver_executionTime: " . $consumption_ftpserver_executionTime . "<br />\n";

	echo "consumption_dataTransfer_changeflag: " . $consumption_dataTransfer_changeflag . "<br />\n";
	echo "consumption_ipaddress_executionTime: " . $consumption_ipaddress_executionTime . "<br />\n";

} // End printConsumption() 

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




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

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

function checkConsumption() {

// --------------
// This function checks the consumption and returns an error message if
// the limit has been reached.
// It returns true if all is OK, false if the limit has been reached.
// --------------

// -------------------------------------------------------------------------
// Global variables
// -------------------------------------------------------------------------
	global $settings;
	global $net2ftp_ftpserver, $REMOTE_ADDR;
	global $consumption_ipaddress_dataTransfer, $consumption_ipaddress_executionTime;
	global $consumption_ftpserver_dataTransfer, $consumption_ftpserver_executionTime;

// -------------------------------------------------------------------------
// Initial checks
// -------------------------------------------------------------------------

// Verify if a database is used, and if consumption checking is turned on. If not: don't continue.
	if ($settings["use_database"] != "yes" || $settings["check_consumption"] != "yes") { return true; }


// -------------------------------------------------------------------------
// Check if the limit has been reached
// -------------------------------------------------------------------------
	if ($consumption_ipaddress_dataTransfer  > $settings["max_consumption_ipaddress_dataTransfer"])  { return false; }
	if ($consumption_ipaddress_executionTime > $settings["max_consumption_ipaddress_executionTime"]) { return false; }
	if ($consumption_ftpserver_dataTransfer  > $settings["max_consumption_ftpserver_dataTransfer"])  { return false; }
	if ($consumption_ftpserver_executionTime > $settings["max_consumption_ftpserver_executionTime"]) { return false; }

	return true;

} // End checkConsumption() 

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

?>