<?php

if (!defined('IN_GEN'))
{
    die('Hacking attempt');
}

class session {

    public $lifeTime;

    public $db;

    function __construct ($db) {

        $this->lifeTime = get_cfg_var("session.gc_maxlifetime");
        $this->db = $db;
        session_set_save_handler(array(&$this, 'open'),
                array(&$this, 'close'),
                array(&$this, 'read'),
                array(&$this, 'write'),
                array(&$this, 'destroy'),
                array(&$this, 'gc'));
        register_shutdown_function('session_write_close');
        session_start();
        return true;
    }
    function open($savePath, $sessName) {
        $this->lifeTime = GEN_SESSION_GC_MAXLIFETIME;
        return true;
    }
    function close() {
        $this->gc(ini_get('session.gc_maxlifetime'));
        return $this->db->close();
    }
    function read($sessID) {
        $query = "
            SELECT session_data FROM " . $this->db->get_table(TB_SESSIONS) . "
            WHERE session = '$sessID'
            AND session_expires >
            ".time();
        $iquery = $this->db->query($query);
        list($value) = $this->db->fetch_row($iquery);
        return $value;
    }
    function write($sessID,$sessData) {
        $newExp = time() + $this->lifeTime;
        $query = "
            SELECT * FROM " . $this->db->get_table(TB_SESSIONS) . "
            WHERE session = '$sessID'
            ";
        $result = $this->db->query($query);
        if($this->db->num_rows($result)) {
            $query = "
                UPDATE " . $this->db->get_table(TB_SESSIONS) . "
                SET session_expires = '$newExp',
                    session_data = '$sessData'
                        WHERE session = '$sessID'
                        ";
        } else {
            $query = "
                INSERT INTO " . $this->db->get_table(TB_SESSIONS) . "(
                        session,
                        session_expires,
                        session_data)
                VALUES(
                        '$sessID',
                        '$newExp',
                        '$sessData')
                ";
        }
        $result = $this->db->query($query);
        if ($result == false) {
            return false;
        } else {
            return true;
        }
    }
    function destroy($sessID) {
        $query = "
            DELETE FROM " . $this->db->get_table(TB_SESSIONS) . "
            WHERE session = '$sessID'
            ";
        $result = $this->db->query($query);
        if ($result == false) {
            return false;
        } else {
            return true;
        }
    }
    function gc($sessMaxLifeTime) {
        $query = "
            DELETE FROM " . $this->db->get_table(TB_SESSIONS) . "
            WHERE session_expires <
            ".time();
        $result = $this->db->query($query);
        if ($result == false) {
            return false;
        }
        return $result;
    }
}
