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