1 <?php rcs_id('$Id: DbSession.php,v 1.9 2004-04-06 20:00:09 rurban Exp $');
4 * Store sessions data in Pear DB / ADODB ....
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>.
19 * Pear DB handle, or WikiDB object (from which the Pear DB handle will
22 * @param string $table
23 * Name of SQL table containing session data.
25 function DB_Session(&$dbh, $table = 'session') {
26 // Coerce WikiDB to PearDB or ADODB.
27 // Todo: adodb/dba handlers
28 $db_type = $GLOBALS['DBParams']['dbtype'];
29 if (isa($dbh, 'WikiDB')) {
30 $backend = &$dbh->_backend;
31 $db_type = substr(get_class($dbh),7);
32 $class = "DB_Session_".$db_type;
33 if (class_exists($class)) {
34 $this->_backend = new $class(&$backend->_dbh, $table);
35 return $this->_backend;
40 //Fixme: E_USER_WARNING ignored!
41 trigger_error(sprintf(
42 _("Your WikiDB DB backend '%s' cannot be used for DB_Session. Set USE_DB_SESSION to false."),
43 $db_type), E_USER_WARNING);
46 function currentSessions() {
47 return $this->_backend->currentSessions();
49 function query($sql) {
50 return $this->_backend->query($sql);
52 function quote($string) {
53 return $this->_backend->quote($string);
61 var $_backend_type = "SQL";
63 function DB_Session_SQL ($dbh, $table) {
66 $this->_table = $table;
68 ini_set('session.save_handler','user');
69 session_module_name('user'); // new style
70 session_set_save_handler(array(&$this, 'open'),
71 array(&$this, 'close'),
72 array(&$this, 'read'),
73 array(&$this, 'write'),
74 array(&$this, 'destroy'),
81 $this->_connected = (bool)$dbh->connection;
82 if (!$this->_connected) {
83 $res = $dbh->connect($dbh->dsn);
84 if (DB::isError($res)) {
85 error_log("PhpWiki::DB_Session::_connect: " . $res->getMessage());
91 function query($sql) {
92 return $this->_dbh->query($sql);
95 function quote($string) {
96 return $this->_dbh->quote($string);
99 function _disconnect() {
100 if (0 and $this->_connected)
101 $this->_dbh->disconnect();
107 * Actually this function is a fake for session_set_save_handle.
108 * @param string $save_path a path to stored files
109 * @param string $session_name a name of the concrete file
110 * @return boolean true just a variable to notify PHP that everything
114 function open ($save_path, $session_name) {
115 //$this->log("_open($save_path, $session_name)");
122 * This function is called just after <i>write</i> call.
124 * @return boolean true just a variable to notify PHP that everything
129 //$this->log("_close()");
134 * Reads the session data from DB.
136 * @param string $id an id of current session
140 function read ($id) {
141 //$this->log("_read($id)");
142 $dbh = &$this->_connect();
143 $table = $this->_table;
144 $qid = $dbh->quote($id);
146 $res = $dbh->getOne("SELECT sess_data FROM $table WHERE sess_id=$qid");
148 $this->_disconnect();
149 if (DB::isError($res) || empty($res))
151 if (preg_match('|^[a-zA-Z0-9/+=]+$|', $res))
152 $res = base64_decode($res);
157 * Saves the session data into DB.
159 * Just a comment: The "write" handler is not
160 * executed until after the output stream is closed. Thus,
161 * output from debugging statements in the "write" handler
162 * will never be seen in the browser. If debugging output
163 * is necessary, it is suggested that the debug output be
164 * written to a file instead.
167 * @param string $sess_data
168 * @return boolean true if data saved successfully and false
172 function write ($id, $sess_data) {
174 $dbh = &$this->_connect();
175 $table = $this->_table;
176 $qid = $dbh->quote($id);
177 $qip = $dbh->quote($GLOBALS['HTTP_SERVER_VARS']['REMOTE_ADDR']);
180 // postgres can't handle binary data in a TEXT field.
181 if (isa($dbh, 'DB_pgsql'))
182 $sess_data = base64_encode($sess_data);
183 $qdata = $dbh->quote($sess_data);
185 $res = $dbh->query("UPDATE $table"
186 . " SET sess_data=$qdata, sess_date=$time, sess_ip=$qip"
187 . " WHERE sess_id=$qid");
189 if ($dbh->affectedRows() == 0)
190 $res = $dbh->query("INSERT INTO $table"
191 . " (sess_id, sess_data, sess_date, sess_ip)"
192 . " VALUES ($qid, $qdata, $time, $qip)");
194 $this->_disconnect();
195 return ! DB::isError($res);
199 * Destroys a session.
201 * Removes a session from the table.
204 * @return boolean true
207 function destroy ($id) {
208 $dbh = &$this->_connect();
209 $table = $this->_table;
210 $qid = $dbh->quote($id);
212 $dbh->query("DELETE FROM $table WHERE sess_id=$qid");
214 $this->_disconnect();
219 * Cleans out all expired sessions.
221 * @param int $maxlifetime session's time to live.
222 * @return boolean true
225 function gc ($maxlifetime) {
226 $dbh = &$this->_connect();
227 $table = $this->_table;
228 $threshold = time() - $maxlifetime;
230 $dbh->query("DELETE FROM $table WHERE sess_date < $threshold");
232 $this->_disconnect();
236 // WhoIsOnline support
237 // TODO: ip-accesstime dynamic blocking API
238 function currentSessions() {
240 $dbh = &$this->_connect();
241 $table = $this->_table;
242 $res = $this->query("SELECT sess_data,sess_date,sess_ip FROM $table ORDER BY sess_date DESC");
243 if (DB::isError($res) || empty($res))
245 while ($row = $res->fetchRow()) {
246 $data = $row['sess_data'];
247 $date = $row['sess_date'];
248 $ip = $row['sess_ip'];
249 if (preg_match('|^[a-zA-Z0-9/+=]+$|', $data))
250 $data = base64_decode($data);
251 // session_data contains the <variable name> + "|" + <packed string>
252 // we need just the wiki_user object (might be array as well)
253 $user = strstr($data,"wiki_user|");
254 $sessions[] = array('wiki_user' => substr($user,10), // from "O:" onwards
258 $this->_disconnect();
263 // self-written adodb-sessions
264 class DB_Session_ADODB
267 var $_backend_type = "ADODB";
269 function DB_Session_ADODB ($dbh, $table) {
272 $this->_table = $table;
274 ini_set('session.save_handler','user');
275 session_module_name('user'); // new style
276 session_set_save_handler(array(&$this, 'open'),
277 array(&$this, 'close'),
278 array(&$this, 'read'),
279 array(&$this, 'write'),
280 array(&$this, 'destroy'),
281 array(&$this, 'gc'));
285 function _connect() {
287 static $parsed = false;
290 if (!$parsed) $parsed = parseDSN($DBParams['dsn']);
291 $this->_dbh = &ADONewConnection($parsed['phptype']); // Probably only MySql works just now
292 $conn = $this->_dbh->Connect($parsed['hostspec'],$parsed['username'],
293 $parsed['password'], $parsed['database']);
299 function query($sql) {
300 return $this->_dbh->Execute($sql);
303 function quote($string) {
304 return $this->_dbh->qstr($string);
307 function _disconnect() {
308 if (0 and $this->_dbh)
309 $this->_dbh->close();
315 * Actually this function is a fake for session_set_save_handle.
316 * @param string $save_path a path to stored files
317 * @param string $session_name a name of the concrete file
318 * @return boolean true just a variable to notify PHP that everything
322 function open ($save_path, $session_name) {
323 //$this->log("_open($save_path, $session_name)");
330 * This function is called just after <i>write</i> call.
332 * @return boolean true just a variable to notify PHP that everything
337 //$this->log("_close()");
342 * Reads the session data from DB.
344 * @param string $id an id of current session
348 function read ($id) {
349 //$this->log("_read($id)");
350 $dbh = &$this->_connect();
351 $table = $this->_table;
352 $qid = $dbh->quote($id);
354 $rs = $dbh->Execute("SELECT sess_data FROM $table WHERE sess_id=$qid");
356 $res = $rs->fields["sess_data"];
358 $this->_disconnect();
359 if (!empty($res) and preg_match('|^[a-zA-Z0-9/+=]+$|', $res))
360 $res = base64_decode($res);
365 * Saves the session data into DB.
367 * Just a comment: The "write" handler is not
368 * executed until after the output stream is closed. Thus,
369 * output from debugging statements in the "write" handler
370 * will never be seen in the browser. If debugging output
371 * is necessary, it is suggested that the debug output be
372 * written to a file instead.
375 * @param string $sess_data
376 * @return boolean true if data saved successfully and false
380 function write ($id, $sess_data) {
382 $dbh = &$this->_connect();
383 $table = $this->_table;
384 $qid = $dbh->quote($id);
385 $qip = $dbh->quote($GLOBALS['HTTP_SERVER_VARS']['REMOTE_ADDR']);
388 // postgres can't handle binary data in a TEXT field.
389 if (isa($dbh, 'DB_pgsql'))
390 $sess_data = base64_encode($sess_data);
391 $qdata = $dbh->quote($sess_data);
392 $res = $dbh->query("UPDATE $table"
393 . " SET sess_data=$qdata, sess_date=$time, sess_ip=$qip"
394 . " WHERE sess_id=$qid");
395 // Warning: This works only only adodb_mysql!
396 // The parent class adodb needs ->AffectedRows()
397 if (!$dbh->_AffectedRows())
398 $res = $dbh->query("INSERT INTO $table"
399 . " (sess_id, sess_data, sess_date, sess_ip)"
400 . " VALUES ($qid, $qdata, $time, $qip)");
401 $this->_disconnect();
406 * Destroys a session.
408 * Removes a session from the table.
411 * @return boolean true
414 function destroy ($id) {
415 $dbh = &$this->_connect();
416 $table = $this->_table;
417 $qid = $dbh->quote($id);
419 $dbh->query("DELETE FROM $table WHERE sess_id=$qid");
421 $this->_disconnect();
426 * Cleans out all expired sessions.
428 * @param int $maxlifetime session's time to live.
429 * @return boolean true
432 function gc ($maxlifetime) {
433 $dbh = &$this->_connect();
434 $table = $this->_table;
435 $threshold = time() - $maxlifetime;
437 $dbh->query("DELETE FROM $table WHERE sess_date < $threshold");
439 $this->_disconnect();
443 // WhoIsOnline support.
444 // TODO: ip-accesstime dynamic blocking API
445 function currentSessions() {
447 $dbh = &$this->_connect();
448 $table = $this->_table;
449 $rs = $this->query("SELECT sess_data,sess_date,sess_ip FROM $table ORDER BY sess_date DESC");
453 while ($row = $rs->fetchRow()) {
454 $data = $row['sess_data'];
455 $date = $row['sess_date'];
456 $ip = $row['sess_ip'];
457 if (preg_match('|^[a-zA-Z0-9/+=]+$|', $data))
458 $data = base64_decode($data);
459 // session_data contains the <variable name> + "|" + <packed string>
460 // we need just the wiki_user object (might be array as well)
461 $user = strstr($data,"wiki_user|");
462 $sessions[] = array('wiki_user' => substr($user,10), // from "O:" onwards
466 $this->_disconnect();
474 * Values: date : IP : data
479 var $_backend_type = "dba";
481 function DB_Session_dba ($dbh, $table) {
483 ini_set('session.save_handler','user');
484 session_module_name('user'); // new style
485 session_set_save_handler(array(&$this, 'open'),
486 array(&$this, 'close'),
487 array(&$this, 'read'),
488 array(&$this, 'write'),
489 array(&$this, 'destroy'),
490 array(&$this, 'gc'));
494 function quote($str) { return $str; }
495 function query($sql) { return false; }
497 function _connect() {
503 $dba_handler = 'gdbm';
506 $dbfile = "$directory/$prefix" . 'session' . '.' . $dba_handler;
507 $dbh = new DbaDatabase($dbfile, false, $dba_handler);
508 $dbh->set_timeout($timeout);
509 if (!$dbh->open('c')) {
510 trigger_error(sprintf(_("%s: Can't open dba database"), $dbfile), E_USER_ERROR);
512 $request->finish(fmt("%s: Can't open dba database", $dbfile));
519 function _disconnect() {
520 if (0 and isset($this->_dbh))
521 $this->_dbh->close();
524 function open ($save_path, $session_name) {
525 $dbh = &$this->_connect();
530 $dbh = &$this->_connect();
534 function read ($id) {
535 $dbh = &$this->_connect();
536 $result = $dbh->get($id);
540 list(,,$packed) = explode(':', $result, 3);
541 $data = unserialize($packed);
542 $this->_disconnect();
546 function write ($id, $sess_data) {
547 $dbh = &$this->_connect();
549 $ip = $GLOBALS['HTTP_SERVER_VARS']['REMOTE_ADDR'];
550 $dbh->set($id,$time.':'.$ip.':'.$sess_data);
551 $this->_disconnect();
555 function destroy ($id) {
556 $dbh = &$this->_connect();
558 $this->_disconnect();
562 function gc ($maxlifetime) {
563 $dbh = &$this->_connect();
564 $threshold = time() - $maxlifetime;
565 for ($id = $dbh->firstkey(); $id !== false; $id = $dbh->nextkey()) {
566 $result = $dbh->get($id);
567 list($date,,) = explode(':', $result, 3);
568 //$dbh->query("DELETE FROM $table WHERE sess_date < $threshold");
569 if ($date < $threshold)
572 $this->_disconnect();
576 // WhoIsOnline support.
577 // TODO: ip-accesstime dynamic blocking API
578 function currentSessions() {
580 $dbh = &$this->_connect();
581 for ($id = $dbh->firstkey(); $id !== false; $id = $dbh->nextkey()) {
582 $result = $dbh->get($id);
583 list($date,$ip,$packed) = explode(':', $result, 3);
584 $data = unserialize($packed);
585 // session_data contains the <variable name> + "|" + <packed string>
586 // we need just the wiki_user object (might be array as well)
587 $user = strstr($data,"wiki_user|");
588 $sessions[] = array('wiki_user' => substr($user,10), // from "O:" onwards
592 $this->_disconnect();
602 // c-hanging-comment-ender-p: nil
603 // indent-tabs-mode: nil