1 <?php rcs_id('$Id: DbSession.php,v 1.19 2004-06-02 17:13:16 rurban Exp $');
4 * Store sessions data in Pear DB / ADODB / dba / ....
8 * Originally by Stanislav Shramko <stanis@movingmail.com>
9 * Minor rewrite by Reini Urban <rurban@x-ray.at> for Phpwiki.
10 * Quasi-major rewrite/decruft/fix by Jeff Dairiki <dairiki@dairiki.org>.
11 * ADODB and dba classes by Reini Urban.
20 * Pear DB handle, or WikiDB object (from which the Pear DB handle will
23 * @param string $table
24 * Name of SQL table containing session data.
26 function DbSession(&$dbh, $table = 'session') {
27 // Coerce WikiDB to PearDB or ADODB.
28 // Todo: adodb/dba handlers
29 $db_type = $dbh->getParam('dbtype');
30 if (isa($dbh, 'WikiDB')) {
31 $backend = &$dbh->_backend;
32 $db_type = substr(get_class($dbh),7);
33 $class = "DbSession_".$db_type;
35 // < 4.1.2 crash on dba sessions at session_write_close().
36 // (Tested with 4.1.1 and 4.1.2)
37 // Didn't try postgres sessions.
38 if (!check_php_version(4,1,2) and $db_type == 'dba')
41 if (class_exists($class)) {
42 $this->_backend = new $class($backend->_dbh, $table);
43 return $this->_backend;
46 //Fixme: E_USER_WARNING ignored!
47 trigger_error(sprintf(_("Your WikiDB DB backend '%s' cannot be used for DbSession.")." ".
48 _("Set USE_DB_SESSION to false."),
49 $db_type), E_USER_WARNING);
53 function currentSessions() {
54 return $this->_backend->currentSessions();
56 function query($sql) {
57 return $this->_backend->query($sql);
59 function quote($string) {
60 return $this->_backend->quote($string);
68 var $_backend_type = "SQL";
70 function DbSession_SQL (&$dbh, $table) {
73 $this->_table = $table;
75 ini_set('session.save_handler','user');
76 session_module_name('user'); // new style
77 session_set_save_handler(array(&$this, 'open'),
78 array(&$this, 'close'),
79 array(&$this, 'read'),
80 array(&$this, 'write'),
81 array(&$this, 'destroy'),
88 $this->_connected = is_resource($dbh->connection);
89 if (!$this->_connected) {
90 $res = $dbh->connect($dbh->dsn);
91 if (DB::isError($res)) {
92 error_log("PhpWiki::DbSession::_connect: " . $res->getMessage());
98 function query($sql) {
99 return $this->_dbh->query($sql);
102 function quote($string) {
103 return $this->_dbh->quote($string);
106 function _disconnect() {
107 if (0 and $this->_connected)
108 $this->_dbh->disconnect();
114 * Actually this function is a fake for session_set_save_handle.
115 * @param string $save_path a path to stored files
116 * @param string $session_name a name of the concrete file
117 * @return boolean true just a variable to notify PHP that everything
121 function open ($save_path, $session_name) {
122 //$this->log("_open($save_path, $session_name)");
129 * This function is called just after <i>write</i> call.
131 * @return boolean true just a variable to notify PHP that everything
136 //$this->log("_close()");
141 * Reads the session data from DB.
143 * @param string $id an id of current session
147 function read ($id) {
148 //$this->log("_read($id)");
149 $dbh = &$this->_connect();
150 $table = $this->_table;
151 $qid = $dbh->quote($id);
153 $res = $dbh->getOne("SELECT sess_data FROM $table WHERE sess_id=$qid");
155 $this->_disconnect();
156 if (DB::isError($res) || empty($res))
158 if (isa($dbh, 'DB_pgsql'))
159 //if (preg_match('|^[a-zA-Z0-9/+=]+$|', $res))
160 $res = base64_decode($res);
165 * Saves the session data into DB.
167 * Just a comment: The "write" handler is not
168 * executed until after the output stream is closed. Thus,
169 * output from debugging statements in the "write" handler
170 * will never be seen in the browser. If debugging output
171 * is necessary, it is suggested that the debug output be
172 * written to a file instead.
175 * @param string $sess_data
176 * @return boolean true if data saved successfully and false
180 function write ($id, $sess_data) {
182 $dbh = &$this->_connect();
183 //$dbh->unlock(false,1);
184 $table = $this->_table;
185 $qid = $dbh->quote($id);
186 $qip = $dbh->quote($GLOBALS['request']->get('REMOTE_ADDR'));
188 if (DEBUG and $sess_data == 'wiki_user|N;') {
189 trigger_error("delete empty session $qid", E_USER_WARNING);
191 print_r($GLOBALS['request']->_user);
195 // postgres can't handle binary data in a TEXT field.
196 if (isa($dbh, 'DB_pgsql'))
197 $sess_data = base64_encode($sess_data);
198 $qdata = $dbh->quote($sess_data);
200 $res = $dbh->query("UPDATE $table"
201 . " SET sess_data=$qdata, sess_date=$time, sess_ip=$qip"
202 . " WHERE sess_id=$qid");
203 if ( ! $dbh->affectedRows() ) { // 0 (none) or -1 (failure) on mysql
204 $res = $dbh->query("INSERT INTO $table"
205 . " (sess_id, sess_data, sess_date, sess_ip)"
206 . " VALUES ($qid, $qdata, $time, $qip)");
208 $this->_disconnect();
209 return ! DB::isError($res);
213 * Destroys a session.
215 * Removes a session from the table.
218 * @return boolean true
221 function destroy ($id) {
222 $dbh = &$this->_connect();
223 $table = $this->_table;
224 $qid = $dbh->quote($id);
226 $dbh->query("DELETE FROM $table WHERE sess_id=$qid");
228 $this->_disconnect();
233 * Cleans out all expired sessions.
235 * @param int $maxlifetime session's time to live.
236 * @return boolean true
239 function gc ($maxlifetime) {
240 $dbh = &$this->_connect();
241 $table = $this->_table;
242 $threshold = time() - $maxlifetime;
244 $dbh->query("DELETE FROM $table WHERE sess_date < $threshold");
246 $this->_disconnect();
250 // WhoIsOnline support
251 // TODO: ip-accesstime dynamic blocking API
252 function currentSessions() {
254 $dbh = &$this->_connect();
255 $table = $this->_table;
256 $res = $dbh->query("SELECT sess_data,sess_date,sess_ip FROM $table ORDER BY sess_date DESC");
257 if (DB::isError($res) || empty($res))
259 while ($row = $res->fetchRow()) {
260 $data = $row['sess_data'];
261 $date = $row['sess_date'];
262 $ip = $row['sess_ip'];
263 if (preg_match('|^[a-zA-Z0-9/+=]+$|', $data))
264 $data = base64_decode($data);
265 // session_data contains the <variable name> + "|" + <packed string>
266 // we need just the wiki_user object (might be array as well)
267 $user = strstr($data,"wiki_user|");
268 $sessions[] = array('wiki_user' => substr($user,10), // from "O:" onwards
272 $this->_disconnect();
277 // self-written adodb-sessions
278 class DbSession_ADODB
281 var $_backend_type = "ADODB";
283 function DbSession_ADODB ($dbh, $table) {
286 $this->_table = $table;
288 ini_set('session.save_handler','user');
289 session_module_name('user'); // new style
290 session_set_save_handler(array(&$this, 'open'),
291 array(&$this, 'close'),
292 array(&$this, 'read'),
293 array(&$this, 'write'),
294 array(&$this, 'destroy'),
295 array(&$this, 'gc'));
299 function _connect() {
301 static $parsed = false;
303 if (!$dbh or !is_resource($dbh->_connectionID)) {
304 if (!$parsed) $parsed = parseDSN($request->_dbi->getParam('dsn'));
305 $this->_dbh = &ADONewConnection($parsed['phptype']); // Probably only MySql works just now
306 $this->_dbh->Connect($parsed['hostspec'],$parsed['username'],
307 $parsed['password'], $parsed['database']);
313 function query($sql) {
314 return $this->_dbh->Execute($sql);
317 function quote($string) {
318 return $this->_dbh->qstr($string);
321 function _disconnect() {
322 if (0 and $this->_dbh)
323 $this->_dbh->close();
329 * Actually this function is a fake for session_set_save_handle.
330 * @param string $save_path a path to stored files
331 * @param string $session_name a name of the concrete file
332 * @return boolean true just a variable to notify PHP that everything
336 function open ($save_path, $session_name) {
337 //$this->log("_open($save_path, $session_name)");
344 * This function is called just after <i>write</i> call.
346 * @return boolean true just a variable to notify PHP that everything
351 //$this->log("_close()");
356 * Reads the session data from DB.
358 * @param string $id an id of current session
362 function read ($id) {
363 //$this->log("_read($id)");
364 $dbh = &$this->_connect();
365 $table = $this->_table;
366 $qid = $dbh->qstr($id);
368 $row = $dbh->GetRow("SELECT sess_data FROM $table WHERE sess_id=$qid");
371 $this->_disconnect();
372 if (!empty($res) and preg_match('|^[a-zA-Z0-9/+=]+$|', $res))
373 $res = base64_decode($res);
378 * Saves the session data into DB.
380 * Just a comment: The "write" handler is not
381 * executed until after the output stream is closed. Thus,
382 * output from debugging statements in the "write" handler
383 * will never be seen in the browser. If debugging output
384 * is necessary, it is suggested that the debug output be
385 * written to a file instead.
388 * @param string $sess_data
389 * @return boolean true if data saved successfully and false
393 function write ($id, $sess_data) {
395 $dbh = &$this->_connect();
396 $table = $this->_table;
397 $qid = $dbh->qstr($id);
398 $qip = $dbh->qstr($GLOBALS['request']->get('REMOTE_ADDR'));
401 // postgres can't handle binary data in a TEXT field.
402 if (isa($dbh, 'ADODB_postgres64'))
403 $sess_data = base64_encode($sess_data);
404 $qdata = $dbh->qstr($sess_data);
405 $rs = $dbh->Execute("UPDATE $table"
406 . " SET sess_data=$qdata, sess_date=$time, sess_ip=$qip"
407 . " WHERE sess_id=$qid");
408 if ( ! $dbh->Affected_Rows() ) { // false or int > 0
409 $rs = $dbh->Execute("INSERT INTO $table"
410 . " (sess_id, sess_data, sess_date, sess_ip)"
411 . " VALUES ($qid, $qdata, $time, $qip)");
413 $result = ! $rs->EOF;
414 if ($result) $rs->free();
415 $this->_disconnect();
420 * Destroys a session.
422 * Removes a session from the table.
425 * @return boolean true
428 function destroy ($id) {
429 $dbh = &$this->_connect();
430 $table = $this->_table;
431 $qid = $dbh->qstr($id);
433 $dbh->Execute("DELETE FROM $table WHERE sess_id=$qid");
435 $this->_disconnect();
440 * Cleans out all expired sessions.
442 * @param int $maxlifetime session's time to live.
443 * @return boolean true
446 function gc ($maxlifetime) {
447 $dbh = &$this->_connect();
448 $table = $this->_table;
449 $threshold = time() - $maxlifetime;
451 $dbh->Execute("DELETE FROM $table WHERE sess_date < $threshold");
453 $this->_disconnect();
457 // WhoIsOnline support.
458 // TODO: ip-accesstime dynamic blocking API
459 function currentSessions() {
461 $dbh = &$this->_connect();
462 $table = $this->_table;
463 $rs = $this->Execute("SELECT sess_data,sess_date,sess_ip FROM $table ORDER BY sess_date DESC");
469 $row = $rs->fetchRow();
473 if (preg_match('|^[a-zA-Z0-9/+=]+$|', $data))
474 $data = base64_decode($data);
475 // session_data contains the <variable name> + "|" + <packed string>
476 // we need just the wiki_user object (might be array as well)
477 $user = strstr($data,"wiki_user|");
478 $sessions[] = array('wiki_user' => substr($user,10), // from "O:" onwards
484 $this->_disconnect();
492 * Values: date : IP : data
497 var $_backend_type = "dba";
499 function DbSession_dba (&$dbh, $table) {
501 ini_set('session.save_handler','user');
502 session_module_name('user'); // new style
503 session_set_save_handler(array(&$this, 'open'),
504 array(&$this, 'close'),
505 array(&$this, 'read'),
506 array(&$this, 'write'),
507 array(&$this, 'destroy'),
508 array(&$this, 'gc'));
512 function quote($str) { return $str; }
513 function query($sql) { return false; }
515 function _connect() {
521 $dba_handler = 'gdbm';
524 $dbfile = "$directory/$prefix" . 'session' . '.' . $dba_handler;
525 $dbh = new DbaDatabase($dbfile, false, $dba_handler);
526 $dbh->set_timeout($timeout);
527 if (!$dbh->open('c')) {
528 trigger_error(sprintf(_("%s: Can't open dba database"), $dbfile), E_USER_ERROR);
530 $request->finish(fmt("%s: Can't open dba database", $dbfile));
537 function _disconnect() {
538 if (0 and isset($this->_dbh))
539 $this->_dbh->close();
542 function open ($save_path, $session_name) {
543 $dbh = &$this->_connect();
549 $this->_dbh->close();
552 function read ($id) {
553 $dbh = &$this->_connect();
554 $result = $dbh->get($id);
558 list(,,$packed) = explode(':', $result, 3);
559 $this->_disconnect();
563 function write ($id, $sess_data) {
564 $dbh = &$this->_connect();
566 $ip = $GLOBALS['request']->get('REMOTE_ADDR');
567 $dbh->set($id,$time.':'.$ip.':'.$sess_data);
568 $this->_disconnect();
572 function destroy ($id) {
573 $dbh = &$this->_connect();
575 $this->_disconnect();
579 function gc ($maxlifetime) {
580 $dbh = &$this->_connect();
581 $threshold = time() - $maxlifetime;
582 for ($id = $dbh->firstkey(); $id !== false; $id = $dbh->nextkey()) {
583 $result = $dbh->get($id);
584 list($date,,) = explode(':', $result, 3);
585 //$dbh->query("DELETE FROM $table WHERE sess_date < $threshold");
586 if ($date < $threshold)
589 $this->_disconnect();
593 // WhoIsOnline support.
594 // TODO: ip-accesstime dynamic blocking API
595 function currentSessions() {
597 $dbh = &$this->_connect();
598 for ($id = $dbh->firstkey(); $id !== false; $id = $dbh->nextkey()) {
599 $result = $dbh->get($id);
600 list($date,$ip,$packed) = explode(':', $result, 3);
601 $data = unserialize($packed);
602 // session_data contains the <variable name> + "|" + <packed string>
603 // we need just the wiki_user object (might be array as well)
604 $user = strstr($data,"wiki_user|");
605 $sessions[] = array('wiki_user' => substr($user,10), // from "O:" onwards
609 $this->_disconnect();
619 // c-hanging-comment-ender-p: nil
620 // indent-tabs-mode: nil