<?php

/* Session Class */

class PhpObject
{
	private $asErrorStack;
	
	function __construct()
	{
		$this->asErrorStack = array();
	}
	
	function addError($sError)
	{
		$this->asErrorStack[] = $sError;
	}
	
	function getCleanErrorStack()
	{
		$sErrorStack = implode("\n", $this->asErrorStack);
		$this->asErrorStack = array();
		return $sErrorStack;
	}
	
	function __destruct()
	{
		file_put_contents('log.html', "\n\n".date('r')."\n".$this->getCleanErrorStack(), FILE_APPEND);
	}
}

class Session extends PhpObject
{
	private $iUserId;
	private $sLogin;
	private $oMySql;	
	
	public function __construct($oMySql)
	{
		parent::__construct();
		$iUserId = $sLogin = false;
		$this->oMySql = $oMySql;
		$this->syncSession();
	}
	
	private function syncSession()
	{
		if(isset($_SESSION['id_user']))
		{
			$this->iUserId = $_SESSION['id_user'];
		}
		if(isset($_SESSION['login']))
		{
			$this->sLogin = $_SESSION['login'];
		}
	}
	
	private function setSession($iUserId, $sLogin)
	{
		$_SESSION['id_user'] = $iUserId;
		$_SESSION['login'] = $sLogin;
		$this->syncSession();
	}
	
	public function logMeIn($sLogin, $sPass)
	{
		$asUser = $this->oMySql->selectRow(MySqlManager::USER_TABLE, array(MySqlManager::USER_TABLE=>$sLogin));
		if(!$asUser)
		{
			$this->addError('Utilisateur inconnu');
		}
		elseif($this->checkPassword($sPass, $asUser['pass']))
		{
			$this->setSession($asUser['id_'.MySqlManager::USER_TABLE], $sLogin);
			return true;
		}
		else
		{
			$this->addError('mot de pass incorrect');
		}
		return false;
	}
	
	public function isLogguedIn()
	{
		$bLogguedIn = false;
		if(isset($_SESSION['id_user']) && isset($_SESSION['login']) && $_SESSION['id_user']!='' && $_SESSION['login']!='')
		{
			$bLogguedIn = $this->oMySql->selectValue(MySqlManager::USER_TABLE, 'COUNT(1)', array('id_'.MySqlManager::USER_TABLE=>$_SESSION['id_user'], MySqlManager::USER_TABLE=>$_SESSION['login']));			      
		}
		return $bLogguedIn;
	}
	
	public function logMeOut()
	{
		$_SESSION = array();
		return session_destroy();
	}
	
	public static function encryptPassword($sPass)
	{
		$sRandomText = 'F_RA-1H2dsdj)5fsd3sdPKUsdIN@(sZ.';
		for($iIndex=0; $iIndex < strlen($sPass); $iIndex++)
		{
			$sPass[$iIndex] = $sRandomText[$iIndex%strlen($sRandomText)] ^ $sPass[$iIndex];
		}
		return md5($sPass);
	}
	private function checkPassword($sClearPass, $sEncodedPass)
	{
		return $this->encryptPassword($sClearPass) == $sEncodedPass;
	}
	
}
?>