]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/DbSession.php
Cleanup of special PageList column types
[SourceForge/phpwiki.git] / lib / DbSession.php
1 <?php rcs_id('$Id: DbSession.php,v 1.9 2004-04-06 20:00:09 rurban Exp $');
2
3 /**
4  * Store sessions data in Pear DB / ADODB ....
5  *
6  * History
7  *
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  */
12 class DB_Session
13 {
14     var $_backend;
15     /**
16      * Constructor
17      *
18      * @param mixed $dbh
19      * Pear DB handle, or WikiDB object (from which the Pear DB handle will
20      * be extracted.
21      *
22      * @param string $table
23      * Name of SQL table containing session data.
24      */
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;
36             }
37         }
38         return false;
39         
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);
44     }
45     
46     function currentSessions() {
47         return $this->_backend->currentSessions();
48     }
49     function query($sql) {
50         return $this->_backend->query($sql);
51     }
52     function quote($string) {
53         return $this->_backend->quote($string);
54     }
55
56 }
57
58 class DB_Session_SQL
59 extends DB_Session
60 {
61     var $_backend_type = "SQL";
62
63     function DB_Session_SQL ($dbh, $table) {
64
65         $this->_dbh = &$dbh;
66         $this->_table = $table;
67
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'),
75                                  array(&$this, 'gc'));
76         return $this;
77     }
78
79     function _connect() {
80         $dbh = &$this->_dbh;
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());
86             }
87         }
88         return $dbh;
89     }
90     
91     function query($sql) {
92         return $this->_dbh->query($sql);
93     }
94
95     function quote($string) {
96         return $this->_dbh->quote($string);
97     }
98
99     function _disconnect() {
100         if (0 and $this->_connected)
101             $this->_dbh->disconnect();
102     }
103
104     /**
105      * Opens a session.
106      *
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 
111      * is good.
112      * @access private
113      */
114     function open ($save_path, $session_name) {
115         //$this->log("_open($save_path, $session_name)");
116         return true;
117     }
118
119     /**
120      * Closes a session.
121      *
122      * This function is called just after <i>write</i> call.
123      *
124      * @return boolean true just a variable to notify PHP that everything 
125      * is good.
126      * @access private
127      */
128     function close() {
129         //$this->log("_close()");
130         return true;
131     }
132
133     /**
134      * Reads the session data from DB.
135      *
136      * @param  string $id an id of current session
137      * @return string
138      * @access private
139      */
140     function read ($id) {
141         //$this->log("_read($id)");
142         $dbh = &$this->_connect();
143         $table = $this->_table;
144         $qid = $dbh->quote($id);
145     
146         $res = $dbh->getOne("SELECT sess_data FROM $table WHERE sess_id=$qid");
147
148         $this->_disconnect();
149         if (DB::isError($res) || empty($res))
150             return '';
151         if (preg_match('|^[a-zA-Z0-9/+=]+$|', $res))
152             $res = base64_decode($res);
153         return $res;
154     }
155   
156     /**
157      * Saves the session data into DB.
158      *
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.
165      *
166      * @param  string $id
167      * @param  string $sess_data
168      * @return boolean true if data saved successfully  and false
169      * otherwise.
170      * @access private
171      */
172     function write ($id, $sess_data) {
173         
174         $dbh = &$this->_connect();
175         $table = $this->_table;
176         $qid = $dbh->quote($id);
177         $qip = $dbh->quote($GLOBALS['HTTP_SERVER_VARS']['REMOTE_ADDR']);
178         $time = time();
179
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);
184         
185         $res = $dbh->query("UPDATE $table"
186                            . " SET sess_data=$qdata, sess_date=$time, sess_ip=$qip"
187                            . " WHERE sess_id=$qid");
188
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)");
193
194         $this->_disconnect();
195         return ! DB::isError($res);
196     }
197
198     /**
199      * Destroys a session.
200      *
201      * Removes a session from the table.
202      *
203      * @param  string $id
204      * @return boolean true 
205      * @access private
206      */
207     function destroy ($id) {
208         $dbh = &$this->_connect();
209         $table = $this->_table;
210         $qid = $dbh->quote($id);
211
212         $dbh->query("DELETE FROM $table WHERE sess_id=$qid");
213
214         $this->_disconnect();
215         return true;     
216     }
217
218     /**
219      * Cleans out all expired sessions.
220      *
221      * @param  int $maxlifetime session's time to live.
222      * @return boolean true
223      * @access private
224      */
225     function gc ($maxlifetime) {
226         $dbh = &$this->_connect();
227         $table = $this->_table;
228         $threshold = time() - $maxlifetime;
229
230         $dbh->query("DELETE FROM $table WHERE sess_date < $threshold");
231
232         $this->_disconnect();
233         return true;
234     }
235
236     // WhoIsOnline support
237     // TODO: ip-accesstime dynamic blocking API
238     function currentSessions() {
239         $sessions = array();
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))
244             return $sessions;
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
255                                 'date' => $date,
256                                 'ip'   => $ip);
257         }
258         $this->_disconnect();
259         return $sessions;
260     }
261 }
262
263 // self-written adodb-sessions
264 class DB_Session_ADODB
265 extends DB_Session
266 {
267     var $_backend_type = "ADODB";
268
269     function DB_Session_ADODB ($dbh, $table) {
270
271         $this->_dbh = &$dbh;
272         $this->_table = $table;
273
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'));
282         return $this;
283     }
284
285     function _connect() {
286         global $DBParams;
287         static $parsed = false;
288         $dbh = &$this->_dbh;
289         if (!$dbh) {
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']);
294             $dbh = &$this->_dbh;                             
295         }
296         return $dbh;
297     }
298     
299     function query($sql) {
300         return $this->_dbh->Execute($sql);
301     }
302
303     function quote($string) {
304         return $this->_dbh->qstr($string);
305     }
306
307     function _disconnect() {
308         if (0 and $this->_dbh)
309             $this->_dbh->close();
310     }
311
312     /**
313      * Opens a session.
314      *
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 
319      * is good.
320      * @access private
321      */
322     function open ($save_path, $session_name) {
323         //$this->log("_open($save_path, $session_name)");
324         return true;
325     }
326
327     /**
328      * Closes a session.
329      *
330      * This function is called just after <i>write</i> call.
331      *
332      * @return boolean true just a variable to notify PHP that everything 
333      * is good.
334      * @access private
335      */
336     function close() {
337         //$this->log("_close()");
338         return true;
339     }
340
341     /**
342      * Reads the session data from DB.
343      *
344      * @param  string $id an id of current session
345      * @return string
346      * @access private
347      */
348     function read ($id) {
349         //$this->log("_read($id)");
350         $dbh = &$this->_connect();
351         $table = $this->_table;
352         $qid = $dbh->quote($id);
353         $res = '';
354         $rs = $dbh->Execute("SELECT sess_data FROM $table WHERE sess_id=$qid");
355         if (!$rs->EOF) {
356             $res = $rs->fields["sess_data"];
357         }
358         $this->_disconnect();
359         if (!empty($res) and preg_match('|^[a-zA-Z0-9/+=]+$|', $res))
360             $res = base64_decode($res);
361         return $res;
362     }
363   
364     /**
365      * Saves the session data into DB.
366      *
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.
373      *
374      * @param  string $id
375      * @param  string $sess_data
376      * @return boolean true if data saved successfully  and false
377      * otherwise.
378      * @access private
379      */
380     function write ($id, $sess_data) {
381         
382         $dbh = &$this->_connect();
383         $table = $this->_table;
384         $qid = $dbh->quote($id);
385         $qip = $dbh->quote($GLOBALS['HTTP_SERVER_VARS']['REMOTE_ADDR']);
386         $time = time();
387
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();
402         return ! $res->EOF;
403     }
404
405     /**
406      * Destroys a session.
407      *
408      * Removes a session from the table.
409      *
410      * @param  string $id
411      * @return boolean true 
412      * @access private
413      */
414     function destroy ($id) {
415         $dbh = &$this->_connect();
416         $table = $this->_table;
417         $qid = $dbh->quote($id);
418
419         $dbh->query("DELETE FROM $table WHERE sess_id=$qid");
420
421         $this->_disconnect();
422         return true;     
423     }
424
425     /**
426      * Cleans out all expired sessions.
427      *
428      * @param  int $maxlifetime session's time to live.
429      * @return boolean true
430      * @access private
431      */
432     function gc ($maxlifetime) {
433         $dbh = &$this->_connect();
434         $table = $this->_table;
435         $threshold = time() - $maxlifetime;
436
437         $dbh->query("DELETE FROM $table WHERE sess_date < $threshold");
438
439         $this->_disconnect();
440         return true;
441     }
442
443     // WhoIsOnline support. 
444     // TODO: ip-accesstime dynamic blocking API
445     function currentSessions() {
446         $sessions = array();
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");
450         if ($rs->EOF) {
451             return $sessions;
452         }
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
463                                 'date' => $date,
464                                 'ip' => $ip);
465         }
466         $this->_disconnect();
467         return $sessions;
468     }
469 }
470
471 /** DBA Sessions
472  *  session:
473  *    Index: session_id
474  *   Values: date : IP : data
475  */
476 class DB_Session_dba
477 extends DB_Session
478 {
479     var $_backend_type = "dba";
480
481     function DB_Session_dba ($dbh, $table) {
482         $this->_dbh = &$dbh;
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'));
491         return $this;
492     }
493
494     function quote($str) { return $str; }
495     function query($sql) { return false; }
496
497     function _connect() {
498         global $DBParams;
499         $dbh = &$this->_dbh;
500         if (!$dbh) {
501             $directory = '/tmp';
502             $prefix = 'wiki_';
503             $dba_handler = 'gdbm';
504             $timeout = 20;
505             extract($DBParams);
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);
511                 global $request;
512                 $request->finish(fmt("%s: Can't open dba database", $dbfile));
513             }
514             $this->_dbh = &$dbh;
515         }
516         return $dbh;
517     }
518
519     function _disconnect() {
520         if (0 and isset($this->_dbh))
521             $this->_dbh->close();
522     }
523
524     function open ($save_path, $session_name) {
525         $dbh = &$this->_connect();
526         $dbh->open();
527     }
528
529     function close() {
530         $dbh = &$this->_connect();
531         $dbh->close();
532     }
533
534     function read ($id) {
535         $dbh = &$this->_connect();
536         $result = $dbh->get($id);
537         if (!$result) {
538             return false;
539         }
540         list(,,$packed) = explode(':', $result, 3);
541         $data = unserialize($packed);
542         $this->_disconnect();
543         return $data;
544     }
545   
546     function write ($id, $sess_data) {
547         $dbh = &$this->_connect();
548         $time = time();
549         $ip = $GLOBALS['HTTP_SERVER_VARS']['REMOTE_ADDR'];
550         $dbh->set($id,$time.':'.$ip.':'.$sess_data);
551         $this->_disconnect();
552         return true;
553     }
554
555     function destroy ($id) {
556         $dbh = &$this->_connect();
557         $dbh->delete($id);
558         $this->_disconnect();
559         return true;
560     }
561
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)
570                 $dbh->delete($id);
571         }
572         $this->_disconnect();
573         return true;
574     }
575
576     // WhoIsOnline support. 
577     // TODO: ip-accesstime dynamic blocking API
578     function currentSessions() {
579         $sessions = array();
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
589                                 'date' => $date,
590                                 'ip' => $ip);
591         }
592         $this->_disconnect();
593         return $sessions;
594     }
595 }
596
597
598 // Local Variables:
599 // mode: php
600 // tab-width: 8
601 // c-basic-offset: 4
602 // c-hanging-comment-ender-p: nil
603 // indent-tabs-mode: nil
604 // End:
605 ?>