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