4 +-----------------------------------------------------------------------+
5 | program/include/rcube_session.php |
7 | This file is part of the Roundcube Webmail client |
8 | Copyright (C) 2005-2011, The Roundcube Dev Team |
9 | Licensed under the GNU GPL |
12 | Provide database supported session management |
14 +-----------------------------------------------------------------------+
15 | Author: Thomas Bruederli <roundcube@gmail.com> |
16 | Author: Aleksander Machniak <alec@alec.pl> |
17 +-----------------------------------------------------------------------+
19 $Id: session.inc 2932 2009-09-07 12:51:21Z alec $
24 * Class to provide database supported session storage
27 * @author Thomas Bruederli <roundcube@gmail.com>
28 * @author Aleksander Machniak <alec@alec.pl>
36 private $unsets = array();
37 private $gc_handlers = array();
38 private $cookiename = 'roundcube_sessauth';
39 private $vars = false;
44 private $ip_check = false;
45 private $logging = false;
46 private $keep_alive = 0;
52 public function __construct($db, $config)
55 $this->start = microtime(true);
56 $this->ip = $_SERVER['REMOTE_ADDR'];
57 $this->logging = $config->get('log_session', false);
58 $this->mc_debug = $config->get('memcache_debug', false);
60 $lifetime = $config->get('session_lifetime', 1) * 60;
61 $this->set_lifetime($lifetime);
63 // use memcache backend
64 if ($config->get('session_storage', 'db') == 'memcache') {
65 $this->memcache = rcmail::get_instance()->get_memcache();
67 // set custom functions for PHP session management if memcache is available
68 if ($this->memcache) {
69 session_set_save_handler(
71 array($this, 'close'),
72 array($this, 'mc_read'),
73 array($this, 'mc_write'),
74 array($this, 'mc_destroy'),
78 raise_error(array('code' => 604, 'type' => 'db',
79 'line' => __LINE__, 'file' => __FILE__,
80 'message' => "Failed to connect to memcached. Please check configuration"),
85 // set custom functions for PHP session management
86 session_set_save_handler(
88 array($this, 'close'),
89 array($this, 'db_read'),
90 array($this, 'db_write'),
91 array($this, 'db_destroy'),
92 array($this, 'db_gc'));
97 public function open($save_path, $session_name)
103 public function close()
110 * Delete session data for the given key
112 * @param string Session ID
114 public function destroy($key)
116 return $this->memcache ? $this->mc_destroy($key) : $this->db_destroy($key);
121 * Read session data from database
123 * @param string Session ID
124 * @return string Session vars
126 public function db_read($key)
128 $sql_result = $this->db->query(
129 "SELECT vars, ip, changed FROM ".get_table_name('session')
130 ." WHERE sess_id = ?", $key);
132 if ($sql_result && ($sql_arr = $this->db->fetch_assoc($sql_result))) {
133 $this->changed = strtotime($sql_arr['changed']);
134 $this->ip = $sql_arr['ip'];
135 $this->vars = base64_decode($sql_arr['vars']);
138 if (!empty($this->vars))
148 * handler for session_read()
150 * @param string Session ID
151 * @param string Serialized session vars
152 * @return boolean True on success
154 public function db_write($key, $vars)
156 $ts = microtime(true);
157 $now = $this->db->fromunixtime((int)$ts);
159 // no session row in DB (db_read() returns false)
163 // use internal data from read() for fast requests (up to 0.5 sec.)
164 else if ($key == $this->key && (!$this->vars || $ts - $this->start < 0.5)) {
165 $oldvars = $this->vars;
167 else { // else read data again from DB
168 $oldvars = $this->db_read($key);
171 if ($oldvars !== false) {
172 $newvars = $this->_fixvars($vars, $oldvars);
174 if ($newvars !== $oldvars) {
176 sprintf("UPDATE %s SET vars=?, changed=%s WHERE sess_id=?",
177 get_table_name('session'), $now),
178 base64_encode($newvars), $key);
180 else if ($ts - $this->changed > $this->lifetime / 2) {
181 $this->db->query("UPDATE ".get_table_name('session')." SET changed=$now WHERE sess_id=?", $key);
186 sprintf("INSERT INTO %s (sess_id, vars, ip, created, changed) ".
187 "VALUES (?, ?, ?, %s, %s)",
188 get_table_name('session'), $now, $now),
189 $key, base64_encode($vars), (string)$this->ip);
197 * Merge vars with old vars and apply unsets
199 private function _fixvars($vars, $oldvars)
201 if ($oldvars !== false) {
202 $a_oldvars = $this->unserialize($oldvars);
203 if (is_array($a_oldvars)) {
204 foreach ((array)$this->unsets as $k)
205 unset($a_oldvars[$k]);
207 $newvars = $this->serialize(array_merge(
208 (array)$a_oldvars, (array)$this->unserialize($vars)));
214 $this->unsets = array();
220 * Handler for session_destroy()
222 * @param string Session ID
223 * @return boolean True on success
225 public function db_destroy($key)
228 sprintf("DELETE FROM %s WHERE sess_id = ?", get_table_name('session')),
236 * Garbage collecting function
238 * @param string Session lifetime in seconds
239 * @return boolean True on success
241 public function db_gc($maxlifetime)
243 // just delete all expired sessions
245 sprintf("DELETE FROM %s WHERE changed < %s",
246 get_table_name('session'), $this->db->fromunixtime(time() - $maxlifetime)));
255 * Read session data from memcache
257 * @param string Session ID
258 * @return string Session vars
260 public function mc_read($key)
262 $value = $this->memcache->get($key);
263 if ($this->mc_debug) write_log('memcache', "get($key): " . strlen($value));
264 if ($value && ($arr = unserialize($value))) {
265 $this->changed = $arr['changed'];
266 $this->ip = $arr['ip'];
267 $this->vars = $arr['vars'];
270 if (!empty($this->vars))
279 * handler for session_read()
281 * @param string Session ID
282 * @param string Serialized session vars
283 * @return boolean True on success
285 public function mc_write($key, $vars)
287 $ts = microtime(true);
289 // no session data in cache (mc_read() returns false)
292 // use internal data for fast requests (up to 0.5 sec.)
293 else if ($key == $this->key && (!$this->vars || $ts - $this->start < 0.5))
294 $oldvars = $this->vars;
295 else // else read data again
296 $oldvars = $this->mc_read($key);
298 $newvars = $oldvars !== false ? $this->_fixvars($vars, $oldvars) : $vars;
300 if ($newvars !== $oldvars || $ts - $this->changed > $this->lifetime / 2) {
301 $value = serialize(array('changed' => time(), 'ip' => $this->ip, 'vars' => $newvars));
302 $ret = $this->memcache->set($key, $value, MEMCACHE_COMPRESSED, $this->lifetime);
303 if ($this->mc_debug) {
304 write_log('memcache', "set($key): " . strlen($value) . ": " . ($ret ? 'OK' : 'ERR'));
305 write_log('memcache', "... get($key): " . strlen($this->memcache->get($key)));
314 * Handler for session_destroy() with memcache backend
316 * @param string Session ID
317 * @return boolean True on success
319 public function mc_destroy($key)
321 $ret = $this->memcache->delete($key);
322 if ($this->mc_debug) write_log('memcache', "delete($key): " . ($ret ? 'OK' : 'ERR'));
328 * Execute registered garbage collector routines
332 foreach ($this->gc_handlers as $fct)
338 * Cleanup session data before saving
340 public function cleanup()
342 // current compose information is stored in $_SESSION['compose'], move it to $_SESSION['compose_data_<ID>']
343 if ($compose_id = $_SESSION['compose']['id']) {
344 $_SESSION['compose_data_'.$compose_id] = $_SESSION['compose'];
345 $this->remove('compose');
351 * Register additional garbage collector functions
353 * @param mixed Callback function
355 public function register_gc_handler($func_name)
357 if ($func_name && !in_array($func_name, $this->gc_handlers))
358 $this->gc_handlers[] = $func_name;
363 * Generate and set new session id
365 * @param boolean $destroy If enabled the current session will be destroyed
367 public function regenerate_id($destroy=true)
369 session_regenerate_id($destroy);
372 $this->key = session_id();
379 * Unset a session variable
381 * @param string Varibale name
382 * @return boolean True on success
384 public function remove($var=null)
387 return $this->destroy(session_id());
389 $this->unsets[] = $var;
390 unset($_SESSION[$var]);
398 public function kill()
401 $this->destroy(session_id());
402 rcmail::setcookie($this->cookiename, '-del-', time() - 60);
407 * Serialize session data
409 private function serialize($vars)
413 foreach ($vars as $var=>$value)
414 $data .= $var.'|'.serialize($value);
422 * Unserialize session data
423 * http://www.php.net/manual/en/function.session-decode.php#56106
425 private function unserialize($str)
428 $endptr = strlen($str);
435 while ($p < $endptr) {
437 while ($str[$q] != '|')
438 if (++$q >= $endptr) break 2;
440 if ($str[$p] == '!') {
447 $name = substr($str, $p, $q - $p);
450 $serialized .= 's:' . strlen($name) . ':"' . $name . '";';
455 switch (strtolower($str[$q])) {
457 case 'b': /* boolean */
458 case 'i': /* integer */
459 case 'd': /* decimal */
461 while ( ($q < $endptr) && ($str[$q] != ';') );
463 $serialized .= substr($str, $p, $q - $p);
464 if ($level == 0) break 2;
466 case 'r': /* reference */
468 for ($id = ''; ($q < $endptr) && ($str[$q] != ';'); $q++) $id .= $str[$q];
470 $serialized .= 'R:' . ($id + 1) . ';'; /* increment pointer because of outer array */
471 if ($level == 0) break 2;
473 case 's': /* string */
475 for ($length=''; ($q < $endptr) && ($str[$q] != ':'); $q++) $length .= $str[$q];
477 $q+= (int)$length + 2;
478 $serialized .= substr($str, $p, $q - $p);
479 if ($level == 0) break 2;
481 case 'a': /* array */
482 case 'o': /* object */
484 while ( ($q < $endptr) && ($str[$q] != '{') );
487 $serialized .= substr($str, $p, $q - $p);
489 case '}': /* end of array|object */
491 $serialized .= substr($str, $p, $q - $p);
492 if (--$level == 0) break 2;
506 return unserialize( 'a:' . $items . ':{' . $serialized . '}' );
511 * Setter for session lifetime
513 public function set_lifetime($lifetime)
515 $this->lifetime = max(120, $lifetime);
517 // valid time range is now - 1/2 lifetime to now + 1/2 lifetime
519 $this->now = $now - ($now % ($this->lifetime / 2));
520 $this->prev = $this->now - ($this->lifetime / 2);
524 * Setter for keep_alive interval
526 public function set_keep_alive($keep_alive)
528 $this->keep_alive = $keep_alive;
530 if ($this->lifetime < $keep_alive)
531 $this->set_lifetime($keep_alive + 30);
535 * Getter for keep_alive interval
537 public function get_keep_alive()
539 return $this->keep_alive;
543 * Getter for remote IP saved with this session
545 public function get_ip()
551 * Setter for cookie encryption secret
553 function set_secret($secret)
555 $this->secret = $secret;
560 * Enable/disable IP check
562 function set_ip_check($check)
564 $this->ip_check = $check;
568 * Setter for the cookie name used for session cookie
570 function set_cookiename($cookiename)
573 $this->cookiename = $cookiename;
578 * Check session authentication cookie
580 * @return boolean True if valid, False if not
582 function check_auth()
584 $this->cookie = $_COOKIE[$this->cookiename];
585 $result = $this->ip_check ? $_SERVER['REMOTE_ADDR'] == $this->ip : true;
588 $this->log("IP check failed for " . $this->key . "; expected " . $this->ip . "; got " . $_SERVER['REMOTE_ADDR']);
590 if ($result && $this->_mkcookie($this->now) != $this->cookie) {
591 // Check if using id from previous time slot
592 if ($this->_mkcookie($this->prev) == $this->cookie) {
593 $this->set_auth_cookie();
597 $this->log("Session authentication failed for " . $this->key . "; invalid auth cookie sent");
606 * Set session authentication cookie
608 function set_auth_cookie()
610 $this->cookie = $this->_mkcookie($this->now);
611 rcmail::setcookie($this->cookiename, $this->cookie, 0);
612 $_COOKIE[$this->cookiename] = $this->cookie;
617 * Create session cookie from session data
619 * @param int Time slot to use
621 function _mkcookie($timeslot)
623 $auth_string = "$this->key,$this->secret,$timeslot";
624 return "S" . (function_exists('sha1') ? sha1($auth_string) : md5($auth_string));
633 write_log('session', $line);