<?php

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

// -------------------------------------------------------------------------
// Overview of the code
// 1   Replace \' by ' (remove_magic_quotes)
// 2   Register $_SERVER variables
// 3.1 Register main variables - POST method
// 3.2 Register main variables - GET method
// 4.1 Set the default values
// 4.2 Register other variables depending on the $state and $state2
// 5   Set defaults
// 6   Register $_COOKIE variables
// 7   Determine the browser agent, version and platform
// 8   Log the login
// -------------------------------------------------------------------------


// -------------------------------------------------------------------------
// 1 When a variable is submitted, quotes ' are replaced by backslash-quotes \'
// This function removes the extra backslash that is added
// -------------------------------------------------------------------------
if (get_magic_quotes_gpc() == 1) {
	remove_magic_quotes(&$_POST);
	remove_magic_quotes(&$_GET);
	remove_magic_quotes(&$_COOKIE);
}

// Do not add remove_magic_quotes for $GLOBALS because this would call the same
// function a second time, replacing \' by ' and \" by "


// -------------------------------------------------------------------------
// 2 SERVER variabes
// -------------------------------------------------------------------------
$PHP_SELF                    = $_SERVER["PHP_SELF"];
$HTTP_REFERER                = $_SERVER["HTTP_REFERER"];
$HTTP_USER_AGENT             = $_SERVER["HTTP_USER_AGENT"];
$REMOTE_ADDR                 = $_SERVER["REMOTE_ADDR"];
$REMOTE_PORT                 = $_SERVER["REMOTE_PORT"];


// -------------------------------------------------------------------------
// 3.1 Register main variables - POST method
// Used by login form, browse screen, action screens
// -------------------------------------------------------------------------
if ($_SERVER["REQUEST_METHOD"] == "POST") {

	$net2ftp_ftpserver          = cleanFtpserver($_POST["ftpserver"]);
	$net2ftp_ftpserverport      = $_POST["ftpserverport"];
	$net2ftp_username           = $_POST["username"];
	if ($_POST["password_encrypted"] == "") { $net2ftp_password_encrypted = encryptPassword(trim($_POST["password"])); }
	else                                    { $net2ftp_password_encrypted = $_POST["password_encrypted"]; }
	$net2ftp_language           = $_POST["language"];
	$net2ftp_skin               = $_POST["skin"];
	$net2ftp_ftpmode            = $_POST["ftpmode"];
	$net2ftp_passivemode        = $_POST["passivemode"];
	$net2ftp_sslconnect         = $_POST["sslconnect"];
// Those fields are not on the login form
	$net2ftp_viewmode           = $_POST["viewmode"];
	$net2ftp_sort               = $_POST["sort"];
	$net2ftp_sortorder          = $_POST["sortorder"];

	$state      = $_POST["state"];
	$state2     = $_POST["state2"];
	$directory  = cleanDirectory($_POST["directory"]);
	$entry      = $_POST["entry"];
	
// -----------------------------
// If the current directory is within the rootdirectory, then it is OK
// If not, redirect to the rootdirectory
// -----------------------------
	if (isAuthorizedDirectory(trim($_POST["directory"])) == true) { $directory = trim($_POST["directory"]); }
	else                                                          { $directory = getRootdirectory(); }

}



