<?php
  class SessionHandler54
  {
  	private $_session ;
	public $maxTime ;
	private $timeout_limit = 108000 ;
	// Constructor: sets up the database connection and binds the PHP session handler functions to the class functions
	public function __construct( $ObjDatabase) {
		if(SESSION_SAVE_HANDLER == 'file'){
			ini_set('session.save_path',SESSION_SAVE_PATH);
		}else if(SESSION_SAVE_HANDLER == 'database'){
			$this->ObjDatabase	=$ObjDatabase;
			$this->maxTime['access'] = time( ) ;
			$this->maxTime['gc'] = $this->timeout_limit ;
			session_set_save_handler(array($this, '_open'),
					array($this, '_close'),
					array($this, '_read'),
					array($this, '_write'),
					array($this, '_destroy'),
					array($this, '_clean')
		   );
		 register_shutdown_function( 'session_write_close' ) ;
	}
	@session_start( ) ; // Start the session
	}
	public function _open( ) {
		return true ;   
	} 
	 
	public function _close( ) {
		$this->_clean( $this->maxTime['gc'] ) ;
		return true ;   
	}
	 
	public function _read( $id ) {
		$sql = "SELECT
					data 
				FROM 
					".DB_PREFIX."sessions AS Session 
				WHERE 
					sessionID='$id'" ;
		$allData =  $this->ObjDatabase->readValue($sql);			
		$totalData = count( $allData ) ;
		$hasData = (bool) $totalData >= 1 ;
		return $hasData ? $allData['data'] : '' ;
	}
	 
	public function _write( $id, $data ) {
		 $expiry = time() + $this->maxTime['gc'] ;
		 $sql = "REPLACE 
					INTO ".DB_PREFIX."sessions
				VALUES (
				'$id', 
				".$expiry.",
				'".$this->ObjDatabase->escape($data)."'
				)" ;
		return $this->ObjDatabase->setQuery($sql);  			 
	}
	 
	public function _destroy( $id ) {
		$sql = "	DELETE
					FROM 
						".DB_PREFIX."sessions 
					WHERE 
						sessionID='$id'" ;
		return $this->ObjDatabase->setQuery($sql);  

	}
	 
	public function _clean( $max ) {
		$sql = "DELETE
				FROM 
					".DB_PREFIX."sessions 
				WHERE 
					access < ".time() ;
		return $this->ObjDatabase->setQuery($sql);  
	}
             
  }