<?php

// Using superglobal var $_SESSION and PHP Sessions

class cSession extends cApp {
	
	public $oDb, $oDb2;
	public $session_name, $session_url, $ssid, $expire, $ip;
	public $idUser, $loginName, $nickName, $firstName, $surName, $wholeName, $vek, $klubId;
	private $superAdmin;
	
	function __construct($oDb) {
		parent::__construct();
		$this->oDb = $oDb;
		$this->session_name = $this->cfg['session_name'];
		$this->expire = $this->cfg['session_expire'];
		if ($this->cookies)
			// Hack
			$this->session_url = array_key_exists($this->session_name,$_COOKIE) ? $_COOKIE[$this->session_name] : "";
			// Fuj :)
			if (empty($this->session_url))
				$this->session_url = "w8";
		else
			$this->session_url = array_key_exists($this->session_name,$_GET) ? $_GET[$this->session_name] : "";
		$this->ssid = "";
		$this->ip = !empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : $REMOTE_ADDR;
		$this->idUser = 0;
		$this->loginName = "";
		$this->nickName = "";
		$this->firstName = "";
		$this->surName = "";
		$this->wholeName = "";
		$this->klubId = "";
		$this->vek = "";
	}
	
	private function getIp() {
		return $this->ip;
	}
	
	public final function start() {
		if (isset($_SESSION) && count($_SESSION) > 0) return;
		$this->_start_session();
		$_SESSION = Array (
			"started" => time(),
			"restored" => time(),
			"expire" => time()+$this->expire,
			"ip" => $this->getIp()
		);
		
	}
	
	function getSalt($login){
		$sql = "SELECT salt FROM users
			WHERE login = ?";
		$rL = $this->oDb->obtain($sql, array($login));
		return $rL['salt'];
	
	}
	
	public function updateLastLogin($id){
		$sql = 'UPDATE `users` SET last_login="'.date('Y-m-d H:i:s').'" WHERE id=?';
		$this->oDb->queryWithBids($sql, array( $id ));
		
	}
	
	public final function login() {
		if ( !isset($_POST['loginname']) || !isset($_POST['password']) )   return;
		$sql = "SELECT * FROM users
			WHERE login = ?
			AND `heslo` = ?";

		$rL = $this->oDb->obtain($sql, array($_POST['loginname'],encryptPass($this->getSalt($_POST['loginname']).$_POST['password'])));
		if (is_array($rL) && array_key_exists("id",$rL)) {
			$this->start();
			$this->idUser = $_SESSION['id_user'] = $rL['id'];
			$this->loginName = $_SESSION['user'] = $rL['login'];
			$this->firstName =$_SESSION['firstname'] = $rL['meno'];
			$this->surName = $_SESSION['surname'] = $rL['priezvisko'];
			$this->vek = $_SESSION['vek'] = $rL['vek'];
			$this->klubId = $_SESSION['klubId'] = $rL['klub_id'];
			$this->updateLastLogin($this->idUser);
			return TRUE;
		}
		return FALSE;
	}
	
	
	
	public final function logout() {
		$this->clean();
		return TRUE;
	}
	
	public final function logged() {
		return $this->idUser > 0;
	}

	
	public final function restore() {
		$this->_start_session();
		if (!$this->_check_security($_SESSION))
			$this->_home();
		$_SESSION['restored'] = time();
		$_SESSION['expire'] = time()+$this->expire;
		if ($this->aKe($_SESSION, "id_user")) {
			$this->idUser = $_SESSION['id_user'];
			$this->loginName = $_SESSION['user'];
			$this->firstName = $_SESSION['firstname'];
			$this->surName = $_SESSION['surname'];
		}
	}
	
