No changes

This commit is contained in:
Frank Harris 2025-09-11 13:29:15 -04:00
parent 8680a02b13
commit b6b398f5bf
17374 changed files with 2475441 additions and 0 deletions

View file

@ -0,0 +1,72 @@
<?php
/////////
//
// Stone PHP SafeCrypt
// -------------------
//
// This library is intended to wrap and distance a programmer from encryption, which is
// not only difficult to use safely, but also difficult to detect flaws in. The purpose of
// SafeCrypt is to provide a convenient, correct, secure and flexible wrapper for the mcrypt
// library, to make encryption available at greater ease and lower risk.
//
// * Stone PHP SafeCrypt is genuinely free software, distributed under the Modified 3-Clause
// BSD License. This library is GPL compatible. Please resist the GPL menace. Free isn't
// truly free if it's only available to some. See LICENSE.TXT for details.
//
// * Stone PHP SafeCrypt may be used in commercial projects at no cost, without permission.
// See LICENSE.TXT for details. Copyright notice must be maintained.
//
// * No library can substitute for a working knowledge of cryptography. See LEARNING.TXT
// for resources on getting up to speed in crypto with relatively little pain.
if (defined('STONE_PHP_SAFE_CRYPT_HOST_DIRECTORY')) {
$basedir = STONE_PHP_SAFE_CRYPT_HOST_DIRECTORY;
} else {
// net2ftp
$basedir = $net2ftp_globals["application_includesdir"] . "/";
}
/////////
//
// Please see USAGE.TXT for general usage instructions, or
/////////
//
// You must set the MD5 salt in the config file before this library will function. All other
// configuration is optional. testconfig checks to make sure the config is valid.
require_once($basedir . 'StonePhpSafeCrypt_config.php');
require_once($basedir . 'StonePhpSafeCrypt_testconfig.php');
/////////
//
// This file sets up the compressor behavior. If you want to add a new compression method,
// put the data in this file.
require_once($basedir . 'StonePhpSafeCrypt_compressors.php');
/////////
//
// Various components added here. You shouldn't need to edit these.
require_once($basedir . 'StonePhpSafeCrypt_blockscramble.php');
require_once($basedir . 'StonePhpSafeCrypt_packcrypt.php');
// TODO add best-algorithm search using mcrypt_list_algorithms()
?>

View file

@ -0,0 +1,92 @@
<?php
/////////
//
// Stone PHP SafeCrypt Block Scrambler
// -----------------------------------
//
// Block scramble and block descramble are utility functions for Pack crypt and Pack decrypt.
// These are usable as lightweight encryption, and are very fast, but are also very weak and
// should not be used independantly. These are only used because of the specific, well-known
// characteristics of the IV stream as used by Pack crypt, where the OTP nature of the IV
// leader makes these scrambles sufficient to prevent CBC MITM leading-block attacks.
function BlockScramble(&$data, &$weakkey) {
// Performs a simple modulo arithmetic cipher on the IV and datastream. The PHP manual
// incorrectly states that the initialization vector may safely be transmitted plaintext;
// in http://www.ciphersbyritter.com/GLOSSARY.HTM#IV it's made clear that in CBC mode, a
// man in the middle attack is possible on the very first block returned by manipulating
// the IV. However, since the IV is just a randomness salt, it carries all of the
// important characteristics of a truncated one time pad; therefore, rotated with the MD5
// hash of the key, which is well-distributed, we have a non-attackable binary result.
// This protects CBC mode encryptions from a MITM leading block attack; also, it's nice
// to have an extra source of white noise in the signal to slow down identifications.
$strongkey = md5($weakkey);
$keysize = strlen($strongkey); // because calling sizeof() every ten cycles is retarded
$datasize = strlen($data); // and again
$output = str_repeat(' ', $datasize); // pre-allocate output buffer to prevent reallocation thrash
$di = 0; // data index cursor
$bi = 0; // block index cursor
// net2ftp - added the next line to avoid a PHP Notice about an "undefined variable"
$ki = 0;
for (; $di < $datasize; ++$di, ++$ki) {
if ($ki >= $keysize) { $ki = 0; } // key's usually smaller than data, so bound it
$output[$di] = chr((ord($data[$di]) + ord($strongkey[$ki])) % 256); // and record the scrambled byte
}
return $output;
}
function BlockDescramble(&$data, &$weakkey) {
// Performs a simple modulo arithmetic cipher on the IV and datastream. The PHP manual
// incorrectly states that the initialization vector may safely be transmitted plaintext;
// in http://www.ciphersbyritter.com/GLOSSARY.HTM#IV it's made clear that in CBC mode, a
// man in the middle attack is possible on the very first block returned by manipulating
// the IV. However, since the IV is just a randomness salt, it carries all of the
// important characteristics of a truncated one time pad; therefore, rotated with the MD5
// hash of the key, which is well-distributed, we have a non-attackable binary result.
// This protects CBC mode encryptions from a MITM leading block attack.
$strongkey = md5($weakkey);
$output = str_repeat(' ', strlen($data)); // pre-allocate output buffer to prevent reallocation thrash
$keysize = strlen($strongkey); // because calling sizeof() every ten cycles is retarded
$datasize = strlen($data); // and again
$di = 0; // data index cursor
$bi = 0; // block index cursor
// net2ftp - added the next line to avoid a PHP Notice about an "undefined variable"
$ki = 0;
for (; $di < $datasize; ++$di, ++$ki) {
if ($ki >= $keysize) { $ki = 0; } // key's usually smaller than data, so bound it
$work = (ord($data[$di]) - ord($strongkey[$ki])); // descramble the scrambled byte
if ($work < 0) { $work += 256; } // reorigin low-range bytes
$output[$di] = chr($work); // record the origin-normalized byte
}
return $output;
}
?>

View file

@ -0,0 +1,56 @@
<?php
/////////
//
// Stone PHP SafeCrypt Compressors
// -------------------------------
//
// To add a new compressor, create a new member in the $compressors array. Its key should be
// the string by which the user calls the compressor. Its value should be an array with two
// members, 'encode' and 'decode', each themselves arrays. Each of the compressor entries
// should also have a 'desc' member, to give a descriptive name to each compression method,
// in case someone wants to build something larger on this library and needs tooltip or
// statusbar descriptive text.
//
// Each encode and decode must have the 'fname' member, which contains the name of the encoding
// or decoding function as appropriate.
//
// Each may have the 'args' member, which is a list of arguments that will be passed to the
// function, in order. If either array has the 'args' member, it must therefore also have the
// 'data_arg' member, which is the index of the argument to override with the actual data to be
// compressed or uncompressed.
//
// If the array does not have the 'args' and 'data_args' members, the function will be assumed
// to take only one value, the data for compression or decompression.
$compressors = array(
'gz' => array(
'encode' => array('fname' => 'gzcompress', 'args' => array(false, 9), 'data_arg' => 0),
'decode' => array('fname' => 'gzuncompress'),
'desc' => 'RFC 1950 ZLib compression at maximum'
),
'gz_deflate' => array(
'encode' => array('fname' => 'gzdeflate', 'args' => array(false, 9), 'data_arg' => 0),
'decode' => array('fname' => 'gzinflate'),
'desc' => 'RFC 1951 ZLib deflate at maximum'
),
'bz' => array(
'encode' => array('fname' => 'bzcompress', 'args' => array(false, 9, 30), 'data_arg' => 0),
'decode' => array('fname' => 'bzdecompress'),
'desc' => 'BZip2 compress at maximum, using work factor 30'
),
// add other compressors here
);
?>

View file

@ -0,0 +1,133 @@
<?php
/////////
//
// Stone PHP SafeCrypt configuration file
// --------------------------------------
//
// You must set the default MD5 salt. Everything else is optional.
//////////////////////////////
////////// REQUIRED //////////
//////////////////////////////
/////////
//
// Default MD5 Salt
//
// Fill this string with pretty much whatever. A phrase, random letters,
// it really doesn't matter. This is a 'salt,' which is a technique used
// to defeat dictionary attacks. Changing the salt will break all of your
// previous keys until the salt is changed back, so if you're expecting to
// change this as a response to attacks, it's probably better to input this
// in the options from the containing application than to leave it in
// defaults. It *must* be set in defaults, though, because a lack of a
// salt is an unacceptable security risk.
//
// The actual contents of the salt don't matter, other than that they are
// a string. You would do well to just slap your hands against the
// keyboard for a while.
//
// For obvious reasons, be careful to escape backslashes and quote marks
// according to PHP rules. Or, avoid them entirely. Doesn't matter.
define('DEFAULT_MD5_SALT', $net2ftp_settings["md5_salt"]); // empty string is illegal
// examples:
//
// define('DEFAULT_MD5_SALT', 'l^3-40#9a+40bn_qr:0b/8n<0b}qrq SPAM SPAM SPAM EGGS AND SPAM');
// define('DEFAULT_MD5_SALT', 'I am the very model of a modern Major General');
// define('DEFAULT_MD5_SALT', 'For a good time, call 867-5309');
// define('DEFAULT_MD5_SALT', '1,3,7-trimethyl-1H-purine-2,6(3H,7H)-dione');
//////////////////////////////
////////// OPTIONAL //////////
//////////////////////////////
// TODO add DEFAULT_INCLUDE_DIRECTORY
/////////
//
// DEFAULT_ENCRYPTION_METHOD
// -------------------------
// default: '' (auto-detect)
//
// TripleDES is reasonable speed, reasonable security and available in
// most countries. Set this to false if you want the library to try to
// autodetect the best available algorithm.
//
// TODO actually make the autodetection, also get rid of tripledes
define('DEFAULT_ENCRYPTION_METHOD', 'twofish');
/////////
//
// DEFAULT_ENCRYPTION_MODE
// -----------------------
// default: 'cbc'
//
// TODO write description
// TODO ofb is badbear. test with CBC soon.
define('DEFAULT_ENCRYPTION_MODE', 'cbc');
/////////
//
// DEFAULT_ALGORITHM_DIRECTORY
// ---------------------------
// default: '' (auto-detect)
//
// On most machines, this should stay empty. This allows you to override
// the directory in which the compressors and decompressors will be looked
// for. PHP defaults for this are almost always correct, and should rarely
// be overridden. Fill only if you have specific reason to do so.
define('DEFAULT_ALGORITHM_DIRECTORY', '');
/////////
//
// DEFAULT_MODE_DIRECTORY
// ----------------------
// default: '' (auto-detect)
//
// As above, but for block modes instead of compressors. Again, fill only
// if you have a specific reason to do so.
define('DEFAULT_MODE_DIRECTORY', '');
/////////
//
// DEFAULT_COMPRESSION_METHOD
// --------------------------
// default: false
//
// Here, you may set the library to compress by default when encrypting.
// Whether this is desirable has a lot to do with whether your server is
// already compressing somewhere else, whether you can afford the CPU time,
// whether the space is important, and so on. I leave this off by default
// because you can turn it on during use, but if you always use it, hell,
// just set it here.
//
// Standard values are [ 'gz' , 'gz_deflate' , 'bz' , false ].
//
// User may add new values in StonePhpSafeCrypt_compressors.php .
//
// A value of false skips default compression, which is probably best.
define('DEFAULT_COMPRESSION_METHOD', false);
?>

View file

@ -0,0 +1,234 @@
<?php
function PackCrypt(&$Data, $WeakKey, $options=array() ) {
$result = array(
'success' => false,
'reason' => 'Incomplete pack for unknown reason; indicates horrible failure.',
'output' => false
);
// load options
if (isset($options['cipher'])) { // Check whether user specified an alternate cipher in the options
$CipherType = $options['cipher']; // if so, use it
} else {
$CipherType = DEFAULT_ENCRYPTION_METHOD; // otherwise, use the default cipher
}
if (isset($options['mode'])) { // Check whether user specified an alternate block mode in the options
$mode = $options['mode']; // if so, use it
} else {
$mode = DEFAULT_ENCRYPTION_MODE; // otherwise, use the default block mode
}
if (isset($options['salt'])) { // Check whether user specified an alternate md5 salt in the options
$salt = $options['salt']; // if so, use it
} else {
$salt = DEFAULT_MD5_SALT; // otherwise, use the default salt
}
// do preparation
$SecretData = serialize($Data); // Convert data into a serialized string for single packing
$compressor = false;
global $compressors;
// handle potential compression
if (isset($options['compressor'])) {
if (isset($compressors[$options['compressor']])) {
$compressor = $compressors[$options['compressor']];
if (function_exists($compressor['encode']['fname'])) {
if (function_exists($compressor['decode']['fname'])) {
if (isset($compressor['encode']['args'])) {
if (isset($compressor['encode']['data_arg'])) {
$largs = $compressor['encode']['args'];
$largs[$compressor['encode']['data_arg']] = $SecretData;
$SecretData = call_user_func_array($compressor['encode']['fname'], $largs);
} else {
$result['reason'] = 'The requested compressor, "' . $options['compressor'] . '", requires an argument list; however the data argument has not been specified, making call impossible.';
return $result;
}
} else {
$SecretData = $compressor['encode']['fname']($SecretData);
}
} else {
$result['reason'] = 'The requested compressor, "' . $options['compressor'] . '", requires the decode function "' . $compressor['decode']['fname'] . '", which is not present in this PHP installation.';
return $result;
}
} else {
$result['reason'] = 'The requested compressor, "' . $options['compressor'] . '", requires the encode function "' . $compressor['encode']['fname'] . '", which is not present in this PHP installation.';
return $result;
}
} else {
$result['reason'] = 'The requested compressor, "' . $options['compressor'] . '", is not configured in this script.';
return $result;
}
}
// do work
$td = mcrypt_module_open($CipherType, '', $mode, ''); // Open the cipher module
$ks = mcrypt_enc_get_key_size($td); // Get required key size
$strongkey = substr(md5($salt . $WeakKey), 0, $ks); // Harden key data into safe key
$ivsz = mcrypt_enc_get_iv_size($td); // Get the size of the appropriate local initialization vector
// net2ftp - the 2nd argument of mcrypt_create_iv must be different on Unix and Windows
// Try first Unix, and if $iv is empty try Windows
// Use prefix @ to suppress PHP Warning messages
$iv = @mcrypt_create_iv($ivsz, MCRYPT_DEV_RANDOM); // Generate an initialization vector ** Unix **
if ($iv == "") {
$iv = @mcrypt_create_iv($ivsz, MCRYPT_RAND); // Generate an initialization vector ** Windows **
}
mcrypt_generic_init($td, $strongkey, $iv); // Init encryption engine
$encrypted = mcrypt_generic($td, $SecretData); // Perform encryption
mcrypt_generic_deinit($td); // Shut down encryption engine
mcrypt_module_close($td); // Close the cipher module
$IvDataPack = $iv . $encrypted; // Prepend the IV onto the data stream for convenient transfer
$result['output'] = BlockScramble($IvDataPack, $strongkey); // Return the IV prepended to the data stream, CBC tamper protected
$result['success'] = true;
$result['reason'] = 'Successful pack.';
return $result;
}
function UnpackCrypt(&$SecretData, $WeakKey, $options=array() ) {// $CipherType = 'tripledes', $mode = 'ofb') {
$result = array(
'success' => false,
'reason' => 'Incomplete unpack for unknown reason; indicates horrible failure.',
'output' => false
);
// load options
if (isset($options['cipher'])) { // Check whether user specified an alternate cipher in the options
$CipherType = $options['cipher']; // if so, use it
} else {
$CipherType = DEFAULT_ENCRYPTION_METHOD; // otherwise, use the default cipher
}
if (isset($options['mode'])) { // Check whether user specified an alternate block mode in the options
$mode = $options['mode']; // if so, use it
} else {
$mode = DEFAULT_ENCRYPTION_MODE; // otherwise, use the default block mode
}
if (isset($options['salt'])) { // Check whether user specified an alternate md5 salt in the options
$salt = $options['salt']; // if so, use it
} else {
$salt = DEFAULT_MD5_SALT; // otherwise, use the default salt
}
// do work
$td = mcrypt_module_open($CipherType, '', $mode, ''); // Open the cipher module
$ks = mcrypt_enc_get_key_size($td); // Get required key size
$strongkey = substr(md5($salt . $WeakKey), 0, $ks); // Regenerate hardened key from weak key
$DescrambleData = BlockDescramble($SecretData, $strongkey); // Remove leading-block CBC tampering attack protection
$ivsz = mcrypt_enc_get_iv_size($td); // Get the size of the appropriate local initialization vector
$iv = substr($DescrambleData, 0, $ivsz); // Recover the initialization vector
$WorkData = substr($DescrambleData, $ivsz); // Recover the data block
mcrypt_generic_init($td, $strongkey, $iv); // Init decryption engine
$decrypted = mdecrypt_generic($td, $WorkData); // Perform decryption
mcrypt_generic_deinit($td); // Shut down decryption engine
mcrypt_module_close($td); // Close the cipher module
// handle potential decompression
global $compressors;
$compressor = false;
if (isset($options['compressor'])) {
if (isset($compressors[$options['compressor']])) {
$compressor = $compressors[$options['compressor']];
if (function_exists($compressor['encode']['fname'])) {
if (function_exists($compressor['decode']['fname'])) {
if (isset($compressor['decode']['args'])) {
if (isset($compressor['decode']['data_arg'])) {
$largs = $compressor['decode']['args'];
$largs[$compressor['decode']['data_arg']] = $decrypted;
$decrypted = call_user_func_array($compressor['decode']['fname'], $largs);
} else {
$result['reason'] = 'The requested compressor, "' . $options['compressor'] . '", requires an argument list; however the data argument has not been specified, making call impossible.';
return $result;
}
} else {
$decrypted = $compressor['decode']['fname']($decrypted);
}
} else {
$result['reason'] = 'The requested compressor, "' . $options['compressor'] . '", requires the decode function "' . $compressor['decode']['fname'] . '", which is not present in this PHP installation.';
return $result;
}
} else {
$result['reason'] = 'The requested compressor, "' . $options['compressor'] . '", requires the encode function "' . $compressor['encode']['fname'] . '", which is not present in this PHP installation.';
return $result;
}
} else {
$result['reason'] = 'The requested compressor, "' . $options['compressor'] . '", is not configured in this script.';
return $result;
}
}
$result['success'] = true;
$result['reason'] = 'Successful unpack.';
$result['output'] = unserialize($decrypted); // Convert data from a serialized string and return
return $result;
}
?>

View file

@ -0,0 +1,9 @@
<?php
$forcefail = array('Apply' => false, 'Reason' => '');
if (DEFAULT_MD5_SALT === '') {
$forcefail['Apply'] = true;
$forcefail['Reason'] = 'You must set the default MD5 salt on line 83 before this library will function.';
}
?>

View file

