<?php

$loggedin = false;

include_once($UTIL_DIR . "/user.php");
include_once($UTIL_DIR . "/log.php");

function checklogin()
{
	global $HTTP_COOKIE_VARS;
	global $userid;
	global $password;
	global $loggedin;
	global $action;
	global $DATA_DIR;
	global $ADMIN_TIMEOUT;

	$users = new Users($DATA_DIR . "/users.xml");

	if($action == "login") {
		$user = $users->findUser($userid);
		if($user) {
			if($user->checkPassword($password)) {
				$loggedin = true;
				_log("Logged in", $userid);
			} else {
				_log("Wrong password", $userid);
			}
			setcookie("UserID", $userid, time()+$ADMIN_TIMEOUT);
			setcookie("Password", $password, time()+$ADMIN_TIMEOUT);
			return;
		} else {
			_log("Failed", $userid);
			return;
		}
	}

	if($action == "logout") {
		_log("Logged out", $HTTP_COOKIE_VARS["UserID"]);
		setcookie("UserID", "", time()-1); // remove cookie
		setcookie("Password", "", time()-1); // remove cookie
		$userid = "";
		$password = "";
		$loggedin = false;
		return;
	}

	if($HTTP_COOKIE_VARS["UserID"] == "") {
		_log("Failed", $UserID);
		return;
	}

	$user = $users->findUser($HTTP_COOKIE_VARS["UserID"]);
	if($user) {
		if($user->checkPassword($HTTP_COOKIE_VARS["Password"])) {
			setcookie("UserID", $HTTP_COOKIE_VARS["UserID"], time()+$ADMIN_TIMEOUT); // expire in 10 minutes
			setcookie("Password", $HTTP_COOKIE_VARS["Password"], time()+$ADMIN_TIMEOUT); // expire in 10 minutes
			$loggedin = true;
			return;
		} else {
			_log("Wrong password", $HTTP_COOKIE_VARS["UserID"]);
		}
	} else {
		_log("Failed", $UserID);
	}
}

?>