<?php
/*
 * This file is part of a larger software package. Please read the License file 
 * in the root of this installation for terms of usage and distribution.
 * 
 * @author The Web Pro Miami, Inc. <info@thewebpro.com>
 * @copyright The Web Pro Miami, Inc. <info@thewebpro.com>, http://www.thewebpro.com/
 * 
 * CORE: manage/process_login.php - version 1.0
*/

// config
$nSuccessURL = "updater.php";

$nRedirect = "";

$nReferrer = $_SERVER['HTTP_REFERER'];
if($nReferrer){
	$nReferrerARRAY = parse_url($nReferrer);
	$nFromManage = strpos($nReferrerARRAY["path"],"/manage/");
	$nFromPwdRec = strpos($nReferrerARRAY["path"],"pwd_recovery.php");
	if($nFromManage===false){
		//header("Location: index.php?error=1"); exit; // disabled to allow for logins from main site
	}
	if($nFromPwdRec){
		// run password recovery
		$nEmail = (isset($_POST["nEmail"]) ? trim($_POST["nEmail"]) : NULL);
		$nEmail = nSanitizeGeneralText(substr(trim($nEmail),0,100));
		if(!$nEmail || !validate_email($nEmail)) {
			// Remove cookies (trigger auto removal by browser by setting date to past
			header("Location: pwd_recovery.php?nEmail=$nEmail&error=3"); exit;
		} else {
			require("../inc/dbconnect.php");
			// Check to see if email exists in user database
			$nSQL = "SELECT * FROM nEditor WHERE nEmail='$nEmail' LIMIT 1";
			mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
			if($Row = mysql_fetch_array($Result)){
				$nUser = $Row["nUser"];
				$nPass = $Row["nPass"];
				//$nPass = rc4Decrypt("xyz123",$Row["nPass"]);
			} else {
				// Email not in database, but pretend anyway so that user doesn't know
				header ("Location: pwd_recovery.php?msg=1"); exit;
			}
			// if so, send login info
			require("../inc/config.php");
			require("inc/lang.php");
			//////////////////////////////
			$nSubject = "Your login information for $nSiteName";
			$nHdr  = 'MIME-Version: 1.0' . "\r\n";
			$nHdr .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
			$nHdr .= 'From: Web Pro Manager <info@thewebpro.com>' . "\r\n";
			// Mail it
			$nBody = "<strong>Following is you account information for the $nCoName website:<BR><BR><div align=\"center\" style=\"font-size:larger;\">Username: <strong style=\"font-size:larger;color:#777;\">$nUser</strong><BR>Password: <strong style=\"font-size:larger;color:#777;\">$nPass</strong></div><BR>You can login here: <a href=\"".$nFullSitePath."manage/\">".$nFullSitePath."manage/</a><BR><BR>";
			if(!mail($nEmail,$nSubject,$nBody,$nHdr)){ header("Location: pwd_recovery.php?nEmail=$nEmail&error=1"); exit; }
			//////////////////////////////
			header ("Location: pwd_recovery.php?msg=1"); exit;
		}
	}
} else {
	header("Location: index.php?r=$nRedirect&nUser=".base64_encode($nUser)."&error=1"); exit;
}

// Ensure login is coming from posted information for added security
if ($_SERVER['REQUEST_METHOD'] != 'POST'){
	// Remove cookies (trigger auto removal by browser by setting date to past
	setcookie ("nMemUser","",time()-3600);
	setcookie ("nMemUserToken","",time()-3600);
	header("Location: index.php?error=1"); exit;
}

// Get passed-in vars
$nUser = (isset($_POST["nUser"]) ? trim($_POST["nUser"]) : NULL);
$nPwd = (isset($_POST["nPwd"]) ? trim($_POST["nPwd"]) : NULL);
$nRememberMe = (isset($_POST["nRememberMe"]) ? trim($_POST["nRememberMe"]) : NULL);

$nUser = trim($nUser);
$nPwd = trim($nPwd);
$nRememberMe = trim($nRememberMe);

// connect to mysql
require("../inc/dbconnect.php");

// Get full site path for redirect
$nSQL = "SELECT * FROM nSettings WHERE nSetting='fullSitePath'";
mysql_select_db($DBName); $Result = mysql_query($nSQL,$Link);
while($Row = mysql_fetch_array($Result)){
	$nFullSitePath = $Row["nValue"];
}

