<?
session_start();
class ses {
	function ses(){
	global $db;
	$this->db=$db;
	}

	/* check if cookie or session exist */
	function checkCook(){
	global $db;
	global $fPath;
		if (isset($_SESSION['tID']) && $this->decrypta($_SESSION['tID'])!=0){
			if (isset($_COOKIE['RishCook'])){	$this->setCook('RishCook',$this->decrypta($_COOKIE['RishCook']));	}
		}
		elseif (isset($_COOKIE['RishCook'])){
		$check=$this->db->select('*','teach',' WHERE t_hash=\''.$this->decrypta($_COOKIE['RishCook']).'\' ','LIMIT 0,1');
			if(!empty($check) && $check!=false){
			$this->startSes($check[0],'u');
			$this->setCook('RishCook',$this->cryptMe($check[0]['t_mail'].time(),'c'));
			}
	  		else{$this->startSes(0,'g');}
		}
		else {
		// start session for guest
		$this->startSes(0,'g');
		}
	}
	
	function setCook($name,$cook){
	setcookie($name,$this->crypta($cook),time()+(3600*24*365),"/", $_SERVER['HTTP_HOST'] );
	}	
	/* kill cookie by name */
	function killCook($w){
	setcookie($w,'',time()-10000,"/", $_SERVER['HTTP_HOST'] );
	unset($_COOKIE[$w]);
	}
	/* kill session variable or destroy all session */
	function killSes($w){
		if ($w=='*'){session_destroy();}
		else {unset($_SESSION[$w]);}
	}
	
	/* start session */	
	function startSes($uID,$uT){
		if ($uID==0 || $uT=='g'){
		$_SESSION['tID']=$this->crypta($uID);
		$this->sesInsert('uName','אורח');
		}
		else {
		$_SESSION['tID']=$this->crypta($uID['t_id']);
		$this->sesInsert('uName',$uID['t_fName']);
		}
	}
	
	
	/* insert into session */
	function sesInsert($name,$val){
	$_SESSION[$name]=$this->crypta($val);
	}
	/* get session variable by name */
	function getSesVar($name){
		if (isset($_SESSION[$name])){
		return $this->decrypta($_SESSION[$name]);
		}
		else {return false;}
	}
	

////////

	/* BashRo Crtyp */
	private function cryptMe($val,$what){
	global $xX;
	return md5($xX->xIni[$what].$val);
	}
	

	/* crypt */
	private function crypta($t){
		if ($t=="") return $t;
		$r = md5(10); $c=0; $v="";
		for ($i=0;$i<strlen($t);$i++){
			if ($c==strlen($r)) $c=0;
			$v.= substr($r,$c,1) . (substr($t,$i,1) ^ substr($r,$c,1));
			$c++;
		}
		return (base64_encode($this->ed($v)));
	}
	/* decrypt */
	private function decrypta($t) {
		if ($t=="") return $t;
		$t = $this->ed(base64_decode(($t)));
		$v = "";
		for ($i=0;$i<strlen($t);$i++){
			$md5 = substr($t,$i,1);
			$i++;
			$v.= (substr($t,$i,1) ^ $md5);
		}
		return $v;
	}
	
	/* used to crypt/decrypt */
	private function ed($t) {
	$cookX=new xX;
	$this->secret=$cookX->xIni['c'];
		$r = md5($this->secret); $c=0; $v="";
		for ($i=0;$i<strlen($t);$i++) {
			if ($c==strlen($r)) $c=0;
			$v.= substr($t,$i,1) ^ substr($r,$c,1);
			$c++;
		}
		return $v;
	}

}

?>