thomascube
2011-04-25 63e9927d5f4a9a2a8ef42697d88649fa7d868ae4
Add support for session storage using memcache

3 files modified
201 ■■■■ changed files
config/main.inc.php.dist 9 ●●●●● patch | view | raw | blame | history
program/include/rcmail.php 7 ●●●●● patch | view | raw | blame | history
program/include/rcube_session.php 185 ●●●● patch | view | raw | blame | history
config/main.inc.php.dist
@@ -213,6 +213,15 @@
// session domain: .example.org
$rcmail_config['session_domain'] = '';
// Backend to use for session storage. Can either be 'db' (default) or 'memcache'
// If set to memcache, a list of servers need to be specified in 'memcache_hosts'
// Make sure the Memcache extension (http://pecl.php.net/package/memcache) version >= 2.0.0 is installed
$rcmail_config['session_storage'] = 'db';
// Use these hosts for accessing memcached
// Define any number of hosts in the form hostname:port
$rcmail_config['memcache_hosts'] = null; // e.g. array( 'localhost:11211', '192.168.1.12:11211' );
// check client IP in session athorization
$rcmail_config['ip_check'] = false;
program/include/rcmail.php
@@ -5,7 +5,7 @@
 | program/include/rcmail.php                                            |
 |                                                                       |
 | This file is part of the Roundcube Webmail client                     |
 | Copyright (C) 2008-2010, The Roundcube Dev Team                       |
 | Copyright (C) 2008-2011, The Roundcube Dev Team                       |
 | Licensed under the GNU GPL                                            |
 |                                                                       |
 | PURPOSE:                                                              |
@@ -570,13 +570,12 @@
    if (session_id())
      return;
    $lifetime = $this->config->get('session_lifetime', 0) * 60;
    // set session domain
    if ($domain = $this->config->get('session_domain')) {
      ini_set('session.cookie_domain', $domain);
    }
    // set session garbage collecting time according to session_lifetime
    $lifetime = $this->config->get('session_lifetime', 0) * 60;
    if ($lifetime) {
      ini_set('session.gc_maxlifetime', $lifetime * 2);
    }
@@ -588,7 +587,7 @@
    ini_set('session.serialize_handler', 'php');
    // use database for storing session data
    $this->session = new rcube_session($this->get_dbh(), $lifetime);
    $this->session = new rcube_session($this->get_dbh(), $this->config);
    $this->session->register_gc_handler('rcmail_temp_gc');
    if ($this->config->get('enable_caching'))
program/include/rcube_session.php
@@ -43,26 +43,59 @@
  private $secret = '';
  private $ip_check = false;
  private $keep_alive = 0;
  private $memcache;
  /**
   * Default constructor
   */
  public function __construct($db, $lifetime=60)
  public function __construct($db, $config)
  {
    $this->db = $db;
    $this->start = microtime(true);
    $this->ip = $_SERVER['REMOTE_ADDR'];
    $lifetime = $config->get('session_lifetime', 1) * 60;
    $this->set_lifetime($lifetime);
    // set custom functions for PHP session management
    session_set_save_handler(
      array($this, 'open'),
      array($this, 'close'),
      array($this, 'read'),
      array($this, 'write'),
      array($this, 'destroy'),
      array($this, 'gc'));
    // use memcache backend
    if ($config->get('session_storage', 'db') == 'memcache') {
      $this->memcache = new Memcache;
      $mc_available = 0;
      foreach ($config->get('memcache_hosts', array()) as $host) {
        list($host, $port) = explode(':', $host);
        if (!$port) $port = 11211;
        // add server and attempt to connect if not already done yet
        if ($this->memcache->addServer($host, $port) && !$mc_available)
          $mc_available += intval($this->memcache->connect($host, $port));
      }
      // set custom functions for PHP session management if memcache is available
      if ($mc_available) {
        session_set_save_handler(
          array($this, 'open'),
          array($this, 'close'),
          array($this, 'mc_read'),
          array($this, 'mc_write'),
          array($this, 'mc_destroy'),
          array($this, 'rcube_gc'));
      }
      else {
        raise_error(array('code' => 604, 'type' => 'db',
          'line' => __LINE__, 'file' => __FILE__,
          'message' => "Failed to connect to memcached. Please check configuration"),
          true, true);
      }
    }
    else {
      // set custom functions for PHP session management
      session_set_save_handler(
        array($this, 'open'),
        array($this, 'close'),
        array($this, 'db_read'),
        array($this, 'db_write'),
        array($this, 'db_destroy'),
        array($this, 'db_gc'));
      }
  }
