source: subversion/trunk/roundcubemail/program/include/rcube.php @ 6092

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