From 66510e20d36cb8da4f3012ef063de7bfce9b51aa Mon Sep 17 00:00:00 2001
From: Aleksander Machniak <alec@alec.pl>
Date: Wed, 09 May 2012 07:52:28 -0400
Subject: [PATCH] Merge pull request #1 from Brianetta/de-svn

---
 program/include/rcube.php |  257 ++++++++++++++++++++++++--------------------------
 1 files changed, 123 insertions(+), 134 deletions(-)

diff --git a/program/include/rcube.php b/program/include/rcube.php
index bee2986..272136f 100644
--- a/program/include/rcube.php
+++ b/program/include/rcube.php
@@ -2,7 +2,7 @@
 
 /*
  +-----------------------------------------------------------------------+
- | program/include/rcmail.php                                            |
+ | program/include/rcube.php                                             |
  |                                                                       |
  | This file is part of the Roundcube Webmail client                     |
  | Copyright (C) 2008-2012, The Roundcube Dev Team                       |
@@ -36,7 +36,7 @@
   const INIT_WITH_PLUGINS = 2;
 
   /**
-   * Singleton instace of rcmail
+   * Singleton instace of rcube
    *
    * @var rcmail
    */
@@ -109,7 +109,7 @@
   /**
    * This implements the 'singleton' design pattern
    *
-   * @return rcmail The one and only instance
+   * @return rcube The one and only instance
    */
   static function get_instance()
   {
@@ -236,7 +236,7 @@
    *
    * @param string $name   Cache identifier
    * @param string $type   Cache type ('db', 'apc' or 'memcache')
-   * @param int    $ttl    Expiration time for cache items in seconds
+   * @param string $ttl    Expiration time for cache items
    * @param bool   $packed Enables/disables data serialization
    *
    * @return rcube_cache Cache object
@@ -244,7 +244,8 @@
   public function get_cache($name, $type='db', $ttl=0, $packed=true)
   {
     if (!isset($this->caches[$name])) {
-      $this->caches[$name] = new rcube_cache($type, $_SESSION['user_id'], $name, $ttl, $packed);
+      $userid = $this->get_user_id();
+      $this->caches[$name] = new rcube_cache($type, $userid, $name, $ttl, $packed);
     }
 
     return $this->caches[$name];
@@ -347,6 +348,7 @@
       $options['port']     = $_SESSION['storage_port'];
       $options['ssl']      = $_SESSION['storage_ssl'];
       $options['password'] = $this->decrypt($_SESSION['password']);
+      $_SESSION[$driver.'_host'] = $_SESSION['storage_host'];
     }
 
     $options = $this->plugins->exec_hook("storage_init", $options);
@@ -408,6 +410,112 @@
       $storage->set_page($_SESSION['page']);
     }
   }