@ -0,0 +1,749 @@
<?php
// -------------------------------------------------------------------------------
// | net2ftp: a web based FTP client |
// | Copyright (c) 2003-2013 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. |
// | |
// -------------------------------------------------------------------------------
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function encryptPassword($password) {
// --------------
// This function encrypts the FTP password
// --------------
// -------------------------------------------------------------------------
// Global variables and settings
// -------------------------------------------------------------------------
global $net2ftp_settings;
// -------------------------------------------------------------------------
// If mcrypt libraries are available, encrypt the password with the Stone PHP SafeCrypt library
// http://blog.sc.tri-bit.com/archives/101
// -------------------------------------------------------------------------
// if (function_exists("mcrypt_module_open") == true) {
// $packed = PackCrypt($password, DEFAULT_MD5_SALT);
// if ($packed["success"] == true) { return $packed["output"]; }
// else {
// setErrorVars(false, "An error occured when trying to encrypt the password: " . $packed["reason"], debug_backtrace(), __FILE__, __LINE__);
// }
// }
// -------------------------------------------------------------------------
// Else, XOR it with a random string
// -------------------------------------------------------------------------
// else {
$password_encrypted = "";
$encryption_string = sha1($net2ftp_settings["encryption_string"]);
if ($encryption_string % 2 == 1) { // we need even number of characters
$encryption_string .= $encryption_string{0};
}
for ($i=0; $i < strlen($password); $i++) { // encrypts one character - two bytes at once
$password_encrypted .= sprintf("%02X", hexdec(substr($encryption_string, 2*$i % strlen($encryption_string), 2)) ^ ord($password{$i}));
}
return $password_encrypted;
// }
} // End function encryptPassword
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function decryptPassword($password_encrypted) {
// --------------
// This function decrypts the FTP password
// --------------
// -------------------------------------------------------------------------
// Global variables and settings
// -------------------------------------------------------------------------
global $net2ftp_settings;
// -------------------------------------------------------------------------
// If mcrypt libraries are available, encrypt the password with the Stone PHP SafeCrypt library
// http://blog.sc.tri-bit.com/archives/101
// -------------------------------------------------------------------------
// if (function_exists("mcrypt_module_open") == true) {
// $unpacked = UnpackCrypt($password_encrypted, DEFAULT_MD5_SALT);
// if ($unpacked["success"] == true) { return $unpacked["output"]; }
// else {
// setErrorVars(false, "An error occured when trying to decrypt the password: " . $unpacked["reason"], debug_backtrace(), __FILE__, __LINE__);
// }
// }
// -------------------------------------------------------------------------
// Else, XOR it with a random string
// -------------------------------------------------------------------------
// else {
$password = "";
$encryption_string = sha1($net2ftp_settings["encryption_string"]);
if ($encryption_string % 2 == 1) { // we need even number of characters
$encryption_string .= $encryption_string{0};
}
for ($i=0; $i < strlen($password_encrypted); $i += 2) { // decrypts two bytes - one character at once
$password .= chr(hexdec(substr($encryption_string, $i % strlen($encryption_string), 2)) ^ hexdec(substr($password_encrypted, $i, 2)));
}
return $password;
// }
} // End function decryptPassword
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function checkIPinNetwork($ip, $network) {
// ----------
// This function checks if an IP address is part of a network
// If yes, it returns true; if no, it returns false
//
// The network's IP address range must be one of these notations:
// - Single IP (example: 192.168.1.1)
// - IP from-to (example: 192.168.1.1-192.168.1.10
// - CIDR notation (example: 192.168.1.0/30 or 192.168.1/30)
// ----------
$ip = trim($ip);
$network = trim($network);
$d = strpos($network,"-");
if ($d===false) {
$ip_arr = explode("/", $network);
if (!preg_match("@\d*\.\d*\.\d*\.\d*@", $ip_arr[0], $matches)){
$ip_arr[0] .= ".0"; // To handle networks like 192.168.1/30 (instead of 192.168.1.0/30)
}
$network_long = ip2long($ip_arr[0]);
$x = ip2long($ip_arr[1]);
$mask = long2ip($x) == $ip_arr[1] ? $x : (0xffffffff << (32 - $ip_arr[1]));
$ip_long = ip2long($ip);
return ($ip_long & $mask) == ($network_long & $mask);
}
else {
$from = ip2long(trim(substr($network,0,$d)));
$to = ip2long(trim(substr($network,$d+1)));
$ip = ip2long($ip);
return ($ip>=$from and $ip<=$to);
}
} // End function checkIPinNetwork
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function printLoginInfo() {
// --------------
// This function prints the ftpserver, username and login information
// --------------
global $net2ftp_globals;
echo "<input type=\"hidden\" name=\"ftpserver\" value=\"" . htmlEncode2($net2ftp_globals["ftpserver"]) . "\" />\n";
echo "<input type=\"hidden\" name=\"ftpserverport\" value=\"" . htmlEncode2($net2ftp_globals["ftpserverport"]) . "\" />\n";
echo "<input type=\"hidden\" name=\"username\" value=\"" . htmlEncode2($net2ftp_globals["username"]) . "\" />\n";
// echo "<input type=\"hidden\" name=\"password_encrypted\" value=\"" . htmlEncode2($net2ftp_globals["password_encrypted"]) . "\" />\n";
echo "<input type=\"hidden\" name=\"language\" value=\"" . htmlEncode2($net2ftp_globals["language"]) . "\" />\n";
echo "<input type=\"hidden\" name=\"skin\" value=\"" . htmlEncode2($net2ftp_globals["skin"]) . "\" />\n";
echo "<input type=\"hidden\" name=\"ftpmode\" value=\"" . htmlEncode2($net2ftp_globals["ftpmode"]) . "\" />\n";
echo "<input type=\"hidden\" name=\"passivemode\" value=\"" . htmlEncode2($net2ftp_globals["passivemode"]) . "\" />\n";
echo "<input type=\"hidden\" name=\"protocol\" value=\"" . htmlEncode2($net2ftp_globals["protocol"]) . "\" />\n";
echo "<input type=\"hidden\" name=\"viewmode\" value=\"" . htmlEncode2($net2ftp_globals["viewmode"]) . "\" />\n";
echo "<input type=\"hidden\" name=\"sort\" value=\"" . htmlEncode2($net2ftp_globals["sort"]) . "\" />\n";
echo "<input type=\"hidden\" name=\"sortorder\" value=\"" . htmlEncode2($net2ftp_globals["sortorder"]) . "\" />\n";
} // End function printLoginInfo
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function printLoginInfo_javascript() {
// --------------
// This function prints the ftpserver, username and login information -- for javascript input
// --------------
global $net2ftp_globals;
echo " d.writeln('<input type=\"hidden\" name=\"ftpserver\" value=\"" . javascriptEncode2($net2ftp_globals["ftpserver"]) . "\" />');\n";
echo " d.writeln('<input type=\"hidden\" name=\"ftpserverport\" value=\"" . javascriptEncode2($net2ftp_globals["ftpserverport"]) . "\" />');\n";
echo " d.writeln('<input type=\"hidden\" name=\"username\" value=\"" . javascriptEncode2($net2ftp_globals["username"]) . "\" />');\n";
// echo " d.writeln('<input type=\"hidden\" name=\"password_encrypted\" value=\"" . javascriptEncode2($net2ftp_globals["password_encrypted"]) . "\" />');\n";
echo " d.writeln('<input type=\"hidden\" name=\"language\" value=\"" . javascriptEncode2($net2ftp_globals["language"]) . "\" />');\n";
echo " d.writeln('<input type=\"hidden\" name=\"skin\" value=\"" . javascriptEncode2($net2ftp_globals["skin"]) . "\" />');\n";
echo " d.writeln('<input type=\"hidden\" name=\"ftpmode\" value=\"" . javascriptEncode2($net2ftp_globals["ftpmode"]) . "\" />');\n";
echo " d.writeln('<input type=\"hidden\" name=\"passivemode\" value=\"" . javascriptEncode2($net2ftp_globals["passivemode"]) . "\" />');\n";
echo " d.writeln('<input type=\"hidden\" name=\"protocol\" value=\"" . javascriptEncode2($net2ftp_globals["protocol"]) . "\" />');\n";
echo " d.writeln('<input type=\"hidden\" name=\"viewmode\" value=\"" . javascriptEncode2($net2ftp_globals["viewmode"]) . "\" />');\n";
echo " d.writeln('<input type=\"hidden\" name=\"sort\" value=\"" . javascriptEncode2($net2ftp_globals["sort"]) . "\" />');\n";
echo " d.writeln('<input type=\"hidden\" name=\"sortorder\" value=\"" . javascriptEncode2($net2ftp_globals["sortorder"]) . "\" />');\n";
} // End function printLoginInfo_javascript
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function printPHP_SELF($case) {
// --------------
// This function prints $PHP_SELF, the name of the script itself
// --------------
// -------------------------------------------------------------------------
// Global variables and settings
// -------------------------------------------------------------------------
global $net2ftp_globals, $net2ftp_settings;
$ftpserver = urlEncode2($net2ftp_globals["ftpserver"]);
$ftpserverport = urlEncode2($net2ftp_globals["ftpserverport"]);
$username = urlEncode2($net2ftp_globals["username"]);
$language = urlEncode2($net2ftp_globals["language"]);
$skin = urlEncode2($net2ftp_globals["skin"]);
$ftpmode = urlEncode2($net2ftp_globals["ftpmode"]);
$passivemode = urlEncode2($net2ftp_globals["passivemode"]);
$protocol = urlEncode2($net2ftp_globals["protocol"]);
$viewmode = urlEncode2($net2ftp_globals["viewmode"]);
$sort = urlEncode2($net2ftp_globals["sort"]);
$sortorder = urlEncode2($net2ftp_globals["sortorder"]);
$state_html = urlEncode2($net2ftp_globals["state"]);
$state2_html = urlEncode2($net2ftp_globals["state2"]);
$directory_html = urlEncode2($net2ftp_globals["directory"]);
$entry_html = urlEncode2($net2ftp_globals["entry"]);
if (isset($_SESSION["net2ftp_password_encrypted_" . $net2ftp_globals["ftpserver"] . $net2ftp_globals["username"]]) == true) {
$password_encrypted = urlEncode2($_SESSION["net2ftp_password_encrypted_" . $net2ftp_globals["ftpserver"] . $net2ftp_globals["username"]]);
}
elseif (isset($net2ftp_globals["password_encrypted"]) == true) {
$password_encrypted = urlEncode2($net2ftp_globals["password_encrypted"]);
}
else {
$password_encrypted = "";
}
// From /includes/registerglobals.inc.php
$URL = $net2ftp_globals["action_url"];
// If the URL already contains parameters (?param1=value1&amp;param2=value2...), append &amp;
// If not, append a ?
if (strpos($URL, "?") !== false) { $URL .= "&amp;"; }
else { $URL .= "?"; }
// Append further parameters
if ($case == "actions") {
$URL .= "ftpserver=$ftpserver&amp;ftpserverport=$ftpserverport&amp;username=$username&amp;language=$language&amp;skin=$skin&amp;ftpmode=$ftpmode&amp;passivemode=$passivemode&amp;protocol=$protocol&amp;viewmode=$viewmode&amp;sort=$sort&amp;sortorder=$sortorder";
}
// Bookmark with password: go straight to the bookmarked state
elseif ($case == "bookmark_withpw") {
$URL .= "ftpserver=$ftpserver&amp;amp;ftpserverport=$ftpserverport&amp;amp;username=$username&amp;amp;password_encrypted=$password_encrypted&amp;amp;language=$language&amp;amp;skin=$skin&amp;amp;ftpmode=$ftpmode&amp;amp;passivemode=$passivemode&amp;amp;protocol=$protocol&amp;amp;viewmode=$viewmode&amp;amp;sort=$sort&amp;amp;sortorder=$sortorder&amp;amp;state=$state_html&amp;amp;state2=$state2_html&amp;amp;directory=$directory_html&amp;amp;entry=$entry_html";
}
// Bookmark without password: go first to the login_small state to enter the password
elseif ($case == "bookmark_withoutpw") {
$URL .= "ftpserver=$ftpserver&amp;amp;ftpserverport=$ftpserverport&amp;amp;username=$username&amp;amp;language=$language&amp;amp;skin=$skin&amp;amp;ftpmode=$ftpmode&amp;amp;passivemode=$passivemode&amp;amp;protocol=$protocol&amp;amp;viewmode=$viewmode&amp;amp;sort=$sort&amp;amp;sortorder=$sortorder&amp;amp;state=login_small&amp;amp;state2=bookmark&amp;amp;go_to_state=$state_html&amp;amp;go_to_state2=$state2_html&amp;amp;directory=$directory_html&amp;amp;entry=$entry_html";
}
// Jupload java applet: the cookie information is added to the page using javascript (/skins/blue/jupload1.template.php)
elseif ($case == "jupload") {
$URL .= "ftpserver=$ftpserver&amp;ftpserverport=$ftpserverport&amp;username=$username&amp;language=$language&amp;skin=$skin&amp;ftpmode=$ftpmode&amp;passivemode=$passivemode&amp;protocol=$protocol&amp;directory=$directory_html&amp;state=jupload&amp;screen=2";
}
elseif ($case == "view") {
$URL .= "ftpserver=$ftpserver&amp;ftpserverport=$ftpserverport&amp;username=$username&amp;language=$language&amp;skin=$skin&amp;ftpmode=$ftpmode&amp;passivemode=$passivemode&amp;protocol=$protocol&amp;viewmode=$viewmode&amp;sort=$sort&amp;sortorder=$sortorder&amp;state=$state_html&amp;state2=image&amp;directory=$directory_html&amp;entry=$entry_html";
}
elseif ($case == "createDirectoryTreeWindow") {
$URL = $net2ftp_globals["application_rootdir_url"] . "/index.php";
}
// Change skin
elseif ($case == "defaultskin") {
$URL .= "ftpserver=$ftpserver&amp;ftpserverport=$ftpserverport&amp;username=$username&amp;language=$language&amp;skin=" . $net2ftp_settings["default_skin"] . "&amp;ftpmode=$ftpmode&amp;passivemode=$passivemode&amp;protocol=$protocol&amp;viewmode=$viewmode&amp;sort=$sort&amp;sortorder=$sortorder&amp;state=$state_html&amp;state2=$state2_html&amp;directory=$directory_html&amp;entry=$entry_html";
}
return $URL;
} // End function printPHP_SELF
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function checkAuthorization($ftpserver, $ftpserverport, $directory, $username) {
// --------------
// This function
// checks if the FTP server is in the list of those that may be accessed
// checks if the FTP server is in the list of those that may NOT be accessed
// checks if the IP address is in the list of banned IP addresses
// checks if the FTP server port is in the allowed range
// If all is OK, then the user may continue...
// --------------
// -------------------------------------------------------------------------
// Global variables
// -------------------------------------------------------------------------
global $net2ftp_globals, $net2ftp_settings, $net2ftp_result;
// -------------------------------------------------------------------------
// Check if the FTP server is in the list of those that may be accessed
// -------------------------------------------------------------------------
if ($net2ftp_settings["allowed_ftpservers"][1] != "ALL") {
$result1 = array_search($ftpserver, $net2ftp_settings["allowed_ftpservers"]);
if ($result1 == false) {
$errormessage = __("The FTP server <b>%1\$s</b> is not in the list of allowed FTP servers.", $ftpserver);
setErrorVars(false, $errormessage, debug_backtrace(), __FILE__, __LINE__);
return false;
}
}
// -------------------------------------------------------------------------
// Check if the FTP server is in the list of those that may NOT be accessed
// -------------------------------------------------------------------------
if (isset($net2ftp_settings["banned_ftpservers"][1]) == true && $net2ftp_settings["banned_ftpservers"][1] != "NONE") {
$result2 = array_search($ftpserver, $net2ftp_settings["banned_ftpservers"]);
if ($result2 != false) {
$errormessage = __("The FTP server <b>%1\$s</b> is in the list of banned FTP servers.", $ftpserver);
setErrorVars(false, $errormessage, debug_backtrace(), __FILE__, __LINE__);
return false;
}
}
// -------------------------------------------------------------------------
// Check if the FTP server port is OK
// -------------------------------------------------------------------------
// Do not perform this check if ALL ports are allowed
if ($net2ftp_settings["allowed_ftpserverport"] != "ALL" ) {
// Report the error if another port nr has been entered than the one which is allowed
if ($ftpserverport != $net2ftp_settings["allowed_ftpserverport"]) {
$errormessage = __("The FTP server port %1\$s may not be used.", $ftpserverport);
setErrorVars(false, $errormessage, debug_backtrace(), __FILE__, __LINE__);
return false;
}
}
// -------------------------------------------------------------------------
// Check if the IP address is in the list of those that may be used
// -------------------------------------------------------------------------
if ($net2ftp_settings["allowed_addresses"][1] != "ALL") {
$result3 = false;
for ($i=1; $i<=sizeof($net2ftp_settings["allowed_addresses"]); $i++) {
if (checkIPinNetwork($net2ftp_globals["REMOTE_ADDR"], $net2ftp_settings["allowed_addresses"][$i]) == true) { $result3 = true; }
}
if ($result3 == false) {
$errormessage = __("Your IP address (%1\$s) is not in the list of allowed IP addresses.", $net2ftp_globals["REMOTE_ADDR"]);
setErrorVars(false, $errormessage, debug_backtrace(), __FILE__, __LINE__);
return false;
}
}
// -------------------------------------------------------------------------
// Check if the IP address is in the list of those that may NOT be used
// -------------------------------------------------------------------------
if (isset($net2ftp_settings["banned_addresses"][1]) == true && $net2ftp_settings["banned_addresses"][1] != "NONE") {
$result4 = false;
for ($i=1; $i<=sizeof($net2ftp_settings["banned_addresses"]); $i++) {
if (checkIPinNetwork($net2ftp_globals["REMOTE_ADDR"], $net2ftp_settings["banned_addresses"][$i]) == true) { $result4 = true; }
}
if ($result4 != false) {
$errormessage = __("Your IP address (%1\$s) is in the list of banned IP addresses.", $net2ftp_globals["REMOTE_ADDR"]);
setErrorVars(false, $errormessage, debug_backtrace(), __FILE__, __LINE__);
return false;
}
}
// -------------------------------------------------------------------------
// Check if the directory is authorised:
// 1 - Whether the current $directory name contains a banned keyword.
// 2 - If the current $directory is a subdirectory of the homedirectory.
// The rootdirectory is first checked for the current user; if this is not set,
// the default rootdirectory is checked.
// -------------------------------------------------------------------------
$result4 = checkAuthorizedDirectory($directory);
if ($net2ftp_result["success"] == false) { return false; }
if ($result4 == false) {
$net2ftp_globals["directory"] = $net2ftp_globals["homedirectory"];
$net2ftp_globals["directory_html"] = htmlEncode2($net2ftp_globals["directory"]);
$net2ftp_globals["directory_js"] = javascriptEncode2($net2ftp_globals["directory"]);
if (strlen($net2ftp_globals["directory"]) > 0) { $net2ftp_globals["printdirectory"] = $net2ftp_globals["directory"]; }
else { $net2ftp_globals["printdirectory"] = "/"; }
}
// -------------------------------------------------------------------------
// If everything is OK, return true
// -------------------------------------------------------------------------
return true;
} // end checkAuthorization
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function checkAuthorizedDirectory($directory) {
// --------------
// 1 - This function checks whether the current $directory name contains a banned
// keyword.
// 2 - It also checks if the current $directory is a subdirectory of the
// homedirectory. The rootdirectory is first checked for the current user;
// if this is not set, the default rootdirectory is checked.
// --------------
// -------------------------------------------------------------------------
// Global variables
// -------------------------------------------------------------------------
global $net2ftp_globals, $net2ftp_settings, $net2ftp_result;
// -------------------------------------------------------------------------
// 1 - Check if the directory name contains a banned keyword
// -------------------------------------------------------------------------
if (checkAuthorizedName($directory) == false) { return false; }
// -------------------------------------------------------------------------
// 2 - Check if the directory is a subdirectory of the homedirectory (set in the DB)
// -------------------------------------------------------------------------
// ----------------------------------------------
// Initial checks
// ----------------------------------------------
if ($net2ftp_settings["use_database"] != "yes" || $net2ftp_settings["check_homedirectory"] != "yes") { return true; }
// ----------------------------------------------
// Get the homedirectory from the database, then store it in a global
// variable, and from then on, don't access the database any more
// ----------------------------------------------
$net2ftp_globals["homedirectory"] = getRootdirectory();
// ----------------------------------------------
// Check if the current directory is a subdirectory of the homedirectory
// ----------------------------------------------
if (isSubdirectory($net2ftp_globals["homedirectory"], $directory) == false) { return false; }
else { return true; }
} // end checkAuthorizedDirectory
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function checkAuthorizedName($dirfilename) {
// --------------
// This function checks if the directory/file/symlink name contains a forbidden keyword
// --------------
// -------------------------------------------------------------------------
// Global variables
// -------------------------------------------------------------------------
global $net2ftp_settings;
// -------------------------------------------------------------------------
// Check
// -------------------------------------------------------------------------
if (isset($net2ftp_settings["banned_keywords"][1]) == true && $net2ftp_settings["banned_keywords"][1] != "NONE") {
for ($i=1; $i<=sizeof($net2ftp_settings["banned_keywords"]); $i++) {
if (strpos($dirfilename, $net2ftp_settings["banned_keywords"][$i]) !== false) { return false; }
}
}
return true;
} // end checkAuthorizedName
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function getRootdirectory() {
// --------------
// This function gets the user's root directory from the database and
// stores it in $net2ftp_globals["homedirectory"].
//
// If $net2ftp_globals["homedirectory"] is already filled in (cache), no connection
// is made to the DB and this value is returned.
// --------------
// -------------------------------------------------------------------------
// Global variables
// -------------------------------------------------------------------------
global $net2ftp_globals, $net2ftp_settings, $net2ftp_result;
// -------------------------------------------------------------------------
// Initial checks
// -------------------------------------------------------------------------
if ($net2ftp_settings["use_database"] != "yes" || $net2ftp_settings["check_homedirectory"] != "yes") {
$net2ftp_globals["homedirectory"] = "/";
}
// -------------------------------------------------------------------------
// Get the homedirectory from the database, then store it in a global
// variable, and from then on, don't access the database any more
// -------------------------------------------------------------------------
if (isset($net2ftp_globals["homedirectory"]) == false) {
// -------------------------------------------------------------------------
// Add slashes to variables which are used in a SQL query, and which are
// potentially unsafe (supplied by the user)
// -------------------------------------------------------------------------
$net2ftp_ftpserver_safe = addslashes($net2ftp_globals["ftpserver"]);
$net2ftp_username_safe = addslashes($net2ftp_globals["username"]);
// -------------------------------------------------------------------------
// Connect
// -------------------------------------------------------------------------
$mydb = connect2db();
if ($net2ftp_result["success"] == false) { return false; }
// -------------------------------------------------------------------------
// Get user's home directory
// -------------------------------------------------------------------------
$sqlquery1 = "SELECT homedirectory FROM net2ftp_users WHERE ftpserver = '$net2ftp_ftpserver_safe' AND username = '$net2ftp_username_safe';";
$result1 = mysql_query("$sqlquery1") or die("Unable to execute SQL SELECT query (isAuthorizedDirectory > sqlquery1) <br /> $sqlquery1");
$nrofrows1 = mysql_num_rows($result1);
if ($nrofrows1 == 0) {
$net2ftp_globals["homedirectory"] = "/";
}
elseif ($nrofrows1 == 1) {
$resultRow1 = mysql_fetch_row($result1);
$net2ftp_globals["homedirectory"] = $resultRow1[0];
}
else {
setErrorVars(false, __("Table net2ftp_users contains duplicate rows."), debug_backtrace(), __FILE__, __LINE__);
return false;
}
}
return $net2ftp_globals["homedirectory"];
} // end getRootdirectory
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function isSubdirectory($parentdir, $childdir) {
// --------------
// Returns true if the childdir is a subdirectory of the parentdir
// --------------
// If the parentdir is empty or the root directory, then the childdir is
// a the same as or a subdirectory of the parentdir
if ($parentdir == "" || $parentdir == "/" || $parentdir == "\\") { return true; }
// Strip the directories of leading and trailing slashes
$parentdir = stripDirectory($parentdir);
$childdir = stripDirectory($childdir);
$parentdir_length = strlen($parentdir);
// Check if the first characters of the childdir are different from the
// parentdir. Example:
// parentdir: /home/abc
// childdir: /home/blabla ==> false
// childdir: /home/abcd ==> continue further checks
// childdir: /home/abc/xyz ==> continue further checks
$childdir_firstchars = substr($childdir, 0, $parentdir_length);
if ($childdir_firstchars != $parentdir) { return false; }
// If the first characters of the childdir are identical to the parentdir,
// check if the first next character of the childdir name is different.
// Example:
// parentdir: /home/abc
// childdir: /home/abcd ==> false
// childdir: /home/abc/xyz ==> true
$childdir_nextchar = substr($childdir, $parentdir_length, 1);
if ($childdir_nextchar != "/" && $childdir_nextchar != "\\") { return false; }
return true;
} // end isSubdirectory
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function checkAdminUsernamePassword() {
// --------------
// This function checks the Administrator username and password.
// If one of the two is not filled in or incorrect, a header() is sent
// to redirect the user to the login_small page.
// --------------
// -------------------------------------------------------------------------
// Global variables
// -------------------------------------------------------------------------
global $net2ftp_globals, $net2ftp_settings, $net2ftp_result;
$input_admin_username = $_POST["input_admin_username"];
$input_admin_password = $_POST["input_admin_password"];
// -------------------------------------------------------------------------
// Check Admin username and password
// -------------------------------------------------------------------------
// Set the error message depending on the case
// Redirect the user to the login_small page
// No username or password filled in
if ($input_admin_username == "" || $input_admin_password == "") {
$errormessage = htmlEncode2(__("You did not enter your Administrator username or password."));
header("Location: " . $net2ftp_globals["action_url"] . "?state=login_small&state2=admin&go_to_state=" . $net2ftp_globals["state"] . "&go_to_state2=" . $net2ftp_globals["state2"] . "&errormessage=" . $errormessage);
$net2ftp_result["exit"] = true;
return false;
}
// Wrong username or password
elseif ($input_admin_username != $net2ftp_settings["admin_username"] ||
$input_admin_password != $net2ftp_settings["admin_password"]) {
$errormessage = htmlEncode2(__("Wrong username or password. Please try again."));
header("Location: " . $net2ftp_globals["action_url"] . "?state=login_small&state2=admin&go_to_state=" . $net2ftp_globals["state"] . "&go_to_state2=" . $net2ftp_globals["state2"] . "&errormessage=" . $errormessage);
$net2ftp_result["exit"] = true;
return false;
}
return true;
} // end checkAdminUsernamePassword()
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
?>

View file

@ -0,0 +1,39 @@
<?php
// -------------------------------------------------------------------------------
// | net2ftp: a web based FTP client |
// | Copyright (c) 2003-2013 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. |
// | |
// -------------------------------------------------------------------------------
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function debug_backtrace() {
// --------------
// This function is defined when the PHP version is < 4.3.0
// --------------
return "There is no backtrace information available, because this websites runs an older version of PHP (before 4.3.0).";
} // end function debug_backtrace
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
?>

View file