// -------------------------------------------------------------------------
// 3.2 Register main variables - GET method
// Used by bookmark, view image, Easy Website Admin Panel
// -------------------------------------------------------------------------
elseif ($_SERVER["REQUEST_METHOD"] == "GET") {

// -----------------------------
// Username and password - if they are included in the URL
// -----------------------------
	if (strlen($_GET["ftpserver"]) > 1 && strlen($_GET["username"]) > 1 && strlen($_GET["password_encrypted"]) > 1) {
		$net2ftp_username           = $_GET["username"];
		$net2ftp_password_encrypted = $_GET["password_encrypted"];
	}

// -----------------------------
// Username and password - if they are not included in the URL
// -----------------------------
	elseif (strlen($_GET["ftpserver"]) > 1 || $_GET["state"] == "admin") {

		// Normal way (old?)
		if     (isset($_SERVER["PHP_AUTH_USER"])) { 
			$PHP_AUTH_USER = $_SERVER["PHP_AUTH_USER"]; 
			$PHP_AUTH_PW   = $_SERVER["PHP_AUTH_PW"]; 
		}
		
		// Normal way (new?)
		elseif (isset($_SERVER["REMOTE_USER"]))   { 
			$PHP_AUTH_USER = $_SERVER["REMOTE_USER"]; 
			$PHP_AUTH_PW   = $_SERVER["PHP_AUTH_PW"]; 
		}
		
		// Externally-authenticated user
		elseif (isset($_ENV["REMOTE_USER"]))      { 
			$PHP_AUTH_USER = $_ENV["REMOTE_USER"]; 
			$PHP_AUTH_PW   = $_SERVER["PHP_AUTH_PW"]; 
		}
		
		// PHP as CGI module
		elseif(isset($_SERVER["REMOTE_USER"]) && preg_match('/Basics+(.*)$/i', $_SERVER["REMOTE_USER"], $matches)) {
			list($name, $password) = explode(':', base64_decode($matches[1]));
			$PHP_AUTH_USER= strip_tags($name);
			$PHP_AUTH_PW   = strip_tags($password);
		}
		
		// IIS module (ISAPI)
		elseif (ereg("^Basic ", $HTTP_AUTHORIZATION)) { 
			list($PHP_AUTH_USER, $PHP_AUTH_PW) = 
			explode(":", base64_decode(substr($HTTP_AUTHORIZATION, 6))); 
		}
		
		if (isset($PHP_AUTH_USER) == false) {
			// Trigger popup asking for the username and password.
			// This will fill the variables $PHP_AUTH_USER and $PHP_AUTH_PW.
			header("WWW-Authenticate: Basic realm=\"" . __("Please enter your username and password for FTP server ") . $_GET["ftpserver"] . "\"");
			header("HTTP/1.0 401 Unauthorized");
			
			// If the user does not enter his username and password after 3 popups, on the following script 
			// call the script will continue to the next statement. Print an error message.
			$errormessage = __("You did not fill in your login information in the popup window.<br />Click on \"Go to the login page\" below.") . "\n";
			setErrorVars(false, $errormessage, debug_backtrace());
			printErrorMessage();
		}
		elseif (strlen($_GET["ftpserver"]) > 1) {
			// The user did fill in his username and password in the popup.
			$net2ftp_username           = $PHP_AUTH_USER;
			$net2ftp_password_encrypted = encryptPassword(trim($PHP_AUTH_PW));
		}
		elseif ($_GET["state"] == "admin") {
			$settings_admin_username = $settings["settings_admin_username"];
			$settings_admin_password = $settings["settings_admin_password"];

			// Check if the Admin password has been set
			if ($settings_admin_password == "") {
				$errormessage = __("Access to the net2ftp Admin panel is disabled, because no password has been set in the file settings.inc.php. Enter a password in that file, and reload this page."); 
				setErrorVars(false, $errormessage, debug_backtrace());
				printErrorMessage();
			}

			// Check if the login information is correct
			if ($PHP_AUTH_USER != $settings_admin_username ||  $PHP_AUTH_PW != $settings_admin_password) { 
				$errormessage = __("Wrong username or password for the net2ftp Admin panel. The username and password can be set in the file settings.inc.php."); 
				setErrorVars(false, $errormessage, debug_backtrace());
				printErrorMessage();
			}
		}
	}

// -----------------------------
// Other variables
// -----------------------------
	$net2ftp_ftpserver          = cleanFtpserver($_GET["ftpserver"]);
	$net2ftp_ftpserverport      = $_GET["ftpserverport"];
	$net2ftp_language           = $_GET["language"];
	$net2ftp_skin               = $_GET["skin"];
	$net2ftp_ftpmode            = $_GET["ftpmode"];
	$net2ftp_passivemode        = $_GET["passivemode"];
	$net2ftp_sslconnect         = $_GET["sslconnect"];
	$net2ftp_viewmode           = $_GET["viewmode"];
	$net2ftp_sort               = $_GET["sort"];
	$net2ftp_sortorder          = $_GET["sortorder"];

	$state      = $_GET["state"];
	$state2     = $_GET["state2"];
	$directory  = cleanDirectory($_GET["directory"]);
	$entry      = $_GET["entry"];
}



// -------------------------------------------------------------------------
// 4.1 Set the default values
// -------------------------------------------------------------------------
if (strlen($state) < 1) { $state = "homepage"; $state2 = "login"; }
if ($net2ftp_language == "") { $net2ftp_language = $settings["default_language"]; }
if ($net2ftp_skin == "")     { $net2ftp_skin     = 1; }


