1 <?php rcs_id('$Id: DbSession.php,v 1.21 2004-07-01 09:29:40 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);
161 if (strlen($res) > 4000) {
162 trigger_error("Overlarge session data!", E_USER_WARNING);
164 //$res = preg_replace('/s:6:"_cache";O:12:"WikiDB_cache".+}$/',"",$res);
170 * Saves the session data into DB.
172 * Just a comment: The "write" handler is not
173 * executed until after the output stream is closed. Thus,
174 * output from debugging statements in the "write" handler
175 * will never be seen in the browser. If debugging output
176 * is necessary, it is suggested that the debug output be
177 * written to a file instead.
180 * @param string $sess_data
181 * @return boolean true if data saved successfully and false
185 function write ($id, $sess_data) {
187 $dbh = &$this->_connect();
188 //$dbh->unlock(false,1);
189 $table = $this->_table;
190 $qid = $dbh->quote($id);
191 $qip = $dbh->quote($GLOBALS['request']->get('REMOTE_ADDR'));
192 $time = $dbh->quote(time());
193 if (DEBUG and $sess_data == 'wiki_user|N;') {
194 trigger_error("delete empty session $qid", E_USER_WARNING);
196 print_r($GLOBALS['request']->_user);
200 // postgres can't handle binary data in a TEXT field.
201 if (isa($dbh, 'DB_pgsql'))
202 $sess_data = base64_encode($sess_data);
203 $qdata = $dbh->quote($sess_data);
205 $res = $dbh->query("UPDATE $table"
206 . " SET sess_data=$qdata, sess_date=$time, sess_ip=$qip"
207 . " WHERE sess_id=$qid");
208 if ( ! $dbh->affectedRows() ) { // 0 (none) or -1 (failure) on mysql
209 $res = $dbh->query("INSERT INTO $table"
210 . " (sess_id, sess_data, sess_date, sess_ip)"
211 . " VALUES ($qid, $qdata, $time, $qip)");
213 $this->_disconnect();
214 return ! DB::isError($res);
218 * Destroys a session.
220 * Removes a session from the table.
223 * @return boolean true
226 function destroy ($id) {
227 $dbh = &$this->_connect();
228 $table = $this->_table;
229 $qid = $dbh->quote($id);
231 $dbh->query("DELETE FROM $table WHERE sess_id=$qid");
233 $this->_disconnect();
238 * Cleans out all expired sessions.
240 * @param int $maxlifetime session's time to live.
241 * @return boolean true
244 function gc ($maxlifetime) {
245 $dbh = &$this->_connect();
246 $table = $this->_table;
247 $threshold = time() - $maxlifetime;
249 $dbh->query("DELETE FROM $table WHERE sess_date < $threshold");
251 $this->_disconnect();
255 // WhoIsOnline support
256 // TODO: ip-accesstime dynamic blocking API
257 function currentSessions() {
259 $dbh = &$this->_connect();
260 $table = $this->_table;
261 $res = $dbh->query("SELECT sess_data,sess_date,sess_ip FROM $table ORDER BY sess_date DESC");
262 if (DB::isError($res) || empty($res))
264 while ($row = $res->fetchRow()) {
265 $data = $row['sess_data'];
266 $date = $row['sess_date'];
267 $ip = $row['sess_ip'];
268 if (preg_match('|^[a-zA-Z0-9/+=]+$|', $data))
269 $data = base64_decode($data);
270 if ($date < 908437560 or $date > 1588437560)
272 // session_data contains the <variable name> + "|" + <packed string>
273 // we need just the wiki_user object (might be array as well)
274 $user = strstr($data,"wiki_user|");
275 $sessions[] = array('wiki_user' => substr($user,10), // from "O:" onwards
279 $this->_disconnect();
284 // self-written adodb-sessions
285 class DbSession_ADODB
288 var $_backend_type = "ADODB";
290 function DbSession_ADODB ($dbh, $table) {
293 $this->_table = $table;
295 ini_set('session.save_handler','user');
296 session_module_name('user'); // new style
297 session_set_save_handler(array(&$this, 'open'),
298 array(&$this, 'close'),
299 array(&$this, 'read'),
300 array(&$this, 'write'),
301 array(&$this, 'destroy'),
302 array(&$this, 'gc'));
306 function _connect() {
308 static $parsed = false;
310 if (!$dbh or !is_resource($dbh->_connectionID)) {
311 if (!$parsed) $parsed = parseDSN($request->_dbi->getParam('dsn'));
312 $this->_dbh = &ADONewConnection($parsed['phptype']); // Probably only MySql works just now
313 $this->_dbh->Connect($parsed['hostspec'],$parsed['username'],
314 $parsed['password'], $parsed['database']);
320 function query($sql) {
321 return $this->_dbh->Execute($sql);
324 function quote($string) {
325 return $this->_dbh->qstr($string);
328 function _disconnect() {
329 if (0 and $this->_dbh)
330 $this->_dbh->close();
336 * Actually this function is a fake for session_set_save_handle.
337 * @param string $save_path a path to stored files
338 * @param string $session_name a name of the concrete file
339 * @return boolean true just a variable to notify PHP that everything
343 function open ($save_path, $session_name) {
344 //$this->log("_open($save_path, $session_name)");
351 * This function is called just after <i>write</i> call.
353 * @return boolean true just a variable to notify PHP that everything
358 //$this->log("_close()");
363 * Reads the session data from DB.
365 * @param string $id an id of current session
369 function read ($id) {
370 //$this->log("_read($id)");
371 $dbh = &$this->_connect();
372 $table = $this->_table;
373 $qid = $dbh->qstr($id);
375 $row = $dbh->GetRow("SELECT sess_data FROM $table WHERE sess_id=$qid");
378 $this->_disconnect();
379 if (!empty($res) and preg_match('|^[a-zA-Z0-9/+=]+$|', $res))
380 $res = base64_decode($res);
381 if (strlen($res) > 4000) {
382 trigger_error("Overlarge session data!", E_USER_WARNING);
389 * Saves the session data into DB.
391 * Just a comment: The "write" handler is not
392 * executed until after the output stream is closed. Thus,
393 * output from debugging statements in the "write" handler
394 * will never be seen in the browser. If debugging output
395 * is necessary, it is suggested that the debug output be
396 * written to a file instead.
399 * @param string $sess_data
400 * @return boolean true if data saved successfully and false
404 function write ($id, $sess_data) {
406 $dbh = &$this->_connect();
407 $table = $this->_table;
408 $qid = $dbh->qstr($id);
409 $qip = $dbh->qstr($GLOBALS['request']->get('REMOTE_ADDR'));
410 $time = $dbh->qstr(time());
412 // postgres can't handle binary data in a TEXT field.
413 if (isa($dbh, 'ADODB_postgres64'))
414 $sess_data = base64_encode($sess_data);
415 $qdata = $dbh->qstr($sess_data);
416 $rs = $dbh->Execute("UPDATE $table"
417 . " SET sess_data=$qdata, sess_date=$time, sess_ip=$qip"
418 . " WHERE sess_id=$qid");
419 if ( ! $dbh->Affected_Rows() ) { // false or int > 0
420 $rs = $dbh->Execute("INSERT INTO $table"
421 . " (sess_id, sess_data, sess_date, sess_ip)"
422 . " VALUES ($qid, $qdata, $time, $qip)");
424 $result = ! $rs->EOF;
425 if ($result) $rs->free();
426 $this->_disconnect();
431 * Destroys a session.
433 * Removes a session from the table.
436 * @return boolean true
439 function destroy ($id) {
440 $dbh = &$this->_connect();
441 $table = $this->_table;
442 $qid = $dbh->qstr($id);
444 $dbh->Execute("DELETE FROM $table WHERE sess_id=$qid");
446 $this->_disconnect();
451 * Cleans out all expired sessions.
453 * @param int $maxlifetime session's time to live.
454 * @return boolean true
457 function gc ($maxlifetime) {
458 $dbh = &$this->_connect();
459 $table = $this->_table;
460 $threshold = time() - $maxlifetime;
462 $dbh->Execute("DELETE FROM $table WHERE sess_date < $threshold");
464 $this->_disconnect();
468 // WhoIsOnline support.
469 // TODO: ip-accesstime dynamic blocking API
470 function currentSessions() {
472 $dbh = &$this->_connect();
473 $table = $this->_table;
474 $rs = $dbh->Execute("SELECT sess_data,sess_date,sess_ip FROM $table ORDER BY sess_date DESC");
480 $row = $rs->fetchRow();
484 if (preg_match('|^[a-zA-Z0-9/+=]+$|', $data))
485 $data = base64_decode($data);
486 if ($date < 908437560 or $date > 1588437560)
488 // session_data contains the <variable name> + "|" + <packed string>
489 // we need just the wiki_user object (might be array as well)
490 $user = strstr($data,"wiki_user|");
491 $sessions[] = array('wiki_user' => substr($user,10), // from "O:" onwards
497 $this->_disconnect();
505 * Values: date : IP : data
510 var $_backend_type = "dba";
512 function DbSession_dba (&$dbh, $table) {
514 ini_set('session.save_handler','user');
515 session_module_name('user'); // new style
516 session_set_save_handler(array(&$this, 'open'),
517 array(&$this, 'close'),
518 array(&$this, 'read'),
519 array(&$this, 'write'),
520 array(&$this, 'destroy'),
521 array(&$this, 'gc'));
525 function quote($str) { return $str; }
526 function query($sql) { return false; }
528 function _connect() {
534 $dba_handler = 'gdbm';
537 $dbfile = "$directory/$prefix" . 'session' . '.' . $dba_handler;
538 $dbh = new DbaDatabase($dbfile, false, $dba_handler);
539 $dbh->set_timeout($timeout);
540 if (!$dbh->open('c')) {
541 trigger_error(sprintf(_("%s: Can't open dba database"), $dbfile), E_USER_ERROR);
543 $request->finish(fmt("%s: Can't open dba database", $dbfile));
550 function _disconnect() {
551 if (0 and isset($this->_dbh))
552 $this->_dbh->close();
555 function open ($save_path, $session_name) {
556 $dbh = &$this->_connect();
562 $this->_dbh->close();
565 function read ($id) {
566 $dbh = &$this->_connect();
567 $result = $dbh->get($id);
571 list(,,$packed) = explode(':', $result, 3);
572 $this->_disconnect();
576 function write ($id, $sess_data) {
577 $dbh = &$this->_connect();
579 $ip = $GLOBALS['request']->get('REMOTE_ADDR');
580 $dbh->set($id,$time.':'.$ip.':'.$sess_data);
581 $this->_disconnect();
585 function destroy ($id) {
586 $dbh = &$this->_connect();
588 $this->_disconnect();
592 function gc ($maxlifetime) {
593 $dbh = &$this->_connect();
594 $threshold = time() - $maxlifetime;
595 for ($id = $dbh->firstkey(); $id !== false; $id = $dbh->nextkey()) {
596 $result = $dbh->get($id);
597 list($date,,) = explode(':', $result, 3);
598 //$dbh->query("DELETE FROM $table WHERE sess_date < $threshold");
599 if ($date < $threshold)
602 $this->_disconnect();
606 // WhoIsOnline support.
607 // TODO: ip-accesstime dynamic blocking API
608 function currentSessions() {
610 $dbh = &$this->_connect();
611 for ($id = $dbh->firstkey(); $id !== false; $id = $dbh->nextkey()) {
612 $result = $dbh->get($id);
613 list($date,$ip,$packed) = explode(':', $result, 3);
614 $data = unserialize($packed);
615 // session_data contains the <variable name> + "|" + <packed string>
616 // we need just the wiki_user object (might be array as well)
617 $user = strstr($data,"wiki_user|");
618 $sessions[] = array('wiki_user' => substr($user,10), // from "O:" onwards
622 $this->_disconnect();
632 // c-hanging-comment-ender-p: nil
633 // indent-tabs-mode: nil