@ -0,0 +1,876 @@
<?php
// -------------------------------------------------------------------------------
// | net2ftp: a web based FTP client |
// | Copyright (c) 2003-2013 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. |
// | |
// -------------------------------------------------------------------------------
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function ftp_getlist($conn_id, $directory) {
// --------------
// This function connects to the FTP server and returns an array with a list of directories and files.
// One row per directory or file, with rows from index 1 to n
//
// Step 1: send ftp_rawlist request to the FTP server; this returns a string
// Step 2: parse that string and get a first array ($templist)
// Step 3: move the rows to another array, to index 1 to n ($list)
//
// This function is used in all functions which process directories recursively.
// --------------
// -------------------------------------------------------------------------
// Global variables
// -------------------------------------------------------------------------
global $net2ftp_globals, $net2ftp_settings;
// -------------------------------------------------------------------------
// Initialization
// -------------------------------------------------------------------------
$warnings = "";
// -------------------------------------------------------------------------
// Step 1: Chdir to the directory and get the current directory
// -------------------------------------------------------------------------
// ----------------------------------------------
// Step 1a - Directory is "/"
// Chdir to the directory because otherwise the ftp_rawlist does not work on some FTP servers
// ----------------------------------------------
if ($directory == "/") {
$result1a = ftp_chdir($conn_id, $directory);
}
// ----------------------------------------------
// Step 1b - Directory is ""
// If the directory is "" then the user can be directed to his home directory
// We don't know which directory it is, so we request it from the FTP server
// ----------------------------------------------
elseif ($directory == "") {
$result1b = @ftp_chdir($conn_id, $directory);
$directory = ftp_pwd($conn_id);
}
// ----------------------------------------------
// Step 1c - Directory is not "/" or ""
// ----------------------------------------------
else {
// 1c1 - Replace \' by \\' to be able to delete directories with names containing \'
$directory1 = str_replace("\'", "\\\'", $directory);
// 1c2 - Chdir to the directory
// This is to check if the directory exists, but also because otherwise
// the ftp_rawlist does not work on some FTP servers.
$result1c = ftp_chdir($conn_id, $directory1);
// 1c3 - If the first ftp_chdir returns false, try a second time without the leading /
// Some Windows FTP servers do not work when you use a leading /
if ($result1c == false) {
$directory2 = stripDirectory($directory1);
$result2 = ftp_chdir($conn_id, $directory2);
// 1c3 - If the second ftp_chdir also does not work:
// For the Browse screen ==> go to the user's root directory
// For all other screens ==> return error
if ($result2 == false) {
if ($net2ftp_globals["state"] == "browse") {
$rootdirectory = getRootdirectory();
// User's root directory is different from the current directory, so switch to it
if ($directory != $rootdirectory) {
$warnings .= __("The directory <b>%1\$s</b> does not exist or could not be selected, so the directory <b>%2\$s</b> is shown instead.", $directory, $rootdirectory);
$directory = $rootdirectory;
$result3 = ftp_chdir($conn_id, $directory);
}
// The current directory *is* the user's root directory!
// We cannot display any other directory (like /), so print an error message.
else {
$errormessage = __("Your root directory <b>%1\$s</b> does not exist or could not be selected.", $directory);
setErrorVars(false, $errormessage, debug_backtrace(), __FILE__, __LINE__);
}
}
else {
$errormessage = __("The directory <b>%1\$s</b> could not be selected - you may not have sufficient rights to view this directory, or it may not exist.", $directory);
setErrorVars(false, $errormessage, debug_backtrace(), __FILE__, __LINE__);
}
} // end if result2
} // end if result1
} // end if / or "" or else
// -------------------------------------------------------------------------
// Step 2 - Get list of directories and files
// The -a option is used to show the hidden files as well on some FTP servers
// Some servers do not return anything when using -a, so in that case try again without the -a option
// -------------------------------------------------------------------------
$rawlist = ftp_rawlist($conn_id, "-a");
if (sizeof($rawlist) <= 1) { $rawlist = ftp_rawlist($conn_id, ""); }
// -------------------------------------------------------------------------
// Step 3 - Parse the raw list
// -------------------------------------------------------------------------
// ----------------------------------------------
// Initialize variables
// ----------------------------------------------
$list["directories"] = array();
$list["files"] = array();
$list["symlinks"] = array();
$list["unrecognized"] = array();
$directory_index = 1;
$file_index = 1;
$symlink_index = 1;
$unrecognized_index = 1;
$list["stats"]["directories"]["total_number"] = 0;
$list["stats"]["directories"]["total_size"] = 0;
$list["stats"]["directories"]["total_skipped"] = 0;
$list["stats"]["files"]["total_number"] = 0;
$list["stats"]["files"]["total_size"] = 0;
$list["stats"]["files"]["total_skipped"] = 0;
$list["stats"]["symlinks"]["total_number"] = 0;
$list["stats"]["symlinks"]["total_size"] = 0;
$list["stats"]["symlinks"]["total_skipped"] = 0;
$list["stats"]["unrecognized"]["total_number"] = 0;
$list["stats"]["unrecognized"]["total_size"] = 0;
$list["stats"]["unrecognized"]["total_skipped"] = 0;
// ----------------------------------------------
// Loop over the raw list lines
// ----------------------------------------------
$nr_entries_banned_keyword = 0;
$nr_entries_too_big = 0;
for($i=0; $i<sizeof($rawlist); $i++) {
// ----------------------------------------------
// Scan each line
// ----------------------------------------------
$listline = ftp_scanline($directory, $rawlist[$i]);
// If $listline is empty (e.g. if it contained ".."), continue to the next line
if ($listline == "") { continue; }
// Encode the name for HTML and Javascript
if (isset($listline["dirfilename"])) {
$listline["dirfilename_html"] = htmlEncode2($listline["dirfilename"]);
$listline["dirfilename_url"] = urlEncode2($listline["dirfilename"]);
$listline["dirfilename_js"] = javascriptEncode2($listline["dirfilename"]);
}
// Check if the filename contains a forbidden keyword
// If it does, then this line will not be selectable on the Browse screen
// Note: even if "selectable" is set to true here, it can still be set to false just below if the filesize is too big
if (checkAuthorizedName($listline["dirfilename"]) == true) { $listline["selectable"] = "ok"; }
else { $listline["selectable"] = "banned_keyword"; $nr_entries_banned_keyword++; }
// Check if the filesize is bigger than the maximum authorized filesize
if ($listline["dirorfile"] == "-" && isset($listline["size"]) && is_numeric($listline["size"])) {
if ($listline["selectable"] == "ok" && $listline["size"] > $net2ftp_settings["max_filesize"]) { $listline["selectable"] = "too_big"; $nr_entries_too_big++; }
}
// Form the new directory filename and encode it too
if ($listline["dirorfile"] == "d") {
$listline["newdir"] = glueDirectories($directory, $listline["dirfilename"]);
$listline["newdir_html"] = htmlEncode2($listline["newdir"]);
$listline["newdir_url"] = urlEncode2($listline["newdir"]);
$listline["newdir_js"] = javascriptEncode2($listline["newdir"]);
}
// ----------------------------------------------
// Depending on if the line contained a directory/file/symlink/unrecognized
// row, store the result in different variables
// ----------------------------------------------
if ($listline["dirorfile"] == "d") {
$list["directories"][$directory_index] = $listline;
$directory_index++;
if (isset($listline["size"]) && is_numeric($listline["size"])) {
$list["stats"]["directories"]["total_size"] = $list["stats"]["directories"]["total_size"] + $listline["size"];
}
else {
$list["stats"]["directories"]["total_skipped"] = $list["stats"]["directories"]["total_skipped"] + 1;
}
} // end if
elseif ($listline["dirorfile"] == "-") {
$list["files"][$file_index] = $listline;
$file_index++;
if (isset($listline["size"]) && is_numeric($listline["size"])) {
$list["stats"]["files"]["total_size"] = $list["stats"]["files"]["total_size"] + $listline["size"];
}
else {
$list["stats"]["files"]["total_skipped"] = $list["stats"]["files"]["total_skipped"] + 1;
}
} // end elseif
elseif ($listline["dirorfile"] == "l") {
$list["symlinks"][$symlink_index] = $listline;
$symlink_index++;
} // end elseif
elseif ($listline["dirorfile"] == "u") {
$list["unrecognized"][$unrecognized_index] = $listline;
$unrecognized_index++;
} // end elseif
} // end for
// Print a warning message if some directories, files or symlinks contain a banned keyword or if a file is
// too big to be downloaded
if ($nr_entries_banned_keyword > 0) {
$warnings .= __("Entries which contain banned keywords can't be managed using net2ftp. This is to avoid Paypal or Ebay scams from being uploaded through net2ftp.");
$warnings .= "<br />\n";
}
if ($nr_entries_too_big > 0) {
$warnings .= __("Files which are too big can't be downloaded, uploaded, copied, moved, searched, zipped, unzipped, viewed or edited; they can only be renamed, chmodded or deleted.");
$warnings .= "<br />\n";
}
// Store the warnings and new directory in $list["stats"]
if (isset($warnings) == true) { $list["stats"]["warnings"] = $warnings; }
else { $list["stats"]["warnings"] = ""; }
$list["stats"]["newdirectory"] = $directory;
// Store the statistics
$list["stats"]["directories"]["total_size_formated"] = formatFilesize($list["stats"]["directories"]["total_size"]);
$list["stats"]["files"]["total_size_formated"] = formatFilesize($list["stats"]["files"]["total_size"]);
$list["stats"]["directories"]["total_number"] = $directory_index - 1;
$list["stats"]["files"]["total_number"] = $file_index - 1;
$list["stats"]["symlinks"]["total_number"] = $symlink_index - 1;
$list["stats"]["unrecognized"]["total_number"] = $unrecognized_index - 1;
// Put everything together in $list["all"]
$list["all"] = $list["directories"] + $list["files"] + $list["symlinks"] + $list["unrecognized"];
// -------------------------------------------------------------------------
// Step 4 - Return the result
// -------------------------------------------------------------------------
return $list;
// -------------------------------------------------------------------------
// Some documentation:
// 1 - Some FTP servers return a total on the first line
// 2 - Some FTP servers return . and .. in their list of directories
// ftp_scanline does not return those entries.
// -------------------------------------------------------------------------
// 1 - After doing some tests on different public FTP servers, it appears that
// they reply differently to the ftp_rawlist request:
// - some FTP servers, like ftp.belnet.be, start with a line summarizing how
// many subdirectories and files there are in the current directory. The
// real list of subdirectories and files starts on the second line.
// [0] => total 15
// [1] => drwxr-xr-x 11 BELNET Archive 512 Feb 6 2000 BELNET
// [2] => drwxr-xr-x 2 BELNET Archive 512 Oct 29 2001 FVD-SFI
// - some other FTP servers, like ftp.redhat.com/pub, start directly with the
// list of subdirectories and files.
// [0] => drwxr-xr-x 9 ftp ftp 4096 Jan 11 06:34 contrib
// [1] => drwxr-xr-x 13 ftp ftp 4096 Jan 29 21:59 redhat
// [2] => drwxrwsr-x 6 ftp ftp 4096 Jun 05 2002 up2date
// 2 - Some FTP servers return "." and ".." as directories. These fake entries
// have to be eliminated!
// They would cause infinite loops in the copy/move/delete functions.
// [0] => drwxr-xr-x 5 80 www 512 Apr 10 09:39 .
// [1] => drwxr-xr-x 16 80 www 512 Apr 9 08:51 ..
// [2] => -rw-r--r-- 1 80 www 5647 Apr 9 08:12 _CHANGES_v0.5
// [3] => -rw-r--r-- 1 80 www 1239 Apr 9 08:12 _CREDITS_v0.5
} // End function ftp_getlist
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function ftp_scanline($directory, $rawlistline) {
// --------------
// This function scans an ftp_rawlist line string and returns its parts (directory/file, name, size,...) using preg_match()
//
// !!! Documentation about preg_match and FTP server's outputs are now at the end of the function !!!
// --------------
// -------------------------------------------------------------------------
// Global variables
// -------------------------------------------------------------------------
global $net2ftp_settings, $net2ftp_messages;
// -------------------------------------------------------------------------
// Scanning:
// 1. first scan with strict rules
// 2. if that does not match, scan with less strict rules
// 3. if that does not match, scan with rules for specific FTP servers (AS400)
// 4. and if that does not match, return the raw line
// -------------------------------------------------------------------------
// ----------------------------------------------
// 1. Strict rules
// ----------------------------------------------
if (preg_match("/([-dl])([rwxsStT-]{9})[ ]+([0-9]+)[ ]+([^ ]+)[ ]+(.+)[ ]+([0-9]+)[ ]+([a-zA-Z]+[ ]+[0-9]+)[ ]+([0-9:]+)[ ]+(.*)/", $rawlistline, $regs) == true) {
// permissions number owner group size month day year/hour filename
$listline["scanrule"] = "rule-1";
$listline["dirorfile"] = "$regs[1]"; // Directory ==> d, File ==> -
$listline["dirfilename"] = "$regs[9]"; // Filename
$listline["size"] = "$regs[6]"; // Size
$listline["owner"] = "$regs[4]"; // Owner
$listline["group"] = trim($regs[5]); // Group
$listline["permissions"] = "$regs[2]"; // Permissions
$listline["mtime"] = "$regs[7] $regs[8]"; // Mtime -- format depends on what FTP server returns (year, month, day, hour, minutes... see above)
}
// ----------------------------------------------
// 2. Less strict rules
// ----------------------------------------------
elseif (preg_match("/([-dl])([rwxsStT-]{9})[ ]+(.*)[ ]+([a-zA-Z0-9 ]+)[ ]+([0-9:]+)[ ]+(.*)/", $rawlistline, $regs) == true) {
// permissions number/owner/group/size
// month-day year/hour filename
$listline["scanrule"] = "rule-2";
$listline["dirorfile"] = "$regs[1]"; // Directory ==> d, File ==> -
$listline["dirfilename"] = "$regs[6]"; // Filename
$listline["size"] = "$regs[3]"; // Number/Owner/Group/Size
$listline["permissions"] = "$regs[2]"; // Permissions
$listline["mtime"] = "$regs[4] $regs[5]"; // Mtime -- format depends on what FTP server returns (year, month, day, hour, minutes... see above)
}
// ----------------------------------------------
// 3. Specific FTP server rules
// ----------------------------------------------
// ---------------
// 3.1 Windows
// ---------------
elseif (preg_match("/([0-9\\/-]+)[ ]+([0-9:AMP]+)[ ]+([0-9]*|<DIR>)[ ]+(.*)/", $rawlistline, $regs) == true) {
// date time size filename
$listline["scanrule"] = "rule-3.1";
if ($regs[3] == "<DIR>") { $listline["size"] = ""; }
else { $listline["size"] = "$regs[3]"; } // Size
$listline["dirfilename"] = "$regs[4]"; // Filename
$listline["owner"] = ""; // Owner
$listline["group"] = ""; // Group
$listline["permissions"] = ""; // Permissions
$listline["mtime"] = "$regs[1] $regs[2]"; // Mtime -- format depends on what FTP server returns (year, month, day, hour, minutes... see above)
if ($listline["size"] != "") { $listline["dirorfile"] = "-"; }
else { $listline["dirorfile"] = "d"; }
}
// ---------------
// 3.2 Netware
// Thanks to Danny!
// ---------------
elseif (preg_match("/([-]|[d])[ ]+(.{10})[ ]+([^ ]+)[ ]+([0-9]*)[ ]+([a-zA-Z]*[ ]+[0-9]*)[ ]+([0-9:]*)[ ]+(.*)/", $rawlistline, $regs) == true) {
// dir/file perms owner size month day hour filename
$listline["scanrule"] = "rule-3.2";
$listline["dirorfile"] = "$regs[1]"; // Directory ==> d, File ==> -
$listline["dirfilename"] = "$regs[7]"; // Filename
$listline["size"] = "$regs[4]"; // Size
$listline["owner"] = "$regs[3]"; // Owner
$listline["group"] = ""; // Group
$listline["permissions"] = "$regs[2]"; // Permissions
$listline["mtime"] = "$regs[5] $regs6"; // Mtime -- format depends on what FTP server returns (year, month, day, hour, minutes... see above)
}
// ---------------
// 3.3 AS400
// ---------------
elseif (preg_match("/([a-zA-Z0-9_-]+)[ ]+([0-9]+)[ ]+([0-9\\/-]+)[ ]+([0-9:]+)[ ]+([a-zA-Z0-9_ -\*]+)[ \\/]+([^\\/]+)/", $rawlistline, $regs) == true) {
// owner size date time type filename
if ($regs[5] != "*STMF") { $directory_or_file = "d"; }
elseif ($regs[5] == "*STMF") { $directory_or_file = "-"; }
$listline["scanrule"] = "rule-3.3";
$listline["dirorfile"] = "$directory_or_file";// Directory ==> d, File ==> -
$listline["dirfilename"] = "$regs[6]"; // Filename
$listline["size"] = "$regs[2]"; // Size
$listline["owner"] = "$regs[1]"; // Owner
$listline["group"] = ""; // Group
$listline["permissions"] = ""; // Permissions
$listline["mtime"] = "$regs[3] $regs[4]"; // Mtime -- format depends on what FTP server returns (year, month, day, hour, minutes... see above)
}
// ---------------
// 3.4 Titan
// Owner, group are modified compared to rule 1
// TO DO: integrate this rule in rule 1 itself
// ---------------
elseif (preg_match("/([-dl])([rwxsStT-]{9})[ ]+([0-9]+)[ ]+([a-zA-Z0-9]+)[ ]+([a-zA-Z0-9]+)[ ]+([0-9]+)[ ]+([a-zA-Z]+[ ]+[0-9]+)[ ]+([0-9:]+)[ ](.*)/", $rawlistline, $regs) == true) {
// dir/file permissions number owner group size month date time file
$listline["scanrule"] = "rule-3.4";
$listline["dirorfile"] = "$regs[1]"; // Directory ==> d, File ==> -
$listline["dirfilename"] = "$regs[9]"; // Filename
$listline["size"] = "$regs[6]"; // Size
$listline["owner"] = "$regs[4]"; // Owner
$listline["group"] = "$regs[5]"; // Group
$listline["permissions"] = "$regs[2]"; // Permissions
$listline["mtime"] = "$regs[7] $regs[8]"; // Mtime -- format depends on what FTP server returns (year, month, day, hour, minutes... see above)
}
// ----------------------------------------------
// 4. If nothing matchs, return the raw line
// ----------------------------------------------
else {
$listline["scanrule"] = "rule-4";
$listline["dirorfile"] = "u";
$listline["dirfilename"] = $rawlistline;
}
// -------------------------------------------------------------------------
// Remove the . and .. entries
// Remove the total line that some servers return
// -------------------------------------------------------------------------
if ($listline["dirfilename"] == "." || $listline["dirfilename"] == "..") { return ""; }
elseif (substr($rawlistline,0,5) == "total") { return ""; }
// -------------------------------------------------------------------------
// And finally... return the nice list!
// -------------------------------------------------------------------------
return $listline;
// -------------------------------------------------------------------------
// Documentation
// -------------------------------------------------------------------------
/*
mholdgate@wakefield.co.uk
11-Jan-2002 11:51
^ Start of String
$ End of string
n* Zero or more of 'n'
n+ One or more of 'n'
n? A possible 'n'
n{2} Exactly two of 'n'
n{2,} At least 2 or more of 'n'
n{2,4} From 2 to 4 of 'n'
() Parenthesis to group expressions
(n|a) Either 'n' or 'a'
. Any single character
[1-6] A number between 1 and 6
[c-h] A lower case character between c and h
[D-M] An upper case character between D and M
[^a-z] Absence of lower case a to z
[_a-zA-Z] An underscore or any letter of the alphabet
^.{2}[a-z]{1,2}_?[0-9]*([1-6]|[a-f])[^1-9]{2}a+$
A string beginning with any two characters
Followed by either 1 or 2 lower case alphabet letters
Followed by an optional underscore
Followed by zero or more digits
Followed by either a number between 1 and 6 or a character between a and f (Lowercase)
Followed by a two characters which are not digits between 1 and 9
Followed by one or more n characters at the end of a string
// $regs can contain a maximum of 10 elements !! (regs[0] to regs[9])
// To specify what you really want back from ereg, use (). Only what is within () will be returned. See below.
*/
// ----------------------------------------------
// Sample FTP server's output
// ----------------------------------------------
// ---------------
// 1. "Standard" FTP servers output
// ---------------
// ftp.redhat.com
//drwxr-xr-x 6 0 0 4096 Aug 21 2001 pub (one or more spaces between entries)
//
// ftp.suse.com
//drwxr-xr-x 2 root root 4096 Jan 9 2001 bin
//-rw-r--r-- 1 suse susewww 664 May 23 16:24 README.txt
//
// ftp.belnet.be
//-rw-r--r-- 1 BELNET Mirror 162 Aug 6 2000 HEADER.html
//drwxr-xr-x 53 BELNET Archive 2048 Nov 13 12:03 mirror
//
// ftp.microsoft.com
//-r-xr-xr-x 1 owner group 0 Nov 27 2000 dirmap.htm
//
// ftp.sourceforge.net
//-rw-r--r-- 1 root staff 29136068 Apr 21 22:07 ls-lR.gz
//
// ftp.nec.com
//dr-xr-xr-x 12 other 512 Apr 3 2002 pub
//
// ftp.intel.com
//drwxr-sr-x 11 root ftp 4096 Sep 23 16:36 pub
// ---------------
// 3.1 Windows
// ---------------
//06-10-04 07:56PM 8175 garantie.html
//04-09-04 04:27PM <DIR> images
//05-25-04 09:18AM 9505 index.html
// ---------------
// 3.2 Netware
// ---------------
// total 0
// - [RWCEAFMS] USER 12 Mar 08 10:48 check.txt
// d [RWCEAFMS] USER 512 Mar 18 17:55 latest
// ---------------
// 3.3 AS400
// ---------------
// RGOVINDAN 932 03/29/01 14:59:53 *STMF /cert.txt
// QSYS 77824 12/17/01 15:33:14 *DIR /QOpenSys/
// QDOC 24576 12/31/69 20:00:00 *FLR /QDLS/
// QSYS 12832768 04/14/03 16:47:25 *LIB /QSYS.LIB/
// QDFTOWN 2147483647 12/31/69 20:00:00 *DDIR /QOPT/
// QSYS 2144 04/12/03 12:49:00 *DDIR /QFileSvr.400/
// QDFTOWN 1136 04/12/03 12:49:01 *DDIR /QNTC/
// ---------------
// 3.4 Titan FTP server
// ---------------
// total 6
// drwxrwx--- 1 owner group 512 Apr 19 11:44 .
// drwxrwx--- 1 owner group 512 Apr 19 11:44 ..
// -rw-rw---- 1 owner group 13171 Apr 15 13:50 default.asp
// drwxrwx--- 1 owner group 512 Apr 19 11:44 forum
// drwxrwx--- 1 owner group 512 Apr 15 13:32 images
// -rw-rw---- 1 owner group 764 Apr 15 11:07 styles.css
} // End function ftp_scanline
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function ftp2http($directory, $list_files, $htmltags) {
// --------------
// This function calculates the HTTP URL based on the FTP URL
//
// Given the FTP server (ftp.name.com),
// the directory and file (/directory/file.php)
// It has to return
// http://www.name.com/directory/file.php
//
// $htmltags indicates whether the url should be returned enclosed in HTML tags or not
//
// For efficiency reasons, this function processes a list of files
// --------------
// -------------------------------------------------------------------------
// Global variables
// -------------------------------------------------------------------------
global $net2ftp_globals;
// -------------------------------------------------------------------------
// If no list is supplied, return ""
// -------------------------------------------------------------------------
if (sizeof($list_files) == 0) { return ""; }
// -------------------------------------------------------------------------
// Prepare the variables
// -------------------------------------------------------------------------
// Directory
if ($directory == "/") { $directory = ""; }
// Convert single quotes from ' to &#039;
if ($htmltags == "no") { $directory = javascriptEncode2($directory); }
else { $directory = urlEncode2($directory); }
// Filenames
if ($htmltags == "no") { $encoding = "dirfilename_js"; }
else { $encoding = "dirfilename_url"; }
// Username
if ($htmltags == "no") { $username = javascriptEncode2($net2ftp_globals["username"]); }
else { $username = htmlEncode2($net2ftp_globals["username"]); }
// -------------------------------------------------------------------------
// "ftp.t35.com" -----> "http://username" (username = username.t35.com)
// "ftp.t35.net" -----> "http://username" (username = username.t35.net)
// -------------------------------------------------------------------------
if (strpos($net2ftp_globals["ftpserver"], "ftp.t35") !== false) {
for ($i=1; $i<=sizeof($list_files); $i++) {
$URL = "http://" . $username . $directory . "/" . $list_files[$i][$encoding];
if ($htmltags == "no") { $list_links[$i] = $URL; }
else { $list_links[$i] = "<a href=\"" . $URL . "\" target=\"_blank\" title=\"" . __("Execute %1\$s in a new window", $list_files[$i][$encoding]) . "\">" . $list_files[$i][$encoding] . "</a>"; }
} // end for
}
// -------------------------------------------------------------------------
// "ftp-www.earthlink.net/webdocs/directory" -----> "http://home.earthlink.net/~username/directory"
// -------------------------------------------------------------------------
elseif (strpos($net2ftp_globals["ftpserver"], "ftp-www.earthlink.net") !== false) {
if (strlen($directory) < 8) {
for ($i=1; $i<=sizeof($list_files); $i++) {
if ($htmltags == "no") { $list_links[$i] = "javascript:alert('" . __("This file is not accessible from the web") . "');"; }
else { $list_links[$i] = "<a title=\"" . __("This file is not accessible from the web") . "\" onclick=\"alert('" . __("This file is not accessible from the web") . "');\">" . $list_files[$i][$encoding] . "</a>"; }
} // end for
}
else {
// Transform directory from /webdocs/dir to /dir --> remove the first 4 characters
$directory = substr($directory, 8);
for ($i=1; $i<=sizeof($list_files); $i++) {
$URL = "http://home.earthlink.net/~" . $username . $directory . "/" . $list_files[$i][$encoding];
if ($htmltags == "no") { $list_links[$i] = $URL; }
else { $list_links[$i] = "<a href=\"" . $URL . "\" target=\"_blank\" title=\"" . __("Execute %1\$s in a new window", $list_files[$i][$encoding]) . "\">" . $list_files[$i][$encoding] . "</a>"; }
} // end for
} // end if else strlen
}
// -------------------------------------------------------------------------
// "ftpperso.free.fr" -----> "http://username.free.fr"
// -------------------------------------------------------------------------
elseif (strpos($net2ftp_globals["ftpserver"], "ftpperso.free.fr") !== false) {
for ($i=1; $i<=sizeof($list_files); $i++) {
$URL = "http://" . $username . ".free.fr" . $directory . "/" . $list_files[$i][$encoding];
if ($htmltags == "no") { $list_links[$i] = $URL; }
else { $list_links[$i] = "<a href=\"" . $URL . "\" target=\"_blank\" title=\"" . __("Execute %1\$s in a new window", $list_files[$i][$encoding]) . "\">" . $list_files[$i][$encoding] . "</a>"; }
} // end for
}
// -------------------------------------------------------------------------
// "ftp.membres.lycos.fr" -----> "http://membres.lycos.fr/username"
// -------------------------------------------------------------------------
elseif (strpos($net2ftp_globals["ftpserver"],"ftp.membres.lycos.fr") !== false) {
for ($i=1; $i<=sizeof($list_files); $i++) {
$URL = "http://membres.lycos.fr/" . $username . $directory . "/" . $list_files[$i][$encoding];
if ($htmltags == "no") { $list_links[$i] = $URL; }
else { $list_links[$i] = "<a href=\"" . $URL . "\" target=\"_blank\" title=\"" . __("Execute %1\$s in a new window", $list_files[$i][$encoding]) . "\">" . $list_files[$i][$encoding] . "</a>"; }
} // end for
}
// -------------------------------------------------------------------------
// "home.planetinternet.be" -----> "http://home.planetinternet.be/~username"
// -------------------------------------------------------------------------
elseif (strpos($net2ftp_globals["ftpserver"], "home.planetinternet.be") !== false) {
for ($i=1; $i<=sizeof($list_files); $i++) {
$URL = "http://home.planetinternet.be/~" . $username . $directory . "/" . $list_files[$i][$encoding];
if ($htmltags == "no") { $list_links[$i] = $URL; }
else { $list_links[$i] = "<a href=\"" . $URL . "\" target=\"_blank\" title=\"" . __("Execute %1\$s in a new window", $list_files[$i][$encoding]) . "\">" . $list_files[$i][$encoding] . "</a>"; }
} // end for
}
// -------------------------------------------------------------------------
// "home.planet.nl" -----> "http://home.planet.nl/~username"
// -------------------------------------------------------------------------
elseif (strpos($net2ftp_globals["ftpserver"], "home.planet.nl") !== false) {
for ($i=1; $i<=sizeof($list_files); $i++) {
$URL = "http://home.planet.nl/~" . $username . $directory . "/" . $list_files[$i][$encoding];
if ($htmltags == "no") { $list_links[$i] = $URL; }
else { $list_links[$i] = "<a href=\"" . $URL . "\" target=\"_blank\" title=\"" . __("Execute %1\$s in a new window", $list_files[$i][$encoding]) . "\">" . $list_files[$i][$encoding] . "</a>"; }
} // end for
}
// -------------------------------------------------------------------------
// "users.skynet.be" -----> "http://users.skynet.be/username"
// -------------------------------------------------------------------------
elseif (strpos($net2ftp_globals["ftpserver"], "users.skynet.be") !== false) {
for ($i=1; $i<=sizeof($list_files); $i++) {
$URL = "http://users.skynet.be/" . $username . $directory . "/" . $list_files[$i][$encoding];
if ($htmltags == "no") { $list_links[$i] = $URL; }
else { $list_links[$i] = "<a href=\"" . $URL . "\" target=\"_blank\" title=\"" . __("Execute %1\$s in a new window", $list_files[$i][$encoding]) . "\">" . $list_files[$i][$encoding] . "</a>"; }
} // end for
}
// -------------------------------------------------------------------------
// "ftp.tripod.com" -----> "http://username.tripod.com"
// -------------------------------------------------------------------------
elseif (strpos($net2ftp_globals["ftpserver"], "ftp.tripod.com") !== false) {
for ($i=1; $i<=sizeof($list_files); $i++) {
$URL = "http://" . $username . ".tripod.com" . $directory . "/" . $list_files[$i][$encoding];
if ($htmltags == "no") { $list_links[$i] = $URL; }
else { $list_links[$i] = "<a href=\"" . $URL . "\" target=\"_blank\" title=\"" . __("Execute %1\$s in a new window", $list_files[$i][$encoding]) . "\">" . $list_files[$i][$encoding] . "</a>"; }
} // end for
}
// -------------------------------------------------------------------------
// "ftp.wanadoo.es" -----> "http://perso.wanadoo.es/username"
// -------------------------------------------------------------------------
elseif (strpos($net2ftp_globals["ftpserver"], "ftp.wanadoo.es") !== false) {
for ($i=1; $i<=sizeof($list_files); $i++) {
$URL = "http://perso.wanadoo.es/" . $username . $directory . "/" . $list_files[$i][$encoding];
if ($htmltags == "no") { $list_links[$i] = $URL; }
else { $list_links[$i] = "<a href=\"" . $URL . "\" target=\"_blank\" title=\"" . __("Execute %1\$s in a new window", $list_files[$i][$encoding]) . "\">" . $list_files[$i][$encoding] . "</a>"; }
} // end for
}
// -------------------------------------------------------------------------
// "perso-ftp.wanadoo.fr" -----> "http://perso.wanadoo.fr/username"
// -------------------------------------------------------------------------
elseif (strpos($net2ftp_globals["ftpserver"], "perso-ftp.wanadoo.fr") !== false) {
for ($i=1; $i<=sizeof($list_files); $i++) {
$URL = "http://perso.wanadoo.fr/" . $username . $directory . "/" . $list_files[$i][$encoding];
if ($htmltags == "no") { $list_links[$i] = $URL; }
else { $list_links[$i] = "<a href=\"" . $URL . "\" target=\"_blank\" title=\"" . __("Execute %1\$s in a new window", $list_files[$i][$encoding]) . "\">" . $list_files[$i][$encoding] . "</a>"; }
} // end for
}
// -------------------------------------------------------------------------
// "home.wanadoo.nl" -----> "http://home.wanadoo.nl/username"
// -------------------------------------------------------------------------
elseif (strpos($net2ftp_globals["ftpserver"], "home.wanadoo.nl") !== false) {
for ($i=1; $i<=sizeof($list_files); $i++) {
$URL = "http://home.wanadoo.nl/" . $username . $directory . "/" . $list_files[$i][$encoding];
if ($htmltags == "no") { $list_links[$i] = $URL; }
else { $list_links[$i] = "<a href=\"" . $URL . "\" target=\"_blank\" title=\"" . __("Execute %1\$s in a new window", $list_files[$i][$encoding]) . "\">" . $list_files[$i][$encoding] . "</a>"; }
} // end for
}
// -------------------------------------------------------------------------
// wanadoo uk
// "uploads.webspace.freeserve.net" -----> "http://www.username.freeserve.co.uk"
// -------------------------------------------------------------------------
elseif (strpos($net2ftp_globals["ftpserver"], "uploads.webspace.freeserve.net") !== false) {
for ($i=1; $i<=sizeof($list_files); $i++) {
$URL = "http://www." . $username . ".freeserve.co.uk" . $directory . "/" . $list_files[$i][$encoding];
if ($htmltags == "no") { $list_links[$i] = $URL; }
else { $list_links[$i] = "<a href=\"" . $URL . "\" target=\"_blank\" title=\"" . __("Execute %1\$s in a new window", $list_files[$i][$encoding]) . "\">" . $list_files[$i][$encoding] . "</a>"; }
} // end for
}
// -------------------------------------------------------------------------
// "ftp.xs4all.nl/WWW/directory" -----> "http://www.xs4all.nl/~username/directory"
// -------------------------------------------------------------------------
elseif (strpos($net2ftp_globals["ftpserver"], "ftp.xs4all.nl") !== false) {
if (strlen($directory) < 4) {
for ($i=1; $i<=sizeof($list_files); $i++) {
if ($htmltags == "no") { $list_links[$i] = "javascript:alert('" . __("This file is not accessible from the web") . "');"; }
else { $list_links[$i] = "<a title=\"" . __("This file is not accessible from the web") . "\" onclick=\"alert('" . __("This file is not accessible from the web") . "');\">" . $list_files[$i][$encoding] . "</a>"; }
} // end for
}
else {
// Transform directory from /WWW/dir to /dir --> remove the first 4 characters
$directory = substr($directory, 4);
for ($i=1; $i<=sizeof($list_files); $i++) {
$URL = "http://www.xs4all.nl/~" . $username . $directory . "/" . $list_files[$i][$encoding];
if ($htmltags == "no") { $list_links[$i] = $URL; }
else { $list_links[$i] = "<a href=\"" . $URL . "\" target=\"_blank\" title=\"" . __("Execute %1\$s in a new window", $list_files[$i][$encoding]) . "\">" . $list_files[$i][$encoding] . "</a>"; }
} // end for
}
}
// -------------------------------------------------------------------------
// "ftp.server.com/directory/file" -----> "http://www.server.com/directory/file"
// -------------------------------------------------------------------------
elseif (preg_match("/ftp.(.+)(.{2,4})/", $net2ftp_globals["ftpserver"], $regs)) {
// Check if the FTP directory contains "htdocs", "httpdocs" or "public_html"
// If it does, the HTTP directory root starts from there on
// Example: /srv/www/htdocs/directory1 ==> /directory1
$specialdirectories[1] = "htdocs";
$specialdirectories[2] = "httpdocs";
$specialdirectories[3] = "public_html";
for ($i=1; $i<=sizeof($specialdirectories); $i++) {
$pos = strpos($directory, $specialdirectories[$i]);
if ($pos !== false) {
$directory = substr($directory, $pos + strlen($specialdirectories[$i]));
break;
}
}
// Calculate all the URLs on the Browse screen
for ($i=1; $i<=sizeof($list_files); $i++) {
$URL = "http://www." . $regs[1] . $regs[2] . $directory . "/" . $list_files[$i][$encoding];
if ($htmltags == "no") { $list_links[$i] = $URL; }
else { $list_links[$i] = "<a href=\"" . $URL . "\" target=\"_blank\" title=\"" . __("Execute %1\$s in a new window", $list_files[$i][$encoding]) . "\">" . $list_files[$i][$encoding] . "</a>"; }
} // end for
}
// -------------------------------------------------------------------------
// "http://192.168.0.1/directory/file" can be determined using "192.168.0.1/directory/file":
// -------------------------------------------------------------------------
else {
// Check if the FTP directory contains "htdocs", "httpdocs" or "public_html"
// If it does, the HTTP directory root starts from there on
// Example: /srv/www/htdocs/directory1 ==> /directory1
$specialdirectories[1] = "htdocs";
$specialdirectories[2] = "httpdocs";
$specialdirectories[3] = "public_html";
for ($i=1; $i<=sizeof($specialdirectories); $i++) {
$pos = strpos($directory, $specialdirectories[$i]);
if ($pos !== false) {
$directory = substr($directory, $pos + strlen($specialdirectories[$i]));
break;
}
}
// Calculate all the URLs on the Browse screen
for ($i=1; $i<=sizeof($list_files); $i++) {
$URL = "http://" . $net2ftp_globals["ftpserver"]. $directory . "/" . $list_files[$i][$encoding];
if ($htmltags == "no") { $list_links[$i] = $URL; }
else { $list_links[$i] = "<a href=\"" . $URL . "\" target=\"_blank\" title=\"" . __("Execute %1\$s in a new window", $list_files[$i][$encoding]) . "\">" . $list_files[$i][$encoding] . "</a>"; }
} // end for
}
return $list_links;
} // end function ftp2http
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
?>

