<?php
/* webroot index page for loganc.net3.0 */
// Iniatalise modules website authentication and classes. Setup global file paths and database connection info.
// 
// Use only Cookies for authentication - turn off PHP session GET_ globals.  
ini_set('session.use_only_cookies', TRUE);
ini_set('session.use_trans_sid', FALSE);

// Set session.cookie timeout to 12 hours. 
ini_set('session.cookie_lifetime', 43200);

// Start the session
session_start();

include_once $APP_ROOT . '/settings/globals.inc';

// Include all classes.
include_once $CLASSES_DIR . '/Logger.pclass';
include_once $CLASSES_DIR . '/RequestCollection.pclass';
include_once $CLASSES_DIR . '/ValidateForm.pclass';
include_once $CLASSES_DIR . '/ErrorHandler.pclass';
include_once $CLASSES_DIR . '/MySqlDatabase.pclass';
include_once $CLASSES_DIR . '/DatabaseCall.pclass';
include_once $CLASSES_DIR . '/UserEncryption.pclass';
include_once $CLASSES_DIR . '/UserAuth.pclass';
include_once $CLASSES_DIR . '/Comments.pclass';

// Set error handler.
set_error_handler("ErrorHandler");

// Setup RequestObject and suck in all URL and cookie vars.
$RC = new RequestCollection($_GET, $_POST, $_COOKIE);

// Initalise the Logging class.
if(!$LOG = new Logger($LOGGER_FILEPATH, $LOGGER_LEVEL)) {
	trigger_error("Failed to initalise Logging class", E_USER_ERROR);
}

// Setup MySql database and connect.
$DBCALL = new DatabaseCall($LOG, $MYSQL_HOST, $MYSQL_USER, $MYSQL_PASS, $MYSQL_NAME);
if(!$DBCALL->IsConnected()) {
	trigger_error("Failed to Connect to Database at $MYSQL_HOST", E_USER_WARNING);
}

// Initalise Authentication class.
if(!$USERAUTH = new UserAuth($LOG, $DBCALL, $AUTHGROUPS, $USERENCRYPTIONKEY, $AUTHCOOKIE, $COOKIEEXPIRE, $LOGINATTEMPTS, $LOCKOUTTIME)) {
	$LOG->LogError("Failed to initalise UserAuth class", E_USER_ERROR);
}

// Check user session authentication.
if($auth && !$_SESSION['auth']) {

	// Check authcookie for package. 
	if($package = $USERAUTH->GetCookie()) {
		if($user = $USERAUTH->Login($package)) {
			
			// Succesfully authenticated. Now regnerate session ID, cookie and set session vars.
			session_regenerate_id(); 
			$USERAUTH->SetSession($user['username'], $user['name'], $user['role'], $user['last_login']);
			session_write_close();		
			header("Location: $_SERVER[SCRIPT_NAME]");
			die();	
		}
	}		
	header("Location: login.php");
	die();
}

if(isset($roles)) {
	$allowed = explode("|", $roles);
	if(!in_array($_SESSION['role'], $allowed)) {
		header("Location: unauthorised-notice.php") ;
		die();
	}
}

$COMMENT = new Comments($DBCALL);
$VALIDATEFORM = new ValidateForm($FORMFIELDSCHECK);
?>