source: github/program/include/rcube.php @ a2f896b

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