<?php

include ('includes/header.html');

# This piece of javascript will default the cursor to the Username input box.
echo "<script type=\"text/javascript\">
window.onload=function(){document.forms['login'].elements['user'].focus();}
</script>";

# Execute this block of code if the user has supplied a username and password.
if ($_POST['user'] && $_POST['pass']) {
	
	# Sanitize the data the user has provided and save them as variables.
	$username = mysqli_real_escape_string($dbc, $_POST['user']);
	$pass = mysqli_real_escape_string($dbc, $_POST['pass']);
	
	# Validate the username and password to contain only a-z, A-Z, 0-9 and . - _ with 4 to 20 characters.
	if (eregi('^[a-z0-9.-_]{4,20}$', $username) && eregi('^[a-z0-9.-_]{4,20}$', $pass)) {
		
	# This statement will return the database row matching their username and password.
	$q = "SELECT user_id FROM users WHERE username='$username' AND password=SHA1('$pass')";
	$r = mysqli_query($dbc, $q);
	$row = mysqli_fetch_array($r);
	# Only execute this block of code if the username and password was correct.
	if (mysqli_num_rows($r) == 1) {
		# Set the user's uniquely registered ID as a session variable.
		$_SESSION['user'] = $row['user_id'];
		# Set the HTTP_USER_AGENT as a session variable for later additional validation checks.
		$_SESSION['agent'] = md5($_SERVER['HTTP_USER_AGENT']);
		# Redirect the user to the home page upon successfully logging in.
		header("Location:index.php");
	} else {
		# If the username and password were incorrect, do not log them in - just display this error.
		echo '<p>Wrong username or password</p>';
	}
	} else {
		# Echo an error if the username and password fail the validation checks.
		echo "<p>Your username and password must contain be between 4 and 20 characters of length and consist only of letters, numbers or a period, dash or underscore.</p>";
	}
}

# A form for the user to log in.
?>
<div id="title">
<h2>Login</h2>
</div>
<div id="box">
<form action="login.php" method="post" name="login">
<p>Username:</p><p><input type="text" name="user" size="10" maxlength="20" value=""/></p>
<p>Password:</p><p><input type="password" name="pass" size="10" maxlength="20" /></p>
<p id="login"><input type="submit" name="submit" value="Login" /></p>
</form>
</div>
<?php

include ('includes/footer.html');

?>