<?php
//============================================================+
// File name   : tce_authorization.php
// Begin       : 2001-09-26
// Last Update : 2006-03-11
//
// Description : Check user authorization level.
//               Grants / deny access to pages.
// 
// Author: Nicola Asuni
//
// (c) Copyright:
//               Tecnick.com S.r.l.
//               Via Ugo Foscolo n.19
//               09045 Quartu Sant'Elena (CA)
//               ITALY
//               www.tecnick.com
//               info@tecnick.com
//
// License: GNU GENERAL PUBLIC LICENSE v.2
//          http://www.gnu.org/copyleft/gpl.html
//============================================================+

/**
 * <p>This script handles user's sessions.<br>
 * Just the registered users granted with a username and a password are entitled to access the restricted areas (level > 0) of TCExam and the public area to perform the tests.<br>
 * The user's level is a numeric value that indicates which resources (pages, modules, services) are accessible by the user.<br>
 * To gain access to a specific resource, the user's level must be equal or greater to the one specified for the requested resource.<br>
 * TCExam has 10 predefined user's levels:<ul>
 * <li>0 = anonymous user (unregistered).</li>
 * <li>1 = basic user (registered);</li>
 * <li>2-9 = configurable/custom levels;</li>
 * <li>10 = administrator with full access rights</li>
 * </ul>
 * </p>
 *
 * @package com.tecnick.tcexam.shared
 * @author Nicola Asuni
 * @copyright Copyright &copy; 2004-2006, Tecnick.com S.r.l. - Via Ugo Foscolo n.19 - 09045 Quartu Sant'Elena (CA) - ITALY - www.tecnick.com - info@tecnick.com
 * @link www.tecnick.com
 * @since 2001-09-26
 */

/**
 */

require_once('../config/tce_config.php');
require_once('../../shared/code/tce_functions_authorization.php');
require_once('../../shared/code/tce_functions_session.php');

$logged = FALSE; // the user is not yet logged in

//read existing user's session data from database
$sqls = "SELECT * FROM ".K_TABLE_SESSIONS." WHERE cpsession_id='".$PHPSESSID."'";
if($rs = F_db_query($sqls, $db)) {
	if($ms = F_db_fetch_array($rs)) { // the user's session already exist
		session_decode($ms['cpsession_data']); //decode session data
		$expiry = date(K_TIMESTAMP_FORMAT); // update session expiration time
		$sqlx = "UPDATE ".K_TABLE_SESSIONS." SET cpsession_expiry='".$expiry."' WHERE cpsession_id='".$PHPSESSID."'";
		if(!$rx = F_db_query($sqlx, $db)) {
			F_display_db_error();
		}
	}
	else { // session do not exist so, create new anonymous session
		$_SESSION['session_user_id'] = 1;
		$_SESSION['session_user_name'] = $l['w_anonymous']." [".substr($PHPSESSID, 12, 8)."]";
		$_SESSION['session_user_ip'] = $_SERVER['REMOTE_ADDR'];
		$_SESSION['session_user_level'] = 0;
		$_SESSION['session_user_firstname'] = "";
		$_SESSION['session_user_lastname'] = "";
		
		// read client cookie 
		if(isset($_COOKIE['LastVisit'])) {
			$_SESSION['session_last_visit'] = $_COOKIE['LastVisit'];
		}
		else {
			$_SESSION['session_last_visit'] = 0;
		}
		
		// set client cookie
		$cookie_now_time = time(); // note: while time() function returns a 32 bit integer, it works fine until year 2038.
		$cookie_expire_time = $cookie_now_time + K_COOKIE_EXPIRE; // set cookie expiration time
		setcookie("LastVisit", $cookie_now_time, $cookie_expire_time, K_COOKIE_PATH, K_COOKIE_DOMAIN, K_COOKIE_SECURE);
		setcookie("PHPSESSID", $PHPSESSID, $cookie_expire_time, K_COOKIE_PATH, K_COOKIE_DOMAIN, K_COOKIE_SECURE); 
	}
}
else {
	F_display_db_error();
}

// check if login information has been submitted
if ((isset($_POST['logaction'])) AND ($_POST['logaction'] == "login")) {
	$xuser_password = md5($_POST['xuser_password']); // one-way password encoding
	// check if submitted login information are correct
	$sql = "SELECT * FROM ".K_TABLE_USERS." WHERE user_name='".$_POST['xuser_name']."' AND user_password='".$xuser_password."'";
	if($r = F_db_query($sql, $db)) {
		if($m = F_db_fetch_array($r)) { 
			// sets some user's session data
			$_SESSION['session_user_id'] = $m['user_id'];
			$_SESSION['session_user_name'] = $m['user_name'];
			$_SESSION['session_user_ip'] = $_SERVER['REMOTE_ADDR'];
			$_SESSION['session_user_level'] = $m['user_level'];
			$_SESSION['session_user_firstname'] = urlencode($m['user_firstname']);
			$_SESSION['session_user_lastname'] = urlencode($m['user_lastname']);
			// read client cookie 
			if(isset($_COOKIE['LastVisit'])) {
				$_SESSION['session_last_visit'] = $_COOKIE['LastVisit'];
			}
			else {
				$_SESSION['session_last_visit'] = 0;
			}
			$logged=TRUE;
		}
		else {
			F_print_error("WARNING", $l['m_login_wrong']);
		}
	}
	else {
		F_display_db_error();
	}
}

if (!isset($pagelevel)) {
	// set default page level
	$pagelevel = 0;
}

// check user's level
if($pagelevel) { // pagelevel=0 means access to anonymous user
	// pagelevel >= 1
	if($_SESSION['session_user_level'] < $pagelevel) { //check user level
		// To gain access to a specific resource, the user's level must be equal or greater to the one specified for the requested resource.
		F_login_form(); //display login form
	}
}

if($logged) { //if user is just logged in: reloads page
	switch(K_REDIRECT_LOGIN_MODE) {
		case 1: {
			// relative redirect
			header("Location: ".$_SERVER['SCRIPT_NAME']);
			break;
		}
		case 2: {
			// absolute redirect
			header("Location: ".K_PATH_HOST.$_SERVER['SCRIPT_NAME']);
			break;
		}
		case 3:
		default: {
			// html redirect
			echo "<"."?xml version=\"1.0\" encoding=\"".$l['a_meta_charset']."\"?".">\n";
			echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
			echo "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"".$l['a_meta_language']."\" lang=\"".$l['a_meta_language']."\" dir=\"".$l['a_meta_dir']."\">\n";
			echo "<head>\n";
			echo "<title>ENTER</title>\n";
			//reload page
			echo "<meta http-equiv=\"refresh\" content=\"0\" />\n"; //reload page
			echo "</head>\n";
			echo "<body>\n";
			echo "<a href=\"".$_SERVER['SCRIPT_NAME']."\" target=\"_top\">ENTER</a>\n";
			echo "</body>\n";
			echo "</html>\n";
			break;
		}
	}
	exit;
}

//============================================================+
// END OF FILE                                                 
//============================================================+
?>