@@ -78,8 +111,24 @@
  }
  // read session data
  public function read($key)
  /**
   * Delete session data for the given key
   *
   * @param string Session ID
   */
  public function destroy($key)
  {
    return $this->memcache ? $this->mc_destroy($key) : $this->db_destroy($key);
  }
  /**
   * Read session data from database
   *
   * @param string Session ID
   * @return string Session vars
   */
  public function db_read($key)
  {
    $sql_result = $this->db->query(
      sprintf("SELECT vars, ip, %s AS changed FROM %s WHERE sess_id = ?",
@@ -108,7 +157,7 @@
   * @param string Serialized session vars
   * @return boolean True on success
   */
  public function write($key, $vars)
  public function db_write($key, $vars)
  {
    $ts = microtime(true);
    $now = $this->db->fromunixtime((int)$ts);
@@ -121,17 +170,8 @@
    }
    if ($oldvars !== false) {
      $a_oldvars = $this->unserialize($oldvars);
      if (is_array($a_oldvars)) {
        foreach ((array)$this->unsets as $k)
          unset($a_oldvars[$k]);
        $newvars = $this->serialize(array_merge(
          (array)$a_oldvars, (array)$this->unserialize($vars)));
      }
      else
        $newvars = $vars;
      $newvars = $this->_fixvars($vars, $oldvars);
      if ($newvars !== $oldvars) {
        $this->db->query(
          sprintf("UPDATE %s SET vars=?, changed=%s WHERE sess_id=?",
@@ -153,6 +193,28 @@
    $this->unsets = array();
    return true;
  }
  private function _fixvars($vars, $oldvars)
  {
    $ts = microtime(true);
    if ($oldvars !== false) {
      $a_oldvars = $this->unserialize($oldvars);
      if (is_array($a_oldvars)) {
        foreach ((array)$this->unsets as $k)
          unset($a_oldvars[$k]);
        $newvars = $this->serialize(array_merge(
          (array)$a_oldvars, (array)$this->unserialize($vars)));
      }
      else
        $newvars = $vars;
    }
    $this->unsets = array();
    return $newvars;
  }
  /**
@@ -161,7 +223,7 @@
   * @param string Session ID
   * @return boolean True on success
   */
  public function destroy($key)
  public function db_destroy($key)
  {
    $this->db->query(
      sprintf("DELETE FROM %s WHERE sess_id = ?", get_table_name('session')),
@@ -177,21 +239,90 @@
   * @param string Session lifetime in seconds
   * @return boolean True on success
   */
  public function gc($maxlifetime)
  public function db_gc($maxlifetime)
  {
    // just delete all expired sessions
    $this->db->query(
      sprintf("DELETE FROM %s WHERE changed < %s",
        get_table_name('session'), $this->db->fromunixtime(time() - $maxlifetime)));
    foreach ($this->gc_handlers as $fct)
      $fct();
    $this->rcube_gc();
    return true;
  }
  /**
   * Read session data from memcache
   *
   * @param string Session ID
   * @return string Session vars
   */
  public function mc_read($key)
  {
    if ($value = $this->memcache->get($key)) {
      $arr = unserialize($value);
      $this->changed = $arr['changed'];
      $this->ip      = $arr['ip'];
      $this->vars    = $arr['vars'];
      $this->key     = $key;
      if (!empty($this->vars))
        return $this->vars;
    }
    return false;
  }
  /**
   * Save session data.
   * handler for session_read()
   *
   * @param string Session ID
   * @param string Serialized session vars
   * @return boolean True on success
   */
  public function mc_write($key, $vars)
  {
    $ts = microtime(true);
    // use internal data for fast requests (up to 0.5 sec.)
    if ($key == $this->key && $ts - $this->start < 0.5)
      $oldvars = $this->vars;
    else // else read data again
      $oldvars = $this->mc_read($key);
    $newvars = $oldvars !== false ? $this->_fixvars($vars, $oldvars) : $vars;
    if ($newvars !== $oldvars || $ts - $this->changed > $this->lifetime / 2)
      return $this->memcache->set($key, serialize(array('changed' => time(), 'ip' => $this->ip, 'vars' => $newvars)), MEMCACHE_COMPRESSED, $this->lifetime);
    return true;
  }
  /**
   * Handler for session_destroy() with memcache backend
   *
   * @param string Session ID
   * @return boolean True on success
   */
  public function mc_destroy($key)
  {
    return $this->memcache->delete($key);
  }
  /**
   * Execute registered garbage collector routines
   */
  public function rcube_gc()
  {
    foreach ($this->gc_handlers as $fct)
      $fct();
  }
  /**
   * Cleanup session data before saving
   */
  public function cleanup()