<?php
/*

	LOGIN.PHP
	
	Written by Tim Krukowski for Cammilleri Consulting and LOP & Associates
	August 2006
	
	Description:
		This code will handle user authentication for the SUR CA application.  
		It will also make sure any data is saved before a user logs out.

*/


require_once 'includes/SUR_globals.php';
require_once 'includes/db.php';
require_once 'includes/save.php';
require_once 'includes/session.php'; 
require_once 'includes/xhtml_login.php';



/*
	GLOBAL declarations
*/
$GLOBALS['SCRIPT_NAME'] = 'index.php';


/*
	isUserLocked

	Args:		$user_record	- The user's account from the database
	Returns:	a flag indicating if the account is locked
	
	Checks to see if the given user account is locked
*/
function isUserLocked($user_record)
{
	//make sure that null values don't break this
	if( $user_record['login_fail_time'] == null ) {
		$user_record['login_fail_time'] = 0;
	} 

	if ( $user_record['login_fail_count'] >= $GLOBALS['MAX_FAIL_COUNT'] && 
		 strtotime($user_record['login_fail_time']) > ( time() - 86400 ) ) {
		
		$locked = true;
	}
	else {
		$locked = false;
	}
	
	return $locked;	
}




/*
	M A I N
*/
//make sure error reporting is set to all
error_reporting(E_ALL);


//set up the page option variable 
$page_option = '';
if ( !empty($_GET['o']) ) {
	$page_option = $_GET['o'];
}


//build script fields
$xhtml_scripts = buildJSTag('js/common.js');


//depending on which page option is set, get ready to build the next page
$message_text = '';
$db_link = openDB();
switch ( $page_option ) {
	//login attempt has been submited
	case 'attempt':
		//query for user information
		$mysql_username = escapeMySQL($_POST['user'], $db_link);
		$qry_str = "SELECT * FROM tbl_a_Users WHERE username = $mysql_username LIMIT 1";
		$user_result = mysql_query($qry_str, $db_link)
			or outputError('DB', 'with $page_option=' . $page_option);
			
		//if the user name was not found, set message
		if ( !mysql_num_rows($user_result) ) {
			$message_text = 'Incorrect username or password.  Please try again.';
		}
		//else - username was found, so check if user is locked out
		else {
			$user_record = mysql_fetch_assoc($user_result);
			mysql_free_result($user_result);
			
			//is user locked out? (MAX_FAIL_COUNT invalid attempts in last 24 hours)
			if ( isUserLocked($user_record) ) {
				$message_text = 'Your account has been locked out.  Please contact Michelle, Mike, or Tim.';
			}
			//else - user is not locked out
			else {
				//escape user_id
				$mysql_userid = escapeMySQL($user_record['user_id'], $db_link);
			
				//do passwords match?
				if ( $user_record['password'] == crypt($_POST['pass'], $user_record['password']) ) {
					//open session and set variables
					session_start();
					$_SESSION['user_id'] = $user_record['user_id'];
					$_SESSION['username'] = $user_record['username'];
					$_SESSION['last_name'] = $user_record['last_name'];
					$_SESSION['first_name'] = $user_record['first_name'];
					$_SESSION['mid_init'] = $user_record['mid_init'];
					$_SESSION['prev_page_id'] = '1';
				
					//reset fail count, set success time and write them back to DB
					$user_record['login_fail_count'] = 0;
					$mysql_successtime = escapeMySQL(date('Y-m-d H:i:s'), $db_link);
					$mysql_failcount = escapeMySQL($user_record['login_fail_count'], $db_link);
					$qry_str = "UPDATE tbl_a_Users 
								SET login_fail_count = $mysql_failcount, login_success_time = $mysql_successtime
								WHERE user_id = $mysql_userid LIMIT 1";
					mysql_query($qry_str, $db_link)
						or outputError('DB', 'with $page_option=' . $page_option);					
									
					//open new page
					updateHeader("home.php");
				}
				//else the passwords do not match
				else { 
					//update failure tracking variables and write them back to DB
					$user_record['login_fail_time'] = date('Y-m-d H:i:s');
					$user_record['login_fail_count']++;
					$mysql_lastfail = escapeMySQL($user_record['login_fail_time'], $db_link);
					$mysql_failcount = escapeMySQL($user_record['login_fail_count'], $db_link);
					$qry_str = "UPDATE tbl_a_Users 
								SET login_fail_time = $mysql_lastfail, login_fail_count = $mysql_failcount
								WHERE user_id = $mysql_userid LIMIT 1";
					mysql_query($qry_str, $db_link)
						or outputError('DB', 'with $page_option=' . $page_option);
					
					//check if user is now locked out
					if ( isUserLocked($user_record) ) {
						$message_text = 'Your account has been locked out. Please contact Michelle, Mike, or Tim.';
					}
					//else, set retry message
					else {
						$message_text = 'Your username and/or password was incorrect. Please try again.';
					}
				}
			}
		}
		
		break;

		
	//user has logged out
	case 'logout':
		//save last page
		verifySession();
		save($db_link);
		closeSession();
		$message_text = 'You have successfully logged out';
		break;

	
	//user has session timed out
	case 'timeout':
		//save last page
		verifySession();
		save($db_link);
		closeSession();
		$message_text = 'You have been logged out because your session was inactive for 20 min.  Please log in again to resume.';
		break;
	

	//session not found
	case 'session':
		closeSession();
		$message_text = 'Session not found.  Please log in again.';
		break;
			
			
	//page is first called	
	default:
		$message_text = '';
}

//DB cleanup
mysql_close($db_link);


//build other code blocks
$xhtml_form = buildLoginFormXHTML();


//get template and fill it up
$xhtml_page = file_get_contents("includes/template_nomenu.xhtml");
$xhtml_page = str_replace('[script_tags]', $xhtml_scripts, $xhtml_page);
$xhtml_page = str_replace('[css_links]', '', $xhtml_page);
$xhtml_page = str_replace('[page_heading]', $message_text, $xhtml_page);
$xhtml_page = str_replace('[page_description]', 'Please enter your username and password.  Click Submit to continue.', $xhtml_page);
$xhtml_page = str_replace('[block_content]', $xhtml_form, $xhtml_page);

//echo that mutha
echo $xhtml_page;
?>
