thomascube
2010-06-08 af3cf8a0a7de74ab169f44277eda73f5f9e18cd7
commit | author | age
929a50 1 <?php
A 2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/include/rcube_session.php                                     |
6  |                                                                       |
7  | This file is part of the RoundCube Webmail client                     |
d062db 8  | Copyright (C) 2005-2010, RoundCube Dev. - Switzerland                 |
929a50 9  | Licensed under the GNU GPL                                            |
A 10  |                                                                       |
11  | PURPOSE:                                                              |
12  |   Provide database supported session management                       |
13  |                                                                       |
14  +-----------------------------------------------------------------------+
15  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16  | Author: Aleksander Machniak <alec@alec.pl>                            |
17  +-----------------------------------------------------------------------+
18
19  $Id: session.inc 2932 2009-09-07 12:51:21Z alec $
20
21 */
22
d062db 23 /**
T 24  * Class to provide database supported session storage
25  *
26  * @package    Core
27  * @author     Thomas Bruederli <roundcube@gmail.com>
28  * @author     Aleksander Machniak <alec@alec.pl>
29  */
929a50 30 class rcube_session
A 31 {
32   private $db;
33   private $ip;
34   private $changed;
35   private $unsets = array();
36   private $gc_handlers = array();
37   private $start;
38   private $vars = false;
39   private $key;
40   private $keep_alive = 0;
41
42   /**
43    * Default constructor
44    */
45   public function __construct($db, $lifetime=60)
46   {
47     $this->db = $db;
48     $this->lifetime = $lifetime;
49     $this->start = microtime(true);
50
51     // set custom functions for PHP session management
52     session_set_save_handler(
53       array($this, 'open'),
54       array($this, 'close'),
55       array($this, 'read'),
56       array($this, 'write'),
57       array($this, 'destroy'),
58       array($this, 'gc'));
59   }
60
61
62   public function open($save_path, $session_name)
63   {
64     return true;
65   }
66
67
68   public function close()
69   {
70     return true;
71   }
72
73
74   // read session data
75   public function read($key)
76   {
77     $sql_result = $this->db->query(
78       sprintf("SELECT vars, ip, %s AS changed FROM %s WHERE sess_id = ?",
79         $this->db->unixtimestamp('changed'), get_table_name('session')),
80       $key);
81
82     if ($sql_arr = $this->db->fetch_assoc($sql_result)) {
83       $this->changed = $sql_arr['changed'];
84       $this->vars = $sql_arr['vars'];
85       $this->ip = $sql_arr['ip'];
86       $this->key = $key; 
87
88       if (!empty($sql_arr['vars']))
89         return $sql_arr['vars'];
90     }
91
92     return false;
93   }
94   
95
96   // save session data
97   public function write($key, $vars)
98   {
99     $ts = microtime(true);
100     $now = $this->db->fromunixtime((int)$ts);
101
102     // use internal data from read() for fast requests (up to 0.5 sec.)
103     if ($key == $this->key && $ts - $this->start < 0.5) {
104       $oldvars = $this->vars;
105     } else { // else read data again from DB
106       $oldvars = $this->read($key);
107     }
108     
109     if ($oldvars !== false) {
110       $a_oldvars = $this->unserialize($oldvars); 
111       foreach ((array)$this->unsets as $k)
112         unset($a_oldvars[$k]);
113
114       $newvars = $this->serialize(array_merge(
115         (array)$a_oldvars, (array)$this->unserialize($vars)));
116
117       if ($this->keep_alive>0) {
118     $timeout = min($this->lifetime * 0.5, 
119                $this->lifetime - $this->keep_alive);
120       } else {
121     $timeout = 0;
122       }
123
124       if (!($newvars === $oldvars) || ($ts - $this->changed > $timeout)) {
125         $this->db->query(
126       sprintf("UPDATE %s SET vars = ?, changed = %s WHERE sess_id = ?",
127         get_table_name('session'), $now),
128       $newvars, $key);
129       }
130     }
131     else {
132       $this->db->query(
133         sprintf("INSERT INTO %s (sess_id, vars, ip, created, changed) ".
134           "VALUES (?, ?, ?, %s, %s)",
135       get_table_name('session'), $now, $now),
136         $key, $vars, (string)$_SERVER['REMOTE_ADDR']);
137     }
138
139     $this->unsets = array();
140     return true;
141   }
142
143
144   // handler for session_destroy()
145   public function destroy($key)
146   {
147     $this->db->query(
148       sprintf("DELETE FROM %s WHERE sess_id = ?", get_table_name('session')),
149       $key);
150
151     return true;
152   }
153
154
155   // garbage collecting function
156   public function gc($maxlifetime)
157   {
158     // just delete all expired sessions
159     $this->db->query(
160       sprintf("DELETE FROM %s WHERE changed < %s",
161         get_table_name('session'), $this->db->fromunixtime(time() - $maxlifetime)));
162
163     foreach ($this->gc_handlers as $fct)
164       $fct();
165
166     return true;
167   }
168
169
170   // registering additional garbage collector functions
171   public function register_gc_handler($func_name)
172   {
173     if ($func_name && !in_array($func_name, $this->gc_handlers))
174       $this->gc_handlers[] = $func_name;
175   }
176
177
178   public function regenerate_id()
179   {
180     $randval = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
181
182     for ($random = '', $i=1; $i <= 32; $i++) {
183       $random .= substr($randval, mt_rand(0,(strlen($randval) - 1)), 1);
184     }
185
186     // use md5 value for id or remove capitals from string $randval
187     $random = md5($random);
188
189     // delete old session record
190     $this->destroy(session_id());
191
192     session_id($random);
193
194     $cookie   = session_get_cookie_params();
195     $lifetime = $cookie['lifetime'] ? time() + $cookie['lifetime'] : 0;
196
197     rcmail::setcookie(session_name(), $random, $lifetime);
198
199     return true;
200   }
201
202
203   // unset session variable
204   public function remove($var=NULL)
205   {
206     if (empty($var))
207       return $this->destroy(session_id());
208
209     $this->unsets[] = $var;
210     unset($_SESSION[$var]);
211
212     return true;
213   }
214
215
216   // serialize session data
217   private function serialize($vars)
218   {
219     $data = '';
220     if (is_array($vars))
221       foreach ($vars as $var=>$value)
222         $data .= $var.'|'.serialize($value);
223     else
224       $data = 'b:0;';
225     return $data;
226   }
227
228
229   // unserialize session data
230   // http://www.php.net/manual/en/function.session-decode.php#56106
231   private function unserialize($str)
232   {
233     $str = (string)$str;
234     $endptr = strlen($str);
235     $p = 0;
236
237     $serialized = '';
238     $items = 0;
239     $level = 0;
240
241     while ($p < $endptr) {
242       $q = $p;
243       while ($str[$q] != '|')
244         if (++$q >= $endptr) break 2;
245
246       if ($str[$p] == '!') {
247         $p++;
248         $has_value = false;
249       } else {
250         $has_value = true;
251       }
252
253       $name = substr($str, $p, $q - $p);
254       $q++;
255
256       $serialized .= 's:' . strlen($name) . ':"' . $name . '";';
257
258       if ($has_value) {
259         for (;;) {
260           $p = $q;
261           switch (strtolower($str[$q])) {
262             case 'n': /* null */
263             case 'b': /* boolean */
264             case 'i': /* integer */
265             case 'd': /* decimal */
266               do $q++;
267               while ( ($q < $endptr) && ($str[$q] != ';') );
268               $q++;
269               $serialized .= substr($str, $p, $q - $p);
270               if ($level == 0) break 2;
271               break;
272             case 'r': /* reference  */
273               $q+= 2;
274               for ($id = ''; ($q < $endptr) && ($str[$q] != ';'); $q++) $id .= $str[$q];
275               $q++;
276               $serialized .= 'R:' . ($id + 1) . ';'; /* increment pointer because of outer array */
277               if ($level == 0) break 2;
278               break;
279             case 's': /* string */
280               $q+=2;
281               for ($length=''; ($q < $endptr) && ($str[$q] != ':'); $q++) $length .= $str[$q];
282               $q+=2;
283               $q+= (int)$length + 2;
284               $serialized .= substr($str, $p, $q - $p);
285               if ($level == 0) break 2;
286               break;
287             case 'a': /* array */
288             case 'o': /* object */
289               do $q++;
290               while ( ($q < $endptr) && ($str[$q] != '{') );
291               $q++;
292               $level++;
293               $serialized .= substr($str, $p, $q - $p);
294               break;
295             case '}': /* end of array|object */
296               $q++;
297               $serialized .= substr($str, $p, $q - $p);
298               if (--$level == 0) break 2;
299               break;
300             default:
301               return false;
302           }
303         }
304       } else {
305         $serialized .= 'N;';
306         $q += 2;
307       }
308       $items++;
309       $p = $q;
310     }
311
312     return unserialize( 'a:' . $items . ':{' . $serialized . '}' );
313   }
314
315   public function set_keep_alive($keep_alive)
316   {
317     $this->keep_alive = $keep_alive;
318   }
319
320   public function get_keep_alive()
321   {
322     return $this->keep_alive;
323   }
324
325   // getter for private variables
326   public function get_ts()
327   {
328     return $this->changed;
329   }
330
331   // getter for private variables
332   public function get_ip()
333   {
334     return $this->ip;
335   }
336
337 }