<?

/*
 * =============
 * PHP DbSession
 * =============
 * Session handling library using a custom database for PHP3/4
 *
 * @2000 by Antonio Gallo aka agx
 * mailto:agx@linux.it			http://www.badpenguin.org/
 * mailto:agx@geocities.com		http://www.linux.it/~agx/
 *
 * This software is released under the GNU GPL license
 * got to http://www.gnu.org to get a copy of this license
 *
 *
 *
 * === ChangeLog ===
 * 2.0.0 - 2001-08-29   Private session full support
 * 2.0.1 - 2001-08-30   Can now check if cookies are enabled or not
 * 2.0.2 - 2001-09-28   Added MySetCookie and fixed cookie detection
 * 2.0.3 - 2001-11-10   Removed cookie detection but added guest handling
 *
 *
 *
 * === Config ===
 * 1) you need to include 'dblib.php' before dbsession.php
 * 2) you have to create a table with the following fields:
 *     session_id   varchar(32)
 *     session_date datetime
 *     session_vars text
 * and include those variables in your source files or edit the one below:
 *	   $dbsession_server   = 'localhost';
 *	   $dbsession_port     = '';
 *	   $dbsession_database = 'test';
 *	   $dbsession_tablename= 'sessions';
 *	   $dbsession_username = 'test';
 *	   $dbsession_password = '';
 *
 *     $dbsession_usecookies = 1;
 *
 * ===============================================================
 */


$dbsession_isload  = 0;
$dbsession_isnew   = 1;
$dbsession_isdirty = 0;

function PushCookie($name,$value,$domain) {
  // By José Afonso Santos aka smog  <smog@kaotik.org> - http://hero.kaotik.org/ 
  // Getting the current date 
  $hour = date("H:i:s"); 
  $year = date("Y"); 
  $year++; // Adding one year to the current year 
  $day = date("d-M-") . $year ;
  $day_off_the_week = date("l"); 
  $day_off_the_week = date("D"); 
  // Setting the validation of the cookie up to one year. 
  $validation = $day_off_the_week . ", " . $day . " " .  
  $hour . " GMT"; 

  // Set a cookie's value. 
//  $cstr = "Set-Cookie: $name=$value; expires=$validation; path=/; domain=$domain;"; 
  $cstr = "Set-Cookie: $name=$value; expires=$validation; path=/;"; 
//  Header('Content-type: text/html');
  Header($cstr);
  return $cstr;
}


function DbSessionLoad($cookie, $flag_create) {
/*
 * This function load or create a new session if it does not exists
 * - cookie: name of the variable that hold the session ID to be loaded
 * - flag_create: if it is 1 then a new session is created if cookie is empty
 */
global $dbconn, $dbsession_usecookies, $REQUEST_URI, $setcookie;
global $dbsession_data, $dbsession_isnew, $dbsession_isdirty;
global $dbsession_server, $dbsession_port, $dbsession_database, $dbsession_tablename, $dbsession_username;
global $dbsession_password, $dbsession_date, $dbsession_sid, $dbsession_isload;
global $dbsession_domain;

// Check if already loaded
if ($dbsession_isload==1) return 0;
$dbsession_isload = 1;

// Check if session has been set, i.e. already exist or is a new one
$dbsession_sid = $GLOBALS[$cookie];
if ($dbsession_sid=='') {
  if ($flag_create < 1) {
    InvalidateSession($cookie);
    return 1;
  }
  // set cookie if requested      
  if ($setcookie == 1 ) {
    //  NO-COOKIE DETECTED: if we are here then your browser has cookie disabled :-P
    InvalidateSession($cookie);
    return 2;
  }
  $uniq = uniqid( rand() );
  if ($dbsession_usecookies == 1 ) {
    PushCookie( $cookie, $uniq, $dbsession_domain );
    InvalidateSession($cookie);
    return 2;
  }
  $dbsession_isnew = 1;
  $dbsession_isdirty = 1;
  $dbsession_sid = $uniq; 
  $GLOBALS[$cookie] = $uniq;
  return 0;
}

// This is an old session
$dbsession_isnew = 0;
$dbsession_isdirty = 0;
if ( ! isset($dbconn) ) $dbconn = DbConnect( 
  $dbsession_server, $dbsession_port, $dbsession_database, $dbsession_username, $dbsession_password 
);
$query = "select * from $dbsession_tablename where session_id = '$dbsession_sid'";
$rs = DbQuery( $dbconn, $query );
if ( DbQuerySize($rs) <= 0 ) {
  // The session has been deleted from the database: no record found
  $dbsession_isnew = 2;
  return 0;
} else {
  $row = DbGetRow( $rs, 0 );
  $dbsession_id   = $row["session_id"];
  $dbsession_date = $row["session_date"];
  $dbsession_vars = StripSlashes( $row["session_vars"] );
  $dbsession_data = unserialize($dbsession_vars);			
  // scatter memvar / export globals
  $l = count($dbsession_data);
  for ($i=0; $i<$l; $i++) {
    if ( trim($dbsession_data[$i][0]) != '' ) {
      $GLOBALS[$dbsession_data[$i][0]] = unserialize($dbsession_data[$i][1]);
    }
  }
}
return 0;
}


