source: github/program/include/rcube.php @ 0d94fd4

pdo
Last change on this file since 0d94fd4 was 0d94fd4, checked in by Aleksander Machniak <alec@…>, 11 months ago

New database layer based on PHP PDO

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