source: github/program/include/rcube.php @ 76e499e

HEADdev-browser-capabilitiespdo
Last change on this file since 76e499e was 76e499e, checked in by Thomas Bruederli <thomas@…>, 13 months ago

Also accept PHP exceptions as argument to rcube::raise_error()

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