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

// a "virtual" class definition for a class implementing a 
// custom PHP session handler
class session_impl extends base
{
	var $_sess_created = false;
	var $_sess_handler_set = false;
	var $_savepath;
	var $_sessid;
	
	function __construct($name=null,$timeout=null,$gc_frequency=null,$mode=DEFAULT_TRIGGER_ON_ERROR)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.' entering', DEBUG_PROC_TRACE);
		
		parent::__construct($mode);
		if ($this->is_ok())
		{
			if (session_set_save_handler ( array(&$this, '_open'),
			                               array(&$this, '_close'),
										   array(&$this, '_read'),
										   array(&$this, '_write'),
										   array(&$this, '_destroy'),
										   array(&$this, '_gc')))
			{
				$this->_sess_handler_set = true;
				if (isset($name)) session_name($name);
				if (isset($timeout)) ini_set('session.gc_maxlifetime', $timeout);
				if (isset($gc_frequency)) ini_set('session.gc_probability', $gc_frequency);
			}
			else
			{
				$this->set_error('Unable to set custom session save handler', __FILE__, __LINE__);
			}
		}
		
		// 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 ($this->is_ok() && (strtolower(get_class($this)) == strtolower(__CLASS__)))
		{
			$this->_start();
		}
		
		if (!$this->is_ok())
		{
			$this->trigger_error();
		}
		$this->dbgecho($proc.' leaving', DEBUG_PROC_TRACE);
//		return $this->is_ok();
	}
	
	function _start()
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.' entering', DEBUG_PROC_TRACE);
		
		// start the session
		session_start();
		
		$this->dbgecho($proc.' leaving', DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function _open($savePath, $id)
	{
		$this->_savepath = $savePath;
		$this->_sessid = $id;
		return $this->_sess_handler_set;
	}
	
	function _close()
	{
		return $this->_sess_handler_set;
	}
	
	function _read($id)
	{
		return '';
	}
	
	function _write($id, $sess_data)
	{
		return $this->_sess_handler_set;
	}
	
	function _destroy($id)
	{
		return $this->_sess_handler_set;
	}
	
	function _gc($maxlifetime)
	{
		return $this->_sess_handler_set;
	}
	
	function session_created()
	{
		return $this->_sess_created;
	}
}

if (!defined('IMPL_SESSION_MYSQL_DB_NAME')) define('IMPL_SESSION_MYSQL_DB_NAME', 'neofsus_sessions');
if (!defined('IMPL_SESSION_MYSQL_USER')) define('IMPL_SESSION_MYSQL_USER', 'neofsus_sessions');
if (!defined('IMPL_SESSION_TABLE_NAME')) define('IMPL_SESSION_TABLE_NAME', 'sessimplmysql');

class session_impl_mysql extends session_impl
{
//	var $_debug = 6;
	var $_dbobj;
	
	function __construct($name=null,$timeout=null,$gc_frequency=null,$mode=DEFAULT_TRIGGER_ON_ERROR)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.' entering', DEBUG_PROC_TRACE);
		
		parent::__construct($name, $timeout, $gc_frequency, $mode);
		if ($this->is_ok())
		{
//                      $this->_dbobj = new basedb(IMPL_SESSION_MYSQL_DB_NAME, IMPL_SESSION_MYSQL_USER, get_mysql_password(IMPL_SESSION_MYSQL_USER), null, $mode);
                        $this->_dbobj = new mysqli('p:127.0.0.1', IMPL_SESSION_MYSQL_USER, get_mysql_password(IMPL_SESSION_MYSQL_USER), IMPL_SESSION_MYSQL_DB_NAME);
			if (!$this->_dbobj->connect_error)
			{
				$mktable = 'sessionid VARCHAR(128) NOT NULL, '.
				           'sessionname VARCHAR(128) NOT NULL, '.
						   'accessed TIMESTAMP NOT NULL, '.
						   'state MEDIUMTEXT, '.
						   'entropy INTEGER UNSIGNED NOT NULL DEFAULT 1, '.
						   'PRIMARY KEY (sessionid, sessionname)';
				if (!$this->_dbobj->query('CREATE TABLE IF NOT EXISTS '.IMPL_SESSION_TABLE_NAME.' ('.$mktable.') COMMENT="PHP Session Store"'))
				{
					$this->set_error('Unable to create session table ('.$this->_dbobj->errno.'): ',$this->_dbobj->error , __FILE__, __LINE__);
				}
			}
			else
			{
				$this->set_error('Unable to initialize database object ('.$this->_dbobj->connect_errno.'): '.$this->_dbobj->connect_error, __FILE__, __LINE__);
			}
		}
		
		// 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 ($this->is_ok() && (strtolower(get_class($this)) == strtolower(__CLASS__)))
		{
			$this->_start();
		}
		
		if (!$this->is_ok())
		{
			$this->trigger_error();
		}
		$this->dbgecho($proc.' leaving', DEBUG_PROC_TRACE);