// -------------------------------------------------------------------------
// 4.2 Browse screens
// -------------------------------------------------------------------------
if ($state == "browse") {
	$FormAndFieldName           = $_POST["FormAndFieldName"];
}

// -------------------------------------------------------------------------
// 4.2 Homepage
// -------------------------------------------------------------------------
elseif ($state == "homepage") {
	$net2ftp_language           = $_GET["language"];

	// cookieset from the homepage Clear Cookies link
	if ($_POST["cookieset"] != "") {
		$cookieset = $_POST["cookieset"];
	}
	// cookieset from the errorpage Back To Login link
	elseif ($_GET["cookieset"] != "") {
		$cookieset = $_GET["cookieset"];
	}
}

// -------------------------------------------------------------------------
// 4.2 Admin panel
// -------------------------------------------------------------------------
elseif ($state == "admin") {
	$formresult                 = $_POST["formresult"];
	$datefrom                   = $_POST["datefrom"];
	$dateto                     = $_POST["dateto"];
	$dbusername2                = $_POST["dbusername2"];
	$dbpassword2                = $_POST["dbpassword2"];
	$dbname2                    = $_POST["dbname2"];
	$dbserver2                  = $_POST["dbserver2"];
	$sqlquerystring             = str_replace("\'", "'", $_POST["sqlquerystring"]);
}

// -------------------------------------------------------------------------
// 4.2 Advanced screens
// -------------------------------------------------------------------------
elseif ($state == "advanced") {
	$formresult                 = $_POST["formresult"];
	$screen                     = $_POST["screen"];
	$functionname               = $_POST["functionname"];

	$troubleshoot_ftpserver     = $_POST["troubleshoot_ftpserver"];
	$troubleshoot_ftpserverport = $_POST["troubleshoot_ftpserverport"];
	$troubleshoot_username      = $_POST["troubleshoot_username"];
	$troubleshoot_password      = $_POST["troubleshoot_password"];
	$troubleshoot_language      = $_POST["troubleshoot_language"];
	$troubleshoot_skin          = $_POST["troubleshoot_skin"];
	$troubleshoot_ftpmode       = $_POST["troubleshoot_ftpmode"];
	$troubleshoot_directory     = $_POST["troubleshoot_directory"];
	$troubleshoot_passivemode   = $_POST["troubleshoot_passivemode"];
	$troubleshoot_sslconnect    = $_POST["troubleshoot_sslconnect"];
}

// -------------------------------------------------------------------------
// 4.2 Manage
// -------------------------------------------------------------------------
elseif ($state == "manage") {
	$list                       = $_POST["list"];
	$newNames                   = $_POST["newNames"];
	$formresult                 = $_POST["formresult"];
	$screen                     = $_POST["screen"];
	$targetDirectories          = $_POST["targetDirectories"];
	$copymovedelete             = $_POST["copymovedelete"];
	$text                       = $_POST["text"];
	$use_folder_names           = $_POST["use_folder_names"];
	$command                    = $_POST["command"];
	$to                         = $_POST["to"];
	$message                    = $_POST["message"];
	$zipactions                 = $_POST["zipactions"];
	$searchoptions              = $_POST["searchoptions"];
	$comparison                 = $_POST["comparison"];

// Edit screen can also be called using GET method (easyWebsite)
	if ($_POST["textareaType"] != "") {
		$textareaType               = $_POST["textareaType"];
	}
	elseif ($_GET["textareaType"] != "") {
		$textareaType               = $_GET["textareaType"];
	}

// Copy, move, delete
	if ($state2 == "copy" || $state2 == "move") {
		$input_ftpserver2           = $_POST["input_ftpserver2"];
		$input_ftpserverport2       = $_POST["input_ftpserverport2"];
		$input_username2            = $_POST["input_username2"];
		$input_password2            = $_POST["input_password2"];
		$input_ftpmode2             = $_POST["input_ftpmode2"];
		$input_passivemode2         = $_POST["input_passivemode2"];
		$input_sslconnect2          = $_POST["input_sslconnect2"];	
	}

// Upload of files and archives
// Move content of $_FILES to $uploadedFilesArray and $uploadedArchivesArray
	elseif ($state2 == "uploadfile") {
		$file_counter = 0;
		$archive_counter = 0;
	
		if (is_array($_FILES["file"])) {
			foreach ($_FILES["file"]["name"] as $key => $val) {
				if ($val != "") {
					$file_counter = $file_counter + 1;
					$uploadedFilesArray["$file_counter"]["name"] = $val;
					$uploadedFilesArray["$file_counter"]["tmp_name"] = $_FILES["file"]["tmp_name"][$key];
					$uploadedFilesArray["$file_counter"]["size"] = $_FILES["file"]["size"][$key];
				} // end if
			} // end foreach
		}
		
		if (is_array($_FILES["archive"])) {
			foreach ($_FILES["archive"]["name"] as $key => $val) {
				if ($val != "") {
					$archive_counter = $archive_counter + 1;
					$uploadedArchivesArray["$archive_counter"]["name"]     = $val;
					$uploadedArchivesArray["$archive_counter"]["tmp_name"] = $_FILES["archive"]["tmp_name"][$key];
					$uploadedArchivesArray["$archive_counter"]["size"]     = $_FILES["archive"]["size"][$key];
				} // end if
			} // end foreach
		}
	}
} // end if ($state == "manage")

