<?php
///////////////////////////////////////////////////////////////////////////////////////////////////
#  Author:   Anil Kumar
#  Version:	 1.0
#  Date:     10-July-2013
#  Purpose:  
#  Requires: PHP 5.2+, MySQL 4.1.3+
///////////////////////////////////////////////////////////////////////////////////////////////////

require_once("../../config.php");
require_once("base.php");
require_once("recaptcha/recaptchalib.php");

///////////////////////////////////////////////////////////////////////////////////////////////////

$login_error = "";

///////////////////////////////////////////////////////////////////////////////////////////////////

# check if there is a session timeout or explicit logout. Otherwise if the user is already logged 
# in redirect him / her to the actual authenticated page.

session_start();
login_verify($login_error);

# login_verify will not return if the user is already logged in.

///////////////////////////////////////////////////////////////////////////////////////////////////

$using_ssl = false;
if(!empty($_SERVER['HTTPS']))
	$using_ssl = true;

///////////////////////////////////////////////////////////////////////////////////////////////////

if(isset($_REQUEST['ui_username']) && isset($_REQUEST['ui_password']))
{
	$username = strip_tags(trim($_REQUEST['ui_username']));
	$password = strip_tags(trim($_REQUEST['ui_password']));
	$login_error = "";
	
	global $admin_user_name, $admin_password, $recaptcha_private_key, $db_table_prefix;
	global $db_config_host, $db_config_database, $db_config_username, $db_config_password;
	global $max_login_attempts, $login_lockout_minutes;
	
	if(is_recaptcha_enabled())
	{
		if ($_POST["recaptcha_response_field"]) 
		{
			$resp = recaptcha_check_answer ($recaptcha_private_key, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
			if (!$resp->is_valid) 
			{
				$login_error = $resp->error;  # set the error value.
			}
		}
		else
			$login_error = "Please enter the two re-captcha words below.";
	}
	if(is_user_auth_enabled() && $login_error == "" && $username != "" && $password != "")
	{
		# init auth system and get login fail count.
		$login_fail_count = 0;
		$last_login_fail_at = date("Y-m-d H:i:s");
		require_once("pdo/cppdo.php");
		require_once("auth/basic.auth.php");
		$pdo = new cpUserManager($db_table_prefix);
		$dbh = $pdo->openMySQL($db_config_host, $db_config_database, $db_config_username, $db_config_password);
		if($dbh)
		{
			$pdo->initTables();
			$failcount = $pdo->getSingleEntry($pdo->auth_log_table, "ip", $_SERVER['REMOTE_ADDR'], "login_fail_count");
			if($failcount !== false);
				$login_fail_count = $failcount;
			$failtime = $pdo->getSingleEntry($pdo->auth_log_table, "ip", $_SERVER['REMOTE_ADDR'], "login_last_failed_at");
			if($failtime !== false)
			{
				if(is_date($failtime))
					$last_login_fail_at = $failtime;
			}
		}
		
		# Check number of login attempts and lockout if required.
		$allow_logins = true;
		$maxlogins = 0;
		$lockout = 5;
		if(isset($max_login_attempts))
			$maxlogins = $max_login_attempts;
		if(isset($login_lockout_minutes))
			$lockout = $login_lockout_minutes;
		if($lockout <= 0)
			$lockout = 30*24*60;
		$unblock_minutes = $lockout;
		if($maxlogins > 0 && $login_fail_count >= $maxlogins)
		{
			$allow_logins = false;
			$timegap = intval((time()-strtotime($last_login_fail_at))/60);
			if($timegap >= $lockout && $lockout > 0)
				$allow_logins = true;
			else
				$unblock_minutes = $lockout-$timegap;
		}
			
		if($allow_logins)
		{
			# first check if admin user
			
			# if salted and hashed
			if(strlen($admin_password) > 25)
				$admpassword = generateHash($password, $admin_password);
			else
				$admpassword = $password;
									
			if($admin_user_name == $username && $admin_password == $admpassword && strlen($admin_password) >= 6)
			{
				if($dbh)
					$pdo->addAuthLog(true);
				$userinfo['admin'] = true;
				$userinfo['name'] = $username;
				$userinfo['readwrite'] = 1;
				$userinfo['fullname'] = "System Admin";
				$userinfo['displayname'] = "System Admin [c]";
				$userinfo['lastsignin'] = date("Y-m-d H:i:s");
				do_login($userinfo);
			}
			else if($dbh)
			{
				$pdo->checkLogin($username, $password);
			}
			
			# Login has failed.
			$login_fail_count++;
			$login_error = "Incorrect Login or Password";
			if($login_fail_count)
			{
				$login_error .= " (";
				$login_error .= $login_fail_count;
				if($maxlogins > 0)
					$login_error .= "/" . $maxlogins;
				$login_error .= ")";
			}
		}
		else
		{
			$login_error = "Temporarily blocked for " . $unblock_minutes . " minutes. Too many failed attempts!";
		}
	}
}

///////////////////////////////////////////////////////////////////////////////////////////////////

# show the login screen.

$jqtheme = get_theme_name("");
$recaptcha_error = null;
$favicon = get_favicon_name();
$favpngf = get_favicon_name(true);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
<html>
	<head>
		<title>Login</title>
		<meta http-equiv="Content-Language" content="en">
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><link rel="shortcut icon" type="image/x-icon" href="../../lib/css/img/<?php echo $favicon; ?>">
		<link type="text/css" rel="stylesheet" href="../../lib/css/default.css">
		<link type="text/css" href="../../lib/css/<?php echo $jqtheme; ?>.css" rel="stylesheet" media="all">
		<style type="text/css">
			body
			{ 
				background-image:url("../../lib/css/img/<?php echo $favpngf; ?>");
				background-position: 55% 45px;
				background-repeat:no-repeat;
				background-attachment:scroll;
			}
			#databox {opacity:0.90;filter: alpha(opacity=90);};
		</style>
<?php
global $recaptcha_theme;
if(isset($recaptcha_theme))
{
	if($recaptcha_theme != "")
	{
?>
		<script type="text/javascript">var RecaptchaOptions = {theme : '<?php echo $recaptcha_theme; ?>',lang : 'en' };</script>
<?php
	}
}
?>
		<script type="text/javascript">
			function FocusOnInput()
			{
				document.getElementById("ui_username").focus();
			}
		</script>
	</head>
	<body onload="FocusOnInput()">
		<div id="databox">
			<p style="text-align:center; margin-top:0px;"><img src="<?php echo get_main_logo_image(); ?>"></p>
			<div class="dotline"></div>
			<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
				<p><label for="ui_name">User Name</label>
				<input type="text" id="ui_username" name="ui_username" size="21">
				</p>

				<p><label for="ui_password">Password</label>
				<input type="password" id="ui_password" name="ui_password" size="21">
				</p>
			<?php
			if($login_error != "")
			{
			?>
				<div class="dotline"></div>
				<div class="errorbox"">
					<p style="margin-bottom:5px;"><?php echo $login_error; ?></p>
				</div>
			<?php
			}
			if(is_recaptcha_enabled())
			{
			?>
				<div class="dotline"></div>
				
				<div style="text-align:center; margin-left:auto; margin-right:auto;">
					<?php echo recaptcha_get_html($recaptcha_public_key, $recaptcha_error, $using_ssl); ?>
				</div>
			<?php
			}
			?>
				<div class="dotline"></div>
				<div style="height:5px;"></div>
				<p><label for="submit">&nbsp;</label>
				<input type="submit" id="ui_submit" value="Login" name="ui_submit"></p>
			</form>
		</div>
	<//body>
</html>

<?php

///////////////////////////////////////////////////////////////////////////////////////////////////
?>