+
+
+    /**
+     * Create session object and start the session.
+     */
+    public function session_init()
+    {
+        // session started (Installer?)
+        if (session_id()) {
+            return;
+        }
+
+        $sess_name   = $this->config->get('session_name');
+        $sess_domain = $this->config->get('session_domain');
+        $lifetime    = $this->config->get('session_lifetime', 0) * 60;
+
+        // set session domain
+        if ($sess_domain) {
+            ini_set('session.cookie_domain', $sess_domain);
+        }
+        // set session garbage collecting time according to session_lifetime
+        if ($lifetime) {
+            ini_set('session.gc_maxlifetime', $lifetime * 2);
+        }
+
+        ini_set('session.cookie_secure', rcube_utils::https_check());
+        ini_set('session.name', $sess_name ? $sess_name : 'roundcube_sessid');
+        ini_set('session.use_cookies', 1);
+        ini_set('session.use_only_cookies', 1);
+        ini_set('session.serialize_handler', 'php');
+
+        // use database for storing session data
+        $this->session = new rcube_session($this->get_dbh(), $this->config);
+
+        $this->session->register_gc_handler(array($this, 'temp_gc'));
+        $this->session->register_gc_handler(array($this, 'cache_gc'));
+
+        // start PHP session (if not in CLI mode)
+        if ($_SERVER['REMOTE_ADDR']) {
+            session_start();
+        }
+    }
+
+
+    /**
+     * Configure session object internals
+     */
+    public function session_configure()
+    {
+        if (!$this->session) {
+            return;
+        }
+
+        $lifetime   = $this->config->get('session_lifetime', 0) * 60;
+        $keep_alive = $this->config->get('keep_alive');
+
+        // set keep-alive/check-recent interval
+        if ($keep_alive) {
+            // be sure that it's less than session lifetime
+            if ($lifetime) {
+                $keep_alive = min($keep_alive, $lifetime - 30);
+            }
+            $keep_alive = max(60, $keep_alive);
+            $this->session->set_keep_alive($keep_alive);
+        }
+
+        $this->session->set_secret($this->config->get('des_key') . dirname($_SERVER['SCRIPT_NAME']));
+        $this->session->set_ip_check($this->config->get('ip_check'));
+    }
+
+
+    /**
+     * Garbage collector function for temp files.
+     * Remove temp files older than two days
+     */
+    public function temp_gc()
+    {
+        $tmp = unslashify($this->config->get('temp_dir'));
+        $expire = time() - 172800;  // expire in 48 hours
+
+        if ($tmp && ($dir = opendir($tmp))) {
+            while (($fname = readdir($dir)) !== false) {
+                if ($fname{0} == '.') {
+                    continue;
+                }
+
+                if (filemtime($tmp.'/'.$fname) < $expire) {
+                    @unlink($tmp.'/'.$fname);
+                }
+            }
+
+            closedir($dir);
+        }
+    }
+
+
+    /**
+     * Garbage collector for cache entries.
+     * Set flag to expunge caches on shutdown
+     */
+    public function cache_gc()
+    {
+        // because this gc function is called before storage is initialized,
+        // we just set a flag to expunge storage cache on shutdown.
+        $this->expunge_cache = true;
+    }
 
 
   /**
@@ -523,7 +631,7 @@
         $this->texts = array_merge($this->texts, $messages);
 
       // include user language files
-      if ($lang != 'en' && is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
+      if ($lang != 'en' && $lang != 'en_US' && is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
         include_once(INSTALL_PATH . 'program/localization/' . $lang . '/labels.inc');
         include_once(INSTALL_PATH . 'program/localization/' . $lang . '/messages.inc');
 
@@ -718,7 +826,7 @@
 
     /*-
      * Trim PHP's padding and the canary byte; see note in
-     * rcmail::encrypt() and http://php.net/mcrypt_generic#68082
+     * rcube::encrypt() and http://php.net/mcrypt_generic#68082
      */
     $clear = substr(rtrim($clear, "\0"), 0, -1);
 