View file

@ -0,0 +1,529 @@
<?php
// -------------------------------------------------------------------------------
// | net2ftp: a web based FTP client |
// | Copyright (c) 2003-2013 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_log_consumption_ipaddress: date, ipaddress, datatransfer, executiontime
net2ftp_log_consumption_ftpserver: 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, script execution time and number of FTP
servers that were accessed. 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 $net2ftp_globals, $net2ftp_settings, $net2ftp_result;
// -------------------------------------------------------------------------
// Initial checks
// -------------------------------------------------------------------------
// Verify if a database is used, and if consumption checking is turned on. If not: don't continue.
if ($net2ftp_settings["use_database"] != "yes" || $net2ftp_settings["check_consumption"] != "yes") { return true; }
// When user is not logged in, the FTP server is not set
if ($net2ftp_globals["ftpserver"] == "") { return true; }
// If the REMOTE_ADDR is not filled in, then there is a problem (IP spoofing), so return an error
if ($net2ftp_globals["REMOTE_ADDR"] == "") {
setErrorVars(false, __("Unable to determine your IP address."), debug_backtrace(), __FILE__, __LINE__);
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($net2ftp_globals["REMOTE_ADDR"]);
$net2ftp_ftpserver_safe = addslashes($net2ftp_globals["ftpserver"]);
// ----------------------------------------------
// Do not log accesses, errors and consumption while the logs are being rotated
// ----------------------------------------------
$logStatus = getLogStatus();
if ($net2ftp_result["success"] == false) { return false; }
if ($logStatus != 0) { return true; }
// -------------------------------------------------------------------------
// Set the change flags to the initial value
// -------------------------------------------------------------------------
$net2ftp_globals["consumption_datatransfer_changeflag"] = 0;
$net2ftp_globals["consumption_database_updated"] = 0;
// -------------------------------------------------------------------------
// Get date
// -------------------------------------------------------------------------
$date = date("Y-m-d");
// -------------------------------------------------------------------------
// Connect
// -------------------------------------------------------------------------
$mydb = connect2db();
if ($net2ftp_result["success"] == false) { return false; }
// -------------------------------------------------------------------------
// Get consumed data volume and execution time by the current IP address
// -------------------------------------------------------------------------
$sqlquery1 = "SELECT datatransfer, executiontime FROM net2ftp_log_consumption_ipaddress 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) {
$net2ftp_globals["consumption_ipaddress_datatransfer"] = 0;
$net2ftp_globals["consumption_ipaddress_executiontime"] = 0;
}
elseif ($nrofrows1 == 1) {
$resultRow1 = mysql_fetch_row($result1);
$net2ftp_globals["consumption_ipaddress_datatransfer"] = $resultRow1[0];
$net2ftp_globals["consumption_ipaddress_executiontime"] = $resultRow1[1];
}
else {
setErrorVars(false, __("Table net2ftp_log_consumption_ipaddress contains duplicate rows."), debug_backtrace(), __FILE__, __LINE__);
return false;
}
// -------------------------------------------------------------------------
// Get consumed data volume and execution time to the current FTP server
// -------------------------------------------------------------------------
$sqlquery2 = "SELECT datatransfer, executiontime FROM net2ftp_log_consumption_ftpserver 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) {
$net2ftp_globals["consumption_ftpserver_datatransfer"] = 0;
$net2ftp_globals["consumption_ftpserver_executiontime"] = 0;
}
elseif ($nrofrows2 == 1) {
$resultRow2 = mysql_fetch_row($result2);
$net2ftp_globals["consumption_ftpserver_datatransfer"] = $resultRow2[0];
$net2ftp_globals["consumption_ftpserver_executiontime"] = $resultRow2[1];
}
else {
setErrorVars(false, __("Table net2ftp_log_consumption_ftpserver contains duplicate rows."), debug_backtrace(), __FILE__, __LINE__);
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 $net2ftp_globals, $net2ftp_settings, $net2ftp_result;
// -------------------------------------------------------------------------
// Initial checks
// -------------------------------------------------------------------------
// Verify if a database is used, and if consumption checking is turned on. If not: don't continue.
if ($net2ftp_settings["use_database"] != "yes" || $net2ftp_settings["check_consumption"] != "yes") { return true; }
// When user is not logged in, the FTP server is not set
if ($net2ftp_globals["ftpserver"] == "") { return true; }
// If the REMOTE_ADDR is not filled in, then there is a problem (IP spoofing), so return an error
if ($net2ftp_globals["REMOTE_ADDR"] == "") {
setErrorVars(false, __("Unable to determine your IP address."), debug_backtrace(), __FILE__, __LINE__);
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 ($net2ftp_globals["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($net2ftp_globals["REMOTE_ADDR"]);
$net2ftp_ftpserver_safe = addslashes($net2ftp_globals["ftpserver"]);
// ----------------------------------------------
// Do not log accesses, errors and consumption while the logs are being rotated
// ----------------------------------------------
$logStatus = getLogStatus();
if ($net2ftp_result["success"] == false) { return false; }
if ($logStatus != 0) { return true; }
// -------------------------------------------------------------------------
// Check the input
// -------------------------------------------------------------------------
// if (preg_match("/^[0-9]+$/", $net2ftp_globals["consumption_ipaddress_datatransfer) == FALSE) {
// setErrorVars(false, __("The variable <b>consumption_ipaddress_datatransfer</b> is not numeric."), debug_backtrace(), __FILE__, __LINE__);
// return false;
// }
// -------------------------------------------------------------------------
// Connect
// -------------------------------------------------------------------------
$mydb = connect2db();
if ($net2ftp_result["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_log_consumption_ipaddress WHERE date = '$date' AND ipaddress = '$REMOTE_ADDR_safe';";
$result1 = mysql_query("$sqlquery1");
$nrofrows1 = mysql_num_rows($result1);
if ($nrofrows1 == 1) {
$sqlquery2 = "UPDATE net2ftp_log_consumption_ipaddress SET datatransfer = '" . $net2ftp_globals["consumption_ipaddress_datatransfer"] . "', executiontime = '" . round($net2ftp_globals["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_log_consumption_ipaddress could not be updated."), debug_backtrace(), __FILE__, __LINE__);
// return false;
// }
}
elseif ($nrofrows1 == 0) {
$sqlquery3 = "INSERT INTO net2ftp_log_consumption_ipaddress VALUES('$date', '$REMOTE_ADDR_safe', '" . $net2ftp_globals["consumption_ipaddress_datatransfer"] . "', '" . round($net2ftp_globals["consumption_ipaddress_executiontime"]) . "');";
$result3 = mysql_query("$sqlquery3");
$nrofrows3 = mysql_affected_rows($mydb);
if ($nrofrows3 != 1) {
setErrorVars(false, __("Table net2ftp_log_consumption_ipaddress could not be updated."), debug_backtrace(), __FILE__, __LINE__);
return false;
}
}
else {
setErrorVars(false, __("Table net2ftp_log_consumption_ipaddress contains duplicate entries."), debug_backtrace(), __FILE__, __LINE__);
return false;
}
// MySQL > 4.1.0
// $sqlquery1 = "INSERT INTO net2ftp_log_consumption_ipaddress VALUES('$date', '$REMOTE_ADDR_safe', '" . $net2ftp_globals["consumption_ipaddress_datatransfer"] . "', '" . round($net2ftp_globals["consumption_ipaddress_executiontime"]) . "') ON DUPLICATE KEY UPDATE datatransfer = '" . $net2ftp_globals["consumption_ipaddress_datatransfer"] . "', executiontime = '" . round($net2ftp_globals["consumption_ipaddress_executiontime"]) . "';";
// -------------------------------------------------------------------------
// Put consumed data volume and execution time to the current FTP server
// -------------------------------------------------------------------------
$sqlquery4 = "SELECT * FROM net2ftp_log_consumption_ftpserver WHERE date = '$date' AND ftpserver = '$net2ftp_ftpserver_safe';";
$result4 = mysql_query("$sqlquery4");
$nrofrows4 = mysql_num_rows($result4);
if ($nrofrows4 == 1) {
$sqlquery5 = "UPDATE net2ftp_log_consumption_ftpserver SET datatransfer = '" . $net2ftp_globals["consumption_ftpserver_datatransfer"] . "', executiontime = '" . round($net2ftp_globals["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_log_consumption_ftpserver could not be updated."), debug_backtrace(), __FILE__, __LINE__);
// return false;
// }
}
elseif ($nrofrows4 == 0) {
$sqlquery6 = "INSERT INTO net2ftp_log_consumption_ftpserver VALUES('$date', '$net2ftp_ftpserver_safe', '" . $net2ftp_globals["consumption_ftpserver_datatransfer"] . "', '" . round($net2ftp_globals["consumption_ftpserver_executiontime"]) . "');";
$result6 = mysql_query("$sqlquery6");
$nrofrows6 = mysql_affected_rows($mydb);
if ($nrofrows6 != 1) {
setErrorVars(false, __("Table net2ftp_log_consumption_ftpserver could not be updated."), debug_backtrace(), __FILE__, __LINE__);
return false;
}
}
else {
setErrorVars(false, __("Table net2ftp_log_consumption_ftpserver contains duplicate entries."), debug_backtrace(), __FILE__, __LINE__);
return false;
}
// -------------------------------------------------------------------------
// Update the net2ftp_log_access record with the consumed data volume and execution time
// -------------------------------------------------------------------------
$sqlquery7 = "SELECT * FROM net2ftp_log_access WHERE id = '" . $net2ftp_globals["log_access_id"] . "';";
$result7 = mysql_query("$sqlquery7");
$nrofrows7 = mysql_num_rows($result7);
if ($nrofrows7 == 1) {
$sqlquery8 = "UPDATE net2ftp_log_access SET datatransfer = '" . $net2ftp_globals["consumption_datatransfer"] . "', executiontime = '" . round($net2ftp_globals["consumption_executiontime"]) . "' WHERE id = '" . $net2ftp_globals["log_access_id"] . "'";
$result8 = mysql_query("$sqlquery8");
$nrofrows8 = 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 ($nrofrows8 != 1) {
// setErrorVars(false, __("Table net2ftp_log_access could not be updated."), debug_backtrace(), __FILE__, __LINE__);
// return false;
// }
}
elseif ($nrofrows7 == 0) {
$sqlquery9 = "INSERT INTO net2ftp_log_access VALUES('$date', '$REMOTE_ADDR_safe', '" . $net2ftp_globals["consumption_ipaddress_datatransfer"] . "', '" . round($net2ftp_globals["consumption_ipaddress_executiontime"]) . "');";
$result9 = mysql_query("$sqlquery9");
$nrofrows9 = mysql_affected_rows($mydb);
if ($nrofrows9 != 1) {
setErrorVars(false, __("Table net2ftp_log_access could not be updated."), debug_backtrace(), __FILE__, __LINE__);
return false;
}
}
else {
setErrorVars(false, __("Table net2ftp_log_access contains duplicate entries."), debug_backtrace(), __FILE__, __LINE__);
return false;
}
// -------------------------------------------------------------------------
// If all 3 tables have been updated, set the flag to 1
// -------------------------------------------------------------------------
$net2ftp_globals["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 $net2ftp_globals, $net2ftp_settings, $net2ftp_result;
// -------------------------------------------------------------------------
// Initial checks
// -------------------------------------------------------------------------
// Verify if a database is used, and if consumption checking is turned on. If not: don't continue.
if ($net2ftp_settings["use_database"] != "yes" || $net2ftp_settings["check_consumption"] != "yes") { return true; }
// Initialize variables if needed
if (isset($net2ftp_globals["consumption_datatransfer"]) == false) { $net2ftp_globals["consumption_datatransfer"] = 0; }
if (isset($net2ftp_globals["consumption_executiontime"]) == false) { $net2ftp_globals["consumption_executiontime"] = 0; }
if (isset($net2ftp_globals["consumption_ipaddress_datatransfer"]) == false) { $net2ftp_globals["consumption_ipaddress_datatransfer"] = 0; }
if (isset($net2ftp_globals["consumption_ipaddress_executiontime"]) == false) { $net2ftp_globals["consumption_ipaddress_executiontime"] = 0; }
if (isset($net2ftp_globals["consumption_ftpserver_datatransfer"]) == false) { $net2ftp_globals["consumption_ftpserver_datatransfer"] = 0; }
if (isset($net2ftp_globals["consumption_ftpserver_executiontime"]) == false) { $net2ftp_globals["consumption_ftpserver_executiontime"] = 0; }
// -------------------------------------------------------------------------
// Add the consumption to the global variables
// -------------------------------------------------------------------------
if ($data != "" && $data > 0) {
$net2ftp_globals["consumption_datatransfer_changeflag"] = 1;
$net2ftp_globals["consumption_datatransfer"] = $net2ftp_globals["consumption_datatransfer"] + $data;
$net2ftp_globals["consumption_ipaddress_datatransfer"] = $net2ftp_globals["consumption_ipaddress_datatransfer"] + $data;
$net2ftp_globals["consumption_ftpserver_datatransfer"] = $net2ftp_globals["consumption_ftpserver_datatransfer"] + $data;
}
if ($time != "" && $time > 0) {
$net2ftp_globals["consumption_executiontime"] = $net2ftp_globals["consumption_executiontime"] + $time;
$net2ftp_globals["consumption_ipaddress_executiontime"] = $net2ftp_globals["consumption_ipaddress_executiontime"] + $time;
$net2ftp_globals["consumption_ftpserver_executiontime"] = $net2ftp_globals["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_globals, $net2ftp_settings, $net2ftp_result;
// -------------------------------------------------------------------------
// Print the variables
// -------------------------------------------------------------------------
echo "FTP server: " . $net2ftp_globals["ftpserver"] . "<br />\n";
echo "Remote address: " . $net2ftp_globals["REMOTE_ADDR"] . "<br />\n";
echo "consumption_datatransfer: " . $net2ftp_globals["consumption_datatransfer"] . "<br />\n";
echo "consumption_executiontime: " . $net2ftp_globals["consumption_executiontime"] . "<br />\n";
echo "consumption_ipaddress_datatransfer: " . $net2ftp_globals["consumption_ipaddress_datatransfer"] . "<br />\n";
echo "consumption_ipaddress_executiontime: " . $net2ftp_globals["consumption_ipaddress_executiontime"] . "<br />\n";
echo "consumption_ftpserver_datatransfer: " . $net2ftp_globals["consumption_ftpserver_datatransfer"] . "<br />\n";
echo "consumption_ftpserver_executiontime: " . $net2ftp_globals["consumption_ftpserver_executiontime"] . "<br />\n";
echo "consumption_datatransfer_changeflag: " . $net2ftp_globals["consumption_datatransfer_changeflag"] . "<br />\n";
echo "consumption_ipaddress_executiontime: " . $net2ftp_globals["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 $net2ftp_globals, $net2ftp_settings, $net2ftp_result;
// -------------------------------------------------------------------------
// Initial checks
// -------------------------------------------------------------------------
// Verify if a database is used, and if consumption checking is turned on. If not: don't continue.
if ($net2ftp_settings["use_database"] != "yes" || $net2ftp_settings["check_consumption"] != "yes") { return true; }
// -------------------------------------------------------------------------
// Check if the limit has been reached
// -------------------------------------------------------------------------
if ($net2ftp_globals["consumption_ipaddress_datatransfer"] > $net2ftp_settings["max_consumption_ipaddress_datatransfer"]) { return false; }
if ($net2ftp_globals["consumption_ipaddress_executiontime"] > $net2ftp_settings["max_consumption_ipaddress_executiontime"]) { return false; }
if ($net2ftp_globals["consumption_ftpserver_datatransfer"] > $net2ftp_settings["max_consumption_ftpserver_datatransfer"]) { return false; }
if ($net2ftp_globals["consumption_ftpserver_executiontime"] > $net2ftp_settings["max_consumption_ftpserver_executiontime"]) { return false; }
return true;
} // End checkConsumption()
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
?>

View file

@ -0,0 +1,52 @@
<?php
// -------------------------------------------------------------------------------
// | net2ftp: a web based FTP client |
// | Copyright (c) 2003-2013 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. |
// | |
// -------------------------------------------------------------------------------
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function connect2db() {
// --------------
// This function logs user accesses to the site
// --------------
// -------------------------------------------------------------------------
// Global variables
// -------------------------------------------------------------------------
global $net2ftp_settings;
$mydb = mysql_connect($net2ftp_settings["dbserver"], $net2ftp_settings["dbusername"], $net2ftp_settings["dbpassword"]);
if ($mydb == false) {
setErrorVars(false, __("Unable to connect to the MySQL database. Please check your MySQL database settings in net2ftp's configuration file settings.inc.php."), debug_backtrace(), __FILE__, __LINE__);
return false;
}
$result2 = mysql_select_db($net2ftp_settings["dbname"]);
if ($result2 == false) {
setErrorVars(false, __("Unable to select the MySQL database. Please check your MySQL database settings in net2ftp's configuration file settings.inc.php."), debug_backtrace(), __FILE__, __LINE__);
return false;
}
return $mydb;
} // End connect2db
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
?>

View file

@ -0,0 +1,168 @@
<?php
// -------------------------------------------------------------------------------
// | net2ftp: a web based FTP client |
// | Copyright (c) 2003-2013 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 is how error-handing works within net2ftp
-------------------------------------------------------------------------
There are 3 global variables:
- $net2ftp_result["success"], which is true or false
- $net2ftp_result["errormessage"], which contains an error message
- $net2ftp_result["debug_backtrace"], which contains the debugging backtrace (to indicate *where* the error happened)
---------------------------------
Low-level function executes a standard PHP function
- If everything goes OK, the low-level function simply returns its $finalresult
- If there is an error, the global variable $net2ftp_result["success"] is set to false, and
$net2ftp_result["errormessage"] will be filled with the error message
---------------------------------
function low_level {
$result = php_function();
if ($result == false) { setErrorVars(false, "errormessage", debug_backtrace(), __FILE, __LINE__); return false; }
...
return $finalresult;
}
---------------------------------
Middle-level function executes a low-level function (it may also execute standard PHP functions)
- If everything goes OK, the middle-level function simply returns its $finalresult
- If there is an error, the function can either return to its parent, or continue
---------------------------------
function middle_level {
global $net2ftp_result;
$result = low_level();
// Return to its parent, leave the error message as is:
if ($net2ftp_result["success"] == false) { return false; }
// Return to its parent, change the error message (leave the debug backtrace as is):
if ($net2ftp_result["success"] == false) { setErrorVars(false, "errormessage2", $net2ftp_result["debug_backtrace"], __FILE, __LINE__); return false; }
// Reset the error variables and continue:
if ($net2ftp_result["success"] == false) { setErrorVars(true, "", "", "", ""); }
...
return $finalresult;
// Print error message and exit -- THIS IS NOT DONE ANY MORE, as exit() calls must be avoided at all cost to
// keep net2ftp integrateable within other web applications.
// This case is replaced by case 1: return to the parent function, and leave the error message as is.
//// if ($net2ftp_result["success"] == false) { printErrorMessage(); }
}
---------------------------------
High-level function executes a middle-level function (it may also execute standard PHP functions)
- If everything goes OK, the high-level function simply returns its $finalresult
- If there is an error, the function returs to its parent (the script which called the net2ftp() function). It is
up to the parent to see if and how an error message should be printed -- see index.php for an example.
---------------------------------
function high_level {
global $net2ftp_result;
$result = middle_level();
if ($net2ftp_result["success"] == false) { return false; }
...
return $finalresult;
}
------------------------------------------------------------------------- */
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function setErrorVars($success, $errormessage, $debug_backtrace, $file, $line) {
// --------------
// This function modifies the 3 global error-handling variables
// --------------
// -------------------------------------------------------------------------
// Global variables
// -------------------------------------------------------------------------
global $net2ftp_result, $net2ftp_settings;
// -------------------------------------------------------------------------
// Set the error-handling variables
// -------------------------------------------------------------------------
$net2ftp_result["success"] = $success;
$net2ftp_result["errormessage"] = $errormessage;
$net2ftp_result["debug_backtrace"] = $debug_backtrace;
$net2ftp_result["file"] = $file;
$net2ftp_result["line"] = $line;
// -------------------------------------------------------------------------
// Log the error if an error occured ($success == false)
// If the error vars are set to true again ($success == true), don't log the error once more
// -------------------------------------------------------------------------
// DON'T LOG THE ERROR HERE, AS THE FUNCTION logError() MAY CALL setErrorVars() AGAIN,
// CAUSING AN INFINITE LOOP!
// if ($success == false) {
// logError();
// }
} // end setErrorVars
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function net2ftpErrorHandler($errno, $errmsg, $file, $line, $vars) {
// --------------
// This function processes PHP notices, warnings and errors
// --------------
// -------------------------------------------------------------------------
// Global variables
// -------------------------------------------------------------------------
global $net2ftp_output;
// -------------------------------------------------------------------------
// Put error details in variable
// -------------------------------------------------------------------------
if ($errno == E_USER_ERROR || $errno == E_ERROR || $errno == E_PARSE) {
$net2ftp_output["php_error"][] = "Error [$errno] $errstr in file $file on line $line";
echo "Error [$errno] $errstr in file $file on line $line";
exit();
}
elseif ($errorno == E_USER_WARNING || $errno == E_WARNING) {
$net2ftp_output["php_warning"][] = "Warning [$errno] $errstr in file $file on line $line";
}
elseif ($errorno == E_USER_NOTICE) {
$net2ftp_output["php_notice"][] = "Notice [$errno] $errstr in file $file on line $line";
}
else {
$net2ftp_output["php_error"][] = "Unknown error type [$errno] $errstr in file $file on line $line";
}
} // end setErrorVars
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
?>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,205 @@
<?php
// -------------------------------------------------------------------------------
// | net2ftp: a web based FTP client |
// | Copyright (c) 2003-2013 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. |
// | |
// -------------------------------------------------------------------------------
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function timer() {
// --------------
// This function calculates the time between starttime and endtime in milliseconds
// --------------
global $net2ftp_globals;
list($start_usec, $start_sec) = explode(' ', $net2ftp_globals["starttime"]);
$starttime = ((float)$start_usec + (float)$start_sec);
list($end_usec, $end_sec) = explode(' ', $net2ftp_globals["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
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function mytime() {
$datetime = date("Y-m-d H:i:s");
return $datetime;
}
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function mytime_short() {
$datetime = date("H:i");
return $datetime;
}
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function getBrowser($what) {
// --------------
// This function returns the browser name, version and platform using the http_user_agent string
// --------------
// Original code comes from http://www.phpbuilder.com/columns/tim20000821.php3?print_mode=1
// Written by Tim Perdue, and released under the GPL license
//
// SourceForge: Breaking Down the Barriers to Open Source Development
// Copyright 1999-2000 (c) The SourceForge Crew
// http://sourceforge.net
//
// $Id: tim20000821.php3,v 1.2 2001/05/22 19:22:47 tim Exp $
// -------------------------------------------------------------------------
// If no information is available, return ""
// -------------------------------------------------------------------------
if (isset($_SERVER["HTTP_USER_AGENT"]) == false) { return ""; }
// -------------------------------------------------------------------------
// Remove XSS code
// -------------------------------------------------------------------------
$http_user_agent = validateGenericInput($_SERVER["HTTP_USER_AGENT"]);
// -------------------------------------------------------------------------
// Determine browser and version
// -------------------------------------------------------------------------
if ($what == "version" || $what == "agent") {
// !!! If a new browser is added, add is also in the plugin properties
// Else, functionality will be broken when loading the plugin in printTextareaSelect().
if (preg_match('#MSIE ([0-9].[0-9]{1,2})#', $http_user_agent, $regs)) {
$BROWSER_VERSION = $regs[1];
$BROWSER_AGENT = 'IE';
}
elseif (preg_match('#Chrome/([0-9]{1,2}.[0-9]{1,4}.[0-9]{1,4}.[0-9]{1,4})#', $http_user_agent, $regs)) {
$BROWSER_VERSION = $regs[1];
$BROWSER_AGENT = 'Chrome';
}
elseif (preg_match('#Safari/([0-9].[0-9]{1,2})#', $http_user_agent, $regs)) {
$BROWSER_VERSION = $regs[1];
$BROWSER_AGENT = 'Safari';
}
elseif (preg_match('#Opera ([0-9].[0-9]{1,2})#', $http_user_agent, $regs)) {
$BROWSER_VERSION = $regs[1];
$BROWSER_AGENT = 'Opera';
}
elseif (preg_match('#Mozilla/([0-9].[0-9]{1,2})#', $http_user_agent, $regs)) {
$BROWSER_VERSION = $regs[1];
$BROWSER_AGENT = 'Mozilla';
}
else {
$BROWSER_VERSION = 0;
$BROWSER_AGENT = 'Other';
}
if ($what == "version") { return $BROWSER_VERSION; }
elseif ($what == "agent") { return $BROWSER_AGENT; }
} // end if
// -------------------------------------------------------------------------
// Determine platform
// -------------------------------------------------------------------------
elseif ($what == "platform") {
if ( strstr($http_user_agent, 'BlackBerry') ||
strstr($http_user_agent, 'DoCoMo') ||
strstr($http_user_agent, 'Nokia') ||
strstr($http_user_agent, 'Palm') ||
strstr($http_user_agent, 'SonyEricsson') ||
strstr($http_user_agent, 'SymbianOS') ||
strstr($http_user_agent, 'Windows CE')) {
$BROWSER_PLATFORM = 'Mobile';
}
/*elseif (strstr($http_user_agent, 'iPhone') || strstr($http_user_agent, 'iPod')) {
$BROWSER_PLATFORM = 'iPhone';
}*/
elseif (strstr($http_user_agent, 'Win')) {
$BROWSER_PLATFORM = 'Win';
}
else if (strstr($http_user_agent, 'Mac')) {
$BROWSER_PLATFORM = 'Mac';
}
else if (strstr($http_user_agent, 'Linux')) {
$BROWSER_PLATFORM = 'Linux';
}
else if (strstr($http_user_agent, 'Unix')) {
$BROWSER_PLATFORM = 'Unix';
}
else {
$BROWSER_PLATFORM = 'Other';
}
return $BROWSER_PLATFORM;
} // end if elseif
} // End function getBrowser
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
?>

View file

@ -0,0 +1,95 @@
<?php
// Samples of FTP LIST responses.
// Some samples are from FileZilla source code, file FtpListResult.cpp
// License: GPL
// Some samples are from http://cr.yp.to/ftpparse/ftpparse.c
// By D. J. Bernstein, djb@cr.yp.to http://cr.yp.to/ftpparse.html
// License: Commercial use is fine, if you let me know what programs you're using this in.
// Some samples are provided by net2ftp users to the net2ftp development team
// License: GPL
$list_samples["UNIX-style listing, without inum and without blocks"][1] = "-rw-r--r-- 1 root other 531 Jan 29 03:26 README";
$list_samples["UNIX-style listing, without inum and without blocks"][2] = "dr-xr-xr-x 2 root other 512 Apr 8 1994 etc";
$list_samples["UNIX-style listing, without inum and without blocks"][3] = "dr-xr-xr-x 2 root 512 Apr 8 1994 etc2";
$list_samples["UNIX-style listing, without inum and without blocks"][4] = "lrwxrwxrwx 1 root other 7 Jan 25 00:17 bin -> usr/bin";
$list_samples["Some listings with uncommon date/time format"][1] = "-rw-r--r-- 1 root other 531 09-26 2000 README2";
$list_samples["Some listings with uncommon date/time format"][2] = "-rw-r--r-- 1 root other 531 09-26 13:45 README3";
$list_samples["Some listings with uncommon date/time format"][3] = "-rw-r--r-- 1 root other 531 2005-06-07 21:22 README4";
$list_samples["Also produced by Microsoft's FTP servers for Windows"][1] = "---------- 1 owner group 1803128 Jul 10 10:18 ls-lR.Z";
$list_samples["Also produced by Microsoft's FTP servers for Windows"][2] = "d--------- 1 owner group 0 May 9 19:45 Softlib";
$list_samples["Also WFTPD for MSDOS"][1] = "-rwxrwxrwx 1 noone nogroup 322 Aug 19 1996 message.ftp";
$list_samples["Also NetWare"][1] = "d [R----F--] supervisor 512 Jan 16 18:53 login";
$list_samples["Also NetWare"][2] = "- [R----F--] rhesus 214059 Oct 20 15:27 cx.exe";
$list_samples["Also NetPresenz for the Mac"][1] = "-------r-- 326 1391972 1392298 Nov 22 1995 MegaPhone.sit";
$list_samples["Also NetPresenz for the Mac"][2] = "drwxrwxr-x folder 2 May 10 1996 network";
$list_samples["MSDOS format"][1] = "04-27-00 09:09PM <DIR> licensed";
$list_samples["MSDOS format"][2] = "07-18-00 10:16AM <DIR> pub";
$list_samples["MSDOS format"][3] = "04-14-00 03:47PM 589 readme.htm";
$list_samples["Some other formats some windows servers send"][1] = "-rw-r--r-- 1 root 531 Jan 29 03:26 README5";
$list_samples["Some other formats some windows servers send"][2] = "-rw-r--r-- 1 group domain user 531 Jan 29 03:26 README6";
$list_samples["EPLF directory listings"][1] = "+i8388621.48594,m825718503,r,s280,\teplf test 1.file";
$list_samples["EPLF directory listings"][2] = "+i8388621.50690,m824255907,/,\teplf test 2.dir";
$list_samples["EPLF directory listings"][3] = "+i8388621.48598,m824253270,r,s612,\teplf test 3.file";
$list_samples["MSDOS type listing used by IIS"][1] = "04-27-00 12:09PM <DIR> DOS dir 1";
$list_samples["MSDOS type listing used by IIS"][2] = "04-14-00 03:47PM 589 DOS file 1";
$list_samples["Another type of MSDOS style listings"][1] = "2002-09-02 18:48 <DIR> DOS dir 2";
$list_samples["Another type of MSDOS style listings"][2] = "2002-09-02 19:06 9,730 DOS file 2";
$list_samples["Numerical Unix style format"][1] = "0100644 500 101 12345 123456789 filename";
$list_samples["This one is used by SSH-2.0-VShell_2_1_2_143, this is the old VShell format"][1] = "206876 Apr 04, 2000 21:06 VShell (old)";
$list_samples["This one is used by SSH-2.0-VShell_2_1_2_143, this is the old VShell format"][2] = "0 Dec 12, 2002 02:13 VShell (old) Dir/";
$list_samples["This type of directory listings is sent by some newer versions of VShell both year and time in one line is uncommon."][1] = "-rwxr-xr-x 1 user group 9 Oct 08, 2002 09:47 VShell (new)";
$list_samples["Next ones come from an OS/2 server. The server obviously isn't Y2K aware"][1] = "36611 A 04-23-103 10:57 OS2 test1.file";
$list_samples["Next ones come from an OS/2 server. The server obviously isn't Y2K aware"][2] = " 1123 A 07-14-99 12:37 OS2 test2.file";
$list_samples["Next ones come from an OS/2 server. The server obviously isn't Y2K aware"][3] = " 0 DIR 02-11-103 16:15 OS2 test1.dir";
$list_samples["Next ones come from an OS/2 server. The server obviously isn't Y2K aware"][4] = " 1123 DIR A 10-05-100 23:38 OS2 test2.dir";
$list_samples["Some servers send localized date formats, here the German one"][1] = "dr-xr-xr-x 2 root other 2235 26. Juli, 20:10 datetest1 (ger)";
$list_samples["Some servers send localized date formats, here the German one"][2] = "-r-xr-xr-x 2 root other 2235 2. Okt. 2003 datetest2 (ger)";
$list_samples["Some servers send localized date formats, here the German one"][3] = "-r-xr-xr-x 2 root other 2235 1999/10/12 17:12 datetest3";
$list_samples["Some servers send localized date formats, here the German one"][4] = "-r-xr-xr-x 2 root other 2235 24-04-2003 17:12 datetest4";
$list_samples["Here a Japanese one"][1] = "-rw-r--r-- 1 root sys 8473 4\x8c\x8e 18\x93\xfa 2003\x94\x4e datatest1 (jap)";
$list_samples["VMS style listings"][1] = "vms_dir_1.DIR;1 1 19-NOV-2001 21:41 [root,root] (RWE,RWE,RE,RE)";
$list_samples["VMS style listings"][2] = "vms_file_3;1 155 2-JUL-2003 10:30:13.64";
$list_samples["VMS style listings without time"][1] = "vms_file_4;1 2/8 15-JAN-2000 [IV2_XXX] (RWED,RWED,RE,)";
$list_samples["VMS style listings without time"][2] = "vms_file_5;1 6/8 15-JUI-2002 PRONAS (RWED,RWED,RE,)";
$list_samples["VMS multiline"][1] = "VMS_file_1;1\r\n170774/170775 24-APR-2003 08:16:15 [FTP_CLIENT,SCOT] (RWED,RWED,RE,)";
$list_samples["VMS multiline"][2] = "VMS_file_2;1\r\n10 2-JUL-2003 10:30:08.59 [FTP_CLIENT,SCOT] (RWED,RWED,RE,)";
$list_samples["IBM AS/400 style listing"][1] = "QSYS 77824 02/23/00 15:09:55 *DIR IBM AS/400 Dir1/";
$list_samples["IBM AS/400 style listing"][2] = "QSYS 77824 23/02/00 15:09:55 *FILE IBM AS/400 File1 strangedate";
$list_samples["aligned directory listing with too long size"][1] = "-r-xr-xr-x longowner longgroup123456 Feb 12 17:20 long size test1";
$list_samples["short directory listing with month name"][1] = "-r-xr-xr-x 2 owner group 4512 01-jun-99 shortdate with monthname";
$list_samples["the following format is sent by the Connect:Enterprise server by Sterling Commerce"][1] = "-C--E-----FTP B BCC3I1 7670 1294495 Jan 13 07:42 ConEnt file";
$list_samples["the following format is sent by the Connect:Enterprise server by Sterling Commerce"][2] = "-C--E-----FTS B BCC3I1 7670 1294495 Jan 13 07:42 ConEnt file2";
$list_samples["the following format is sent by the Connect:Enterprise server by Sterling Commerce"][3] = "-AR--M----TCP B ceunix 17570 2313708 Mar 29 08:56 ALL_SHORT1.zip";
$list_samples["Nortel wfFtp router"][1] = "nortel.wfFtp 1014196 06/03/04 Thur. 10:20:03";
$list_samples["VxWorks based server used in Nortel routers"][1] = "2048 Feb-28-1998 05:23:30 nortel.VwWorks dir <DIR>";
?>

View file

@ -0,0 +1,734 @@
<?php
// -------------------------------------------------------------------------------
// | net2ftp: a web based FTP client |
// | Copyright (c) 2003-2013 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. |
// | |
// -------------------------------------------------------------------------------
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function logAccess() {
// --------------
// This function logs user accesses to the site
// --------------
// -------------------------------------------------------------------------
// Global variables
// -------------------------------------------------------------------------
global $net2ftp_globals, $net2ftp_settings, $net2ftp_result;
if ($net2ftp_settings["log_access"] == "yes") {
// -------------------------------------------------------------------------
// Date and time
// -------------------------------------------------------------------------
$date = date("Y-m-d");
$time = date("H:i:s");
// -------------------------------------------------------------------------
// Logging to the database
// -------------------------------------------------------------------------
if ($net2ftp_settings["use_database"] == "yes") {
// ----------------------------------------------
// Do not log accesses, errors and consumption while the logs are being rotated
// ----------------------------------------------
$logStatus = getLogStatus();
if ($net2ftp_result["success"] == false) { return false; }
if ($logStatus != 0) { return true; }
// ----------------------------------------------
// Input checks
// ----------------------------------------------
// 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($net2ftp_globals["REMOTE_ADDR"]);
$REMOTE_PORT_safe = addslashes($net2ftp_globals["REMOTE_PORT"]);
$HTTP_USER_AGENT_safe = addslashes($net2ftp_globals["HTTP_USER_AGENT"]);
$PHP_SELF_safe = addslashes($net2ftp_globals["PHP_SELF"]);
if (isset($net2ftp_globals["consumption_datatransfer"]) == true) {
$consumption_datatransfer_safe = addslashes($net2ftp_globals["consumption_datatransfer"]);
}
else {
$consumption_datatransfer_safe = "0";
}
if (isset($net2ftp_globals["consumption_executiontime"]) == true) {
$consumption_executiontime_safe = addslashes($net2ftp_globals["consumption_executiontime"]);
}
else {
$consumption_executiontime_safe = "0";
}
$net2ftp_ftpserver_safe = addslashes($net2ftp_globals["ftpserver"]);
$net2ftp_username_safe = addslashes($net2ftp_globals["username"]);
$state_safe = addslashes($net2ftp_globals["state"]);
$state2_safe = addslashes($net2ftp_globals["state2"]);
$screen_safe = addslashes($net2ftp_globals["screen"]);
$directory_safe = addslashes($net2ftp_globals["directory"]);
$entry_safe = addslashes($net2ftp_globals["entry"]);
$HTTP_REFERER_safe = addslashes($net2ftp_globals["HTTP_REFERER"]);
// ----------------------------------------------
// Connect to the DB
// ----------------------------------------------
$mydb = connect2db();
if ($net2ftp_result["success"] == false) { return false; }
// ----------------------------------------------
// Add record to the database table
// ----------------------------------------------
$sqlquery1 = "INSERT INTO net2ftp_log_access VALUES(null, '$date', '$time', '$REMOTE_ADDR_safe', '$REMOTE_PORT_safe', '$HTTP_USER_AGENT_safe', '$PHP_SELF_safe', '$consumption_datatransfer_safe', '$consumption_executiontime_safe', '$net2ftp_ftpserver_safe', '$net2ftp_username_safe', '$state_safe', '$state2_safe', '$screen_safe', '$directory_safe', '$entry_safe', '$HTTP_REFERER_safe')";
$result1 = mysql_query($sqlquery1);
if ($result1 == false) {
$errormessage = __("Unable to execute the SQL query.");
setErrorVars(false, $errormessage, debug_backtrace(), __FILE__, __LINE__);
return false;
}
$nrofrows1 = mysql_affected_rows($mydb);
$net2ftp_globals["log_access_id"] = mysql_insert_id();
} // end if use_database
// -------------------------------------------------------------------------
// Logging to the system log
// -------------------------------------------------------------------------
if ($net2ftp_settings["use_syslog"] == "yes") {
// ----------------------------------------------
// Get consumption values
// ----------------------------------------------
if (isset($net2ftp_globals["consumption_datatransfer"]) == true) {
$consumption_datatransfer = $net2ftp_globals["consumption_datatransfer"];
}
else {
$consumption_datatransfer = "0";
}
if (isset($net2ftp_globals["consumption_executiontime"]) == true) {
$consumption_executiontime = $net2ftp_globals["consumption_executiontime"];
}
else {
$consumption_executiontime = "0";
}
// ----------------------------------------------
// Create message
// ----------------------------------------------
$message2log = "$date $time " . $net2ftp_globals["REMOTE_ADDR"] . " " . $net2ftp_globals["REMOTE_PORT"] . " " . $net2ftp_globals["PHP_SELF"] . " " . $consumption_datatransfer . " " . $consumption_executiontime . " " . $net2ftp_globals["ftpserver"] . " " . $net2ftp_globals["username"] . " " . $net2ftp_globals["state"] . " " . $net2ftp_globals["state2"] . " " . $net2ftp_globals["screen"] . " " . $net2ftp_globals["directory"] . " " . $net2ftp_globals["entry"];
$result2 = openlog($net2ftp_settings["syslog_ident"], 0, $net2ftp_settings["syslog_facility"]);
if ($result2 == false) {
$errormessage = __("Unable to open the system log.");
setErrorVars(false, $errormessage, debug_backtrace(), __FILE__, __LINE__);
return false;
}
// ----------------------------------------------
// Write message to system logger
// ----------------------------------------------
$result3 = syslog($net2ftp_settings["syslog_priority"], $message2log);
if ($result3 == false) {
$errormessage = __("Unable to write a message to the system log.");
setErrorVars(false, $errormessage, debug_backtrace(), __FILE__, __LINE__);
return false;
}
} // end if use_syslog
} // end if log_access
} // end logAccess()
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function logError() {
// --------------
// This function logs user accesses to the site
//
// IMPORTANT: this function uses, but does not change the global $net2ftp_result[""] variables.
// It returns true on success, false on failure.
// --------------
// -------------------------------------------------------------------------
// Global variables
// -------------------------------------------------------------------------
global $net2ftp_globals, $net2ftp_settings, $net2ftp_result;
if ($net2ftp_settings["log_error"] == "yes") {
// -------------------------------------------------------------------------
// Take a copy of the $net2ftp_result
// If an error occurs within logError, logError will return false and reset the
// $net2ftp_result variable to it's original value
// Also if no error occurs logError will return the variable to it's original value
// -------------------------------------------------------------------------
$net2ftp_result_original = $net2ftp_result;
setErrorVars(true, "", "", "", "");
// -------------------------------------------------------------------------
// Errormessage and debug backtrace
// -------------------------------------------------------------------------
$errormessage = addslashes($net2ftp_result_original["errormessage"]);
$debug_backtrace = "";
$i = sizeof($net2ftp_result_original["debug_backtrace"])-1;
if ($i > 0) {
$debug_backtrace .= addslashes("function " . $net2ftp_result_original["debug_backtrace"][$i]["function"] . " (" . $net2ftp_result_original["debug_backtrace"][$i]["file"] . " on line " . $net2ftp_result_original["debug_backtrace"][$i]["line"] . ")\n");
for ($j=0; $j<sizeof($net2ftp_result_original["debug_backtrace"][$i]["args"]); $j++) {
$debug_backtrace .= addslashes("argument $j: " . $net2ftp_result_original["debug_backtrace"][$i]["args"][$j] . "\n");
}
}
// -------------------------------------------------------------------------
// Date and time
// -------------------------------------------------------------------------
$date = date("Y-m-d");
$time = date("H:i:s");
// -------------------------------------------------------------------------
// Logging to the database
// -------------------------------------------------------------------------
if ($net2ftp_settings["use_database"] == "yes") {
// ----------------------------------------------
// Do not log accesses and errors while the logs are being rotated
// ----------------------------------------------
$logStatus = getLogStatus();
if ($net2ftp_result["success"] == false) { return false; }
if ($logStatus != 0) { return true; }
// ----------------------------------------------
// Input checks
// ----------------------------------------------
// 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
$net2ftp_ftpserver_safe = addslashes($net2ftp_globals["ftpserver"]);
$net2ftp_username_safe = addslashes($net2ftp_globals["username"]);
$state_safe = addslashes($net2ftp_globals["state"]);
$state2_safe = addslashes($net2ftp_globals["state2"]);
$directory_safe = addslashes($net2ftp_globals["directory"]);
$REMOTE_ADDR_safe = addslashes($net2ftp_globals["REMOTE_ADDR"]);
$REMOTE_PORT_safe = addslashes($net2ftp_globals["REMOTE_PORT"]);
$HTTP_USER_AGENT_safe = addslashes($net2ftp_globals["HTTP_USER_AGENT"]);
// ----------------------------------------------
// Connect to the DB
// ----------------------------------------------
$mydb = connect2db();
if ($net2ftp_result["success"] == false) {
setErrorVars($net2ftp_result_original["success"], $net2ftp_result_original["errormessage"], $net2ftp_result_original["debug_backtrace"], $net2ftp_result_original["file"], $net2ftp_result_original["line"]);
return false;
}
// ----------------------------------------------
// Add record to the database table
// ----------------------------------------------
$sqlquerystring = "INSERT INTO net2ftp_log_error VALUES('$date', '$time', '$net2ftp_ftpserver_safe', '$net2ftp_username_safe', '$errormessage', '$debug_backtrace', '$state_safe', '$state2_safe', '$directory_safe', '$REMOTE_ADDR_safe', '$REMOTE_PORT_safe', '$HTTP_USER_AGENT_safe')";
$result_mysql_query = mysql_query($sqlquerystring);
if ($result_mysql_query == false) {
setErrorVars($net2ftp_result_original["success"], $net2ftp_result_original["errormessage"], $net2ftp_result_original["debug_backtrace"], $net2ftp_result_original["file"], $net2ftp_result_original["line"]);
return false;
}
} // end if use_database
// -------------------------------------------------------------------------
// Logging to the system log
// -------------------------------------------------------------------------
if ($net2ftp_settings["use_syslog"] == "yes") {
// ----------------------------------------------
// Get consumption values
// ----------------------------------------------
if (isset($net2ftp_globals["consumption_datatransfer"]) == true) {
$consumption_datatransfer = $net2ftp_globals["consumption_datatransfer"];
}
else {
$consumption_datatransfer = "0";
}
if (isset($net2ftp_globals["consumption_executiontime"]) == true) {
$consumption_executiontime = $net2ftp_globals["consumption_executiontime"];
}
else {
$consumption_executiontime = "0";
}
// ----------------------------------------------
// Create message
// ----------------------------------------------
$message2log = "$date $time " . $net2ftp_globals["ftpserver"] . " " . $net2ftp_globals["username"] . " " . $net2ftp_result["errormessage"] . " $debug_backtrace " . $net2ftp_globals["state"] . " " . $net2ftp_globals["state2"] . " " . $net2ftp_globals["directory"] . " " . $net2ftp_globals["REMOTE_ADDR"] . " " . $net2ftp_globals["HTTP_USER_AGENT"];
$result2 = openlog($net2ftp_settings["syslog_ident"], 0, $net2ftp_settings["syslog_facility"]);
if ($result2 == false) {
$errormessage = __("Unable to open the system log.");
setErrorVars(false, $errormessage, debug_backtrace(), __FILE__, __LINE__);
return false;
}
// ----------------------------------------------
// Write message to system logger
// ----------------------------------------------
$result3 = syslog($net2ftp_settings["syslog_priority"], $message2log);
if ($result3 == false) {
$errormessage = __("Unable to write a message to the system log.");
setErrorVars(false, $errormessage, debug_backtrace(), __FILE__, __LINE__);
return false;
}
} // end if use_syslog
// -------------------------------------------------------------------------
// Reset the variable to it's original value
// -------------------------------------------------------------------------
setErrorVars($net2ftp_result_original["success"], $net2ftp_result_original["errormessage"], $net2ftp_result_original["debug_backtrace"], $net2ftp_result_original["file"], $net2ftp_result_original["line"]);
} // end if logErrors
} // end logError()
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function getLogStatus() {
// --------------
// This function reads the log rotation status from the database.
// --------------
// -------------------------------------------------------------------------
// Global variables
// -------------------------------------------------------------------------
global $net2ftp_globals, $net2ftp_settings, $net2ftp_result;
// -------------------------------------------------------------------------
// Initial checks
// -------------------------------------------------------------------------
// Verify if a database is used. If not: don't continue.
if ($net2ftp_settings["use_database"] != "yes") { return true; }
// -------------------------------------------------------------------------
// Determine current month and last month
// -------------------------------------------------------------------------
$currentmonth = date("Ym"); // e.g. 201207
$lastmonth = date("Ym", mktime(0, 0, 0, date("m")-1, date("d"), date("Y")));
// -------------------------------------------------------------------------
// Connect to the database
// -------------------------------------------------------------------------
$mydb = connect2db();
if ($net2ftp_result["success"] == false) { return false; }
// -------------------------------------------------------------------------
// Get log rotation status
// -------------------------------------------------------------------------
$sqlquery1 = "SELECT status FROM net2ftp_log_status WHERE month = '$currentmonth';";
$result1 = mysql_query("$sqlquery1") or die("Unable to execute SQL SELECT query (getLogStatus > sqlquery1) <br /> $sqlquery1");
$nrofrows1 = mysql_num_rows($result1);
if ($nrofrows1 == 0) {
$logStatus = 1;
}
elseif ($nrofrows1 == 1) {
$resultRow1 = mysql_fetch_row($result1);
$logStatus = $resultRow1[0];
}
else {
setErrorVars(false, __("Table net2ftp_log_status contains duplicate entries."), debug_backtrace(), __FILE__, __LINE__);
return false;
}
// Return $logStatus
return $logStatus;
} // End getLogStatus
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function putLogStatus($logStatus) {
// --------------
// This function writes the log rotation status to the database.
// --------------
// -------------------------------------------------------------------------
// Global variables
// -------------------------------------------------------------------------
global $net2ftp_globals, $net2ftp_settings, $net2ftp_result;
// -------------------------------------------------------------------------
// Initial checks
// -------------------------------------------------------------------------
// Verify if a database is used. If not: don't continue.
if ($net2ftp_settings["use_database"] != "yes") { return true; }
// -------------------------------------------------------------------------
// Determine current month and last month
// -------------------------------------------------------------------------
$currentmonth = date("Ym"); // e.g. 201207
$lastmonth = date("Ym", mktime(0, 0, 0, date("m")-1, date("d"), date("Y")));
$datetime = mytime();
// -------------------------------------------------------------------------
// Connect to the database
// -------------------------------------------------------------------------
$mydb = connect2db();
if ($net2ftp_result["success"] == false) { return false; }
// -------------------------------------------------------------------------
// Put log rotation status
// -------------------------------------------------------------------------
$sqlquery1 = "SELECT status, changelog FROM net2ftp_log_status WHERE month = '$currentmonth';";
$result1 = mysql_query("$sqlquery1");
$nrofrows1 = mysql_num_rows($result1);
if ($nrofrows1 == 1) {
$resultRow1 = mysql_fetch_row($result1);
$logStatus_old = $resultRow1[0];
$changelog_old = $resultRow1[1];
$changelog_new = $changelog_old . "From $logStatus_old to $logStatus on $datetime. ";
$sqlquery2 = "UPDATE net2ftp_log_status SET status = '" . $logStatus . "', changelog = '" . $changelog_new . "' WHERE month = '$currentmonth';";
$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.
elseif ($nrofrows1 == 0) {
$changelog_new = "Set to $logStatus on $datetime. ";
$sqlquery3 = "INSERT INTO net2ftp_log_status VALUES('$currentmonth', '" . $logStatus . "', '" . $changelog_new . "');";
$result3 = mysql_query("$sqlquery3");
$nrofrows3 = mysql_affected_rows($mydb);
if ($nrofrows3 != 1) {
setErrorVars(false, __("Table net2ftp_log_status could not be updated."), debug_backtrace(), __FILE__, __LINE__);
return false;
}
}
else {
setErrorVars(false, __("Table net2ftp_log_status contains duplicate entries."), debug_backtrace(), __FILE__, __LINE__);
return false;
}
// -------------------------------------------------------------------------
// Return true
// -------------------------------------------------------------------------
return true;
} // End putLogStatus
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function emptyLogs($datefrom, $dateto) {
// --------------
// This function deletes the log records for the dates between $datefrom
// and $dateto.
// The global variable $net2ftp_output["emptyLogs"] is filled with result messages.
// The function returns true on success, false on failure.
// --------------
// -------------------------------------------------------------------------
// Global variables
// -------------------------------------------------------------------------
global $net2ftp_globals, $net2ftp_result, $net2ftp_output;
$toreturn = true;
// -------------------------------------------------------------------------
// Connect to the database
// -------------------------------------------------------------------------
$mydb = connect2db();
if ($net2ftp_result["success"] == false) { return false; }
$tables[1] = "net2ftp_log_access";
$tables[2] = "net2ftp_log_error";
$tables[3] = "net2ftp_log_consumption_ftpserver";
$tables[4] = "net2ftp_log_consumption_ipaddress";
// -------------------------------------------------------------------------
// Execute the queries
// -------------------------------------------------------------------------
for ($i=1; $i<=sizeof($tables); $i++) {
$sqlquery_empty = "DELETE FROM $tables[$i] WHERE date BETWEEN '$datefrom' AND '$dateto';";
$result_empty[$i] = mysql_query("$sqlquery_empty");
$sqlquery_optimize = "OPTIMIZE TABLE `" . $tables[$i] . "`;";
$result_optimize[$i] = mysql_query("$sqlquery_optimize");
if ($result_empty[$i] == true) {
$net2ftp_output["emptyLogs"][] = __("The table <b>%1\$s</b> was emptied successfully.", $tables[$i]);
}
else {
$toreturn = false;
$net2ftp_output["emptyLogs"][] = __("The table <b>%1\$s</b> could not be emptied.", $tables[$i]);
}
if ($result_optimize[$i] == true) {
$net2ftp_output["emptyLogs"][] = __("The table <b>%1\$s</b> was optimized successfully.", $tables[$i]);
}
else {
$toreturn = false;
$net2ftp_output["emptyLogs"][] = __("The table <b>%1\$s</b> could not be optimized.", $tables[$i]);
}
} // end for
return $toreturn;
} // end emptyLogs()
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function rotateLogs() {
// --------------
// Rotate the tables
// net2ftp_log_access = active table
// net2ftp_log_access_YYYYMM = archive table with information of month MM and year YYYY
// net2ftp_log_access_template = template table (empty table)
//
// To avoid that the log rotation actions would be executed multiple times at
// the end of the period, a "log rotation status" is used:
// 0 = no rotation needed
// 1 = step 1 not yet started (renaming active tables to archived tables)
// 2 = step 1 in progress
// 3 = step 2 not yet started (copying template tables to the active tables)
// 4 = step 2 in progress
// 5 = step 3 not yet started (dropping oldest archive tables)
// 6 = step 3 in progress
// --------------
// -------------------------------------------------------------------------
// Global variables
// -------------------------------------------------------------------------
global $net2ftp_globals, $net2ftp_settings, $net2ftp_result, $net2ftp_output;
$toreturn = true;
// -------------------------------------------------------------------------
// Verify if a database is used. If not: don't continue.
// -------------------------------------------------------------------------
if ($net2ftp_settings["use_database"] != "yes") { return true; }
// -------------------------------------------------------------------------
// Check if the setting is within the allowed range; if not, set it to 12 months
// -------------------------------------------------------------------------
if (!($net2ftp_settings["log_length_months"] > 1 && $net2ftp_settings["log_length_months"] < 99)) {
$net2ftp_settings["log_length_months"] = 12;
}
// -------------------------------------------------------------------------
// Current month, next month, previous month
// -------------------------------------------------------------------------
$currentmonth = date("Ym"); // e.g. 201207
$lastmonth = date("Ym", mktime(0, 0, 0, date("m")-1, date("d"), date("Y")));
$nextmonth = date("Ym", mktime(0, 0, 0, date("m")+1, date("d"), date("Y")));
$dropmonth = date("Ym", mktime(0, 0, 0, date("m")-$net2ftp_settings["log_length_months"]-1, date("d"), date("Y")));
// -------------------------------------------------------------------------
// Connect to the database
// -------------------------------------------------------------------------
$mydb = connect2db();
if ($net2ftp_result["success"] == false) { return false; }
// -------------------------------------------------------------------------
// Get the log rotation status
// -------------------------------------------------------------------------
$logStatus = getLogStatus();
if ($net2ftp_result["success"] == false) { return false; }
// No log rotation needed
if ($logStatus === 0) { return true; }
// -------------------------------------------------------------------------
// Table names and SQL queries to create the tables
// -------------------------------------------------------------------------
$tables[1]["name"] = "net2ftp_log_access";
$tables[2]["name"] = "net2ftp_log_error";
$tables[3]["name"] = "net2ftp_log_consumption_ftpserver";
$tables[4]["name"] = "net2ftp_log_consumption_ipaddress";
// -------------------------------------------------------------------------
// step 1 of rotation: rename active tables to archived tables
// -------------------------------------------------------------------------
if ($logStatus == 1) {
// Set the log status to indicate this step is in progress
putLogStatus(2);
if ($net2ftp_result["success"] == false) { return false; }
// Execute the step
for ($i=1; $i<=sizeof($tables); $i++) {
$table = $tables[$i]["name"]; // Example: net2ftp_log_access
$table_archive = $table . "_" . $lastmonth; // Example: net2ftp_log_access_201206
$table_archive_drop = $table . "_" . $dropmonth; // Example: net2ftp_log_access_201106
$sqlquery_rename = "RENAME TABLE $table TO $table_archive";
$result_rename[$i] = mysql_query("$sqlquery_rename");
if ($result_rename[$i] == true) {
$net2ftp_output["rotateLogs"][] = __("The log tables were renamed successfully.");
}
else {
$toreturn = false;
$net2ftp_output["rotateLogs"][] = __("The log tables could not be renamed.");
}
} // end for
// Set the log status to indicate this step is in done and the next can start
putLogStatus(3);
if ($net2ftp_result["success"] == false) { return false; }
}
// -------------------------------------------------------------------------
// step 2 of rotation: copy template tables to the active
// -------------------------------------------------------------------------
elseif ($logStatus == 3) {
// Set the log status to indicate this step is in progress
putLogStatus(4);
if ($net2ftp_result["success"] == false) { return false; }
// Execute the step
for ($i=1; $i<=sizeof($tables); $i++) {
$table = $tables[$i]["name"]; // Example: net2ftp_log_access
$table_archive = $table . "_" . $lastmonth; // Example: net2ftp_log_access_201206
$table_archive_drop = $table . "_" . $dropmonth; // Example: net2ftp_log_access_201106
$sqlquery_copy = "CREATE TABLE $table LIKE $table_archive";
$result_copy[$i] = mysql_query("$sqlquery_copy");
if ($result_copy[$i] == true) {
$net2ftp_output["rotateLogs"][] = __("The log tables were copied successfully.");
}
else {
$toreturn = false;
$net2ftp_output["rotateLogs"][] = __("The log tables could not be copied.");
}
} // end for
// Set the log status to indicate this step is in done and the next can start
putLogStatus(5);
if ($net2ftp_result["success"] == false) { return false; }
}
// -------------------------------------------------------------------------
// step 3 of rotation: drop oldest archive tables
// -------------------------------------------------------------------------
elseif ($logStatus == 5) {
// Set the log status to indicate this step is in progress
putLogStatus(6);
if ($net2ftp_result["success"] == false) { return false; }
// Execute the step
for ($i=1; $i<=sizeof($tables); $i++) {
$table = $tables[$i]["name"]; // Example: net2ftp_log_access
$table_archive = $table . "_" . $lastmonth; // Example: net2ftp_log_access_201206
$table_archive_drop = $table . "_" . $dropmonth; // Example: net2ftp_log_access_201106
$sqlquery_drop = "DROP TABLE IF EXISTS $table_archive_drop;";
$result_drop[$i] = mysql_query("$sqlquery_drop");
if ($result_drop[$i] == true) {
$net2ftp_output["rotateLogs"][] = __("The oldest log table was dropped successfully.");
}
else {
$toreturn = false;
$net2ftp_output["rotateLogs"][] = __("The oldest log table could not be dropped.");
}
} // end for
// Set the log status to indicate this step is in done and the rotation is over
putLogStatus(0);
if ($net2ftp_result["success"] == false) { return false; }
}
return $toreturn;
} // end rotateLogs()
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
?>

View file

@ -0,0 +1,509 @@
<?php
// -------------------------------------------------------------------------------
// | net2ftp: a web based FTP client |
// | Copyright (c) 2003-2013 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 program is distributed in the hope that it will be useful, |
// | but WITHOUT ANY WARRANTY; without even the implied warranty of |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
// | GNU General Public License for more details. |
// | |
// | You should have received a copy of the GNU General Public License |
// | along with this program; if not, write to the Free Software |
// | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
// | |
// -------------------------------------------------------------------------------
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function net2ftp($action) {
// --------------
// This function is the main net2ftp function; it is the interface between 3rd party
// scripts (CMS, control panels, etc), and the internal net2ftp modules and plugins.
//
// This function is called 5 times per pageload: to send the HTTP headers, to print
// the javascript code, to print the CSS code, to print the body onload actions and
// finally to print the body content.
// --------------
// -------------------------------------------------------------------------
// Check that "sendHttpHeaders" action is only executed once
// Check that no other actions can be executed if "sendHttpHeaders" has not yet been executed
// -------------------------------------------------------------------------
if ($action == "sendHttpHeaders") {
if (defined("NET2FTP_SENDHTTPHEADERS") == true) { echo "Error: please call the net2ftp(\$action) function only once with \$action = \"sendHttpHeaders\"!"; return false; }
else { define("NET2FTP_SENDHTTPHEADERS", 1); }
}
else {
if (defined("NET2FTP_SENDHTTPHEADERS") == false) { echo "Error: please call the net2ftp(\$action) function first with \$action = \"sendHttpHeaders\"!"; return false; }
}
// -------------------------------------------------------------------------
// Global variables
// -------------------------------------------------------------------------
global $net2ftp_settings, $net2ftp_globals, $net2ftp_result, $net2ftp_messages;
// Set the NET2FTP constant which is used to check if template files are called by net2ftp
if (defined("NET2FTP") == false) { define("NET2FTP", 1); }
// Initialize the global variables
if ($action == "sendHttpHeaders") {
$net2ftp_globals = array();
$net2ftp_messages = array();
$net2ftp_output = array();
$net2ftp_result["success"] = true;
$net2ftp_result["errormessage"] = "";
$net2ftp_result["debug_backtrace"] = "";
$net2ftp_result["exit"] = false;
$net2ftp_settings = array();
}
// -------------------------------------------------------------------------
// If an error occured during a previous execution of net2ftp(), return false
// and let index.php print the error message
// -------------------------------------------------------------------------
if ($net2ftp_result["success"] == false) { return false; }
// -------------------------------------------------------------------------
// Input checks
// -------------------------------------------------------------------------
if ($action != "sendHttpHeaders" && $action != "printJavascript" && $action != "printCss" && $action != "printBodyOnload" && $action != "printBody") {
$net2ftp_result["success"] = false;
$net2ftp_result["errormessage"] = "The \$action variable has an unknown value: $action.";
$net2ftp_result["debug_backtrace"] = debug_backtrace();
logError();
return false;
}
// -------------------------------------------------------------------------
// Read settings files
// -------------------------------------------------------------------------
if ($action == "sendHttpHeaders") {
require(NET2FTP_APPLICATION_ROOTDIR . "/settings.inc.php");
require(NET2FTP_APPLICATION_ROOTDIR . "/settings_authorizations.inc.php");
require(NET2FTP_APPLICATION_ROOTDIR . "/settings_screens.inc.php");
}
// -------------------------------------------------------------------------
// Main directories
// -------------------------------------------------------------------------
$net2ftp_globals["application_rootdir"] = NET2FTP_APPLICATION_ROOTDIR;
if (NET2FTP_APPLICATION_ROOTDIR_URL == "/") { $net2ftp_globals["application_rootdir_url"] = ""; }
else { $net2ftp_globals["application_rootdir_url"] = NET2FTP_APPLICATION_ROOTDIR_URL; }
$net2ftp_globals["application_includesdir"] = $net2ftp_globals["application_rootdir"] . "/includes";
$net2ftp_globals["application_languagesdir"] = $net2ftp_globals["application_rootdir"] . "/languages";
$net2ftp_globals["application_modulesdir"] = $net2ftp_globals["application_rootdir"] . "/modules";
$net2ftp_globals["application_pluginsdir"] = $net2ftp_globals["application_rootdir"] . "/plugins";
$net2ftp_globals["application_skinsdir"] = $net2ftp_globals["application_rootdir"] . "/skins";
$net2ftp_globals["application_tempdir"] = $net2ftp_globals["application_rootdir"] . "/temp";
// -------------------------------------------------------------------------
// Set basic settings
// -------------------------------------------------------------------------
if ($action == "sendHttpHeaders") {
// Do not run the script to the end if the user hits the stop button
// ignore_user_abort();
// Execute function shutdown() if the script reaches the maximum execution time (usually 30 seconds)
// DON'T REGISTER IT HERE YET, as this causes errors on newer versions of PHP; first include the function libraries
// register_shutdown_function("net2ftp_shutdown");
// Set the error reporting level
// Note: the error reporting level is already set to none in index.xml.php, to avoid XML parsing errors
if (substr($_SERVER["PHP_SELF"], strlen($_SERVER["PHP_SELF"])-8, 8) == ".xml.php") { error_reporting(0); }
elseif ($net2ftp_settings["error_reporting"] == "ALL") { error_reporting(E_ALL); }
elseif ($net2ftp_settings["error_reporting"] == "NONE") { error_reporting(0); }
else { error_reporting(E_ERROR | E_WARNING | E_PARSE); }
// Timer: start
$net2ftp_globals["starttime"] = microtime();
$net2ftp_globals["endtime"] = microtime();
}
// Set default timezone
date_default_timezone_set("Europe/Paris");
// Set the PHP temporary directory
// putenv("TMPDIR=" . $net2ftp_globals["application_tempdir"]);
// -------------------------------------------------------------------------
// Function libraries:
// 1. Libraries which are always needed
// 2. Register global variables
// 3. Function libraries which are needed depending on certain variables
// // --> Do this only once, when $action == "sendHttpHeaders"
// -------------------------------------------------------------------------
if ($action == "sendHttpHeaders") {
// 1. Libraries which are always needed
require_once($net2ftp_globals["application_includesdir"] . "/authorizations.inc.php");
require_once($net2ftp_globals["application_includesdir"] . "/consumption.inc.php");
require_once($net2ftp_globals["application_includesdir"] . "/database.inc.php");
require_once($net2ftp_globals["application_includesdir"] . "/errorhandling.inc.php");
require_once($net2ftp_globals["application_includesdir"] . "/filesystem.inc.php");
require_once($net2ftp_globals["application_includesdir"] . "/html.inc.php");
require_once($net2ftp_globals["application_includesdir"] . "/StonePhpSafeCrypt.php");
require_once($net2ftp_globals["application_includesdir"] . "/logging.inc.php");
require_once($net2ftp_globals["application_languagesdir"] . "/languages.inc.php");
require_once($net2ftp_globals["application_skinsdir"] . "/skins.inc.php");
// 1. Define functions which are used, but which did not exist before PHP version 4.3.0
if (version_compare(phpversion(), "4.3.0", "<")) {
require_once($net2ftp_globals["application_includesdir"] . "/before430.inc.php");
}
// 2. Register global variables (POST, GET, GLOBAL, ...)
require_once($net2ftp_globals["application_includesdir"] . "/registerglobals.inc.php");
// 3. Function libraries which are needed depending on certain variables
if ($net2ftp_globals["state"] == "upload" || $net2ftp_globals["state"] == "unzip") {
require_once($net2ftp_globals["application_includesdir"] . "/pclerror.lib.php");
require_once($net2ftp_globals["application_includesdir"] . "/pcltar.lib.php");
require_once($net2ftp_globals["application_includesdir"] . "/pcltrace.lib.php");
require_once($net2ftp_globals["application_includesdir"] . "/pclzip.lib.php");
}
if ($net2ftp_globals["state"] == "advanced_ftpserver" || $net2ftp_globals["state"] == "advanced_parsing" ||
$net2ftp_globals["state"] == "advanced_webserver" || $net2ftp_globals["state"] == "browse" ||
$net2ftp_globals["state"] == "copymovedelete" || $net2ftp_globals["state"] == "chmod" ||
$net2ftp_globals["state"] == "calculatesize" || $net2ftp_globals["state"] == "downloadzip" ||
$net2ftp_globals["state"] == "findstring" || $net2ftp_globals["state"] == "followsymlink" ||
$net2ftp_globals["state"] == "install" || $net2ftp_globals["state"] == "zip") {
require_once($net2ftp_globals["application_includesdir"] . "/browse.inc.php");
}
if ($net2ftp_globals["state"] == "downloadzip" || $net2ftp_globals["state"] == "zip") {
require_once($net2ftp_globals["application_includesdir"] . "/zip.lib.php");
}
// 4. Load the plugins
require_once($net2ftp_globals["application_pluginsdir"] . "/plugins.inc.php");
$net2ftp_globals["activePlugins"] = getActivePlugins();
net2ftp_plugin_includePhpFiles();
// 5. Load the language file
includeLanguageFile();
}
// -------------------------------------------------------------------------
// Execute function shutdown() if the script reaches the maximum execution time (usually 30 seconds)
// -------------------------------------------------------------------------
if ($action == "sendHttpHeaders") {
register_shutdown_function("net2ftp_shutdown");
}
// -------------------------------------------------------------------------
// Log access and rotate logs
// --> Do this only once, when $action == "sendHttpHeaders"
// -------------------------------------------------------------------------
if ($action == "sendHttpHeaders") {
logAccess();
if ($net2ftp_result["success"] == false) {
logError();
return false;
}
rotateLogs();
if ($net2ftp_result["success"] == false) {
logError();
return false;
}
}
// -------------------------------------------------------------------------
// Check authorizations
// --> Do this only once, when $action == "sendHttpHeaders"
// -------------------------------------------------------------------------
if ($action == "sendHttpHeaders" && $net2ftp_settings["check_authorization"] == "yes" && $net2ftp_globals["ftpserver"] != "") {
checkAuthorization($net2ftp_globals["ftpserver"], $net2ftp_globals["ftpserverport"], $net2ftp_globals["directory"], $net2ftp_globals["username"]);
if ($net2ftp_result["success"] == false) {
logError();
return false;
}
}
// -------------------------------------------------------------------------
// Get the consumption counter values from the database
// This retrieves the consumption of network and server resources for the
// current IP address and FTP server from the database, and stores these
// values in global variables. See /includes/consumption.inc.php for the details.
// --> Do this only once, when $action == "sendHttpHeaders"
// -------------------------------------------------------------------------
if ($action == "sendHttpHeaders") {
getConsumption();
if ($net2ftp_result["success"] == false) {
logError();
return false;
}
}
// -------------------------------------------------------------------------
// Execute the action!
// -------------------------------------------------------------------------
// ------------------------------------
// For most modules, everything must be done: send headers, print body, etc
// ------------------------------------
if ($net2ftp_globals["state"] == "admin" ||
$net2ftp_globals["state"] == "admin_createtables" ||
$net2ftp_globals["state"] == "admin_emptylogs" ||
$net2ftp_globals["state"] == "admin_viewlogs" ||
$net2ftp_globals["state"] == "advanced" ||
$net2ftp_globals["state"] == "advanced_ftpserver" ||
$net2ftp_globals["state"] == "advanced_parsing" ||
$net2ftp_globals["state"] == "advanced_webserver" ||
$net2ftp_globals["state"] == "bookmark" ||
$net2ftp_globals["state"] == "browse" ||
$net2ftp_globals["state"] == "calculatesize" ||
$net2ftp_globals["state"] == "chmod" ||
$net2ftp_globals["state"] == "copymovedelete" ||
$net2ftp_globals["state"] == "edit" ||
$net2ftp_globals["state"] == "findstring" ||
$net2ftp_globals["state"] == "getcookies" ||
$net2ftp_globals["state"] == "install" ||
($net2ftp_globals["state"] == "jupload" && $net2ftp_globals["screen"] == 1) ||
$net2ftp_globals["state"] == "login" ||
$net2ftp_globals["state"] == "login_small" ||
$net2ftp_globals["state"] == "logout" ||
$net2ftp_globals["state"] == "newdir" ||
$net2ftp_globals["state"] == "raw" ||
$net2ftp_globals["state"] == "rename" ||
$net2ftp_globals["state"] == "unzip" ||
$net2ftp_globals["state"] == "upload" ||
($net2ftp_globals["state"] == "view" && $net2ftp_globals["state2"] == "") ||
$net2ftp_globals["state"] == "zip") {
require_once($net2ftp_globals["application_modulesdir"] . "/" . $net2ftp_globals["state"] . "/" . $net2ftp_globals["state"] . ".inc.php");
if ($action == "sendHttpHeaders") {
net2ftp_module_sendHttpHeaders();
// If needed, exit to avoid sending non-header output (by net2ftp or other application)
// Example: if a module sends a HTTP redirect header (See /includes/authorizations.inc.php function checkAdminUsernamePassword()!)
if ($net2ftp_result["exit"] == true) { exit(); }
}
elseif ($action == "printJavascript") {
net2ftp_module_printJavascript();
net2ftp_plugin_printJavascript();
net2ftp_skin_printJavascript();
}
elseif ($action == "printCss") {
net2ftp_module_printCss();
net2ftp_plugin_printCss();
net2ftp_skin_printCss();
}
elseif ($action == "printBodyOnload") {
net2ftp_module_printBodyOnload();
net2ftp_plugin_printBodyOnload();
}
elseif ($action == "printBody") {
// Print the status bar to be able to show the progress
if (isStatusbarActive() == true) {
require_once($net2ftp_globals["application_skinsdir"] . "/" . $net2ftp_globals["skin"] . "/header.template.php");
}
require_once($net2ftp_globals["application_skinsdir"] . "/" . $net2ftp_globals["skin"] . "/status/status.inc.php");
// Do the work and meanwhile update the progress bar
net2ftp_module_printBody();
// Update the consumption statistics
$net2ftp_globals["endtime"] = microtime();
$net2ftp_globals["time_taken"] = timer();
addConsumption(0, $net2ftp_globals["time_taken"]);
putConsumption();
// Set the progress bar to "finished"
if (isStatusbarActive() == true) {
$statusmessage = __("Script finished in %1\$s seconds", $net2ftp_globals["time_taken"]);
setStatus(1, 1, $statusmessage);
}
}
}
// ------------------------------------
// For some modules, only headers must be sent
// ------------------------------------
elseif ($net2ftp_globals["state"] == "clearcookies" ||
$net2ftp_globals["state"] == "downloadfile" ||
$net2ftp_globals["state"] == "downloadzip" ||
$net2ftp_globals["state"] == "followsymlink" ||
($net2ftp_globals["state"] == "jupload" && $net2ftp_globals["screen"] == 2) ||
($net2ftp_globals["state"] == "view" && $net2ftp_globals["state2"] != "")) {
require_once($net2ftp_globals["application_modulesdir"] . "/" . $net2ftp_globals["state"] . "/" . $net2ftp_globals["state"] . ".inc.php");
if ($action == "sendHttpHeaders") {
// Do the work - do not update the progress bar
net2ftp_module_sendHttpHeaders();
// Update the consumption statistics
$net2ftp_globals["endtime"] = microtime();
$net2ftp_globals["time_taken"] = timer();
addConsumption(0, $net2ftp_globals["time_taken"]);
putConsumption();
// Exit to avoid sending non-header output (by net2ftp or other application)
exit();
}
elseif ($action == "printJavascript") { }
elseif ($action == "printCss") { }
elseif ($action == "printBodyOnload") { }
elseif ($action == "printBody") { }
}
else {
$errormessage = __("Unexpected state string: %1\$s. Exiting.", $net2ftp_globals["state"]);
setErrorVars(false, $errormessage, debug_backtrace(), __FILE__, __LINE__);
logError();
return false;
}
// -------------------------------------------------------------------------
// Log errors
// -------------------------------------------------------------------------
if ($net2ftp_result["success"] == false) {
logError();
return false;
}
} // end function net2ftp_main
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function isStatusbarActive() {
// --------------
// This function returns if the status bar should be shown or not, depending
// on the state and state2 variables
// --------------
global $net2ftp_globals;
// If $net2ftp_globals["isStatusbarActive"] is not yet filled, calculate its value
// and fill it in
if (isset($net2ftp_globals["isStatusbarActive"]) == false) {
if ($net2ftp_globals["skin"] == "openlaszlo") { $net2ftp_globals["isStatusbarActive"] = false; }
elseif (
$net2ftp_globals["state"] == "admin" ||
$net2ftp_globals["state"] == "admin_createtables" ||
$net2ftp_globals["state"] == "admin_emptylogs" ||
$net2ftp_globals["state"] == "admin_viewlogs" ||
$net2ftp_globals["state"] == "advanced" ||
$net2ftp_globals["state"] == "advanced_ftpserver" ||
$net2ftp_globals["state"] == "advanced_parsing" ||
$net2ftp_globals["state"] == "advanced_webserver" ||
$net2ftp_globals["state"] == "bookmark" ||
($net2ftp_globals["state"] == "browse" && $net2ftp_globals["state2"] == "main") ||
$net2ftp_globals["state"] == "calculatesize" ||
$net2ftp_globals["state"] == "chmod" ||
$net2ftp_globals["state"] == "copymovedelete" ||
$net2ftp_globals["state"] == "easywebsite" ||
$net2ftp_globals["state"] == "findstring" ||
$net2ftp_globals["state"] == "install" ||
$net2ftp_globals["state"] == "jupload" ||
$net2ftp_globals["state"] == "newdir" ||
$net2ftp_globals["state"] == "newfile" ||
$net2ftp_globals["state"] == "raw" ||
$net2ftp_globals["state"] == "rename" ||
$net2ftp_globals["state"] == "unzip" ||
$net2ftp_globals["state"] == "updatefile" ||
$net2ftp_globals["state"] == "upload" ||
$net2ftp_globals["state"] == "view" ||
$net2ftp_globals["state"] == "zip") {
$net2ftp_globals["isStatusbarActive"] = true;
}
else {
$net2ftp_globals["isStatusbarActive"] = false;
}
}
// Return the value of $net2ftp_globals["isStatusbarActive"]
return $net2ftp_globals["isStatusbarActive"];
} // end function isStatusbarActive
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// **************************************************************************************
// ** **
// ** **
function stopwatch() {
// --------------
// This function prints the total time elapsed, and the time elapsed since the previous call
// --------------
global $net2ftp_globals;
// Now
list($now_usec, $now_sec) = explode(' ', microtime());
$now = ((float)$now_usec + (float)$now_sec);
// Initialization
if (isset($net2ftp_globals["stopwatch_starttime"]) == false) {
$net2ftp_globals["stopwatch_starttime"] = $now;
}
if (isset($net2ftp_globals["stopwatch_endtime"]) == false) {
$net2ftp_globals["stopwatch_endtime"] = $now;
}
// Total time elapsed = now - starttime
$total_elapsed = $now - $net2ftp_globals["stopwatch_starttime"];
$total_elapsed = number_format($total_elapsed, 4);
// Time since previous stopwatch = now - previous endtime
$delta_elapsed = $now - $net2ftp_globals["stopwatch_endtime"];
$delta_elapsed = number_format($delta_elapsed, 4);
// Set the new value for endtime
$net2ftp_globals["stopwatch_endtime"] = $now;
// Print $total_elapsed and $delta_elapsed
echo $total_elapsed . " - " . $delta_elapsed . "<br />\n";
} // End function stopwatch()
// ** **
// ** **
// **************************************************************************************
// **************************************************************************************
?>

View file

@ -0,0 +1,132 @@
<?php
// --------------------------------------------------------------------------------
// PhpConcept Library (PCL) Error 1.0
// --------------------------------------------------------------------------------
// License GNU/GPL - Vincent Blavet - Mars 2001
// http://www.phpconcept.net & http://phpconcept.free.fr
// --------------------------------------------------------------------------------
// Français :
// La description de l'usage de la librairie PCL Error 1.0 n'est pas encore
// disponible. Celle-ci n'est pour le moment distribuée qu'avec les
// développements applicatifs de PhpConcept.
// Une version indépendante sera bientot disponible sur http://www.phpconcept.net
//
// English :
// The PCL Error 1.0 library description is not available yet. This library is
// released only with PhpConcept application and libraries.
// An independant release will be soon available on http://www.phpconcept.net
//
// --------------------------------------------------------------------------------
//
// * Avertissement :
//
// Cette librairie a été créée de façon non professionnelle.
// Son usage est au risque et péril de celui qui l'utilise, en aucun cas l'auteur
// de ce code ne pourra être tenu pour responsable des éventuels dégats qu'il pourrait
// engendrer.
// Il est entendu cependant que l'auteur a réalisé ce code par plaisir et n'y a
// caché aucun virus, ni malveillance.
// Cette libairie est distribuée sous la license GNU/GPL (http://www.gnu.org)
//
// * Auteur :
//
// Ce code a été écrit par Vincent Blavet (vincent@blavet.net) sur son temps
// de loisir.
//
// --------------------------------------------------------------------------------
// ----- Look for double include
if (!defined("PCLERROR_LIB"))
{
define( "PCLERROR_LIB", 1 );
// ----- Version
$g_pcl_error_version = "1.0";
// ----- Internal variables
// These values must only be change by PclError library functions
$g_pcl_error_string = "";
$g_pcl_error_code = 1;
// --------------------------------------------------------------------------------
// Function : PclErrorLog()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function PclErrorLog($p_error_code=0, $p_error_string="")
{
global $g_pcl_error_string;
global $g_pcl_error_code;
$g_pcl_error_code = $p_error_code;
$g_pcl_error_string = $p_error_string;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclErrorFatal()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function PclErrorFatal($p_file, $p_line, $p_error_string="")
{
global $g_pcl_error_string;
global $g_pcl_error_code;
$v_message = "<html><body>";
$v_message .= "<p align=center><font color=red bgcolor=white><b>PclError Library has detected a fatal error on file '$p_file', line $p_line</b></font></p>";
$v_message .= "<p align=center><font color=red bgcolor=white><b>$p_error_string</b></font></p>";
$v_message .= "</body></html>";
die($v_message);
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclErrorReset()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function PclErrorReset()
{
global $g_pcl_error_string;
global $g_pcl_error_code;
$g_pcl_error_code = 1;
$g_pcl_error_string = "";
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclErrorCode()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function PclErrorCode()
{
global $g_pcl_error_string;
global $g_pcl_error_code;
return($g_pcl_error_code);
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclErrorString()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function PclErrorString()
{
global $g_pcl_error_string;
global $g_pcl_error_code;
return($g_pcl_error_string." [code $g_pcl_error_code]");
}
// --------------------------------------------------------------------------------
// ----- End of double include look
}
?>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,735 @@
<?php
// --------------------------------------------------------------------------------
// PhpConcept Library (PCL) Trace 2.0-beta1
// --------------------------------------------------------------------------------
// License GNU/GPL - Vincent Blavet - August 2003
// http://www.phpconcept.net
// --------------------------------------------------------------------------------
//
// The PCL Trace library description is not available yet.
// This library was first released only with PclZip library.
// An independant release will be soon available on http://www.phpconcept.net
//
// --------------------------------------------------------------------------------
//
// Warning :
// This library and the associated files are non commercial, non professional
// work.
// It should not have unexpected results. However if any damage is caused by
// this software the author can not be responsible.
// The use of this software is at the risk of the user.
//
// --------------------------------------------------------------------------------
// ----- Version
$g_pcltrace_version = "2.0-beta1";
// ----- Internal variables
// These values must be change by PclTrace library functions
$g_pcl_trace_mode = "memory";
$g_pcl_trace_filename = "trace.txt";
$g_pcl_trace_name = array();
$g_pcl_trace_index = 0;
$g_pcl_trace_level = 0;
$g_pcl_trace_suspend = false;
//$g_pcl_trace_entries = array();
// ----- For compatibility reason
define ('PCLTRACE_LIB', 1);
// --------------------------------------------------------------------------------
// Function : TrOn($p_level, $p_mode, $p_filename)
// Description :
// Parameters :
// $p_level : Trace level
// $p_mode : Mode of trace displaying :
// 'normal' : messages are displayed at function call
// 'memory' : messages are memorized in a table and can be display by
// TrDisplay() function. (default)
// 'log' : messages are writed in the file $p_filename
// --------------------------------------------------------------------------------
function PclTraceOn($p_level=1, $p_mode="memory", $p_filename="trace.txt")
{
TrOn($p_level, $p_mode, $p_filename);
}
function TrOn($p_level=1, $p_mode="memory", $p_filename="trace.txt")
{
global $g_pcl_trace_level;
global $g_pcl_trace_mode;
global $g_pcl_trace_filename;
global $g_pcl_trace_name;
global $g_pcl_trace_index;
global $g_pcl_trace_entries;
global $g_pcl_trace_suspend;
// ----- Enable trace mode
$g_pcl_trace_level = $p_level;
// ----- Memorize mode and filename
switch ($p_mode) {
case "normal" :
case "memory" :
case "log" :
$g_pcl_trace_mode = $p_mode;
break;
default :
$g_pcl_trace_mode = "logged";
}
// ----- Memorize filename
$g_pcl_trace_filename = $p_filename;
$g_pcl_trace_suspend = false;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : IsTrOn()
// Description :
// Return value :
// The trace level (0 for disable).
// --------------------------------------------------------------------------------
function PclTraceIsOn()
{
return IsTrOn();
}
function IsTrOn()
{
global $g_pcl_trace_level;
return($g_pcl_trace_level);
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : TrOff()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function PclTraceOff()
{
TrOff();
}
function TrOff()
{
global $g_pcl_trace_level;
global $g_pcl_trace_mode;
global $g_pcl_trace_filename;
global $g_pcl_trace_name;
global $g_pcl_trace_index;
// ----- Clean
$g_pcl_trace_mode = "memory";
unset($g_pcl_trace_entries);
unset($g_pcl_trace_name);
unset($g_pcl_trace_index);
// ----- Switch off trace
$g_pcl_trace_level = 0;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTraceSuspend()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function PclTraceSuspend()
{
global $g_pcl_trace_suspend;
$g_pcl_trace_suspend = true;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTraceResume()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function PclTraceResume()
{
global $g_pcl_trace_suspend;
$g_pcl_trace_suspend = false;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : TrFctStart()
// Description :
// Just a trace function for debbugging purpose before I use a better tool !!!!
// Start and stop of this function is by $g_pcl_trace_level global variable.
// Parameters :
// $p_level : Level of trace required.
// --------------------------------------------------------------------------------
function PclTraceFctStart($p_file, $p_line, $p_name, $p_param="", $p_message="")
{
TrFctStart($p_file, $p_line, $p_name, $p_param, $p_message);
}
function TrFctStart($p_file, $p_line, $p_name, $p_param="", $p_message="")
{
global $g_pcl_trace_level;
global $g_pcl_trace_mode;
global $g_pcl_trace_filename;
global $g_pcl_trace_name;
global $g_pcl_trace_index;
global $g_pcl_trace_entries;
global $g_pcl_trace_suspend;
// ----- Look for disabled trace
if (($g_pcl_trace_level < 1) || ($g_pcl_trace_suspend))
return;
// ----- Add the function name in the list
if (!isset($g_pcl_trace_name))
$g_pcl_trace_name = $p_name;
else
$g_pcl_trace_name .= ",".$p_name;
// ----- Update the function entry
$i = sizeof($g_pcl_trace_entries);
$g_pcl_trace_entries[$i]['name'] = $p_name;
$g_pcl_trace_entries[$i]['param'] = $p_param;
$g_pcl_trace_entries[$i]['message'] = "";
$g_pcl_trace_entries[$i]['file'] = $p_file;
$g_pcl_trace_entries[$i]['line'] = $p_line;
$g_pcl_trace_entries[$i]['index'] = $g_pcl_trace_index;
$g_pcl_trace_entries[$i]['type'] = "1"; // means start of function
// ----- Update the message entry
if ($p_message != "")
{
$i = sizeof($g_pcl_trace_entries);
$g_pcl_trace_entries[$i]['name'] = "";
$g_pcl_trace_entries[$i]['param'] = "";
$g_pcl_trace_entries[$i]['message'] = $p_message;
$g_pcl_trace_entries[$i]['file'] = $p_file;
$g_pcl_trace_entries[$i]['line'] = $p_line;
$g_pcl_trace_entries[$i]['index'] = $g_pcl_trace_index;
$g_pcl_trace_entries[$i]['type'] = "3"; // means message
}
// ----- Action depending on mode
PclTraceAction($g_pcl_trace_entries[$i]);
// ----- Increment the index
$g_pcl_trace_index++;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : TrFctEnd()
// Description :
// Just a trace function for debbugging purpose before I use a better tool !!!!
// Start and stop of this function is by $g_pcl_trace_level global variable.
// Parameters :
// $p_level : Level of trace required.
// --------------------------------------------------------------------------------
function PclTraceFctEnd($p_file, $p_line, $p_return=1, $p_message="")
{
TrFctEnd($p_file, $p_line, $p_return, $p_message);
}
function TrFctEnd($p_file, $p_line, $p_return=1, $p_message="")
{
global $g_pcl_trace_level;
global $g_pcl_trace_mode;
global $g_pcl_trace_filename;
global $g_pcl_trace_name;
global $g_pcl_trace_index;
global $g_pcl_trace_entries;
global $g_pcl_trace_suspend;
// ----- Look for disabled trace
if (($g_pcl_trace_level < 1) || ($g_pcl_trace_suspend))
return;
// ----- Extract the function name in the list
// ----- Remove the function name in the list
if (!($v_name = strrchr($g_pcl_trace_name, ",")))
{
$v_name = $g_pcl_trace_name;
$g_pcl_trace_name = "";
}
else
{
$g_pcl_trace_name = substr($g_pcl_trace_name, 0, strlen($g_pcl_trace_name)-strlen($v_name));
$v_name = substr($v_name, -strlen($v_name)+1);
}
// ----- Decrement the index
$g_pcl_trace_index--;
// ----- Update the message entry
if ($p_message != "")
{
$i = sizeof($g_pcl_trace_entries);
$g_pcl_trace_entries[$i]['name'] = "";
$g_pcl_trace_entries[$i]['param'] = "";
$g_pcl_trace_entries[$i]['message'] = $p_message;
$g_pcl_trace_entries[$i]['file'] = $p_file;
$g_pcl_trace_entries[$i]['line'] = $p_line;
$g_pcl_trace_entries[$i]['index'] = $g_pcl_trace_index;
$g_pcl_trace_entries[$i]['type'] = "3"; // means message
}
// ----- Update the function entry
$i = sizeof($g_pcl_trace_entries);
$g_pcl_trace_entries[$i]['name'] = $v_name;
$g_pcl_trace_entries[$i]['param'] = $p_return;
$g_pcl_trace_entries[$i]['message'] = "";
$g_pcl_trace_entries[$i]['file'] = $p_file;
$g_pcl_trace_entries[$i]['line'] = $p_line;
$g_pcl_trace_entries[$i]['index'] = $g_pcl_trace_index;
$g_pcl_trace_entries[$i]['type'] = "2"; // means end of function
// ----- Action depending on mode
PclTraceAction($g_pcl_trace_entries[$i]);
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : TrFctMessage()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function PclTraceFctMessage($p_file, $p_line, $p_level, $p_message="")
{
TrFctMessage($p_file, $p_line, $p_level, $p_message);
}
function TrFctMessage($p_file, $p_line, $p_level, $p_message="")
{
global $g_pcl_trace_level;
global $g_pcl_trace_mode;
global $g_pcl_trace_filename;
global $g_pcl_trace_name;
global $g_pcl_trace_index;
global $g_pcl_trace_entries;
global $g_pcl_trace_suspend;
// ----- Look for disabled trace
if (($g_pcl_trace_level < $p_level) || ($g_pcl_trace_suspend))
return;
// ----- Update the entry
$i = sizeof($g_pcl_trace_entries);
$g_pcl_trace_entries[$i]['name'] = "";
$g_pcl_trace_entries[$i]['param'] = "";
$g_pcl_trace_entries[$i]['message'] = $p_message;
$g_pcl_trace_entries[$i]['file'] = $p_file;
$g_pcl_trace_entries[$i]['line'] = $p_line;
$g_pcl_trace_entries[$i]['index'] = $g_pcl_trace_index;
$g_pcl_trace_entries[$i]['type'] = "3"; // means message of function
// ----- Action depending on mode
PclTraceAction($g_pcl_trace_entries[$i]);
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : TrMessage()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function PclTraceMessage($p_file, $p_line, $p_level, $p_message="")
{
TrMessage($p_file, $p_line, $p_level, $p_message);
}
function TrMessage($p_file, $p_line, $p_level, $p_message="")
{
global $g_pcl_trace_level;
global $g_pcl_trace_mode;
global $g_pcl_trace_filename;
global $g_pcl_trace_name;
global $g_pcl_trace_index;
global $g_pcl_trace_entries;
global $g_pcl_trace_suspend;
// ----- Look for disabled trace
if (($g_pcl_trace_level < $p_level) || ($g_pcl_trace_suspend))
return;
// ----- Update the entry
$i = sizeof($g_pcl_trace_entries);
$g_pcl_trace_entries[$i]['name'] = "";
$g_pcl_trace_entries[$i]['param'] = "";
$g_pcl_trace_entries[$i]['message'] = $p_message;
$g_pcl_trace_entries[$i]['file'] = $p_file;
$g_pcl_trace_entries[$i]['line'] = $p_line;
$g_pcl_trace_entries[$i]['index'] = $g_pcl_trace_index;
$g_pcl_trace_entries[$i]['type'] = "4"; // means simple message
// ----- Action depending on mode
PclTraceAction($g_pcl_trace_entries[$i]);
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : TrDisplay()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function PclTraceDisplay()
{
TrDisplay();
}
function TrDisplay()
{
global $g_pcl_trace_level;
global $g_pcl_trace_mode;
global $g_pcl_trace_filename;
global $g_pcl_trace_name;
global $g_pcl_trace_index;
global $g_pcl_trace_entries;
global $g_pcl_trace_suspend;
// ----- Look for disabled trace
if (($g_pcl_trace_level <= 0) || ($g_pcl_trace_mode != "memory") || ($g_pcl_trace_suspend))
return;
$v_font = "\"Verdana, Arial, Helvetica, sans-serif\"";
// ----- Trace Header
echo "<table width=100% border=0 cellspacing=0 cellpadding=0>";
echo "<tr bgcolor=#0000CC>";
echo "<td bgcolor=#0000CC width=1>";
echo "</td>";
echo "<td><div align=center><font size=3 color=#FFFFFF face=$v_font>Trace</font></div></td>";
echo "</tr>";
echo "<tr>";
echo "<td bgcolor=#0000CC width=1>";
echo "</td>";
echo "<td>";
// ----- Content header
echo "<table width=100% border=0 cellspacing=0 cellpadding=0>";
// ----- Display
$v_again=0;
for ($i=0; $i<sizeof($g_pcl_trace_entries); $i++)
{
// ---- Row header
echo "<tr>";
echo "<td><table width=100% border=0 cellspacing=0 cellpadding=0><tr>";
$n = ($g_pcl_trace_entries[$i]['index']+1)*10;
echo "<td width=".$n."><table width=100% border=0 cellspacing=0 cellpadding=0><tr>";
for ($j=0; $j<=$g_pcl_trace_entries[$i]['index']; $j++)
{
if ($j==$g_pcl_trace_entries[$i]['index'])
{
if (($g_pcl_trace_entries[$i]['type'] == 1) || ($g_pcl_trace_entries[$i]['type'] == 2))
echo "<td width=10><div align=center><font size=2 face=$v_font>+</font></div></td>";
}
else
echo "<td width=10><div align=center><font size=2 face=$v_font>|</font></div></td>";
}
//echo "<td>&nbsp</td>";
echo "</tr></table></td>";
echo "<td width=2></td>";
switch ($g_pcl_trace_entries[$i]['type']) {
case 1:
echo "<td><font size=2 face=$v_font>".$g_pcl_trace_entries[$i]['name']."(".$g_pcl_trace_entries[$i]['param'].")</font></td>";
break;
case 2:
echo "<td><font size=2 face=$v_font>".$g_pcl_trace_entries[$i]['name']."()=".$g_pcl_trace_entries[$i]['param']."</font></td>";
break;
case 3:
case 4:
echo "<td><table width=100% border=0 cellspacing=0 cellpadding=0><td width=20></td><td>";
echo "<font size=2 face=$v_font>".$g_pcl_trace_entries[$i]['message']."</font>";
echo "</td></table></td>";
break;
default:
echo "<td><font size=2 face=$v_font>".$g_pcl_trace_entries[$i]['name']."(".$g_pcl_trace_entries[$i]['param'].")</font></td>";
}
echo "</tr></table></td>";
echo "<td width=5></td>";
echo "<td><font size=1 face=$v_font>".basename($g_pcl_trace_entries[$i]['file'])."</font></td>";
echo "<td width=5></td>";
echo "<td><font size=1 face=$v_font>".$g_pcl_trace_entries[$i]['line']."</font></td>";
echo "</tr>";
}
// ----- Content footer
echo "</table>";
// ----- Trace footer
echo "</td>";
echo "<td bgcolor=#0000CC width=1>";
echo "</td>";
echo "</tr>";
echo "<tr bgcolor=#0000CC>";
echo "<td bgcolor=#0000CC width=1>";
echo "</td>";
echo "<td><div align=center><font color=#FFFFFF face=$v_font>&nbsp</font></div></td>";
echo "</tr>";
echo "</table>";
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : TrDisplayNew()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function PclTraceDisplayNew()
{
global $g_pcl_trace_level;
global $g_pcl_trace_mode;
global $g_pcl_trace_filename;
global $g_pcl_trace_name;
global $g_pcl_trace_index;
global $g_pcl_trace_entries;
global $g_pcl_trace_suspend;
// ----- Look for disabled trace
if (($g_pcl_trace_level <= 0) || ($g_pcl_trace_mode != "memory") || ($g_pcl_trace_suspend))
return;
?>
<script language="javascript">
function PclTraceToggleView(element) {
if (element.style.visibility == 'visible') {
PclTraceHide(element);
} else {
PclTraceShow(element);
}
}
function PclTraceShow(element) {
element.style.visibility = 'visible';
element.style.position='relative';
}
function PclTraceHide(element) {
element.style.visibility = 'hidden';
element.style.position='absolute';
}
</script>
<table width="100%" border="0" cellspacing="0" cellpadding="0" bordercolor="#0000CC">
<tr>
<td bgcolor="#0000CC">
<div align="center"><font face="Verdana, Arial, Helvetica, sans-serif" color="#FFFFFF"><b>Trace</b></font></div>
</td>
</tr>
<tr>
<td>
<?php
$v_font = "\"Verdana, Arial, Helvetica, sans-serif\"";
// ----- Trace Header
// ----- Display the items
$v_again=0;
for ($i=0; $i<sizeof($g_pcl_trace_entries); $i++)
{
switch ($g_pcl_trace_entries[$i]['type']) {
case 1: // fct start
PclTraceDisplayItemStart($i);
break;
case 2: // fct stop
PclTraceDisplayItemStop($i);
break;
case 3: // fct msg
case 4: // msg
PclTraceDisplayItemMsg($i);
break;
default:
}
/*
echo "</tr></table></td>";
echo "<td width=5></td>";
echo "<td><font size=1 face=$v_font>".basename($g_pcl_trace_entries[$i]['file'])."</font></td>";
echo "<td width=5></td>";
echo "<td><font size=1 face=$v_font>".$g_pcl_trace_entries[$i]['line']."</font></td>";
echo "</tr>";
*/
}
// ----- Trace footer
?>
</td>
</tr>
<tr>
<td bgcolor="#0000CC">&nbsp;</td>
</tr>
</table>
<script language="javascript">
function PclTraceShowAll() {
<?php
for ($i=0; $i<sizeof($g_pcl_trace_entries); $i++) {
if ($g_pcl_trace_entries[$i]['type'] == 1) {
echo "PclTraceShow(document.getElementById('fct-".$i."'));";
}
}
?>
}
function PclTraceHideAll() {
<?php
for ($i=0; $i<sizeof($g_pcl_trace_entries); $i++) {
if ($g_pcl_trace_entries[$i]['type'] == 1) {
echo "PclTraceHide(document.getElementById('fct-".$i."'));";
}
}
?>
}
</script>
<form id="formulaire" action="POST">
<p>
<input type='button' value='Show All' onclick="PclTraceShowAll();"></input>
<input type='button' value='Hide All' onclick="PclTraceHideAll();"></input>
</p>
</form>
<?php
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : TrDisplayNew()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function PclTraceDisplayItemStart($p_id)
{
global $g_pcl_trace_level;
global $g_pcl_trace_mode;
global $g_pcl_trace_filename;
global $g_pcl_trace_name;
global $g_pcl_trace_index;
global $g_pcl_trace_entries;
global $g_pcl_trace_suspend;
?>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="10"><font face="Verdana, Arial, Helvetica, sans-serif" color="#FFFFFF"><b><font color="#000000" size="2">+</font></b></font></td>
<td style="width:2px;"></td>
<td><font face="Verdana, Arial, Helvetica, sans-serif" color="#FFFFFF"><b><font color="#000000" size="2">
<a href="javascript:null();"
title="<?php echo 'File:'.basename($g_pcl_trace_entries[$p_id]['file'])." Line: ".$g_pcl_trace_entries[$p_id]['line'];?>"
onclick="PclTraceToggleView(document.getElementById('<?php echo 'fct-'.$p_id; ?>'));">
<?php echo $g_pcl_trace_entries[$p_id]['name']."(".$g_pcl_trace_entries[$p_id]['param'].")" ?>
</a></font></b></font></td>
</tr>
<tr id="<?php echo 'fct-'.$p_id; ?>" style="visibility:hidden;position:absolute;">
<td width="10">&nbsp;</td>
<td style="width:2px;" bgcolor="#0000CC"></td>
<td>
<?php
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : TrDisplayNew()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function PclTraceDisplayItemStop($p_id)
{
global $g_pcl_trace_level;
global $g_pcl_trace_mode;
global $g_pcl_trace_filename;
global $g_pcl_trace_name;
global $g_pcl_trace_index;
global $g_pcl_trace_entries;
global $g_pcl_trace_suspend;
?>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td><font face="Verdana, Arial, Helvetica, sans-serif" color="#FFFFFF"><b><font color="#000000" size="2">
<?php echo $g_pcl_trace_entries[$p_id]['name']."()=".$g_pcl_trace_entries[$p_id]['param']; ?>
</font></b></font></td>
</tr>
</table>
</td>
</tr>
</table>
<?php
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : TrDisplayNew()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function PclTraceDisplayItemMsg($p_id)
{
global $g_pcl_trace_level;
global $g_pcl_trace_mode;
global $g_pcl_trace_filename;
global $g_pcl_trace_name;
global $g_pcl_trace_index;
global $g_pcl_trace_entries;
global $g_pcl_trace_suspend;
?>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="10"><font face="Verdana, Arial, Helvetica, sans-serif" color="#FFFFFF"><b><font color="#000000" size="2"><center>.</center></font></b></font></td>
<td style="width:2px;"></td>
<td><font face="Verdana, Arial, Helvetica, sans-serif" color="#FFFFFF"><b><font color="#000000" size="2">
<?php echo $g_pcl_trace_entries[$p_id]['message'] ?>
</font></b></font></td>
<td width=5></td>
<td><font size=1 face="Verdana, Arial, Helvetica, sans-serif"><?php echo basename($g_pcl_trace_entries[$p_id]['file']); ?></font></td>
<td width=5></td>
<td><font size=1 face="Verdana, Arial, Helvetica, sans-serif"><?php echo $g_pcl_trace_entries[$p_id]['line']; ?></font></td>
</tr>
</table>
<?php
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : PclTraceAction()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function PclTraceAction($p_entry)
{
global $g_pcl_trace_level;
global $g_pcl_trace_mode;
global $g_pcl_trace_filename;
global $g_pcl_trace_name;
global $g_pcl_trace_index;
global $g_pcl_trace_entries;
if ($g_pcl_trace_mode == "normal")
{
for ($i=0; $i<$p_entry['index']; $i++)
echo "---";
if ($p_entry['type'] == 1)
echo "<b>".$p_entry['name']."</b>(".$p_entry['param'].") : ".$p_entry['message']." [".$p_entry[file].", ".$p_entry[line]."]<br>";
else if ($p_entry['type'] == 2)
echo "<b>".$p_entry['name']."</b>()=".$p_entry['param']." : ".$p_entry['message']." [".$p_entry[file].", ".$p_entry[line]."]<br>";
else
echo $p_entry['message']." [".$p_entry['file'].", ".$p_entry['line']."]<br>";
}
}
// --------------------------------------------------------------------------------
?>

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,208 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
*
* @package PhpMyAdmin
*/
/**
* Zip file creation class.
* Makes zip files.
*
* @see Official ZIP file format: http://www.pkware.com/support/zip-app-note
*
* @access public
* @package PhpMyAdmin
*/
class zipfile
{
/**
* Whether to echo zip as it's built or return as string from -> file
*
* @var boolean $doWrite
*/
var $doWrite = false;
/**
* Array to store compressed data
*
* @var array $datasec
*/
var $datasec = array();
/**
* Central directory
*
* @var array $ctrl_dir
*/
var $ctrl_dir = array();
/**
* End of central directory record
*
* @var string $eof_ctrl_dir
*/
var $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00";
/**
* Last offset position
*
* @var integer $old_offset
*/
var $old_offset = 0;
/**
* Sets member variable this -> doWrite to true
* - Should be called immediately after class instantiantion
* - If set to true, then ZIP archive are echo'ed to STDOUT as each
* file is added via this -> addfile(), and central directories are
* echoed to STDOUT on final call to this -> file(). Also,
* this -> file() returns an empty string so it is safe to issue a
* "echo $zipfile;" command
*
* @access public
*
* @return nothing
*/
function setDoWrite()
{
$this -> doWrite = true;
} // end of the 'setDoWrite()' method
/**
* Converts an Unix timestamp to a four byte DOS date and time format (date
* in high two bytes, time in low two bytes allowing magnitude comparison).
*
* @param integer $unixtime the current Unix timestamp
*
* @return integer the current date in a four byte DOS format
*
* @access private
*/
function unix2DosTime($unixtime = 0)
{
$timearray = ($unixtime == 0) ? getdate() : getdate($unixtime);
if ($timearray['year'] < 1980) {
$timearray['year'] = 1980;
$timearray['mon'] = 1;
$timearray['mday'] = 1;
$timearray['hours'] = 0;
$timearray['minutes'] = 0;
$timearray['seconds'] = 0;
} // end if
return (($timearray['year'] - 1980) << 25) | ($timearray['mon'] << 21) | ($timearray['mday'] << 16) |
($timearray['hours'] << 11) | ($timearray['minutes'] << 5) | ($timearray['seconds'] >> 1);
} // end of the 'unix2DosTime()' method
/**
* Adds "file" to archive
*
* @param string $data file contents
* @param string $name name of the file in the archive (may contains the path)
* @param integer $time the current timestamp
*
* @access public
*
* @return nothing
*/
function addFile($data, $name, $time = 0)
{
$name = str_replace('\\', '/', $name);
$dtime = substr("00000000" . dechex($this->unix2DosTime($time)), -8);
$hexdtime = '\x' . $dtime[6] . $dtime[7]
. '\x' . $dtime[4] . $dtime[5]
. '\x' . $dtime[2] . $dtime[3]
. '\x' . $dtime[0] . $dtime[1];
eval('$hexdtime = "' . $hexdtime . '";');
$fr = "\x50\x4b\x03\x04";
$fr .= "\x14\x00"; // ver needed to extract
$fr .= "\x00\x00"; // gen purpose bit flag
$fr .= "\x08\x00"; // compression method
$fr .= $hexdtime; // last mod time and date
// "local file header" segment
$unc_len = strlen($data);
$crc = crc32($data);
$zdata = gzcompress($data);
$zdata = substr(substr($zdata, 0, strlen($zdata) - 4), 2); // fix crc bug
$c_len = strlen($zdata);
$fr .= pack('V', $crc); // crc32
$fr .= pack('V', $c_len); // compressed filesize
$fr .= pack('V', $unc_len); // uncompressed filesize
$fr .= pack('v', strlen($name)); // length of filename
$fr .= pack('v', 0); // extra field length
$fr .= $name;
// "file data" segment
$fr .= $zdata;
// echo this entry on the fly, ...
if ( $this -> doWrite) {
echo $fr;
} else { // ... OR add this entry to array
$this -> datasec[] = $fr;
}
// now add to central directory record
$cdrec = "\x50\x4b\x01\x02";
$cdrec .= "\x00\x00"; // version made by
$cdrec .= "\x14\x00"; // version needed to extract
$cdrec .= "\x00\x00"; // gen purpose bit flag
$cdrec .= "\x08\x00"; // compression method
$cdrec .= $hexdtime; // last mod time & date
$cdrec .= pack('V', $crc); // crc32
$cdrec .= pack('V', $c_len); // compressed filesize
$cdrec .= pack('V', $unc_len); // uncompressed filesize
$cdrec .= pack('v', strlen($name)); // length of filename
$cdrec .= pack('v', 0); // extra field length
$cdrec .= pack('v', 0); // file comment length
$cdrec .= pack('v', 0); // disk number start
$cdrec .= pack('v', 0); // internal file attributes
$cdrec .= pack('V', 32); // external file attributes - 'archive' bit set
$cdrec .= pack('V', $this -> old_offset); // relative offset of local header
$this -> old_offset += strlen($fr);
$cdrec .= $name;
// optional extra field, file comment goes here
// save to central directory
$this -> ctrl_dir[] = $cdrec;
} // end of the 'addFile()' method
/**
* Echo central dir if ->doWrite==true, else build string to return
*
* @return string if ->doWrite {empty string} else the ZIP file contents
*
* @access public
*/
function file()
{
$ctrldir = implode('', $this -> ctrl_dir);
$header = $ctrldir .
$this -> eof_ctrl_dir .
pack('v', sizeof($this -> ctrl_dir)) . // total # of entries "on this disk"
pack('v', sizeof($this -> ctrl_dir)) . // total # of entries overall
pack('V', strlen($ctrldir)) . // size of central dir
pack('V', $this -> old_offset) . // offset to start of central dir
"\x00\x00"; // .zip file comment length
if ( $this -> doWrite ) { // Send central directory & end ctrl dir to STDOUT
echo $header;
return ""; // Return empty string
} else { // Return entire ZIP archive as string
$data = implode('', $this -> datasec);
return $data . $header;
}
} // end of the 'file()' method
} // end of the 'zipfile' class
?>