class DbSession
{
    private $alive = true;
    private $database = NULL;
       
   
    public function __construct()
    {   
        $this->fetchGlobalDbInstanceOrDie ();

        // We are installing somehow ?
        if (defined("INNER_UPGRADE_SCRIPT") OR defined("INNER_INSTALLER")) {
            $this->createDbTablesIfNotThere ();
        }
        else {
            // Set session handler to overide PHP default
            session_set_save_handler(
                array(&$this, 'open'),
                array(&$this, 'close'),
                array(&$this, 'read'),
                array(&$this, 'write'),
                array(&$this, 'destroy'),
                array(&$this, 'gc')     // Garbage collection gc
            );     
			 $this->gc(1);
        }
        
        // Start the session // not starting it here  at all 
        // session_start();
    }
    
    
    public function __destruct()
    {
        if($this->alive)
        {
        session_write_close();
        $this->alive = false;
        }
    }
    
    

    public function delete()
    {
    
        // Inactivate/Delete Cookies if used
        if(ini_get('session.use_cookies'))
        {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000,
            $params['path'], $params['domain'],
            $params['secure'], $params['httponly']
        );
        }
    
        // Triggers the destroy Method 
        session_destroy();
    
        $this->alive = false;
    }
 
    public function open()
    {        
        return true;
    }
    
   
    public  function close()
    { 
        return true;
    }
    
   
    public  function read($sid)
    {
        $sql = "SELECT `data` FROM `{TP}dbsessions` WHERE `id` = '".$this->database->escapeString($sid)."' LIMIT 1";
        $res = $this->database->query($sql);
        if($this->database->is_error()) return '';
        if($res->numRows() == 1)
        {
        $fields = $res->fetchRow();
    
        return $fields['data'];
        }
        else
        {
        return '';
        }
    }


		
    
   
    public  function write($sid, $data)
    {
        $user=WSession::get('USER_ID');
        if (!is_numeric($user)) $user='0';
        $sql = "REPLACE INTO `{TP}dbsessions` (`id`, `data`, `user`) 
        VALUES ('".$this->database->escapeString($sid)."', '".$this->database->escapeString($data)."', '$user')";
        $this->database->query($sql);
        
        return true;
    }

    
   
    public function destroy($sid)
    {
        $sql = "DELETE FROM `{TP}dbsessions` WHERE `id` = '".$this->database->escapeString($sid)."'"; 
        $this->database->query($sql);
    
        $_SESSION = array();
    
        
        return true;
    }

    
    public function gc($expire)
    {
        $expire = ini_get("session.gc_maxlifetime");
        
        if (Settings::Get ("in_session_timeout") !==false){
            $expire = Settings::Get ("in_session_timeout");
        }
        elseif (Settings::Get ("in_secform_timeout") !==false){
            $expire = Settings::Get ("in_secform_timeout");
        }
        $q = "DELETE FROM `{TP}dbsessions` WHERE DATE_ADD(`last_accessed`, INTERVAL ".(int) $expire." SECOND) < NOW()"; 
        $this->database->query($q);
    
        return true;
    }
    

    protected function checkDbTableExist ($sTableName)
    {
        $sql=" SHOW TABLES LIKE '{$sTableName}'";
        $result = $this->database->query($sql);
        if($result->num_rows == 1) return true;
        return false;  
    }
    

    protected function createDbTablesIfNotThere ()
    {    

		//ALTER TABLE `wbce_dbsessions` CHANGE `id` `id` VARCHAR(256) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL COMMENT 'Session Id';

        $sql="
            CREATE TABLE IF NOT EXISTS `{TP}dbsessions` (
                `id` varchar(148) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Session Id',
                `data` longtext COLLATE utf8_unicode_ci NOT NULL COMMENT 'Session Data',
                `last_accessed` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Last timestamp',
                `user` int(11) NOT NULL COMMENT 'User Id',
                PRIMARY KEY (`id`),
                INDEX (`last_accessed`),
                INDEX (`user`) 
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='WBCE Session Table';
        ";
        $this->database->query($sql);   

		// Doing this in multiple steps as i had problems whith the index
		$sql="
			ALTER TABLE 
				`{TP}dbsessions` 
			DROP PRIMARY KEY;
		";
		$this->database->query($sql);

		$sql="
			ALTER TABLE 
				`{TP}dbsessions` 
			CHANGE 
				`id` `id` VARCHAR(148) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL COMMENT 'Session Id';
		";
		$this->database->query($sql);

		$sql="
			ALTER TABLE 
				`{TP}dbsessions` 
			ADD PRIMARY KEY(`id`);
		";
		$this->database->query($sql);

    }
    
    
    
    protected function fetchGlobalDbInstanceOrDie ()
    {
        // fetch database instance
        global $database;
        
        if (!is_object ($database)){ 
            die('DBSession $database is no resource (DbConnection)');
        }
        
        // Store to this class
        $this->database=$database;
    }
    
    
}