]> git.donarmstrong.com Git - roundcube.git/blob - program/include/rcube_session.php
Imported Upstream version 0.5.1
[roundcube.git] / program / include / rcube_session.php
1 <?php
2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/include/rcube_session.php                                     |
6  |                                                                       |
7  | This file is part of the Roundcube Webmail client                     |
8  | Copyright (C) 2005-2010, Roundcube Dev. - Switzerland                 |
9  | Licensed under the GNU GPL                                            |
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
23 /**
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  */
30 class rcube_session
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->ip      = $sql_arr['ip'];
85       $this->vars    = base64_decode($sql_arr['vars']);
86       $this->key     = $key;
87
88       if (!empty($this->vars))
89         return $this->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       if (is_array($a_oldvars)) {
112         foreach ((array)$this->unsets as $k)
113           unset($a_oldvars[$k]);
114
115         $newvars = $this->serialize(array_merge(
116           (array)$a_oldvars, (array)$this->unserialize($vars)));
117       }
118       else
119         $newvars = $vars;
120
121       if (!$this->lifetime) {
122         $timeout = 600;
123       }
124       else if ($this->keep_alive>0) {
125         $timeout = min($this->lifetime * 0.5, $this->lifetime - $this->keep_alive);
126       } else {
127         $timeout = 0;
128       }
129
130       if (!($newvars === $oldvars) || ($ts - $this->changed > $timeout)) {
131         $this->db->query(
132           sprintf("UPDATE %s SET vars = ?, changed = %s WHERE sess_id = ?",
133             get_table_name('session'), $now),
134           base64_encode($newvars), $key);
135       }
136     }
137     else {
138       $this->db->query(
139         sprintf("INSERT INTO %s (sess_id, vars, ip, created, changed) ".
140           "VALUES (?, ?, ?, %s, %s)",
141           get_table_name('session'), $now, $now),
142         $key, base64_encode($vars), (string)$_SERVER['REMOTE_ADDR']);
143     }
144
145     $this->unsets = array();
146     return true;
147   }
148
149
150   // handler for session_destroy()
151   public function destroy($key)
152   {
153     $this->db->query(
154       sprintf("DELETE FROM %s WHERE sess_id = ?", get_table_name('session')),
155       $key);
156
157     if ($key == $this->key)
158         $this->vars = false;
159     return true;
160   }
161
162
163   // garbage collecting function
164   public function gc($maxlifetime)
165   {
166     // just delete all expired sessions
167     $this->db->query(
168       sprintf("DELETE FROM %s WHERE changed < %s",
169         get_table_name('session'), $this->db->fromunixtime(time() - $maxlifetime)));
170
171     foreach ($this->gc_handlers as $fct)
172       $fct();
173
174     return true;
175   }
176
177
178   // registering additional garbage collector functions
179   public function register_gc_handler($func_name)
180   {
181     if ($func_name && !in_array($func_name, $this->gc_handlers))
182       $this->gc_handlers[] = $func_name;
183   }
184
185
186   public function regenerate_id()
187   {
188     $randval = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
189
190     for ($random = '', $i=1; $i <= 32; $i++) {
191       $random .= substr($randval, mt_rand(0,(strlen($randval) - 1)), 1);
192     }
193
194     // use md5 value for id or remove capitals from string $randval
195     $random = md5($random);
196
197     // delete old session record
198     $this->destroy(session_id());
199
200     session_id($random);
201
202     $cookie   = session_get_cookie_params();
203     $lifetime = $cookie['lifetime'] ? time() + $cookie['lifetime'] : 0;
204
205     rcmail::setcookie(session_name(), $random, $lifetime);
206
207     return true;
208   }
209
210
211   // unset session variable
212   public function remove($var=NULL)
213   {
214     if (empty($var))
215       return $this->destroy(session_id());
216
217     $this->unsets[] = $var;
218     unset($_SESSION[$var]);
219
220     return true;
221   }
222
223
224   // serialize session data
225   private function serialize($vars)
226   {
227     $data = '';
228     if (is_array($vars))
229       foreach ($vars as $var=>$value)
230         $data .= $var.'|'.serialize($value);
231     else
232       $data = 'b:0;';
233     return $data;
234   }
235
236
237   // unserialize session data
238   // http://www.php.net/manual/en/function.session-decode.php#56106
239   private function unserialize($str)
240   {
241     $str = (string)$str;
242     $endptr = strlen($str);
243     $p = 0;
244
245     $serialized = '';
246     $items = 0;
247     $level = 0;
248
249     while ($p < $endptr) {
250       $q = $p;
251       while ($str[$q] != '|')
252         if (++$q >= $endptr) break 2;
253
254       if ($str[$p] == '!') {
255         $p++;
256         $has_value = false;
257       } else {
258         $has_value = true;
259       }
260
261       $name = substr($str, $p, $q - $p);
262       $q++;
263
264       $serialized .= 's:' . strlen($name) . ':"' . $name . '";';
265
266       if ($has_value) {
267         for (;;) {
268           $p = $q;
269           switch (strtolower($str[$q])) {
270             case 'n': /* null */
271             case 'b': /* boolean */
272             case 'i': /* integer */
273             case 'd': /* decimal */
274               do $q++;
275               while ( ($q < $endptr) && ($str[$q] != ';') );
276               $q++;
277               $serialized .= substr($str, $p, $q - $p);
278               if ($level == 0) break 2;
279               break;
280             case 'r': /* reference  */
281               $q+= 2;
282               for ($id = ''; ($q < $endptr) && ($str[$q] != ';'); $q++) $id .= $str[$q];
283               $q++;
284               $serialized .= 'R:' . ($id + 1) . ';'; /* increment pointer because of outer array */
285               if ($level == 0) break 2;
286               break;
287             case 's': /* string */
288               $q+=2;
289               for ($length=''; ($q < $endptr) && ($str[$q] != ':'); $q++) $length .= $str[$q];
290               $q+=2;
291               $q+= (int)$length + 2;
292               $serialized .= substr($str, $p, $q - $p);
293               if ($level == 0) break 2;
294               break;
295             case 'a': /* array */
296             case 'o': /* object */
297               do $q++;
298               while ( ($q < $endptr) && ($str[$q] != '{') );
299               $q++;
300               $level++;
301               $serialized .= substr($str, $p, $q - $p);
302               break;
303             case '}': /* end of array|object */
304               $q++;
305               $serialized .= substr($str, $p, $q - $p);
306               if (--$level == 0) break 2;
307               break;
308             default:
309               return false;
310           }
311         }
312       } else {
313         $serialized .= 'N;';
314         $q += 2;
315       }
316       $items++;
317       $p = $q;
318     }
319
320     return unserialize( 'a:' . $items . ':{' . $serialized . '}' );
321   }
322
323   public function set_keep_alive($keep_alive)
324   {
325     $this->keep_alive = $keep_alive;
326   }
327
328   public function get_keep_alive()
329   {
330     return $this->keep_alive;
331   }
332
333   // getter for private variables
334   public function get_ts()
335   {
336     return $this->changed;
337   }
338
339   // getter for private variables
340   public function get_ip()
341   {
342     return $this->ip;
343   }
344
345 }