<?php
require_once(searchinc('sessimp.inc'));

if (!defined('SESS_SESSION_TIMOUT_DEFAULT')) define('SESS_SESSION_TIMOUT_DEFAULT', 1800);  // seconds in 30 minutes
if (!defined('SESS_GC_FREQUENCY_DEFAULT')) define('SESS_GC_FREQUENCY_DEFAULT', 20);  // 1 in 5
if (!defined('SESS_SESSION_NAME')) define('SESS_SESSION_NAME', 'GENPHPSESS');

class gen_session_obj extends session_impl_mysql
{
	var $session_nm = SESS_SESSION_NAME;					// override in derived classes
	var $timeout_interval = SESS_SESSION_TIMOUT_DEFAULT;	// override in derived classes
	var $gc_frequency = SESS_GC_FREQUENCY_DEFAULT;
	
	private static $instance = NULL;
	
	function __construct($mode=DEFAULT_TRIGGER_ON_ERROR)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.' entering', DEBUG_PROC_TRACE);
		
//		static $instance;
		
		// this is intended to ensure that there is only one session object
		// used in any one HTTP request context
		if (!isset(self::$instance))
		{
			parent::__construct($this->session_nm,
								$this->timeout_interval,
								$this->gc_frequency,
								$mode);
			if ($this->is_ok())
			{
				// include this clause in all child constructors.  This ensures
				// that the _start method is only invoked by by the constructor of
				// the outermost enclosing class.  Note that this also requires
				// each child class to implement a constructor, otherwise _start
				// will never be called
				if ((strtolower(get_class($this)) == strtolower(__CLASS__)))
				{
					$this->_start();
				}
				if ($this->is_ok())
				{
					self::$instance = &$this;
					$this->dbgecho($proc.'Creating singleton instance'.$this->_instance.' of '.get_class($this), DEBUG_DETAIL_TRACE);
				}
			}
		}
		else
		{
//			$this = &$instance;	// can't assign ref to $this, workaround below
			foreach (get_class_vars(get_class($this)) as $var => $value)
			{
				$this->$var =& self::$instance->$var;
			}
			$this->dbgecho($proc.'Initializing from singleton instance '.$this->_instance.' of '.get_class($this), DEBUG_DETAIL_TRACE);
		}
		
		if (!$this->is_ok())
		{
			$this->trigger_error();
		}
//		$this->dbgecho($proc.' leaving', DEBUG_PROC_TRACE);
		return $this->is_ok();
	}

	function _read($id)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$id.') entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		// load users permanent settings
		$res = parent::_read($id);
		
		$this->dbgecho($proc.' leaving', DEBUG_PROC_TRACE);
		return $res;
	}
	
	function _write($id, $sess_data)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$id.') entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		// store users permanent settings
		parent::_write($id, $sess_data);
		
		$this->dbgecho($proc.' leaving', DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
}
 ?>