<?php
#error_reporting(0);
class sesion
{
	private $ar;
	private $valid;
	function __construct($k = "4c4d3m14_2102")
	{
		if (!isset($_SESSION)) {
			session_start();
		}
		//session_start();
		$this->ar = $k;
		$this->init_session();
	}

	/*
    function sesion($k="4c4d3m14_2102"){
        session_start();
        $this->ar=$k;
        $this->init_session();
    }
     */
	private function init_session()
	{
		$ip = $_SERVER['REMOTE_ADDR'];
		$user_agent = !empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : "";

		//if(!preg_match("/proxy\.aol\.com$/", gethostbyaddr($ip))){//if surfer's ISP is not AOL

		if ($this->isSetVar("config")) {
			if ($ip == $this->getVar("config.ip") || $user_agent == $this->getVar("config.user_agent"))
				$this->valid = true;
			else {
				$this->valid = true;
				//					$this->setError(1, "Hacking attempt !!!");
			}
		} else {
			$this->setVar("config.ip", $ip);
			$this->setVar("config.user_agent", $user_agent);
			$this->valid = true;
		}
		//}
		/*else{//if surfer's ISP is AOL, we can't verify IP adress
		
			if(!$this->isSetVar("config")){				
				$this->setVar("config.ip", $ip);
				$this->setVar("config.user_agent", $user_agent);
			}
			
			$this->valid = true; //So the session validity is always "true"
		}*/
	}
	private function getNames($name)
	{
		if (is_string($name)) {
			if (strpos($name, ".")) //S'il y a un "." dans le nom de la variable à stocker dans la session, c'est qu'on veut stocker un tableau
				$names = explode(".", $name);
			else
				$names = array($name);

			$expr = $expr = "\$_SESSION['" . $this->ar . "']"; //añado la clave

			foreach ($names as $item)
				$expr .= is_numeric($item) ? "[$item]" : "['$item']";

			return $expr;
		}
		$this->setError(3, "$name is not a string");
		return false;
	}

	public function isSetVar($name)
	{
		$expr = "return isset(" . $this->getNames($name) . ");";
		return eval($expr);
	}
	public function getVar($name)
	{
		$result = eval("return " . $this->getNames($name) . ";");
		return $result;
	}

	public function setVar($name, $value)
	{
		$expr = $this->getNames($name);
		$expr .= " = \$value;";
		eval($expr);
	}

	/* Test if the session has not been hacked.
	* Use it at the beginning of your script
	*/
	public function isValid()
	{
		return $this->valid;
	}


	public function set($nombre, $valor)
	{
		$_SESSION[$this->ar][$nombre] = $valor;
	}

	public function get($nombre)
	{
		if (isset($_SESSION[$this->ar][$nombre]) && $_SESSION[$this->ar][$nombre] != '') {
			return $_SESSION[$this->ar][$nombre];
		} else {
			return false;
		}
	}

	public function borrar_variable($nombre)
	{
		unset($_SESSION[$this->ar][$nombre]);
	}

	public function existe($nombre)
	{
		if (isset($_SESSION[$this->ar][$nombre]) && $_SESSION[$this->ar][$nombre] != '') {
			return 1;
		} else {
			return 0;
		}
	}

	public function borrarsesion()
	{
		$_SESSION = array();
		$_COOKIE =  array();
		$_SESSION[$this->ar] = false;
		session_destroy();
	}
}