function InvalidateSession($cookie) {
global $dbsession_sid;
  $dbsession_sid = '';
  $GLOBALS[$cookie] = '';
}


function DbSessionAdd($name, &$var) {
/*
 * Add or replace a variable into the current session:
 * - name: name of the session variable to create
 * - var: this should not be a string or costant! but the variable to save
 */
global $dbsession_isload, $dbsession_data, $dbsession_isdirty, $dbsession_sid;

  // Make the variable global
  $GLOBALS[$name] = $var;

  if ($dbsession_sid=='') return 0;

  // Change the session
	$l = count($dbsession_data);
	for ($i=0; $i<$l; $i++) {
		// Overwrite data
		if ( $dbsession_data[$i][0] == $name ) {
			$dbsession_data[$i][0] = $name;
			$dbsession_data[$i][1] = serialize($var);
			$dbsession_isdirty     = 1;
			return 0;
		}
	}
	// Not found adding ... into an empty space
	for ($i=0; $i<$l; $i++) {
		// Overwrite data
		if ( $dbsession_data[$i][0] == '' ) {
			$dbsession_data[$i][0] = $name;
			$dbsession_data[$i][1] = serialize($var);
			$dbsession_isdirty     = 1;			
			return 0;
		}
	}
	// Not found adding ... into a new space
	$dbsession_data[$l][0] = $name;
	$dbsession_data[$l][1] = serialize($var);
	$dbsession_isdirty     = 1;
    return 0;
}



function DbSessionDelete($name) {
/*
 * Delete a variable from the current session:
 * - name: name of the session variable to delete
 */
global $dbsession_data, $dbsession_isdirty, $dbsession_isload, $dbsession_sid;

  // remove global
  $GLOBALS[$name] = '';

  // return if guest
  if ($dbsession_sid=='') return 0;

  // remove from session array
  $l = count($dbsession_data);
	for ($i=0; $i<$l; $i++) {
		if ( $name == ($dbsession_data[$i][0]) ) {
			// Deleted $name at $i
			$dbsession_data[$i][1] = '';
			$dbsession_data[$i][0] = '';
			$dbsession_isdirty     = 1;
			// CONTINUE SEARCHING!!! return 0;
		}
	}
    return 1;
}


// WARNING: THIS FUNCTION DOES NOT WORK!!
function DbSessionChangeID($cookie,$value) {
/*
 * changesession is used to change the cookie value with the session ID:
 * - cookie: variable name that contains the session ID
 * - value: new session ID value
 */
global $dbsession_isdirty, $dbsession_usecookies;
  if ($dbsession_usecookies == 1 ) {
    SetCookie( $cookie, $value, time() + 31536000, '/');
  }
  $GLOBALS[$cookie] = $value;
  $dbsession_isdirty = 1;
  return 0;
}



function DbSessionSave($cookie) {
/*
 * Save all the changes applied to the current session:
 * - cookie: name of the variable that contains the session ID
 */
global $dbconn;
global $dbsession_isload, $dbsession_isdirty, $dbsession_data, $dbsession_isnew;
global $dbsession_server, $dbsession_port, $dbsession_database, $dbsession_tablename, $dbsession_username;
global $dbsession_password, $dbsession_sid;

  // avoid saving if nothing has changed
  if ($dbsession_isdirty==0) return 0;

  // avoid saving spiders sessions
  if ($dbsession_sid=='') return 0;

  $dbsession_isdirty = 0;
  $dbsession_sid = $GLOBALS[$cookie];
  if ($dbsession_sid=='') {
    echo "<H1>DbSessionSave(): INVALID SESSION ID</H1>";
    exit;
  }
  if ( ! isset($dbconn) ) $dbconn = DbConnect( 
	$dbsession_server, $dbsession_port, $dbsession_database, $dbsession_username, $dbsession_password 
  );
  if ($dbsession_isnew>0) {
    // "inserting";
    $dbsession_isnew=0;
    $query = "insert into $dbsession_tablename (session_id,session_date,session_vars) VALUES ( '$dbsession_sid', 'NOW()', '" . AddSlashes( serialize($dbsession_data) ) . "' )";
  } else {
    // "updating";
    $query = "update $dbsession_tablename set session_date = NOW(), session_vars = '" . AddSlashes( serialize($dbsession_data) ) . "' where session_id = '$dbsession_sid'";
  }
  $rs = DbQuery( $dbconn, $query );
  return $rs;
}



function DbSessionDebug() {
global $dbsession_data;
  $l = count($dbsession_data);
  echo "<p>session vars: $l<ol>";
  for ($i=0; $i<$l; $i++) {
    echo "<li>". $dbsession_data[$i][0] ." - ".
         $dbsession_data[$i][1] . "</li>";
  }
  echo "</ol>";
}



?>
