]> git.donarmstrong.com Git - roundcube.git/blob - program/include/rcube_session.php
Imported Upstream version 0.5
[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     return true;
158   }
159
160
161   // garbage collecting function
162   public function gc($maxlifetime)
163   {
164     // just delete all expired sessions
165     $this->db->query(
166       sprintf("DELETE FROM %s WHERE changed < %s",
167         get_table_name('session'), $this->db->fromunixtime(time() - $maxlifetime)));
168
169     foreach ($this->gc_handlers as $fct)
170       $fct();
171
172     return true;
173   }
174
175
176   // registering additional garbage collector functions
177   public function register_gc_handler($func_name)
178   {
179     if ($func_name && !in_array($func_name, $this->gc_handlers))
180       $this->gc_handlers[] = $func_name;
181   }
182
183
184   public function regenerate_id()
185   {
186     $randval = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
187
188     for ($random = '', $i=1; $i <= 32; $i++) {
189       $random .= substr($randval, mt_rand(0,(strlen($randval) - 1)), 1);
190     }
191
192     // use md5 value for id or remove capitals from string $randval
193     $random = md5($random);
194
195     // delete old session record
196     $this->destroy(session_id());
197
198     session_id($random);
199
200     $cookie   = session_get_cookie_params();
201     $lifetime = $cookie['lifetime'] ? time() + $cookie['lifetime'] : 0;
202
203     rcmail::setcookie(session_name(), $random, $lifetime);
204
205     return true;
206   }
207
208
209   // unset session variable
210   public function remove($var=NULL)
211   {
212     if (empty($var))
213       return $this->destroy(session_id());
214
215     $this->unsets[] = $var;
216     unset($_SESSION[$var]);
217
218     return true;
219   }
220
221
222   // serialize session data
223   private function serialize($vars)
224   {
225     $data = '';
226     if (is_array($vars))
227       foreach ($vars as $var=>$value)
228         $data .= $var.'|'.serialize($value);
229     else
230       $data = 'b:0;';
231     return $data;
232   }
233
234
235   // unserialize session data
236   // http://www.php.net/manual/en/function.session-decode.php#56106
237   private function unserialize($str)
238   {
239     $str = (string)$str;
240     $endptr = strlen($str);
241     $p = 0;
242
243     $serialized = '';
244     $items = 0;
245     $level = 0;
246
247     while ($p < $endptr) {
248       $q = $p;
249       while ($str[$q] != '|')
250         if (++$q >= $endptr) break 2;
251
252       if ($str[$p] == '!') {
253         $p++;
254         $has_value = false;
255       } else {
256         $has_value = true;
257       }
258
259       $name = substr($str, $p, $q - $p);
260       $q++;
261
262       $serialized .= 's:' . strlen($name) . ':"' . $name . '";';
263
264       if ($has_value) {
265         for (;;) {
266           $p = $q;
267           switch (strtolower($str[$q])) {
268             case 'n': /* null */
269             case 'b': /* boolean */
270             case 'i': /* integer */
271             case 'd': /* decimal */
272               do $q++;
273               while ( ($q < $endptr) && ($str[$q] != ';') );
274               $q++;
275               $serialized .= substr($str, $p, $q - $p);
276               if ($level == 0) break 2;
277               break;
278             case 'r': /* reference  */
279               $q+= 2;
280               for ($id = ''; ($q < $endptr) && ($str[$q] != ';'); $q++) $id .= $str[$q];
281               $q++;
282               $serialized .= 'R:' . ($id + 1) . ';'; /* increment pointer because of outer array */
283               if ($level == 0) break 2;
284               break;
285             case 's': /* string */
286               $q+=2;
287               for ($length=''; ($q < $endptr) && ($str[$q] != ':'); $q++) $length .= $str[$q];
288               $q+=2;
289               $q+= (int)$length + 2;
290               $serialized .= substr($str, $p, $q - $p);
291               if ($level == 0) break 2;
292               break;
293             case 'a': /* array */
294             case 'o': /* object */
295               do $q++;
296               while ( ($q < $endptr) && ($str[$q] != '{') );
297               $q++;
298               $level++;
299               $serialized .= substr($str, $p, $q - $p);
300               break;
301             case '}': /* end of array|object */
302               $q++;
303               $serialized .= substr($str, $p, $q - $p);
304               if (--$level == 0) break 2;
305               break;
306             default:
307               return false;
308           }
309         }
310       } else {
311         $serialized .= 'N;';
312         $q += 2;
313       }
314       $items++;
315       $p = $q;
316     }
317
318     return unserialize( 'a:' . $items . ':{' . $serialized . '}' );
319   }
320
321   public function set_keep_alive($keep_alive)
322   {
323     $this->keep_alive = $keep_alive;
324   }
325
326   public function get_keep_alive()
327   {
328     return $this->keep_alive;
329   }
330
331   // getter for private variables
332   public function get_ts()
333   {
334     return $this->changed;
335   }
336
337   // getter for private variables
338   public function get_ip()
339   {
340     return $this->ip;
341   }
342
343 }