<?php

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

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

function checklogin()
{
	// The cookies...
	global $HTTP_COOKIE_VARS;

	// User vars
	global $users;
	global $current_user;
	global $current_username;
	global $current_password;

	// What are we doin'?
	global $action;

	// Config vars
	global $DATA_DIR;
	global $ADMIN_TIMEOUT;

	if($action == "login") {
		/**
		 * Login
		 */

		$current_uid = $users->getUserID($current_username);
		$u = $users->getUser($current_uid);

		if($u && $u->checkPassword($current_password) ) {
			$current_user = $u;
			setcookie("current_uid", $current_uid, time()+$ADMIN_TIMEOUT);
			setcookie("current_password", $current_password, time()+$ADMIN_TIMEOUT);

			_log($u->username, "logged in");

			if($current_user->notified > 0) {
				$current_user->notified = 0;
				$users->write();
			}

		} else {
			// Remove cookies
			setcookie("current_uid", "", time()-1);
			setcookie("current_password", "", time()-1);
		}

	} else if($action == "logout") {

		/**
		 * Logout
		 */
		$u = $users->getUser($HTTP_COOKIE_VARS["current_uid"]);

		// Remove cookies
		setcookie("current_uid", "", time()-1);
		setcookie("current_password", "", time()-1);

		$current_uid = "";
		$current_password = "";
		$current_user = false;

		_log($u->username, "logged out");

	} else {

		/**
		 * Usage
		 */

		if($HTTP_COOKIE_VARS["current_uid"] == "") return;

		$u = $users->getUser($HTTP_COOKIE_VARS["current_uid"]);
		if($u->checkPassword($HTTP_COOKIE_VARS["current_password"]) ) {
			setcookie("current_uid", $HTTP_COOKIE_VARS["current_uid"], time()+$ADMIN_TIMEOUT);
			setcookie("current_password", $HTTP_COOKIE_VARS["current_password"], time()+$ADMIN_TIMEOUT);

			$current_user = $u;

			if($current_user->notified > 0) {
				$current_user->notified = 0;
				$users->write();
			}

			_log($u->username, "seen");

		} else {
			// Remove cookies
			setcookie("current_uid", "", time()-1);
			setcookie("current_password", "", time()-1);

			$current_uid = "";
			$current_password = "";
			$current_user = false;

		}
	}

}

?>