<?

if (!defined("__CFG_SESSION_IP_CHECK"))
    define("__CFG_SESSION_IP_CHECK",false);
if (!defined("__CFG_SESSION_TABLE_PREFIX"))
    define("__CFG_SESSION_TABLE_PREFIX","db");

/**
 *This function retrive the more detailed info possible on client IP adress
 */
function get_full_ip(){
    // get client real ip
    if ( !empty($_SERVER['HTTP_X_FORWARDED_FOR']) )
        $IP_ADDR = $_SERVER['HTTP_X_FORWARDED_FOR'] ;
    elseif ( !empty($_SERVER['HTTP_CLIENT_IP']) )
        $IP_ADDR =  $_SERVER['HTTP_CLIENT_IP'] ;
    else
        $IP_ADDR = $_SERVER['REMOTE_ADDR'];

    // get server ip and resolved it
    $FIRE_IP_ADDR = $_SERVER['REMOTE_ADDR'];
    $ip_resolved = gethostbyaddr($FIRE_IP_ADDR);

    // builds server ip infos string
    if ($FIRE_IP_ADDR != $ip_resolved && $ip_resolved)
        $FIRE_IP_LITT = $FIRE_IP_ADDR." - ". $ip_resolved;
    else
        $FIRE_IP_LITT = $FIRE_IP_ADDR;

    // builds client ip full infos string
    if ($IP_ADDR != $FIRE_IP_ADDR  )
        $FULL_IP_INFOS = "$IP_ADDR | $FIRE_IP_LITT" ;
    else
        $FULL_IP_INFOS = $FIRE_IP_LITT ;

    return $FULL_IP_INFOS;

}

/**
 *Called by session_start()
 *only opens a Mysql connection
 */
function sess_open($save_path, $_session_name) {
    return true;
}

function sess_close() {
    return true;
}

/**
 *Reads session data in mySql
 *also do an ip check
 */
function sess_read($session_id) {
    global $CONST_LINK_ROOT;

    if (strlen($session_id) != 32) return '';
	$db = & db::getInstance();
    $session = $db->get_row("SELECT * FROM ".__CFG_SESSION_TABLE_PREFIX."_sessions WHERE session_id = '".$db->escape($session_id)."'");
    if ($session) {
        if (!__CFG_SESSION_IP_CHECK || $session->session_remote_address==get_full_ip())
            return $session->session_data;
        else {
            return '';
        }
    }
}

/**
 *Write session data in mySql
 *also do an ip check
 */
function sess_write($session_id, $session_data) {
    if (strlen($session_id) != 32) return false;
    $_user_id = 0;
    $_data = explode(";", $session_data);
    foreach($_data as $value) {
        if (strstr($value, 'Sess_UserId')) {
            $_user_id = unserialize(substr(strrchr($value, "|"), 1 ));
        }
    }

	$db = & db::getInstance();

	$session_data = $db->escape($session_data);

    $query="INSERT IGNORE INTO ".__CFG_SESSION_TABLE_PREFIX."_sessions
                            SET session_id='$session_id',
                                session_created=UNIX_TIMESTAMP(NOW()),
                                session_remote_address='".get_full_ip()."',
                                session_data='$session_data'";
	$db->query($query);
    $query="UPDATE ".__CFG_SESSION_TABLE_PREFIX."_sessions
            SET session_active = UNIX_TIMESTAMP(NOW()),
                session_counter = session_counter + 1,
                session_data = '$session_data',
                session_userid = '$_user_id'
          WHERE session_id = '$session_id';";
    $db->query($query);

    $query="UPDATE  members
                SET mem_timeout = NOW()
              WHERE mem_userid = '$_user_id'";
	$db->query($query);
    return true;
}
/**
 *detroys the session
 */
function sess_destroy($session_id) {

	$db = & db::getInstance();

    $query="DELETE FROM ".__CFG_SESSION_TABLE_PREFIX."_sessions WHERE session_id = '".$db->escape($session_id)."'";
    $db->query($query);
    return true;
}
/**
 *delete old sessions
 */
function sess_gc($_sess_gc_maxlifetime=1440) {
    /* $fp =fopen('gc.txt',ab);
    fwrite ($fp,"gc\n"."DELETE FROM {$_sess_tblPrefix}_sessions WHERE session_active < ". (time() - $_sess_gc_maxlifetime));
    fclose($fp);
    */

	$db = & db::getInstance();

    $query="DELETE FROM ".__CFG_SESSION_TABLE_PREFIX."_sessions WHERE session_active < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL $_sess_gc_maxlifetime SECOND))";
    $db->query($query);
    $query="OPTIMIZE TABLE `".__CFG_SESSION_TABLE_PREFIX."_sessions`";
    $db->query($query);
    return true;
}

session_set_save_handler(
        "sess_open",
        "sess_close",
        "sess_read",
        "sess_write",
        "sess_destroy",
        "sess_gc");

?>