// -------------------------------------------------------------------------
// 4.2 Easy Website
// -------------------------------------------------------------------------
elseif ($state == "easyWebsite") {
	$screen = $_POST["screen"];
	if ($_POST["template"] != "") {
		$template   = $_POST["template"];
		$standalone = $_POST["standalone"];
	}
	elseif ($_GET["template"] != "") {
		$template   = $_GET["template"];
		$standalone = $_GET["standalone"];
	}
}

// -------------------------------------------------------------------------
// 4.2 Bookmark
// -------------------------------------------------------------------------
elseif ($state == "bookmark") {
	$url  = $_POST["url"];
	$text = $_POST["text"];
}


// -------------------------------------------------------------------------
// 5 COOKIE variabes
// They are declared in the net2ftp_loginform() function in the net2ftp_loginform.inc.php file
// -------------------------------------------------------------------------
$net2ftpcookie_ftpserver     = $_COOKIE["net2ftpcookie_ftpserver"];
$net2ftpcookie_ftpserverport = $_COOKIE["net2ftpcookie_ftpserverport"];
$net2ftpcookie_username      = $_COOKIE["net2ftpcookie_username"];
$net2ftpcookie_language      = $_COOKIE["net2ftpcookie_language"];
$net2ftpcookie_skin          = $_COOKIE["net2ftpcookie_skin"];
$net2ftpcookie_ftpmode       = $_COOKIE["net2ftpcookie_ftpmode"];
$net2ftpcookie_passivemode   = $_COOKIE["net2ftpcookie_passivemode"];
$net2ftpcookie_sslconnect    = $_COOKIE["net2ftpcookie_sslconnect"];
$net2ftpcookie_viewmode      = $_COOKIE["net2ftpcookie_viewmode"];
$net2ftpcookie_directory     = $_COOKIE["net2ftpcookie_directory"];
$net2ftpcookie_sort          = $_COOKIE["net2ftpcookie_sort"];
$net2ftpcookie_sortorder     = $_COOKIE["net2ftpcookie_sortorder"];


// -------------------------------------------------------------------------
// 6 Get information about the browser and protocol
// -------------------------------------------------------------------------
$browser_agent    = getBrowser("agent");
$browser_version  = getBrowser("version");
$browser_platform = getBrowser("platform");


// -------------------------------------------------------------------------
// 7 Log the login
// -------------------------------------------------------------------------
logLogin($net2ftp_ftpserver, $net2ftp_username);
if ($execution_success == false) { printErrorMessage(); }




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

function remove_magic_quotes(&$x, $keyname="") {

	// http://www.php.net/manual/en/configuration.php#ini.magic-quotes-gpc (by the way: gpc = get post cookie)
	// if (magic_quotes_gpc == 1), then PHP converts automatically " --> \", ' --> \'
	// Has only to be done when getting info from get post cookie
	if (get_magic_quotes_gpc() == 1) {

		if (is_array($x)) {
			while (list($key,$value) = each($x)) {
				if ($value) { remove_magic_quotes(&$x[$key],$key); }
			}
		}
		else { 
			$quote = "'";
			$doublequote = "\"";
			$backslash = "\\";

			$x = str_replace("$backslash$quote", $quote, $x);
			$x = str_replace("$backslash$doublequote", $doublequote, $x);
			$x = str_replace("$backslash$backslash", $backslash, $x);
		}

	} // end if get_magic_quotes_gpc

	return $x;

} // end function remove_magic_quotes

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


?>