5 V5.18 3 Sep 2012 (c) 2000-2012 John Lim (jlim#natsoft.com). All rights reserved.
6 Contributed by Ross Smith (adodb@netebb.com).
7 Released under both BSD license and Lesser GPL library license.
8 Whenever there is any discrepancy between the two licenses,
9 the BSD license will take precedence.
10 Set tabs to 4 for best viewing.
22 CREATE TABLE SESSIONS2
24 SESSKEY VARCHAR2(48 BYTE) NOT NULL,
26 EXPIREREF VARCHAR2(200 BYTE),
27 CREATED DATE NOT NULL,
28 MODIFIED DATE NOT NULL,
34 CREATE INDEX SESS2_EXPIRY ON SESSIONS2(EXPIRY);
35 CREATE UNIQUE INDEX SESS2_PK ON SESSIONS2(SESSKEY);
36 CREATE INDEX SESS2_EXP_REF ON SESSIONS2(EXPIREREF);
43 CREATE TABLE sessions2(
44 sesskey VARCHAR( 64 ) NOT NULL DEFAULT '',
45 expiry TIMESTAMP NOT NULL ,
46 expireref VARCHAR( 250 ) DEFAULT '',
47 created TIMESTAMP NOT NULL ,
48 modified TIMESTAMP NOT NULL ,
49 sessdata LONGTEXT DEFAULT '',
50 PRIMARY KEY ( sesskey ) ,
51 INDEX sess2_expiry( expiry ),
52 INDEX sess2_expireref( expireref )
58 if (!defined('_ADODB_LAYER')) {
59 require realpath(dirname(__FILE__) . '/../adodb.inc.php');
62 if (defined('ADODB_SESSION')) return 1;
64 define('ADODB_SESSION', dirname(__FILE__));
65 define('ADODB_SESSION2', ADODB_SESSION);
68 Unserialize session data manually. See http://phplens.com/lens/lensforum/msgs.php?id=9821
70 From Kerr Schere, to unserialize session data stored via ADOdb.
71 1. Pull the session data from the db and loop through it.
72 2. Inside the loop, you will need to urldecode the data column.
73 3. After urldecode, run the serialized string through this function:
76 function adodb_unserialize( $serialized_string )
78 $variables = array( );
79 $a = preg_split( "/(\w+)\|/", $serialized_string, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE );
80 for( $i = 0; $i < count( $a ); $i = $i+2 ) {
81 $variables[$a[$i]] = unserialize( $a[$i+1] );
87 Thanks Joe Li. See http://phplens.com/lens/lensforum/msgs.php?id=11487&x=1
90 function adodb_session_regenerate_id()
92 $conn = ADODB_Session::_conn();
93 if (!$conn) return false;
95 $old_id = session_id();
96 if (function_exists('session_regenerate_id')) {
97 session_regenerate_id();
99 session_id(md5(uniqid(rand(), true)));
100 $ck = session_get_cookie_params();
101 setcookie(session_name(), session_id(), false, $ck['path'], $ck['domain'], $ck['secure']);
104 $new_id = session_id();
105 $ok = $conn->Execute('UPDATE '. ADODB_Session::table(). ' SET sesskey='. $conn->qstr($new_id). ' WHERE sesskey='.$conn->qstr($old_id));
107 /* it is possible that the update statement fails due to a collision */
110 if (empty($ck)) $ck = session_get_cookie_params();
111 setcookie(session_name(), session_id(), false, $ck['path'], $ck['domain'], $ck['secure']);
119 Generate database table for session data
120 @see http://phplens.com/lens/lensforum/msgs.php?id=12280
121 @return 0 if failure, 1 if errors, 2 if successful.
122 @author Markus Staab http://www.public-4u.de
124 function adodb_session_create_table($schemaFile=null,$conn = null)
126 // set default values
127 if ($schemaFile===null) $schemaFile = ADODB_SESSION . '/session_schema2.xml';
128 if ($conn===null) $conn = ADODB_Session::_conn();
130 if (!$conn) return 0;
132 $schema = new adoSchema($conn);
133 $schema->ParseSchema($schemaFile);
134 return $schema->ExecuteSchema();
140 class ADODB_Session {
141 /////////////////////
142 // getter/setter methods
143 /////////////////////
147 function Lock($lock=null)
149 static $_lock = false;
151 if (!is_null($lock)) $_lock = $lock;
157 static function driver($driver = null)
159 static $_driver = 'mysql';
162 if (!is_null($driver)) {
163 $_driver = trim($driver);
166 // backwards compatibility
167 if (isset($GLOBALS['ADODB_SESSION_DRIVER'])) {
168 return $GLOBALS['ADODB_SESSION_DRIVER'];
177 static function host($host = null) {
178 static $_host = 'localhost';
181 if (!is_null($host)) {
182 $_host = trim($host);
185 // backwards compatibility
186 if (isset($GLOBALS['ADODB_SESSION_CONNECT'])) {
187 return $GLOBALS['ADODB_SESSION_CONNECT'];
196 static function user($user = null)
198 static $_user = 'root';
201 if (!is_null($user)) {
202 $_user = trim($user);
205 // backwards compatibility
206 if (isset($GLOBALS['ADODB_SESSION_USER'])) {
207 return $GLOBALS['ADODB_SESSION_USER'];
216 static function password($password = null)
218 static $_password = '';
221 if (!is_null($password)) {
222 $_password = $password;
225 // backwards compatibility
226 if (isset($GLOBALS['ADODB_SESSION_PWD'])) {
227 return $GLOBALS['ADODB_SESSION_PWD'];
236 static function database($database = null)
238 static $_database = '';
241 if (!is_null($database)) {
242 $_database = trim($database);
245 // backwards compatibility
246 if (isset($GLOBALS['ADODB_SESSION_DB'])) {
247 return $GLOBALS['ADODB_SESSION_DB'];
255 static function persist($persist = null)
257 static $_persist = true;
259 if (!is_null($persist)) {
260 $_persist = trim($persist);
268 static function lifetime($lifetime = null)
273 if (!is_null($lifetime)) {
274 $_lifetime = (int) $lifetime;
277 // backwards compatibility
278 if (isset($GLOBALS['ADODB_SESS_LIFE'])) {
279 return $GLOBALS['ADODB_SESS_LIFE'];
283 $_lifetime = ini_get('session.gc_maxlifetime');
284 if ($_lifetime <= 1) {
285 // bug in PHP 4.0.3 pl 1 -- how about other versions?
286 //print "<h3>Session Error: PHP.INI setting <i>session.gc_maxlifetime</i>not set: $lifetime</h3>";
296 static function debug($debug = null)
298 static $_debug = false;
301 if (!is_null($debug)) {
302 $_debug = (bool) $debug;
304 $conn = ADODB_Session::_conn();
306 #$conn->debug = $_debug;
310 // backwards compatibility
311 if (isset($GLOBALS['ADODB_SESS_DEBUG'])) {
312 return $GLOBALS['ADODB_SESS_DEBUG'];
321 static function expireNotify($expire_notify = null)
323 static $_expire_notify;
326 if (!is_null($expire_notify)) {
327 $_expire_notify = $expire_notify;
330 // backwards compatibility
331 if (isset($GLOBALS['ADODB_SESSION_EXPIRE_NOTIFY'])) {
332 return $GLOBALS['ADODB_SESSION_EXPIRE_NOTIFY'];
336 return $_expire_notify;
341 static function table($table = null)
343 static $_table = 'sessions2';
346 if (!is_null($table)) {
347 $_table = trim($table);
350 // backwards compatibility
351 if (isset($GLOBALS['ADODB_SESSION_TBL'])) {
352 return $GLOBALS['ADODB_SESSION_TBL'];
361 static function optimize($optimize = null)
363 static $_optimize = false;
366 if (!is_null($optimize)) {
367 $_optimize = (bool) $optimize;
370 // backwards compatibility
371 if (defined('ADODB_SESSION_OPTIMIZE')) {
381 static function syncSeconds($sync_seconds = null) {
382 //echo ("<p>WARNING: ADODB_SESSION::syncSeconds is longer used, please remove this function for your code</p>");
389 static function clob($clob = null) {
390 static $_clob = false;
393 if (!is_null($clob)) {
394 $_clob = strtolower(trim($clob));
397 // backwards compatibility
398 if (isset($GLOBALS['ADODB_SESSION_USE_LOBS'])) {
399 return $GLOBALS['ADODB_SESSION_USE_LOBS'];
408 static function dataFieldName($data_field_name = null) {
409 //echo ("<p>WARNING: ADODB_SESSION::dataFieldName() is longer used, please remove this function for your code</p>");
415 static function filter($filter = null) {
416 static $_filter = array();
418 if (!is_null($filter)) {
419 if (!is_array($filter)) {
420 $filter = array($filter);
430 static function encryptionKey($encryption_key = null) {
431 static $_encryption_key = 'CRYPTED ADODB SESSIONS ROCK!';
433 if (!is_null($encryption_key)) {
434 $_encryption_key = $encryption_key;
437 return $_encryption_key;
440 /////////////////////
442 /////////////////////
446 static function _conn($conn=null) {
447 return isset($GLOBALS['ADODB_SESS_CONN']) ? $GLOBALS['ADODB_SESS_CONN'] : false;
452 static function _crc($crc = null) {
453 static $_crc = false;
455 if (!is_null($crc)) {
464 static function _init() {
465 session_module_name('user');
466 session_set_save_handler(
467 array('ADODB_Session', 'open'),
468 array('ADODB_Session', 'close'),
469 array('ADODB_Session', 'read'),
470 array('ADODB_Session', 'write'),
471 array('ADODB_Session', 'destroy'),
472 array('ADODB_Session', 'gc')
479 static function _sessionKey() {
480 // use this function to create the encryption key for crypted sessions
481 // crypt the used key, ADODB_Session::encryptionKey() as key and session_id() as salt
482 return crypt(ADODB_Session::encryptionKey(), session_id());
487 static function _dumprs(&$rs) {
488 $conn = ADODB_Session::_conn();
489 $debug = ADODB_Session::debug();
500 echo "<br />\$rs is null or false<br />\n";
504 //echo "<br />\nAffected_Rows=",$conn->Affected_Rows(),"<br />\n";
506 if (!is_object($rs)) {
509 $rs = $conn->_rs2rs($rs);
511 require_once ADODB_SESSION.'/../tohtml.inc.php';
516 /////////////////////
518 /////////////////////
520 static function config($driver, $host, $user, $password, $database=false,$options=false)
522 ADODB_Session::driver($driver);
523 ADODB_Session::host($host);
524 ADODB_Session::user($user);
525 ADODB_Session::password($password);
526 ADODB_Session::database($database);
528 if ($driver == 'oci8' || $driver == 'oci8po') $options['lob'] = 'CLOB';
530 if (isset($options['table'])) ADODB_Session::table($options['table']);
531 if (isset($options['lob'])) ADODB_Session::clob($options['lob']);
532 if (isset($options['debug'])) ADODB_Session::debug($options['debug']);
536 Create the connection to the database.
538 If $conn already exists, reuse that connection
540 static function open($save_path, $session_name, $persist = null)
542 $conn = ADODB_Session::_conn();
548 $database = ADODB_Session::database();
549 $debug = ADODB_Session::debug();
550 $driver = ADODB_Session::driver();
551 $host = ADODB_Session::host();
552 $password = ADODB_Session::password();
553 $user = ADODB_Session::user();
555 if (!is_null($persist)) {
556 ADODB_Session::persist($persist);
558 $persist = ADODB_Session::persist();
561 # these can all be defaulted to in php.ini
562 # assert('$database');
566 $conn = ADONewConnection($driver);
570 ADOConnection::outp( " driver=$driver user=$user db=$database ");
573 if (empty($conn->_connectionID)) { // not dsn
577 case 'P': $ok = $conn->PConnect($host, $user, $password, $database); break;
578 case 'C': $ok = $conn->Connect($host, $user, $password, $database); break;
579 case 'N': $ok = $conn->NConnect($host, $user, $password, $database); break;
582 $ok = $conn->Connect($host, $user, $password, $database);
586 if ($ok) $GLOBALS['ADODB_SESS_CONN'] = $conn;
588 ADOConnection::outp('<p>Session: connection failed</p>', false);
597 static function close()
600 $conn = ADODB_Session::_conn();
601 if ($conn) $conn->Close();
607 Slurp in the session variables and return the serialized string
609 static function read($key)
611 $conn = ADODB_Session::_conn();
612 $filter = ADODB_Session::filter();
613 $table = ADODB_Session::table();
621 $binary = $conn->dataProvider === 'mysql' ? '/*! BINARY */' : '';
623 global $ADODB_SESSION_SELECT_FIELDS;
624 if (!isset($ADODB_SESSION_SELECT_FIELDS)) $ADODB_SESSION_SELECT_FIELDS = 'sessdata';
625 $sql = "SELECT $ADODB_SESSION_SELECT_FIELDS FROM $table WHERE sesskey = $binary ".$conn->Param(0)." AND expiry >= " . $conn->sysTimeStamp;
627 /* Lock code does not work as it needs to hold transaction within whole page, and we don't know if
628 developer has commited elsewhere... :(
630 #if (ADODB_Session::Lock())
631 # $rs = $conn->RowLock($table, "$binary sesskey = $qkey AND expiry >= " . time(), sessdata);
633 $rs = $conn->Execute($sql, array($key));
634 //ADODB_Session::_dumprs($rs);
639 $v = reset($rs->fields);
640 $filter = array_reverse($filter);
641 foreach ($filter as $f) {
643 $v = $f->read($v, ADODB_Session::_sessionKey());
646 $v = rawurldecode($v);
651 ADODB_Session::_crc(strlen($v) . crc32($v));
659 Write the serialized data to a database.
661 If the data has not been modified since the last read(), we do not write.
663 static function write($key, $oval)
665 global $ADODB_SESSION_READONLY;
667 if (!empty($ADODB_SESSION_READONLY)) return;
669 $clob = ADODB_Session::clob();
670 $conn = ADODB_Session::_conn();
671 $crc = ADODB_Session::_crc();
672 $debug = ADODB_Session::debug();
673 $driver = ADODB_Session::driver();
674 $expire_notify = ADODB_Session::expireNotify();
675 $filter = ADODB_Session::filter();
676 $lifetime = ADODB_Session::lifetime();
677 $table = ADODB_Session::table();
682 if ($debug) $conn->debug = 1;
683 $sysTimeStamp = $conn->sysTimeStamp;
687 $expiry = $conn->OffsetDate($lifetime/(24*3600),$sysTimeStamp);
689 $binary = $conn->dataProvider === 'mysql' ? '/*! BINARY */' : '';
691 // crc32 optimization since adodb 2.1
692 // now we only update expiry date, thx to sebastian thom in adodb 2.32
693 if ($crc !== '00' && $crc !== false && $crc == (strlen($oval) . crc32($oval))) {
695 echo '<p>Session: Only updating date - crc32 not changed</p>';
699 if ($expire_notify) {
700 $var = reset($expire_notify);
708 $sql = "UPDATE $table SET expiry = $expiry ,expireref=".$conn->Param('0').", modified = $sysTimeStamp WHERE $binary sesskey = ".$conn->Param('1')." AND expiry >= $sysTimeStamp";
709 $rs = $conn->Execute($sql,array($expirevar,$key));
712 $val = rawurlencode($oval);
713 foreach ($filter as $f) {
715 $val = $f->write($val, ADODB_Session::_sessionKey());
720 if ($expire_notify) {
721 $var = reset($expire_notify);
728 if (!$clob) { // no lobs, simply use replace()
729 $rs = $conn->Execute("SELECT COUNT(*) AS cnt FROM $table WHERE $binary sesskey = ".$conn->Param(0),array($key));
730 if ($rs) $rs->Close();
732 if ($rs && reset($rs->fields) > 0) {
733 $sql = "UPDATE $table SET expiry=$expiry, sessdata=".$conn->Param(0).", expireref= ".$conn->Param(1).",modified=$sysTimeStamp WHERE sesskey = ".$conn->Param(2);
736 $sql = "INSERT INTO $table (expiry, sessdata, expireref, sesskey, created, modified)
737 VALUES ($expiry,".$conn->Param('0').", ". $conn->Param('1').", ".$conn->Param('2').", $sysTimeStamp, $sysTimeStamp)";
741 $rs = $conn->Execute($sql,array($val,$expireref,$key));
744 // what value shall we insert/update for lob row?
746 // empty_clob or empty_lob for oracle dbs
751 $lob_value = sprintf('empty_%s()', strtolower($clob));
754 // null for all other
762 $rs = $conn->Execute("SELECT COUNT(*) AS cnt FROM $table WHERE $binary sesskey = ".$conn->Param(0),array($key));
764 if ($rs && reset($rs->fields) > 0) {
765 $sql = "UPDATE $table SET expiry=$expiry, sessdata=$lob_value, expireref= ".$conn->Param(0).",modified=$sysTimeStamp WHERE sesskey = ".$conn->Param('1');
768 $sql = "INSERT INTO $table (expiry, sessdata, expireref, sesskey, created, modified)
769 VALUES ($expiry,$lob_value, ". $conn->Param('0').", ".$conn->Param('1').", $sysTimeStamp, $sysTimeStamp)";
772 $rs = $conn->Execute($sql,array($expireref,$key));
774 $qkey = $conn->qstr($key);
775 $rs2 = $conn->UpdateBlob($table, 'sessdata', $val, " sesskey=$qkey", strtoupper($clob));
776 if ($debug) echo "<hr>",htmlspecialchars($oval), "<hr>";
777 $rs = @$conn->CompleteTrans();
783 ADOConnection::outp('<p>Session Replace: ' . $conn->ErrorMsg() . '</p>', false);
786 // bug in access driver (could be odbc?) means that info is not committed
787 // properly unless select statement executed in Win2000
788 if ($conn->databaseType == 'access') {
789 $sql = "SELECT sesskey FROM $table WHERE $binary sesskey = $qkey";
790 $rs = $conn->Execute($sql);
791 ADODB_Session::_dumprs($rs);
797 if (ADODB_Session::Lock()) {
798 $conn->CommitTrans();
800 return $rs ? true : false;
805 static function destroy($key) {
806 $conn = ADODB_Session::_conn();
807 $table = ADODB_Session::table();
808 $expire_notify = ADODB_Session::expireNotify();
813 $debug = ADODB_Session::debug();
814 if ($debug) $conn->debug = 1;
817 $qkey = $conn->quote($key);
818 $binary = $conn->dataProvider === 'mysql' ? '/*! BINARY */' : '';
820 if ($expire_notify) {
821 reset($expire_notify);
822 $fn = next($expire_notify);
823 $savem = $conn->SetFetchMode(ADODB_FETCH_NUM);
824 $sql = "SELECT expireref, sesskey FROM $table WHERE $binary sesskey = $qkey";
825 $rs = $conn->Execute($sql);
826 ADODB_Session::_dumprs($rs);
827 $conn->SetFetchMode($savem);
832 $ref = $rs->fields[0];
833 $key = $rs->fields[1];
841 $sql = "DELETE FROM $table WHERE $binary sesskey = $qkey";
842 $rs = $conn->Execute($sql);
847 return $rs ? true : false;
852 static function gc($maxlifetime)
854 $conn = ADODB_Session::_conn();
855 $debug = ADODB_Session::debug();
856 $expire_notify = ADODB_Session::expireNotify();
857 $optimize = ADODB_Session::optimize();
858 $table = ADODB_Session::table();
865 $debug = ADODB_Session::debug();
875 $time = $conn->OffsetDate(-$maxlifetime/24/3600,$conn->sysTimeStamp);
876 $binary = $conn->dataProvider === 'mysql' ? '/*! BINARY */' : '';
878 if ($expire_notify) {
879 reset($expire_notify);
880 $fn = next($expire_notify);
885 $savem = $conn->SetFetchMode(ADODB_FETCH_NUM);
886 $sql = "SELECT expireref, sesskey FROM $table WHERE expiry < $time ORDER BY 2"; # add order by to prevent deadlock
887 $rs = $conn->SelectLimit($sql,1000);
888 if ($debug) ADODB_Session::_dumprs($rs);
889 $conn->SetFetchMode($savem);
891 $tr = $conn->hasTransactions;
892 if ($tr) $conn->BeginTrans();
896 $ref = $rs->fields[0];
897 $key = $rs->fields[1];
898 if ($fn) $fn($ref, $key);
899 $del = $conn->Execute("DELETE FROM $table WHERE sesskey=".$conn->Param('0'),array($key));
902 if ($tr && $ccnt % $COMMITNUM == 0) {
903 if ($debug) echo "Commit<br>\n";
904 $conn->CommitTrans();
910 if ($tr) $conn->CommitTrans();
914 // suggested by Cameron, "GaM3R" <gamr@outworld.cx>
916 $driver = ADODB_Session::driver();
918 if (preg_match('/mysql/i', $driver)) {
919 $sql = "OPTIMIZE TABLE $table";
921 if (preg_match('/postgres/i', $driver)) {
922 $sql = "VACUUM $table";
925 $conn->Execute($sql);
934 ADODB_Session::_init();
935 if (empty($ADODB_SESSION_READONLY))
936 register_shutdown_function('session_write_close');
938 // for backwards compatability only
939 function adodb_sess_open($save_path, $session_name, $persist = true) {
940 return ADODB_Session::open($save_path, $session_name, $persist);
943 // for backwards compatability only
944 function adodb_sess_gc($t)
946 return ADODB_Session::gc($t);