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