//		return $this->is_ok();
	}
	
	function _open($savePath, $id)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.' entering', DEBUG_PROC_TRACE);
		
		if (parent::_open($savePath, $id))
		{
			// this may be a place to indicate something
		}
		
		$this->dbgecho($proc.' leaving', DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function _close()
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.' entering', DEBUG_PROC_TRACE);
		
		if (parent::_close())
		{
			// this may be a place to indicate something
		}
		
		$this->dbgecho($proc.' leaving', DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function _read($id)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.' entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		$res = '';
		if (is_a(($db = $this->_dbobj), 'mysqli'))
		{
			$db->query('LOCK TABLES '.IMPL_SESSION_TABLE_NAME.' WRITE');
			if ($db->error)
			{
				$this->set_error('Unable to lock session table '.IMPL_SESSION_TABLE_NAME.' ('.$db->errno.'): '.$db->error, __FILE__, __LINE__);
			}
			else
			{
				$query = 'SELECT state from '.IMPL_SESSION_TABLE_NAME.' WHERE sessionid=\''.$db->real_escape_string($id).'\' && sessionname=\''.session_name().'\'';
				$qres = $db->query($query);
				if ($db->error)
				{
					$this->set_error('Unable to find requested session '.$id.' ('.$db->errno.'): '.$db->error, __FILE__, __LINE__);
				}
				else
				{
                                        $res_array = $qres->fetch_row();
					if (is_null($res_array) || is_null($res_array[0]))
					{
						$this->dbgecho($proc.'session '.$id.' state is null, session most likely expired', DEBUG_DETAIL_TRACE);
						$res = '';
					}
					else
					{
                                                $res = $res_array[0];
						// reset access time
						$db->query('UPDATE '.IMPL_SESSION_TABLE_NAME.' SET accessed=NULL, entropy=entropy+1 WHERE sessionid=\''.$db->real_escape_string($id).'\' && sessionname=\''.session_name().'\'');
						if ($db->error)
						{
							$this->set_error('Unable to upodate access time of session '.$id.' entry'.' ('.$db->errno.'): '.$db->error, __FILE__, __LINE__);
						}
					}
				}
				$db->query('UNLOCK TABLES');
				if ($db->error)
				{
					$this->set_error('Unable to unlock session table '.IMPL_SESSION_TABLE_NAME.' ('.$db->errno.'): '.$db->error, __FILE__, __LINE__);
				}
			}
		}
		else
		{
			$this->set_error('Session implemetation object not initialized'.$id, __FILE__, __LINE__);
		}
		
		$this->dbgecho($proc.' leaving ('.look_r($res).')', DEBUG_PROC_TRACE);
		return $res;
	}
	
	function _write($id, $sess_data)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.'('.$id.', ['.look_r($sess_data).']) entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (is_a(($db = $this->_dbobj), 'mysqli'))
		{
			$db->query('LOCK TABLES '.IMPL_SESSION_TABLE_NAME.' WRITE');
			if ($db->error)
			{
				$this->set_error('Unable to lock session table '.IMPL_SESSION_TABLE_NAME.' ('.$db->errno.'): '.$db->error, __FILE__, __LINE__);
			}
			else
			{
				// assume entry is present
				$query = 'UPDATE '.IMPL_SESSION_TABLE_NAME.' SET state=\''.$db->real_escape_string($sess_data).'\', entropy=entropy+1 WHERE sessionid=\''.$db->escape_string($id).'\' && sessionname=\''.session_name().'\'';
				$db->query($query);
				if ($db->error)
				{
					$this->set_error('Unable to update session table entry for session '.$id.' ('.$db->errno.'): '.$db->error, __FILE__, __LINE__);
				}
				elseif ($db->affected_rows!=1)
				{
					// that didn't work, so try adding a new entry
					$query = 'INSERT '.IMPL_SESSION_TABLE_NAME.' SET state=\''.$db->real_escape_string($sess_data).'\', sessionid=\''.$db->escape_string($id).'\', sessionname=\''.session_name().'\'';
					$db->query($query);
					if ($db->error)
					{
						$this->set_error('Unable to insert session table entry for session '.$id.' ('.$db->errno.'): '.$db->error, __FILE__, __LINE__);
					}
				}
				$db->query('UNLOCK TABLES');
				if ($db->error)
				{
					$this->set_error('Unable to unlock session table '.IMPL_SESSION_TABLE_NAME.' ('.$db->errno.'): '.$db->error, __FILE__, __LINE__);
				}
			}
		}
		else
		{
			$this->set_error('Session implemetation object not initialized'.$id, __FILE__, __LINE__);
		}
		
		$this->dbgecho($proc.' leaving', DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function _destroy($id)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.' entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (is_a(($db = $this->_dbobj), 'mysqli'))
		{
			$query = 'DELETE FROM '.IMPL_SESSION_TABLE_NAME.' WHERE sessionid=\''.$db->real_escape_string($id).'\' && sessionname=\''.session_name().'\'';
			$db->query($query);
			if ($db->error)
			{
				$this->set_error('Unable to delete session table entry for session '.$id.' ('.$db->errno.'): '.$db->error, __FILE__, __LINE__);
			}
		}
		else
		{
			$this->set_error('Session implemetation object not initialized'.$id, __FILE__, __LINE__);
		}
		
		$this->dbgecho($proc.' leaving', DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
	
	function _gc($maxlifetime)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		$this->dbgecho($proc.' entering', DEBUG_PROC_TRACE);
		$this->clear_error();
		
		if (is_a(($db = $this->_dbobj), 'mysqli'))
		{
			$query = 'DELETE FROM '.IMPL_SESSION_TABLE_NAME.' WHERE accessed < NOW() - INTERVAL '.$maxlifetime.' SECOND && sessionname=\''.session_name().'\'';
			$db->query($query);
			if ($db->error)
			{
				$this->set_error('Unable to delete expired session table entries ('.$db->errno.'): '.$db->error, __FILE__, __LINE__);
			}
			else
			{
				$this->dbgecho($proc.$db->affected_rows.' entries removed from session table', DEBUG_DETAIL_TRACE);
			}
		}
		else
		{
			$this->set_error('Session implemetation object not initialized'.$id, __FILE__, __LINE__);
		}
		
		$this->dbgecho($proc.' leaving', DEBUG_PROC_TRACE);
		return $this->is_ok();
	}
}
 ?>