	public function getRights($idMenu, $act) {
		// Initialization
		$rightsList = Array("can_read","can_write","can_grant","can_comment");
		// Insertion
		if ($act < 0) {
			$act = 0;
			$ret[$idMenu][$act] = Array();
			$q = $this->oDb->query($this->generateSql("perms_init", $idMenu, $act));
			if ($this->oDb->numrows($q) == 0)
				$q = $this->oDb->query($this->generateSql("perms", $idMenu, $act));
			else {
				$rightsList[] = "can_insert";
				while ($hR = $this->oDb->get($q))
					for ($i=0;$i<count($rightsList);$i++)
						if (!array_key_exists($rightsList[$i],$ret[$idMenu][$act]) || (boolean) $hR[$rightsList[$i]] == TRUE)
							$ret[$idMenu][$act][$rightsList[$i]] = (boolean) $hR[$rightsList[$i]];
				return $ret;
			}
		// Other operations
		} else {
			$ret[$idMenu][$act] = Array();
			$q = $this->oDb->query($this->generateSql("perms", $idMenu, $act));
		}
		if ($this->oDb->numrows($q) > 0) {
			while ($hR = $this->oDb->get($q))
				for ($i=0;$i<count($rightsList);$i++)
					if (!array_key_exists($rightsList[$i],$ret[$idMenu][$act]) || (boolean) $hR[$rightsList[$i]] == TRUE) {
						$ret[$idMenu][$act][$rightsList[$i]] = (boolean) $hR[$rightsList[$i]];
						if ($rightsList[$i] == "can_write" && (boolean) $hR[$rightsList[$i]] == TRUE)
							$ret[$idMenu][$act]["can_insert"] = TRUE;
					}
		} else
			for ($i=0;$i<count($rightsList);$i++)
				$ret[$idMenu][$act][$rightsList[$i]] = FALSE;
		return $ret;
	}
	
	protected function generateSql($table, $idMenu, $act) {
		$ret = "SELECT * FROM {$table}
			WHERE id_{$table} IN (SELECT id_{$table} FROM {$table}
				WHERE id_owner = '".$this->idUser."'
				AND owner_type = 'user'
				AND id_menu = '".$idMenu."'
				".($table == "perms_init" ? "" : "AND id_element = '".$act."'")."
			) OR id_{$table} IN (SELECT id_{$table} FROM {$table}
				WHERE id_owner IN (SELECT id_group FROM `group_user`
					WHERE id_user = '".$this->idUser."')
				AND owner_type = 'group'
				AND id_menu = '".$idMenu."'
				".($table == "perms_init" ? "" : "AND id_element = '".$act."'")."
			) OR id_{$table} IN (SELECT id_{$table} FROM {$table}
				WHERE owner_type = 'public'
				AND id_menu = '".$idMenu."'
				".($table == "perms_init" ? "" : "AND id_element = '".$act."'")."
			)";
		//echo $ret;
		return $ret;
	}
	
	public function superAdmin() {
		if ($this->oDb->dbnumrows("SELECT id_user FROM group_user
			WHERE id_user = '{$this->idUser}'
			AND id_group = '1'") > 0)
			return TRUE;
		else
			return FALSE;
	}
	
	//TODO odstranit/nahradit
	public function wholeName($id = 0) {
		if (!$id)
			$id = $this->idUser;
		$n = $this->oDb->obtain("SELECT `title`,firstname,midname,surname,subtitle FROM users
			WHERE id = '".$id."'");
		if (is_array($n))
			return (empty($n['title']) ? "" : $n['title'] . " ") .
			$n['firstname'] . " " . (empty($n['midname']) ? "" : $n['midname'] . " ") . $n['surname'] .
			(empty($n['subtitle']) ? "" : ", " . $n['subtitle']);
		return ""; 
	}
	
	private function clean() {
		if (!empty($this->ssid)) {
			unset($_SESSION);
			if ($this->cookies) {
				unset($_COOKIE);
				SetCookie($this->session_name, "", time()-42000, '/');
			}
			session_destroy();
			$this->ssid = "";
		}
	}
	
	public final function _home($other_addr="") {
		$this->clean();
		parent::_home($other_addr);
	}
	
	private function _start_session() {
		if (!$this->session_url || (ereg("[0-9]",$this->session_url) && ereg("[a-zA-Z]",$this->session_url))) {
			@ini_set("session.auto_start" , "0");
			@ini_set("session.name" , $this->session_name);
			@ini_set("session.use_cookies" , intval($this->cookies));
			@ini_set("session.cache_expire" , $this->expire);
			@ini_set("session.use_trans_sid", "1");
			if ($this->cookies) {
				@ini_set("session.cookie_lifetime", 0);
				// Nefunguje
				// @ini_set("session.cookie_domain", $_SERVER['HTTP_HOST']);
				session_set_cookie_params(0);
			}
			@session_start();
			$this->ssid = session_id();
		} else
			// Prec, h4x0r
			$this->_home();
	}
	
	private function _check_security($sess) {
		if (array_key_exists("expire",$sess))
			$expire = $sess['expire'];
		else $expire = 0;
		if ($expire < time()) return false;
		if ($this->getIp() <> $sess['ip']) return false;
		return TRUE;
	}
	
}

?>
