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