// sanitize for security
$nUser = nSanitizeGeneralText(substr($nUser,0,50));
$nPwd = nSanitizeGeneralText(substr($nPwd,0,20));
if($nRedirect){ $nRedirect = nSanitizeURL(substr($nRedirect,0,250)); }

// Check for cookie
if(isset($_COOKIE['nMemUser'])){ $nMemUser = base64_decode($_COOKIE['nMemUser']); } else { $nMemUser = ""; }
if(isset($_COOKIE['nMemUserToken'])){ $nMemUserToken = $_COOKIE['nMemUserToken']; } else { $nMemUserToken = ""; }
// authenticate if valid user and token are found
if($nMemUser && $nMemUserToken && nVerifyUserToken($nMemUserToken,$nMemUser)){
	$nTokenVerified = 1;
	$nUser = nSanitizeGeneralText(substr($nMemUser,0,64));
	$nPwd = nGetPwd($nUser);
}

// First we test our variables to make sure that neither are empty strings and if they are, 
// we redirect back to the login page telling the person that both fields need to be filled in
if ($nUser == "" || $nPwd == "") {
	// Remove cookies (trigger auto removal by browser by setting date to past
	setcookie ("nMemUser","",time()-3600);
	setcookie ("nMemUserToken","",time()-3600);
	header ("Location: index.php?r=$nRedirect&nUser=".base64_encode($nUser)."&error=3");
	exit;
}

$nUserMatch = FALSE;

// Stop more than 5 login attempts in 5 minutes for IP
$nIP = PMA_getIp();
$nNow = date("Y-m-d H:i:s");
$nTimeLimitLogin = 60*5; // in seconds
$nTimeLimitLogin = strtotime($nNow)-$nTimeLimitLogin;
$Query = "SELECT nIP FROM nLoginLog WHERE UNIX_TIMESTAMP(nAccessDate) >= $nTimeLimitLogin AND nIP='$nIP'";
mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
$nLoginAttempts = mysql_num_rows($Result);
if($nLoginAttempts>5) {
	header ("Location: index.php?error=6");
	exit;
}

// Log this login attempt
$Query = "INSERT INTO nLoginLog VALUES ('0','$nIP','$nUser','$nPwd','$nNow')";
mysql_select_db($DBName);
mysql_query($Query, $Link);

// Pull in user info if a match is found
$Link = mysql_connect($Host,$User,$Password);
$Query = "SELECT * FROM nEditor";
mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
$Num = mysql_num_rows($Result);
while ($Row = mysql_fetch_array($Result)) {
	if ($Row["nUser"] == $nUser) {
		$nUserMatch = TRUE;
		$nPass = $Row["nPass"];
		$nUserID = $Row["nID"];
		$nAdmin = $Row["nAdmin"];
		$nUserLang = $Row["nUserLang"];
		//$nTheme = $Row["nTheme"];
	}
}
// set default theme, if none set
//if(!$nTheme){ $nTheme = "forest"; }

// If we find the nUser that the person entered, move ahead. Otherwise, close all connections and redirect back
// to the login page informing the user that his/her nUser was not found in the database.
if($nUserMatch == FALSE) {
	// Remove cookies (trigger auto removal by browser by setting date to past
	setcookie ("nMemUser","",time()-3600);
	setcookie ("nMemUserToken","",time()-3600);
	mysql_close($Link);
	header ("Location: index.php?r=$nRedirect&nUser=".base64_encode($nUser)."&error=1");
	exit;
}

