<?php
/**
* Security..handles all the user access functionality
*
* @name Security
* @verision --
* @package --
* @author Rashaud Teague <rashaud.teague@gmail.com>
* @since 03/05/2009
* @license GNU GPL
*/


class Security {
	public function redirect($location, $delay = 0) {
		print '<script type="text/javascript">
		setTimeout(function () {window.location = "'.$location.'"}, '.$delay.');
		</script>';
		die();
	}
	
	public function is_email($email) {
		if (preg_match("/^([^\@].*?)(\@.*?[^@]\.*?)$/i", stripslashes(trim($email)), $matches)) {
			return true;
		} else {
			return false;
		}
	}
	
	public function validate_get_int($var) {
		if (!isset($var)) {
			$this->redirect(APP_DIR);
		} else {
			if ($var == '') {
				$this->redirect(APP_DIR);
			}
		
			if (!is_numeric($var)) {
				$this->redirect(APP_DIR);
			}
		}
	}
	
	public function validate_action_get($var) {
		if ($var == '') {
			$this->redirect(APP_DIR);
		}
	}
	
	public function check_session() {
		if (isset($_SESSION['docu_user'])) {
			return true;
		} else {
			return false;
		}
	}
	
	public function login_user($username) {
		global $db, $uc;
		
		$data = $uc->user_data($username);
		$_SESSION['docu_user'] = $data['id'];
		$_SESSION['user_agent'] = getenv('HTTP_USER_AGENT');
		$_SESSION['session_ip'] = getenv('REMOTE_ADDR');
		$uc->update_last_ip($username);
		$this->redirect(APP_DIR);
	}
	
	public function logout_user() {
		unset($_SESSION['docu_user']);
		unset($_SESSION['user_agent']);
		unset($_SESSION['session_ip']);
		session_destroy();
		$this->redirect(APP_DIR.'?p=login');
	}
	
	public function check_page_access($page, $action) {
		$pages = array('cp', 'order', 'new_page', 'profile');
		$actions = array('edit', 'delete', 'message');
		
		//check pages first
		if (in_array($page, $pages))
			if (!$this->check_session())
				$this->redirect(APP_DIR.'?p=login');
		if (in_array($action, $actions))
			if (!$this->check_session())
				$this->redirect(APP_DIR.'?p=login');
	}
}
?>