@@ -794,66 +902,6 @@
 
 
   /**
-   * Use imagemagick or GD lib to read image properties
-   *
-   * @param string Absolute file path
-   * @return mixed Hash array with image props like type, width, height or False on error
-   */
-  public static function imageprops($filepath)
-  {
-    $rcube = self::get_instance();
-    if ($cmd = $rcube->config->get('im_identify_path', false)) {
-      list(, $type, $size) = explode(' ', strtolower(self::exec($cmd. ' 2>/dev/null {in}', array('in' => $filepath))));
-      if ($size)
-        list($width, $height) = explode('x', $size);
-    }
-    else if (function_exists('getimagesize')) {
-      $imsize = @getimagesize($filepath);
-      $width = $imsize[0];
-      $height = $imsize[1];
-      $type = preg_replace('!image/!', '', $imsize['mime']);
-    }
-
-    return $type ? array('type' => $type, 'width' => $width, 'height' => $height) : false;
-  }
-
-
-  /**
-   * Convert an image to a given size and type using imagemagick (ensures input is an image)
-   *
-   * @param $p['in']  Input filename (mandatory)
-   * @param $p['out'] Output filename (mandatory)
-   * @param $p['size']  Width x height of resulting image, e.g. "160x60"
-   * @param $p['type']  Output file type, e.g. "jpg"
-   * @param $p['-opts'] Custom command line options to ImageMagick convert
-   * @return Success of convert as true/false
-   */
-  public static function imageconvert($p)
-  {
-    $result = false;
-    $rcube = self::get_instance();
-    $convert  = $rcube->config->get('im_convert_path', false);
-    $identify = $rcube->config->get('im_identify_path', false);
-
-    // imagemagick is required for this
-    if (!$convert)
-        return false;
-
-    if (!(($imagetype = @exif_imagetype($p['in'])) && ($type = image_type_to_extension($imagetype, false))))
-      list(, $type) = explode(' ', strtolower(self::exec($identify . ' 2>/dev/null {in}', $p))); # for things like eps
-
-    $type = strtr($type, array("jpeg" => "jpg", "tiff" => "tif", "ps" => "eps", "ept" => "eps"));
-    $p += array('type' => $type, 'types' => "bmp,eps,gif,jp2,jpg,png,svg,tif", 'quality' => 75);
-    $p['-opts'] = array('-resize' => $p['size'].'>') + (array)$p['-opts'];
-
-    if (in_array($type, explode(',', $p['types']))) # Valid type?
-      $result = self::exec($convert . ' 2>&1 -flatten -auto-orient -colorspace RGB -quality {quality} {-opts} {in} {type}:{out}', $p) === "";
-
-    return $result;
-  }
-
-
-  /**
    * Construct shell command, execute it and return output as string.
    * Keywords {keyword} are replaced with arguments
    *
@@ -900,39 +948,6 @@
 
 
     /**
-     * Replaces hostname variables.
-     *
-     * @param string $name Hostname
-     * @param string $host Optional IMAP hostname
-     *
-     * @return string Hostname
-     */
-    public static function parse_host($name, $host = '')
-    {
-        // %n - host
-        $n = preg_replace('/:\d+$/', '', $_SERVER['SERVER_NAME']);
-        // %d - domain name without first part, e.g. %n=mail.domain.tld, %d=domain.tld
-        $d = preg_replace('/^[^\.]+\./', '', $n);
-        // %h - IMAP host
-        $h = $_SESSION['storage_host'] ? $_SESSION['storage_host'] : $host;
-        // %z - IMAP domain without first part, e.g. %h=imap.domain.tld, %z=domain.tld
-        $z = preg_replace('/^[^\.]+\./', '', $h);
-        // %s - domain name after the '@' from e-mail address provided at login screen. Returns FALSE if an invalid email is provided
-        if (strpos($name, '%s') !== false) {
-            $user_email = rcube_ui::get_input_value('_user', rcube_ui::INPUT_POST);
-            $user_email = rcube_idn_convert($user_email, true);
-            $matches    = preg_match('/(.*)@([a-z0-9\.\-\[\]\:]+)/i', $user_email, $s);
-            if ($matches < 1 || filter_var($s[1]."@".$s[2], FILTER_VALIDATE_EMAIL) === false) {
-                return false;
-            }
-        }
-
-        $name = str_replace(array('%n', '%d', '%h', '%z', '%s'), array($n, $d, $h, $z, $s[2]), $name);
-        return $name;
-    }
-
-
-    /**
      * Print or write debug messages
      *
      * @param mixed Debug message or data
@@ -941,15 +956,13 @@
     {
         $args = func_get_args();
 
-        if (class_exists('rcmail', false)) {
+        if (class_exists('rcube', false)) {
             $rcube = self::get_instance();
-            if (is_object($rcube->plugins)) {
-                $plugin = $rcube->plugins->exec_hook('console', array('args' => $args));
-                if ($plugin['abort']) {
-                    return;
-                }
-               $args = $plugin['args'];
+            $plugin = $rcube->plugins->exec_hook('console', array('args' => $args));
+            if ($plugin['abort']) {
+                return;
             }
+           $args = $plugin['args'];
         }
 
         $msg = array();
@@ -1115,32 +1128,6 @@
 
 
     /**
-     * Returns remote IP address and forwarded addresses if found
-     *
-     * @return string Remote IP address(es)
-     */
-    public static function remote_ip()
-    {
-        $address = $_SERVER['REMOTE_ADDR'];
-
-        // append the NGINX X-Real-IP header, if set
-        if (!empty($_SERVER['HTTP_X_REAL_IP'])) {
-            $remote_ip[] = 'X-Real-IP: ' . $_SERVER['HTTP_X_REAL_IP'];
-        }
-        // append the X-Forwarded-For header, if set
-        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
-            $remote_ip[] = 'X-Forwarded-For: ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
-        }
-
-        if (!empty($remote_ip)) {
-            $address .= '(' . implode(',', $remote_ip) . ')';
-        }
-
-        return $address;
-    }
-
-
-    /**
      * Returns current time (with microseconds).
      *
      * @return float Current time in seconds since the Unix
@@ -1186,6 +1173,9 @@
         if (is_object($this->user)) {
             return $this->user->ID;
         }
+        else if (isset($_SESSION['user_id'])) {
+            return $_SESSION['user_id'];
+        }
 
         return null;
     }
@@ -1223,4 +1213,3 @@
         return $args;
     }
 }
-

--
Gitblit v1.9.1