// Assuming we have found the nUser, we now compare the nPass they entered to the nPass for that nUser
// in the database. If they don't match, then we redirect them back to the login page and let them know they didn't match
if ($nPwd!=$nPass) {
	// Remove cookies (trigger auto removal by browser by setting date to past
	setcookie ("nMemUser","",time()-3600);
	setcookie ("nMemUserToken","",time()-3600);
	mysql_close($Link);
	header ("Location: index.php?r=$nRedirect&nUser=".base64_encode($nUser)."&error=1");
	exit;
} else {
	// Assuming that both the nUser and nPass match what is in the database, we redirect the user to our
	// welcome page and assign a session variable called Valid with the nUser.
	if(!isset($_SESSION)){ session_start(); }
	
	// Change the session timeout value to 1 hr
	ini_set("session.gc_maxlifetime", 60*60);
	
	$_SESSION["uID"] = base64_encode($nUserID);
	$_SESSION["ValidUser"] = $nUser;
	//$_SESSION["nSessTheme"] = $nTheme;
	$_SESSION["nUserLang"] = $nUserLang;
	
	// Save login date
	$Query = "UPDATE nEditor SET nLastLoginDate='".date("Y-m-d h:i:s")."' WHERE nID=$nUserID LIMIT 1";
	mysql_select_db($DBName);
	mysql_query($Query, $Link);
	
	// Create "remembered" cookie so user stays logged in always (expires in 30 days)
	if($nRememberMe){
		$nBase64User = base64_encode($nUser);
		setcookie("nMemUser",$nBase64User,time()+(30*24*60*60));
		$nToken = nCreateToken($nUserID);
		setcookie("nMemUserToken",$nToken,time()+(30*24*60*60));
	} else {
		setcookie ("nMemUser","",time()-3600);
		setcookie ("nMemUserToken","",time()-3600);
	}
	
	// log system event
	$nSystemEventDesc = "User logged in";
	$Query = "INSERT INTO nSystemEventLog (nEventTime,nEventDesc,nEditorUser) VALUES ('".date("Y-m-d H:i:s")."','$nSystemEventDesc','$nUser')";
	mysql_select_db($DBName); mysql_query($Query, $Link);
	
	mysql_close($Link);
	
	if($nRedirect){ $nSuccessURL = "$nSuccessURL"."?nRedirect=".$nRedirect; }
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
	<title>Logging in...</title>
	<meta name="Robots" content="None">
<style>
	BODY{ font-family:Arial, Helvetica, sans-serif; color:#555; font-size:11px; line-height:2.5em; }
</style>
<script language="JavaScript">
<!--
setTimeout("loadHome();",3000);

function loadHome(){
	nHomePage = "<?php echo $nSuccessURL?>";
	window.location = nHomePage;
}
//-->
</script>
</head>

<body>

<BR><BR><BR><BR><BR>
<div align="center" class="content">
  Logging in...<BR><BR>
  <img src="assets/images/loading.gif" alt="" width="42" height="42" border="0">
  <BR><BR><BR>
  <span class="caption">If page does not reload, please <a href="<?=$nSuccessURL?>" class="caption">click here</a>.</span>
</div>

</body>
</html>
<?php
function nCreateToken($nUserID){
	global $DBName,$Link;
	if(!$nUserID){ return; }
	$nNow = date("Y-m-d H:i:s");
	$nLoginToken = nGenRandomStr(50);
	$Query = "UPDATE nEditor SET nLoginToken='$nLoginToken',nTokenDate='$nNow' WHERE nID='$nUserID'";
	mysql_select_db($DBName);
	mysql_query($Query, $Link);
	
	return $nLoginToken;
}

function nGenRandomStr($nLength){
	if(!$nLength){ return; }
	$base='ABCDEFGHIKLMNOPQRSTWXYZabcdefghijkmnpqrstwxyz1234567890';
	$max=strlen($base)-1;
	$nStr='';
	mt_srand((double)microtime()*1000000);
	while(strlen($nStr)<$nLength+1){ $nStr.=$base{mt_rand(0,$max)}; }
  	return $nStr;
}

function nSanitizeGeneralText($nText){
	$notAllowed = array("<",">","\"","'","(",")","=","%");
	$nText = trim(str_replace($notAllowed,"",$nText));
	return $nText;
}

// cleans URL of strange characters, like exploits and injection attacks
// also checks for the presence of this website in the URL, if does not exist, adds it
function nSanitizeURL($nURL){
	global $nFullSitePath;
	if($nURL==$nFullSitePath){ return $nFullSitePath; }
	$nURL = str_ireplace($nFullSitePath,"",$nURL);
	// clean up trailing and leading slashes
	$nURLARRAY = explode("/",$nURL);
	$nURLARRAY = array_filter($nURLARRAY); // clean out empties
	$nURL = implode("/",$nURLARRAY);
	// clean out all strange chars and hack attempts
	$notAllowed = array("<",">","\"","'","(",")","having","insert","select","update","delete","group by","where");
	$nURL = trim(str_ireplace($notAllowed,"",$nURL));
	$nURL ="$nFullSitePath$nURL";
	$nURL = str_replace(" ","",$nURL);
	return $nURL;
}

function nGetPwd($nUser){
	global $DBName,$Link;
	if(!$nUser){ return; }
	$Query = "SELECT nPass FROM nEditor WHERE nUser='$nUser'";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	if($Row = mysql_fetch_array($Result)) {
		$nPass = $Row["nPass"];
	}
	return $nPass;
}

function nVerifyUserToken($nMemUserToken,$nMemUser){
	global $DBName,$Link;
	$nUserMatch = FALSE;
	$nNow = date("Y-m-d H:i:s");
	$nTimeLimitToken = 60*60*24*30; // in seconds (token valid for 30 days)
	$nTimeLimitToken = strtotime($nNow)-$nTimeLimitToken;
	$Query = "SELECT nUser,nLoginToken FROM nEditor WHERE UNIX_TIMESTAMP(nTokenDate) >= $nTimeLimitToken";
	mysql_select_db($DBName); $Result = mysql_query($Query,$Link);
	$Num = mysql_num_rows($Result);
	while ($Row = mysql_fetch_array($Result)) {
		if ($Row["nUser"] == $nMemUser) {
			$nUserMatch = TRUE;
			$nLoginToken = $Row["nLoginToken"];
		}
	}
	if($nUserMatch && $nLoginToken==$nMemUserToken){ return true; }
	return false;
}

function validate_email($email) { 
	$nIsValid = TRUE;
	if(preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $email)) {
		$nIsValid = TRUE;
	} else {
		$nIsValid = FALSE;
	}
	return $nIsValid; 
}

/**
 * Gets the "true" IP address of the current user
 *
 * @return  string   the ip of the user
 *
 * @access  private
 */
function PMA_getIp()
{
    global $REMOTE_ADDR;
    global $HTTP_X_FORWARDED_FOR, $HTTP_X_FORWARDED, $HTTP_FORWARDED_FOR, $HTTP_FORWARDED;
    global $HTTP_VIA, $HTTP_X_COMING_FROM, $HTTP_COMING_FROM;

    // Get some server/environment variables values
    if (empty($REMOTE_ADDR)) {
        if (!empty($_SERVER) && isset($_SERVER['REMOTE_ADDR'])) {
            $REMOTE_ADDR = $_SERVER['REMOTE_ADDR'];
        }
        else if (!empty($_ENV) && isset($_ENV['REMOTE_ADDR'])) {
            $REMOTE_ADDR = $_ENV['REMOTE_ADDR'];
        }
        else if (@getenv('REMOTE_ADDR')) {
            $REMOTE_ADDR = getenv('REMOTE_ADDR');
        }
    } // end if
    if (empty($HTTP_X_FORWARDED_FOR)) {
        if (!empty($_SERVER) && isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $HTTP_X_FORWARDED_FOR = $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        else if (!empty($_ENV) && isset($_ENV['HTTP_X_FORWARDED_FOR'])) {
            $HTTP_X_FORWARDED_FOR = $_ENV['HTTP_X_FORWARDED_FOR'];
        }
        else if (@getenv('HTTP_X_FORWARDED_FOR')) {
            $HTTP_X_FORWARDED_FOR = getenv('HTTP_X_FORWARDED_FOR');
        }
    } // end if
    if (empty($HTTP_X_FORWARDED)) {
        if (!empty($_SERVER) && isset($_SERVER['HTTP_X_FORWARDED'])) {
            $HTTP_X_FORWARDED = $_SERVER['HTTP_X_FORWARDED'];
        }
        else if (!empty($_ENV) && isset($_ENV['HTTP_X_FORWARDED'])) {
            $HTTP_X_FORWARDED = $_ENV['HTTP_X_FORWARDED'];
        }
        else if (@getenv('HTTP_X_FORWARDED')) {
            $HTTP_X_FORWARDED = getenv('HTTP_X_FORWARDED');
        }
    } // end if
    if (empty($HTTP_FORWARDED_FOR)) {
        if (!empty($_SERVER) && isset($_SERVER['HTTP_FORWARDED_FOR'])) {
            $HTTP_FORWARDED_FOR = $_SERVER['HTTP_FORWARDED_FOR'];
        }
        else if (!empty($_ENV) && isset($_ENV['HTTP_FORWARDED_FOR'])) {
            $HTTP_FORWARDED_FOR = $_ENV['HTTP_FORWARDED_FOR'];
        }
        else if (@getenv('HTTP_FORWARDED_FOR')) {
            $HTTP_FORWARDED_FOR = getenv('HTTP_FORWARDED_FOR');
        }
    } // end if
    if (empty($HTTP_FORWARDED)) {
        if (!empty($_SERVER) && isset($_SERVER['HTTP_FORWARDED'])) {
            $HTTP_FORWARDED = $_SERVER['HTTP_FORWARDED'];
        }
        else if (!empty($_ENV) && isset($_ENV['HTTP_FORWARDED'])) {
            $HTTP_FORWARDED = $_ENV['HTTP_FORWARDED'];
        }
        else if (@getenv('HTTP_FORWARDED')) {
            $HTTP_FORWARDED = getenv('HTTP_FORWARDED');
        }
    } // end if
    if (empty($HTTP_VIA)) {
        if (!empty($_SERVER) && isset($_SERVER['HTTP_VIA'])) {
            $HTTP_VIA = $_SERVER['HTTP_VIA'];
        }
        else if (!empty($_ENV) && isset($_ENV['HTTP_VIA'])) {
            $HTTP_VIA = $_ENV['HTTP_VIA'];
        }
        else if (@getenv('HTTP_VIA')) {
            $HTTP_VIA = getenv('HTTP_VIA');
        }
    } // end if
    if (empty($HTTP_X_COMING_FROM)) {
        if (!empty($_SERVER) && isset($_SERVER['HTTP_X_COMING_FROM'])) {
            $HTTP_X_COMING_FROM = $_SERVER['HTTP_X_COMING_FROM'];
        }
        else if (!empty($_ENV) && isset($_ENV['HTTP_X_COMING_FROM'])) {
            $HTTP_X_COMING_FROM = $_ENV['HTTP_X_COMING_FROM'];
        }
        else if (@getenv('HTTP_X_COMING_FROM')) {
            $HTTP_X_COMING_FROM = getenv('HTTP_X_COMING_FROM');
        }
    } // end if
    if (empty($HTTP_COMING_FROM)) {
        if (!empty($_SERVER) && isset($_SERVER['HTTP_COMING_FROM'])) {
            $HTTP_COMING_FROM = $_SERVER['HTTP_COMING_FROM'];
        }
        else if (!empty($_ENV) && isset($_ENV['HTTP_COMING_FROM'])) {
            $HTTP_COMING_FROM = $_ENV['HTTP_COMING_FROM'];
        }
        else if (@getenv('HTTP_COMING_FROM')) {
            $HTTP_COMING_FROM = getenv('HTTP_COMING_FROM');
        }
    } // end if

    // Gets the default ip sent by the user
    if (!empty($REMOTE_ADDR)) {
        $direct_ip = $REMOTE_ADDR;
    }

    // Gets the proxy ip sent by the user
    $proxy_ip     = '';
    if (!empty($HTTP_X_FORWARDED_FOR)) {
        $proxy_ip = $HTTP_X_FORWARDED_FOR;
    } else if (!empty($HTTP_X_FORWARDED)) {
        $proxy_ip = $HTTP_X_FORWARDED;
    } else if (!empty($HTTP_FORWARDED_FOR)) {
        $proxy_ip = $HTTP_FORWARDED_FOR;
    } else if (!empty($HTTP_FORWARDED)) {
        $proxy_ip = $HTTP_FORWARDED;
    } else if (!empty($HTTP_VIA)) {
        $proxy_ip = $HTTP_VIA;
    } else if (!empty($HTTP_X_COMING_FROM)) {
        $proxy_ip = $HTTP_X_COMING_FROM;
    } else if (!empty($HTTP_COMING_FROM)) {
        $proxy_ip = $HTTP_COMING_FROM;
    } // end if... else if...

    // Returns the true IP if it has been found, else FALSE
    if (empty($proxy_ip)) {
        // True IP without proxy
        return $direct_ip;
    } else {
        $is_ip = preg_match('|^([0-9]{1,3}\.){3,3}[0-9]{1,3}|', $proxy_ip, $regs);
        if ($is_ip && (count($regs) > 0)) {
            // True IP behind a proxy
            return $regs[0];
        } else {
            // Can't define IP: there is a proxy but we don't have
            // information about the true IP
            return FALSE;
        }
    } // end if... else...
} // end of the 'PMA_getIp()' function
?>

