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