source: github/program/include/rcube.php @ 5d66a4b

HEADcourier-fixdev-browser-capabilitiespdo
Last change on this file since 5d66a4b was 5d66a4b, checked in by alecpl <alec@…>, 13 months ago
  • Improved ttl values handling
  • Property mode set to 100644
File size: 32.9 KB
Line 
1<?php
2
3/*
4 +-----------------------------------------------------------------------+
5 | program/include/rcube.php                                             |
6 |                                                                       |
7 | This file is part of the Roundcube Webmail client                     |
8 | Copyright (C) 2008-2012, The Roundcube Dev Team                       |
9 | Copyright (C) 2011-2012, Kolab Systems AG                             |
10 |                                                                       |
11 | Licensed under the GNU General Public License version 3 or            |
12 | any later version with exceptions for skins & plugins.                |
13 | See the README file for a full license statement.                     |
14 |                                                                       |
15 | PURPOSE:                                                              |
16 |   Framework base class providing core functions and holding           |
17 |   instances of all 'global' objects like db- and storage-connections  |
18 +-----------------------------------------------------------------------+
19 | Author: Thomas Bruederli <roundcube@gmail.com>                        |
20 +-----------------------------------------------------------------------+
21
22 $Id$
23
24*/
25
26
27/**
28 * Base class of the Roundcube Framework
29 * implemented as singleton
30 *
31 * @package Core
32 */
33class rcube
34{
35  const INIT_WITH_DB = 1;
36  const INIT_WITH_PLUGINS = 2;
37
38  /**
39   * Singleton instace of rcube
40   *
41   * @var rcmail
42   */
43  static protected $instance;
44
45  /**
46   * Stores instance of rcube_config.
47   *
48   * @var rcube_config
49   */
50  public $config;
51
52  /**
53   * Instace of database class.
54   *
55   * @var rcube_mdb2
56   */
57  public $db;
58
59  /**
60   * Instace of Memcache class.
61   *
62   * @var rcube_mdb2
63   */
64  public $memcache;
65
66  /**
67   * Instace of rcube_session class.
68   *
69   * @var rcube_session
70   */
71  public $session;
72
73  /**
74   * Instance of rcube_smtp class.
75   *
76   * @var rcube_smtp
77   */
78  public $smtp;
79
80  /**
81   * Instance of rcube_storage class.
82   *
83   * @var rcube_storage
84   */
85  public $storage;
86
87  /**
88   * Instance of rcube_output class.
89   *
90   * @var rcube_output
91   */
92  public $output;
93
94  /**
95   * Instance of rcube_plugin_api.
96   *
97   * @var rcube_plugin_api
98   */
99  public $plugins;
100
101
102  /* private/protected vars */
103  protected $texts;
104  protected $caches = array();
105  protected $shutdown_functions = array();
106  protected $expunge_cache = false;
107
108
109  /**
110   * This implements the 'singleton' design pattern
111   *
112   * @return rcube The one and only instance
113   */
114  static function get_instance()
115  {
116    if (!self::$instance) {
117      self::$instance = new rcube();
118    }
119
120    return self::$instance;
121  }
122
123
124  /**
125   * Private constructor
126   */
127  protected function __construct()
128  {
129    // load configuration
130    $this->config = new rcube_config();
131    $this->plugins = new rcube_dummy_plugin_api;
132
133    register_shutdown_function(array($this, 'shutdown'));
134  }
135
136
137  /**
138   * Initial startup function
139   */
140  protected function init($mode = 0)
141  {
142    // initialize syslog
143    if ($this->config->get('log_driver') == 'syslog') {
144      $syslog_id = $this->config->get('syslog_id', 'roundcube');
145      $syslog_facility = $this->config->get('syslog_facility', LOG_USER);
146      openlog($syslog_id, LOG_ODELAY, $syslog_facility);
147    }
148
149    // connect to database
150    if ($mode & self::INIT_WITH_DB) {
151      $this->get_dbh();
152    }
153
154    // create plugin API and load plugins
155    if ($mode & self::INIT_WITH_PLUGINS) {
156      $this->plugins = rcube_plugin_api::get_instance();
157    }
158  }
159
160
161  /**
162   * Get the current database connection
163   *
164   * @return rcube_mdb2  Database connection object
165   */
166  public function get_dbh()
167  {
168    if (!$this->db) {
169      $config_all = $this->config->all();
170
171      $this->db = new rcube_mdb2($config_all['db_dsnw'], $config_all['db_dsnr'], $config_all['db_persistent']);
172      $this->db->sqlite_initials = INSTALL_PATH . 'SQL/sqlite.initial.sql';
173      $this->db->set_debug((bool)$config_all['sql_debug']);
174    }
175
176    return $this->db;
177  }
178
179
180  /**
181   * Get global handle for memcache access
182   *
183   * @return object Memcache
184   */
185  public function get_memcache()
186  {
187    if (!isset($this->memcache)) {
188      // no memcache support in PHP
189      if (!class_exists('Memcache')) {
190        $this->memcache = false;
191        return false;
192      }
193
194      $this->memcache = new Memcache;
195      $this->mc_available = 0;
196
197      // add alll configured hosts to pool
198      $pconnect = $this->config->get('memcache_pconnect', true);
199      foreach ($this->config->get('memcache_hosts', array()) as $host) {
200        list($host, $port) = explode(':', $host);
201        if (!$port) $port = 11211;
202        $this->mc_available += intval($this->memcache->addServer($host, $port, $pconnect, 1, 1, 15, false, array($this, 'memcache_failure')));
203      }
204
205      // test connection and failover (will result in $this->mc_available == 0 on complete failure)
206      $this->memcache->increment('__CONNECTIONTEST__', 1);  // NOP if key doesn't exist
207
208      if (!$this->mc_available)
209        $this->memcache = false;
210    }
211
212    return $this->memcache;
213  }
214
215
216  /**
217   * Callback for memcache failure
218   */
219  public function memcache_failure($host, $port)
220  {
221    static $seen = array();
222
223    // only report once
224    if (!$seen["$host:$port"]++) {
225      $this->mc_available--;
226      self::raise_error(array('code' => 604, 'type' => 'db',
227        'line' => __LINE__, 'file' => __FILE__,
228        'message' => "Memcache failure on host $host:$port"),
229        true, false);
230    }
231  }
232
233
234  /**
235   * Initialize and get cache object
236   *
237   * @param string $name   Cache identifier
238   * @param string $type   Cache type ('db', 'apc' or 'memcache')
239   * @param string $ttl    Expiration time for cache items
240   * @param bool   $packed Enables/disables data serialization
241   *
242   * @return rcube_cache Cache object
243   */
244  public function get_cache($name, $type='db', $ttl=0, $packed=true)
245  {
246    if (!isset($this->caches[$name])) {
247      $this->caches[$name] = new rcube_cache($type, $_SESSION['user_id'], $name, $ttl, $packed);
248    }
249
250    return $this->caches[$name];
251  }
252
253
254  /**
255   * Create SMTP object and connect to server
256   *
257   * @param boolean True if connection should be established
258   */
259  public function smtp_init($connect = false)
260  {
261    $this->smtp = new rcube_smtp();
262
263    if ($connect)
264      $this->smtp->connect();
265  }
266
267
268  /**
269   * Initialize and get storage object
270   *
271   * @return rcube_storage Storage object
272   */
273  public function get_storage()
274  {
275    // already initialized
276    if (!is_object($this->storage)) {
277      $this->storage_init();
278    }
279
280    return $this->storage;
281  }
282
283
284  /**
285   * Initialize storage object
286   */
287  public function storage_init()
288  {
289    // already initialized
290    if (is_object($this->storage)) {
291      return;
292    }
293
294    $driver = $this->config->get('storage_driver', 'imap');
295    $driver_class = "rcube_{$driver}";
296
297    if (!class_exists($driver_class)) {
298      self::raise_error(array(
299        'code' => 700, 'type' => 'php',
300        'file' => __FILE__, 'line' => __LINE__,
301        'message' => "Storage driver class ($driver) not found!"),
302        true, true);
303    }
304
305    // Initialize storage object
306    $this->storage = new $driver_class;
307
308    // for backward compat. (deprecated, will be removed)
309    $this->imap = $this->storage;
310
311    // enable caching of mail data
312    $storage_cache  = $this->config->get("{$driver}_cache");
313    $messages_cache = $this->config->get('messages_cache');
314    // for backward compatybility
315    if ($storage_cache === null && $messages_cache === null && $this->config->get('enable_caching')) {
316        $storage_cache  = 'db';
317        $messages_cache = true;
318    }
319
320    if ($storage_cache)
321        $this->storage->set_caching($storage_cache);
322    if ($messages_cache)
323        $this->storage->set_messages_caching(true);
324
325    // set pagesize from config
326    $pagesize = $this->config->get('mail_pagesize');
327    if (!$pagesize) {
328        $pagesize = $this->config->get('pagesize', 50);
329    }
330    $this->storage->set_pagesize($pagesize);
331
332    // set class options
333    $options = array(
334      'auth_type'   => $this->config->get("{$driver}_auth_type", 'check'),
335      'auth_cid'    => $this->config->get("{$driver}_auth_cid"),
336      'auth_pw'     => $this->config->get("{$driver}_auth_pw"),
337      'debug'       => (bool) $this->config->get("{$driver}_debug"),
338      'force_caps'  => (bool) $this->config->get("{$driver}_force_caps"),
339      'timeout'     => (int) $this->config->get("{$driver}_timeout"),
340      'skip_deleted' => (bool) $this->config->get('skip_deleted'),
341      'driver'      => $driver,
342    );
343
344    if (!empty($_SESSION['storage_host'])) {
345      $options['host']     = $_SESSION['storage_host'];
346      $options['user']     = $_SESSION['username'];
347      $options['port']     = $_SESSION['storage_port'];
348      $options['ssl']      = $_SESSION['storage_ssl'];
349      $options['password'] = $this->decrypt($_SESSION['password']);
350    }
351
352    $options = $this->plugins->exec_hook("storage_init", $options);
353
354    // for backward compat. (deprecated, to be removed)
355    $options = $this->plugins->exec_hook("imap_init", $options);
356
357    $this->storage->set_options($options);
358    $this->set_storage_prop();
359  }
360
361
362  /**
363   * Connect to the mail storage server with stored session data
364   *
365   * @return bool True on success, False on error
366   */
367  public function storage_connect()
368  {
369    $storage = $this->get_storage();
370
371    if ($_SESSION['storage_host'] && !$storage->is_connected()) {
372      $host = $_SESSION['storage_host'];
373      $user = $_SESSION['username'];
374      $port = $_SESSION['storage_port'];
375      $ssl  = $_SESSION['storage_ssl'];
376      $pass = $this->decrypt($_SESSION['password']);
377
378      if (!$storage->connect($host, $user, $pass, $port, $ssl)) {
379        if (is_object($this->output))
380          $this->output->show_message($storage->get_error_code() == -1 ? 'storageerror' : 'sessionerror', 'error');
381      }
382      else {
383        $this->set_storage_prop();
384        return $storage->is_connected();
385      }
386    }
387
388    return false;
389  }
390
391  /**
392   * Set storage parameters.
393   * This must be done AFTER connecting to the server!
394   */
395  protected function set_storage_prop()
396  {
397    $storage = $this->get_storage();
398
399    $storage->set_charset($this->config->get('default_charset', RCMAIL_CHARSET));
400
401    if ($default_folders = $this->config->get('default_folders')) {
402      $storage->set_default_folders($default_folders);
403    }
404    if (isset($_SESSION['mbox'])) {
405      $storage->set_folder($_SESSION['mbox']);
406    }
407    if (isset($_SESSION['page'])) {
408      $storage->set_page($_SESSION['page']);
409    }
410  }
411
412
413    /**
414     * Create session object and start the session.
415     */
416    public function session_init()
417    {
418        // session started (Installer?)
419        if (session_id()) {
420            return;
421        }
422
423        $sess_name   = $this->config->get('session_name');
424        $sess_domain = $this->config->get('session_domain');
425        $lifetime    = $this->config->get('session_lifetime', 0) * 60;
426
427        // set session domain
428        if ($sess_domain) {
429            ini_set('session.cookie_domain', $sess_domain);
430        }
431        // set session garbage collecting time according to session_lifetime
432        if ($lifetime) {
433            ini_set('session.gc_maxlifetime', $lifetime * 2);
434        }
435
436        ini_set('session.cookie_secure', rcube_utils::https_check());
437        ini_set('session.name', $sess_name ? $sess_name : 'roundcube_sessid');
438        ini_set('session.use_cookies', 1);
439        ini_set('session.use_only_cookies', 1);
440        ini_set('session.serialize_handler', 'php');
441
442        // use database for storing session data
443        $this->session = new rcube_session($this->get_dbh(), $this->config);
444
445        $this->session->register_gc_handler(array($this, 'temp_gc'));
446        $this->session->register_gc_handler(array($this, 'cache_gc'));
447
448        // start PHP session (if not in CLI mode)
449        if ($_SERVER['REMOTE_ADDR']) {
450            session_start();
451        }
452    }
453
454
455    /**
456     * Configure session object internals
457     */
458    public function session_configure()
459    {
460        if (!$this->session) {
461            return;
462        }
463
464        $lifetime   = $this->config->get('session_lifetime', 0) * 60;
465        $keep_alive = $this->config->get('keep_alive');
466
467        // set keep-alive/check-recent interval
468        if ($keep_alive) {
469            // be sure that it's less than session lifetime
470            if ($lifetime) {
471                $keep_alive = min($keep_alive, $lifetime - 30);
472            }
473            $keep_alive = max(60, $keep_alive);
474            $this->session->set_keep_alive($keep_alive);
475        }
476
477        $this->session->set_secret($this->config->get('des_key') . $_SERVER['HTTP_USER_AGENT']);
478        $this->session->set_ip_check($this->config->get('ip_check'));
479    }
480
481
482    /**
483     * Garbage collector function for temp files.
484     * Remove temp files older than two days
485     */
486    public function temp_gc()
487    {
488        $tmp = unslashify($this->config->get('temp_dir'));
489        $expire = time() - 172800;  // expire in 48 hours
490
491        if ($tmp && ($dir = opendir($tmp))) {
492            while (($fname = readdir($dir)) !== false) {
493                if ($fname{0} == '.') {
494                    continue;
495                }
496
497                if (filemtime($tmp.'/'.$fname) < $expire) {
498                    @unlink($tmp.'/'.$fname);
499                }
500            }
501
502            closedir($dir);
503        }
504    }
505
506
507    /**
508     * Garbage collector for cache entries.
509     * Set flag to expunge caches on shutdown
510     */
511    public function cache_gc()
512    {
513        // because this gc function is called before storage is initialized,
514        // we just set a flag to expunge storage cache on shutdown.
515        $this->expunge_cache = true;
516    }
517
518
519  /**
520   * Get localized text in the desired language
521   *
522   * @param mixed   $attrib  Named parameters array or label name
523   * @param string  $domain  Label domain (plugin) name
524   *
525   * @return string Localized text
526   */
527  public function gettext($attrib, $domain=null)
528  {
529    // load localization files if not done yet
530    if (empty($this->texts))
531      $this->load_language();
532
533    // extract attributes
534    if (is_string($attrib))
535      $attrib = array('name' => $attrib);
536
537    $name = $attrib['name'] ? $attrib['name'] : '';
538
539    // attrib contain text values: use them from now
540    if (($setval = $attrib[strtolower($_SESSION['language'])]) || ($setval = $attrib['en_us']))
541        $this->texts[$name] = $setval;
542
543    // check for text with domain
544    if ($domain && ($text = $this->texts[$domain.'.'.$name]))
545      ;
546    // text does not exist
547    else if (!($text = $this->texts[$name])) {
548      return "[$name]";
549    }
550
551    // replace vars in text
552    if (is_array($attrib['vars'])) {
553      foreach ($attrib['vars'] as $var_key => $var_value)
554        $text = str_replace($var_key[0]!='$' ? '$'.$var_key : $var_key, $var_value, $text);
555    }
556
557    // format output
558    if (($attrib['uppercase'] && strtolower($attrib['uppercase']=='first')) || $attrib['ucfirst'])
559      return ucfirst($text);
560    else if ($attrib['uppercase'])
561      return mb_strtoupper($text);
562    else if ($attrib['lowercase'])
563      return mb_strtolower($text);
564
565    return strtr($text, array('\n' => "\n"));
566  }
567
568
569  /**
570   * Check if the given text label exists
571   *
572   * @param string  $name       Label name
573   * @param string  $domain     Label domain (plugin) name or '*' for all domains
574   * @param string  $ref_domain Sets domain name if label is found
575   *
576   * @return boolean True if text exists (either in the current language or in en_US)
577   */
578  public function text_exists($name, $domain = null, &$ref_domain = null)
579  {
580    // load localization files if not done yet
581    if (empty($this->texts))
582      $this->load_language();
583
584    if (isset($this->texts[$name])) {
585        $ref_domain = '';
586        return true;
587    }
588
589    // any of loaded domains (plugins)
590    if ($domain == '*') {
591      foreach ($this->plugins->loaded_plugins() as $domain)
592        if (isset($this->texts[$domain.'.'.$name])) {
593          $ref_domain = $domain;
594          return true;
595        }
596    }
597    // specified domain
598    else if ($domain) {
599      $ref_domain = $domain;
600      return isset($this->texts[$domain.'.'.$name]);
601    }
602
603    return false;
604  }
605
606  /**
607   * Load a localization package
608   *
609   * @param string Language ID
610   */
611  public function load_language($lang = null, $add = array())
612  {
613    $lang = $this->language_prop(($lang ? $lang : $_SESSION['language']));
614
615    // load localized texts
616    if (empty($this->texts) || $lang != $_SESSION['language']) {
617      $this->texts = array();
618
619      // handle empty lines after closing PHP tag in localization files
620      ob_start();
621
622      // get english labels (these should be complete)
623      @include(INSTALL_PATH . 'program/localization/en_US/labels.inc');
624      @include(INSTALL_PATH . 'program/localization/en_US/messages.inc');
625
626      if (is_array($labels))
627        $this->texts = $labels;
628      if (is_array($messages))
629        $this->texts = array_merge($this->texts, $messages);
630
631      // include user language files
632      if ($lang != 'en' && is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
633        include_once(INSTALL_PATH . 'program/localization/' . $lang . '/labels.inc');
634        include_once(INSTALL_PATH . 'program/localization/' . $lang . '/messages.inc');
635
636        if (is_array($labels))
637          $this->texts = array_merge($this->texts, $labels);
638        if (is_array($messages))
639          $this->texts = array_merge($this->texts, $messages);
640      }
641
642      ob_end_clean();
643
644      $_SESSION['language'] = $lang;
645    }
646
647    // append additional texts (from plugin)
648    if (is_array($add) && !empty($add))
649      $this->texts += $add;
650  }
651
652
653  /**
654   * Check the given string and return a valid language code
655   *
656   * @param string Language code
657   * @return string Valid language code
658   */
659  protected function language_prop($lang)
660  {
661    static $rcube_languages, $rcube_language_aliases;
662
663    // user HTTP_ACCEPT_LANGUAGE if no language is specified
664    if (empty($lang) || $lang == 'auto') {
665       $accept_langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
666       $lang = str_replace('-', '_', $accept_langs[0]);
667     }
668
669    if (empty($rcube_languages)) {
670      @include(INSTALL_PATH . 'program/localization/index.inc');
671    }
672
673    // check if we have an alias for that language
674    if (!isset($rcube_languages[$lang]) && isset($rcube_language_aliases[$lang])) {
675      $lang = $rcube_language_aliases[$lang];
676    }
677    // try the first two chars
678    else if (!isset($rcube_languages[$lang])) {
679      $short = substr($lang, 0, 2);
680
681      // check if we have an alias for the short language code
682      if (!isset($rcube_languages[$short]) && isset($rcube_language_aliases[$short])) {
683        $lang = $rcube_language_aliases[$short];
684      }
685      // expand 'nn' to 'nn_NN'
686      else if (!isset($rcube_languages[$short])) {
687        $lang = $short.'_'.strtoupper($short);
688      }
689    }
690
691    if (!isset($rcube_languages[$lang]) || !is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
692      $lang = 'en_US';
693    }
694
695    return $lang;
696  }
697
698
699  /**
700   * Read directory program/localization and return a list of available languages
701   *
702   * @return array List of available localizations
703   */
704  public function list_languages()
705  {
706    static $sa_languages = array();
707
708    if (!sizeof($sa_languages)) {
709      @include(INSTALL_PATH . 'program/localization/index.inc');
710
711      if ($dh = @opendir(INSTALL_PATH . 'program/localization')) {
712        while (($name = readdir($dh)) !== false) {
713          if ($name[0] == '.' || !is_dir(INSTALL_PATH . 'program/localization/' . $name))
714            continue;
715
716          if ($label = $rcube_languages[$name])
717            $sa_languages[$name] = $label;
718        }
719        closedir($dh);
720      }
721    }
722
723    return $sa_languages;
724  }
725
726
727  /**
728   * Encrypt using 3DES
729   *
730   * @param string $clear clear text input
731   * @param string $key encryption key to retrieve from the configuration, defaults to 'des_key'
732   * @param boolean $base64 whether or not to base64_encode() the result before returning
733   *
734   * @return string encrypted text
735   */
736  public function encrypt($clear, $key = 'des_key', $base64 = true)
737  {
738    if (!$clear)
739      return '';
740
741    /*-
742     * Add a single canary byte to the end of the clear text, which
743     * will help find out how much of padding will need to be removed
744     * upon decryption; see http://php.net/mcrypt_generic#68082
745     */
746    $clear = pack("a*H2", $clear, "80");
747
748    if (function_exists('mcrypt_module_open') &&
749        ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_CBC, ""))) {
750      $iv = $this->create_iv(mcrypt_enc_get_iv_size($td));
751      mcrypt_generic_init($td, $this->config->get_crypto_key($key), $iv);
752      $cipher = $iv . mcrypt_generic($td, $clear);
753      mcrypt_generic_deinit($td);
754      mcrypt_module_close($td);
755    }
756    else {
757      @include_once 'des.inc';
758
759      if (function_exists('des')) {
760        $des_iv_size = 8;
761        $iv = $this->create_iv($des_iv_size);
762        $cipher = $iv . des($this->config->get_crypto_key($key), $clear, 1, 1, $iv);
763      }
764      else {
765        self::raise_error(array(
766          'code' => 500, 'type' => 'php',
767          'file' => __FILE__, 'line' => __LINE__,
768          'message' => "Could not perform encryption; make sure Mcrypt is installed or lib/des.inc is available"
769        ), true, true);
770      }
771    }
772
773    return $base64 ? base64_encode($cipher) : $cipher;
774  }
775
776  /**
777   * Decrypt 3DES-encrypted string
778   *
779   * @param string $cipher encrypted text
780   * @param string $key encryption key to retrieve from the configuration, defaults to 'des_key'
781   * @param boolean $base64 whether or not input is base64-encoded
782   *
783   * @return string decrypted text
784   */
785  public function decrypt($cipher, $key = 'des_key', $base64 = true)
786  {
787    if (!$cipher)
788      return '';
789
790    $cipher = $base64 ? base64_decode($cipher) : $cipher;
791
792    if (function_exists('mcrypt_module_open') &&
793        ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_CBC, ""))) {
794      $iv_size = mcrypt_enc_get_iv_size($td);
795      $iv = substr($cipher, 0, $iv_size);
796
797      // session corruption? (#1485970)
798      if (strlen($iv) < $iv_size)
799        return '';
800
801      $cipher = substr($cipher, $iv_size);
802      mcrypt_generic_init($td, $this->config->get_crypto_key($key), $iv);
803      $clear = mdecrypt_generic($td, $cipher);
804      mcrypt_generic_deinit($td);
805      mcrypt_module_close($td);
806    }
807    else {
808      @include_once 'des.inc';
809
810      if (function_exists('des')) {
811        $des_iv_size = 8;
812        $iv = substr($cipher, 0, $des_iv_size);
813        $cipher = substr($cipher, $des_iv_size);
814        $clear = des($this->config->get_crypto_key($key), $cipher, 0, 1, $iv);
815      }
816      else {
817        self::raise_error(array(
818          'code' => 500, 'type' => 'php',
819          'file' => __FILE__, 'line' => __LINE__,
820          'message' => "Could not perform decryption; make sure Mcrypt is installed or lib/des.inc is available"
821        ), true, true);
822      }
823    }
824
825    /*-
826     * Trim PHP's padding and the canary byte; see note in
827     * rcube::encrypt() and http://php.net/mcrypt_generic#68082
828     */
829    $clear = substr(rtrim($clear, "\0"), 0, -1);
830
831    return $clear;
832  }
833
834  /**
835   * Generates encryption initialization vector (IV)
836   *
837   * @param int Vector size
838   * @return string Vector string
839   */
840  private function create_iv($size)
841  {
842    // mcrypt_create_iv() can be slow when system lacks entrophy
843    // we'll generate IV vector manually
844    $iv = '';
845    for ($i = 0; $i < $size; $i++)
846        $iv .= chr(mt_rand(0, 255));
847    return $iv;
848  }
849
850
851  /**
852   * Build a valid URL to this instance of Roundcube
853   *
854   * @param mixed Either a string with the action or url parameters as key-value pairs
855   * @return string Valid application URL
856   */
857  public function url($p)
858  {
859      // STUB: should be overloaded by the application
860      return '';
861  }
862
863
864  /**
865   * Function to be executed in script shutdown
866   * Registered with register_shutdown_function()
867   */
868  public function shutdown()
869  {
870    foreach ($this->shutdown_functions as $function)
871      call_user_func($function);
872
873    if (is_object($this->smtp))
874      $this->smtp->disconnect();
875
876    foreach ($this->caches as $cache) {
877        if (is_object($cache))
878            $cache->close();
879    }
880
881    if (is_object($this->storage)) {
882      if ($this->expunge_cache)
883        $this->storage->expunge_cache();
884      $this->storage->close();
885    }
886  }
887
888
889  /**
890   * Registers shutdown function to be executed on shutdown.
891   * The functions will be executed before destroying any
892   * objects like smtp, imap, session, etc.
893   *
894   * @param callback Function callback
895   */
896  public function add_shutdown_function($function)
897  {
898    $this->shutdown_functions[] = $function;
899  }
900
901
902  /**
903   * Construct shell command, execute it and return output as string.
904   * Keywords {keyword} are replaced with arguments
905   *
906   * @param $cmd Format string with {keywords} to be replaced
907   * @param $values (zero, one or more arrays can be passed)
908   * @return output of command. shell errors not detectable
909   */
910  public static function exec(/* $cmd, $values1 = array(), ... */)
911  {
912    $args = func_get_args();
913    $cmd = array_shift($args);
914    $values = $replacements = array();
915
916    // merge values into one array
917    foreach ($args as $arg)
918      $values += (array)$arg;
919
920    preg_match_all('/({(-?)([a-z]\w*)})/', $cmd, $matches, PREG_SET_ORDER);
921    foreach ($matches as $tags) {
922      list(, $tag, $option, $key) = $tags;
923      $parts = array();
924
925      if ($option) {
926        foreach ((array)$values["-$key"] as $key => $value) {
927          if ($value === true || $value === false || $value === null)
928            $parts[] = $value ? $key : "";
929          else foreach ((array)$value as $val)
930            $parts[] = "$key " . escapeshellarg($val);
931        }
932      }
933      else {
934        foreach ((array)$values[$key] as $value)
935          $parts[] = escapeshellarg($value);
936      }
937
938      $replacements[$tag] = join(" ", $parts);
939    }
940
941    // use strtr behaviour of going through source string once
942    $cmd = strtr($cmd, $replacements);
943
944    return (string)shell_exec($cmd);
945  }
946
947
948    /**
949     * Print or write debug messages
950     *
951     * @param mixed Debug message or data
952     */
953    public static function console()
954    {
955        $args = func_get_args();
956
957        if (class_exists('rcube', false)) {
958            $rcube = self::get_instance();
959            $plugin = $rcube->plugins->exec_hook('console', array('args' => $args));
960            if ($plugin['abort']) {
961                return;
962            }
963           $args = $plugin['args'];
964        }
965
966        $msg = array();
967        foreach ($args as $arg) {
968            $msg[] = !is_string($arg) ? var_export($arg, true) : $arg;
969        }
970
971        self::write_log('console', join(";\n", $msg));
972    }
973
974
975    /**
976     * Append a line to a logfile in the logs directory.
977     * Date will be added automatically to the line.
978     *
979     * @param $name name of log file
980     * @param line Line to append
981     */
982    public static function write_log($name, $line)
983    {
984        if (!is_string($line)) {
985            $line = var_export($line, true);
986        }
987
988        $date_format = self::$instance ? self::$instance->config->get('log_date_format') : null;
989        $log_driver  = self::$instance ? self::$instance->config->get('log_driver') : null;
990
991        if (empty($date_format)) {
992            $date_format = 'd-M-Y H:i:s O';
993        }
994
995        $date = date($date_format);
996
997        // trigger logging hook
998        if (is_object(self::$instance) && is_object(self::$instance->plugins)) {
999            $log  = self::$instance->plugins->exec_hook('write_log', array('name' => $name, 'date' => $date, 'line' => $line));
1000            $name = $log['name'];
1001            $line = $log['line'];
1002            $date = $log['date'];
1003            if ($log['abort'])
1004                return true;
1005        }
1006
1007        if ($log_driver == 'syslog') {
1008            $prio = $name == 'errors' ? LOG_ERR : LOG_INFO;
1009            syslog($prio, $line);
1010            return true;
1011        }
1012
1013        // log_driver == 'file' is assumed here
1014
1015        $line = sprintf("[%s]: %s\n", $date, $line);
1016        $log_dir  = self::$instance ? self::$instance->config->get('log_dir') : null;
1017
1018        if (empty($log_dir)) {
1019            $log_dir = INSTALL_PATH . 'logs';
1020        }
1021
1022        // try to open specific log file for writing
1023        $logfile = $log_dir.'/'.$name;
1024
1025        if ($fp = @fopen($logfile, 'a')) {
1026            fwrite($fp, $line);
1027            fflush($fp);
1028            fclose($fp);
1029            return true;
1030        }
1031
1032        trigger_error("Error writing to log file $logfile; Please check permissions", E_USER_WARNING);
1033        return false;
1034    }
1035
1036
1037    /**
1038     * Throw system error (and show error page).
1039     *
1040     * @param array Named parameters
1041     *      - code:    Error code (required)
1042     *      - type:    Error type [php|db|imap|javascript] (required)
1043     *      - message: Error message
1044     *      - file:    File where error occured
1045     *      - line:    Line where error occured
1046     * @param boolean True to log the error
1047     * @param boolean Terminate script execution
1048     */
1049    public static function raise_error($arg = array(), $log = false, $terminate = false)
1050    {
1051        // installer
1052        if (class_exists('rcube_install', false)) {
1053            $rci = rcube_install::get_instance();
1054            $rci->raise_error($arg);
1055            return;
1056        }
1057
1058        if ($log && $arg['type'] && $arg['message']) {
1059            self::log_bug($arg);
1060        }
1061
1062        // display error page and terminate script
1063        if ($terminate && is_object(self::$instance->output)) {
1064            self::$instance->output->raise_error($arg['code'], $arg['message']);
1065        }
1066    }
1067
1068
1069    /**
1070     * Report error according to configured debug_level
1071     *
1072     * @param array Named parameters
1073     * @see self::raise_error()
1074     */
1075    public static function log_bug($arg_arr)
1076    {
1077        $program = strtoupper($arg_arr['type']);
1078        $level   = self::get_instance()->config->get('debug_level');
1079
1080        // disable errors for ajax requests, write to log instead (#1487831)
1081        if (($level & 4) && !empty($_REQUEST['_remote'])) {
1082            $level = ($level ^ 4) | 1;
1083        }
1084
1085        // write error to local log file
1086        if ($level & 1) {
1087            if ($_SERVER['REQUEST_METHOD'] == 'POST') {
1088                $post_query = '?_task='.urlencode($_POST['_task']).'&_action='.urlencode($_POST['_action']);
1089            }
1090            else {
1091                $post_query = '';
1092            }
1093
1094            $log_entry = sprintf("%s Error: %s%s (%s %s)",
1095                $program,
1096                $arg_arr['message'],
1097                $arg_arr['file'] ? sprintf(' in %s on line %d', $arg_arr['file'], $arg_arr['line']) : '',
1098                $_SERVER['REQUEST_METHOD'],
1099                $_SERVER['REQUEST_URI'] . $post_query);
1100
1101            if (!self::write_log('errors', $log_entry)) {
1102                // send error to PHPs error handler if write_log didn't succeed
1103                trigger_error($arg_arr['message']);
1104            }
1105        }
1106
1107        // report the bug to the global bug reporting system
1108        if ($level & 2) {
1109            // TODO: Send error via HTTP
1110        }
1111
1112        // show error if debug_mode is on
1113        if ($level & 4) {
1114            print "<b>$program Error";
1115
1116            if (!empty($arg_arr['file']) && !empty($arg_arr['line'])) {
1117                print " in $arg_arr[file] ($arg_arr[line])";
1118            }
1119
1120            print ':</b>&nbsp;';
1121            print nl2br($arg_arr['message']);
1122            print '<br />';
1123            flush();
1124        }
1125    }
1126
1127
1128    /**
1129     * Returns current time (with microseconds).
1130     *
1131     * @return float Current time in seconds since the Unix
1132     */
1133    public static function timer()
1134    {
1135        return microtime(true);
1136    }
1137
1138
1139    /**
1140     * Logs time difference according to provided timer
1141     *
1142     * @param float  $timer  Timer (self::timer() result)
1143     * @param string $label  Log line prefix
1144     * @param string $dest   Log file name
1145     *
1146     * @see self::timer()
1147     */
1148    public static function print_timer($timer, $label = 'Timer', $dest = 'console')
1149    {
1150        static $print_count = 0;
1151
1152        $print_count++;
1153        $now  = self::timer();
1154        $diff = $now - $timer;
1155
1156        if (empty($label)) {
1157            $label = 'Timer '.$print_count;
1158        }
1159
1160        self::write_log($dest, sprintf("%s: %0.4f sec", $label, $diff));
1161    }
1162
1163
1164    /**
1165     * Getter for logged user ID.
1166     *
1167     * @return mixed User identifier
1168     */
1169    public function get_user_id()
1170    {
1171        if (is_object($this->user)) {
1172            return $this->user->ID;
1173        }
1174
1175        return null;
1176    }
1177
1178
1179    /**
1180     * Getter for logged user name.
1181     *
1182     * @return string User name
1183     */
1184    public function get_user_name()
1185    {
1186        if (is_object($this->user)) {
1187            return $this->user->get_username();
1188        }
1189
1190        return null;
1191    }
1192}
1193
1194
1195/**
1196 * Lightweight plugin API class serving as a dummy if plugins are not enabled
1197 *
1198 * @package Core
1199 */
1200class rcube_dummy_plugin_api
1201{
1202    /**
1203     * Triggers a plugin hook.
1204     * @see rcube_plugin_api::exec_hook()
1205     */
1206    public function exec_hook($hook, $args = array())
1207    {
1208        return $args;
1209    }
1210}
Note: See TracBrowser for help on using the repository browser.