Aleksander Machniak
2015-11-06 48ab1add3548beecedb60e6355e4c4dbfb1d6bc1
commit | author | age
0c2596 1 <?php
A 2
3 /*
4  +-----------------------------------------------------------------------+
5  | This file is part of the Roundcube Webmail client                     |
6  | Copyright (C) 2008-2012, The Roundcube Dev Team                       |
7  | Copyright (C) 2011-2012, Kolab Systems AG                             |
8  |                                                                       |
9  | Licensed under the GNU General Public License version 3 or            |
10  | any later version with exceptions for skins & plugins.                |
11  | See the README file for a full license statement.                     |
12  |                                                                       |
13  | PURPOSE:                                                              |
14  |   Framework base class providing core functions and holding           |
15  |   instances of all 'global' objects like db- and storage-connections  |
16  +-----------------------------------------------------------------------+
17  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
18  +-----------------------------------------------------------------------+
19 */
20
21
22 /**
23  * Base class of the Roundcube Framework
24  * implemented as singleton
25  *
315418 26  * @package    Framework
AM 27  * @subpackage Core
0c2596 28  */
A 29 class rcube
30 {
315418 31     const INIT_WITH_DB = 1;
AM 32     const INIT_WITH_PLUGINS = 2;
0c2596 33
315418 34     /**
AM 35      * Singleton instace of rcube
36      *
996af3 37      * @var rcube
315418 38      */
AM 39     static protected $instance;
0c2596 40
315418 41     /**
AM 42      * Stores instance of rcube_config.
43      *
44      * @var rcube_config
45      */
46     public $config;
0c2596 47
315418 48     /**
AM 49      * Instace of database class.
50      *
51      * @var rcube_db
52      */
53     public $db;
0c2596 54
315418 55     /**
AM 56      * Instace of Memcache class.
57      *
58      * @var Memcache
59      */
60     public $memcache;
0c2596 61
315418 62    /**
AM 63      * Instace of rcube_session class.
64      *
65      * @var rcube_session
66      */
67     public $session;
0c2596 68
315418 69     /**
AM 70      * Instance of rcube_smtp class.
71      *
72      * @var rcube_smtp
73      */
74     public $smtp;
0c2596 75
315418 76     /**
AM 77      * Instance of rcube_storage class.
78      *
79      * @var rcube_storage
80      */
81     public $storage;
0c2596 82
315418 83     /**
AM 84      * Instance of rcube_output class.
85      *
86      * @var rcube_output
87      */
88     public $output;
0c2596 89
315418 90     /**
AM 91      * Instance of rcube_plugin_api.
92      *
93      * @var rcube_plugin_api
94      */
95     public $plugins;
0c2596 96
A 97
315418 98     /* private/protected vars */
AM 99     protected $texts;
100     protected $caches = array();
101     protected $shutdown_functions = array();
0c2596 102
A 103
315418 104     /**
AM 105      * This implements the 'singleton' design pattern
106      *
107      * @param integer Options to initialize with this instance. See rcube::INIT_WITH_* constants
deb2b8 108      * @param string Environment name to run (e.g. live, dev, test)
315418 109      *
AM 110      * @return rcube The one and only instance
111      */
deb2b8 112     static function get_instance($mode = 0, $env = '')
315418 113     {
AM 114         if (!self::$instance) {
deb2b8 115             self::$instance = new rcube($env);
315418 116             self::$instance->init($mode);
71ee56 117         }
AM 118
315418 119         return self::$instance;
0c2596 120     }
A 121
122
315418 123     /**
AM 124      * Private constructor
125      */
deb2b8 126     protected function __construct($env = '')
315418 127     {
AM 128         // load configuration
deb2b8 129         $this->config  = new rcube_config($env);
315418 130         $this->plugins = new rcube_dummy_plugin_api;
0c2596 131
315418 132         register_shutdown_function(array($this, 'shutdown'));
0c2596 133     }
A 134
135
315418 136     /**
AM 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         }
0c2596 147
315418 148         // connect to database
AM 149         if ($mode & self::INIT_WITH_DB) {
150             $this->get_dbh();
151         }
0c2596 152
315418 153         // create plugin API and load plugins
AM 154         if ($mode & self::INIT_WITH_PLUGINS) {
155             $this->plugins = rcube_plugin_api::get_instance();
156         }
0c2596 157     }
A 158
159
315418 160     /**
AM 161      * Get the current database connection
162      *
163      * @return rcube_db Database object
164      */
165     public function get_dbh()
166     {
167         if (!$this->db) {
168             $config_all = $this->config->all();
169             $this->db = rcube_db::factory($config_all['db_dsnw'], $config_all['db_dsnr'], $config_all['db_persistent']);
170             $this->db->set_debug((bool)$config_all['sql_debug']);
171         }
0c2596 172
315418 173         return $this->db;
0c2596 174     }
A 175
176
315418 177     /**
AM 178      * Get global handle for memcache access
179      *
180      * @return object Memcache
181      */
182     public function get_memcache()
183     {
184         if (!isset($this->memcache)) {
185             // no memcache support in PHP
186             if (!class_exists('Memcache')) {
187                 $this->memcache = false;
188                 return false;
189             }
190
191             $this->memcache     = new Memcache;
192             $this->mc_available = 0;
193
194             // add all configured hosts to pool
195             $pconnect = $this->config->get('memcache_pconnect', true);
196             foreach ($this->config->get('memcache_hosts', array()) as $host) {
197                 if (substr($host, 0, 7) != 'unix://') {
198                     list($host, $port) = explode(':', $host);
199                     if (!$port) $port = 11211;
200                 }
201                 else {
202                     $port = 0;
203                 }
204
205                 $this->mc_available += intval($this->memcache->addServer(
206                     $host, $port, $pconnect, 1, 1, 15, false, array($this, 'memcache_failure')));
207             }
208
209             // test connection and failover (will result in $this->mc_available == 0 on complete failure)
210             $this->memcache->increment('__CONNECTIONTEST__', 1);  // NOP if key doesn't exist
211
212             if (!$this->mc_available) {
213                 $this->memcache = false;
214             }
215         }
216
217         return $this->memcache;
0c2596 218     }
A 219
220
315418 221     /**
AM 222      * Callback for memcache failure
223      */
224     public function memcache_failure($host, $port)
225     {
226         static $seen = array();
0c2596 227
315418 228         // only report once
AM 229         if (!$seen["$host:$port"]++) {
230             $this->mc_available--;
231             self::raise_error(array(
232                 'code' => 604, 'type' => 'db',
233                 'line' => __LINE__, 'file' => __FILE__,
234                 'message' => "Memcache failure on host $host:$port"),
235                 true, false);
236         }
0c2596 237     }
A 238
239
315418 240     /**
AM 241      * Initialize and get cache object
242      *
243      * @param string $name   Cache identifier
244      * @param string $type   Cache type ('db', 'apc' or 'memcache')
245      * @param string $ttl    Expiration time for cache items
246      * @param bool   $packed Enables/disables data serialization
247      *
248      * @return rcube_cache Cache object
249      */
250     public function get_cache($name, $type='db', $ttl=0, $packed=true)
251     {
252         if (!isset($this->caches[$name]) && ($userid = $this->get_user_id())) {
253             $this->caches[$name] = new rcube_cache($type, $userid, $name, $ttl, $packed);
254         }
0c2596 255
315418 256         return $this->caches[$name];
0c2596 257     }
A 258
259
315418 260     /**
50abd5 261      * Initialize and get shared cache object
AM 262      *
263      * @param string $name   Cache identifier
264      * @param bool   $packed Enables/disables data serialization
265      *
266      * @return rcube_cache_shared Cache object
267      */
268     public function get_cache_shared($name, $packed=true)
269     {
270         $shared_name = "shared_$name";
271
22a41b 272         if (!array_key_exists($shared_name, $this->caches)) {
50abd5 273             $opt  = strtolower($name) . '_cache';
AM 274             $type = $this->config->get($opt);
275             $ttl  = $this->config->get($opt . '_ttl');
276
277             if (!$type) {
22a41b 278                 // cache is disabled
AM 279                 return $this->caches[$shared_name] = null;
50abd5 280             }
22a41b 281
50abd5 282             if ($ttl === null) {
22a41b 283                 $ttl = $this->config->get('shared_cache_ttl', '10d');
50abd5 284             }
AM 285
286             $this->caches[$shared_name] = new rcube_cache_shared($type, $name, $ttl, $packed);
287         }
288
289         return $this->caches[$shared_name];
290     }
291
292
293     /**
315418 294      * Create SMTP object and connect to server
AM 295      *
296      * @param boolean True if connection should be established
297      */
298     public function smtp_init($connect = false)
299     {
300         $this->smtp = new rcube_smtp();
0c2596 301
315418 302         if ($connect) {
AM 303             $this->smtp->connect();
304         }
0c2596 305     }
315418 306
AM 307
308     /**
309      * Initialize and get storage object
310      *
311      * @return rcube_storage Storage object
312      */
313     public function get_storage()
314     {
315         // already initialized
316         if (!is_object($this->storage)) {
317             $this->storage_init();
318         }
319
320         return $this->storage;
0c2596 321     }
315418 322
AM 323
324     /**
325      * Initialize storage object
326      */
327     public function storage_init()
328     {
329         // already initialized
330         if (is_object($this->storage)) {
331             return;
332         }
333
334         $driver       = $this->config->get('storage_driver', 'imap');
335         $driver_class = "rcube_{$driver}";
336
337         if (!class_exists($driver_class)) {
338             self::raise_error(array(
339                 'code' => 700, 'type' => 'php',
340                 'file' => __FILE__, 'line' => __LINE__,
341                 'message' => "Storage driver class ($driver) not found!"),
342                 true, true);
343         }
344
345         // Initialize storage object
346         $this->storage = new $driver_class;
347
348         // for backward compat. (deprecated, will be removed)
349         $this->imap = $this->storage;
350
351         // enable caching of mail data
352         $storage_cache  = $this->config->get("{$driver}_cache");
353         $messages_cache = $this->config->get('messages_cache');
354         // for backward compatybility
355         if ($storage_cache === null && $messages_cache === null && $this->config->get('enable_caching')) {
356             $storage_cache  = 'db';
357             $messages_cache = true;
358         }
359
360         if ($storage_cache) {
361             $this->storage->set_caching($storage_cache);
362         }
363         if ($messages_cache) {
364             $this->storage->set_messages_caching(true);
365         }
366
367         // set pagesize from config
368         $pagesize = $this->config->get('mail_pagesize');
369         if (!$pagesize) {
370             $pagesize = $this->config->get('pagesize', 50);
371         }
372         $this->storage->set_pagesize($pagesize);
373
374         // set class options
375         $options = array(
3b55da 376             'auth_type'      => $this->config->get("{$driver}_auth_type", 'check'),
AM 377             'auth_cid'       => $this->config->get("{$driver}_auth_cid"),
378             'auth_pw'        => $this->config->get("{$driver}_auth_pw"),
379             'debug'          => (bool) $this->config->get("{$driver}_debug"),
380             'force_caps'     => (bool) $this->config->get("{$driver}_force_caps"),
381             'disabled_caps'  => $this->config->get("{$driver}_disabled_caps"),
382             'socket_options' => $this->config->get("{$driver}_conn_options"),
383             'timeout'        => (int) $this->config->get("{$driver}_timeout"),
384             'skip_deleted'   => (bool) $this->config->get('skip_deleted'),
385             'driver'         => $driver,
315418 386         );
AM 387
388         if (!empty($_SESSION['storage_host'])) {
389             $options['host']     = $_SESSION['storage_host'];
390             $options['user']     = $_SESSION['username'];
391             $options['port']     = $_SESSION['storage_port'];
392             $options['ssl']      = $_SESSION['storage_ssl'];
393             $options['password'] = $this->decrypt($_SESSION['password']);
394             $_SESSION[$driver.'_host'] = $_SESSION['storage_host'];
395         }
396
397         $options = $this->plugins->exec_hook("storage_init", $options);
398
399         // for backward compat. (deprecated, to be removed)
400         $options = $this->plugins->exec_hook("imap_init", $options);
401
402         $this->storage->set_options($options);
403         $this->set_storage_prop();
0c2596 404     }
315418 405
AM 406
407     /**
408      * Set storage parameters.
409      * This must be done AFTER connecting to the server!
410      */
411     protected function set_storage_prop()
412     {
413         $storage = $this->get_storage();
414
a92beb 415         $storage->set_charset($this->config->get('default_charset', RCUBE_CHARSET));
315418 416
AM 417         if ($default_folders = $this->config->get('default_folders')) {
418             $storage->set_default_folders($default_folders);
419         }
420         if (isset($_SESSION['mbox'])) {
421             $storage->set_folder($_SESSION['mbox']);
422         }
423         if (isset($_SESSION['page'])) {
424             $storage->set_page($_SESSION['page']);
425         }
426     }
0c2596 427
A 428
963a10 429     /**
A 430      * Create session object and start the session.
431      */
432     public function session_init()
433     {
434         // session started (Installer?)
435         if (session_id()) {
436             return;
437         }
438
439         $sess_name   = $this->config->get('session_name');
440         $sess_domain = $this->config->get('session_domain');
ae7027 441         $sess_path   = $this->config->get('session_path');
963a10 442         $lifetime    = $this->config->get('session_lifetime', 0) * 60;
8e4b49 443         $is_secure   = $this->config->get('use_https') || rcube_utils::https_check();
963a10 444
A 445         // set session domain
446         if ($sess_domain) {
447             ini_set('session.cookie_domain', $sess_domain);
448         }
ae7027 449         // set session path
AM 450         if ($sess_path) {
451             ini_set('session.cookie_path', $sess_path);
452         }
963a10 453         // set session garbage collecting time according to session_lifetime
A 454         if ($lifetime) {
455             ini_set('session.gc_maxlifetime', $lifetime * 2);
456         }
457
8e4b49 458         ini_set('session.cookie_secure', $is_secure);
963a10 459         ini_set('session.name', $sess_name ? $sess_name : 'roundcube_sessid');
A 460         ini_set('session.use_cookies', 1);
461         ini_set('session.use_only_cookies', 1);
0afe27 462         ini_set('session.cookie_httponly', 1);
963a10 463
A 464         // use database for storing session data
465         $this->session = new rcube_session($this->get_dbh(), $this->config);
466
48ab1a 467         $path = $_SERVER['SCRIPT_NAME'];
AM 468         if (strpos($path, '://')) {
469             $path = parse_url($path, PHP_URL_PATH); // #1490582
470         }
471
3dbe4f 472         $this->session->register_gc_handler(array($this, 'gc'));
48ab1a 473         $this->session->set_secret($this->config->get('des_key') . dirname($path));
c442f8 474         $this->session->set_ip_check($this->config->get('ip_check'));
AM 475
8d2963 476         if ($this->config->get('session_auth_name')) {
TB 477             $this->session->set_cookiename($this->config->get('session_auth_name'));
478         }
479
963a10 480         // start PHP session (if not in CLI mode)
A 481         if ($_SERVER['REMOTE_ADDR']) {
42de33 482             $this->session->start();
963a10 483         }
A 484     }
485
486
487     /**
ee73a7 488      * Garbage collector - cache/temp cleaner
AM 489      */
490     public function gc()
491     {
60b6d7 492         rcube_cache::gc();
AM 493         rcube_cache_shared::gc();
494         $this->get_storage()->cache_gc();
ee73a7 495
AM 496         $this->gc_temp();
497     }
498
499
500     /**
963a10 501      * Garbage collector function for temp files.
A 502      * Remove temp files older than two days
503      */
ee73a7 504     public function gc_temp()
963a10 505     {
A 506         $tmp = unslashify($this->config->get('temp_dir'));
de8687 507
DC 508         // expire in 48 hours by default
509         $temp_dir_ttl = $this->config->get('temp_dir_ttl', '48h');
510         $temp_dir_ttl = get_offset_sec($temp_dir_ttl);
511         if ($temp_dir_ttl < 6*3600)
512             $temp_dir_ttl = 6*3600;   // 6 hours sensible lower bound.
513
514         $expire = time() - $temp_dir_ttl;
963a10 515
A 516         if ($tmp && ($dir = opendir($tmp))) {
517             while (($fname = readdir($dir)) !== false) {
311d87 518                 if ($fname[0] == '.') {
963a10 519                     continue;
A 520                 }
521
311d87 522                 if (@filemtime($tmp.'/'.$fname) < $expire) {
963a10 523                     @unlink($tmp.'/'.$fname);
A 524                 }
525             }
526
527             closedir($dir);
528         }
ee73a7 529     }
AM 530
531
532     /**
533      * Runs garbage collector with probability based on
534      * session settings. This is intended for environments
535      * without a session.
536      */
537     public function gc_run()
538     {
539         $probability = (int) ini_get('session.gc_probability');
540         $divisor     = (int) ini_get('session.gc_divisor');
541
542         if ($divisor > 0 && $probability > 0) {
543             $random = mt_rand(1, $divisor);
544             if ($random <= $probability) {
545                 $this->gc();
546             }
547         }
963a10 548     }
A 549
550
315418 551     /**
AM 552      * Get localized text in the desired language
553      *
554      * @param mixed   $attrib  Named parameters array or label name
555      * @param string  $domain  Label domain (plugin) name
556      *
557      * @return string Localized text
0c2596 558      */
315418 559     public function gettext($attrib, $domain=null)
AM 560     {
561         // load localization files if not done yet
562         if (empty($this->texts)) {
563             $this->load_language();
564         }
0c2596 565
315418 566         // extract attributes
AM 567         if (is_string($attrib)) {
568             $attrib = array('name' => $attrib);
569         }
0c2596 570
315418 571         $name = $attrib['name'] ? $attrib['name'] : '';
AM 572
573         // attrib contain text values: use them from now
574         if (($setval = $attrib[strtolower($_SESSION['language'])]) || ($setval = $attrib['en_us'])) {
575             $this->texts[$name] = $setval;
576         }
577
578         // check for text with domain
579         if ($domain && ($text = $this->texts[$domain.'.'.$name])) {
580         }
581         // text does not exist
582         else if (!($text = $this->texts[$name])) {
583             return "[$name]";
584         }
585
586         // replace vars in text
587         if (is_array($attrib['vars'])) {
588             foreach ($attrib['vars'] as $var_key => $var_value) {
589                 $text = str_replace($var_key[0]!='$' ? '$'.$var_key : $var_key, $var_value, $text);
590             }
591         }
592
593         // format output
594         if (($attrib['uppercase'] && strtolower($attrib['uppercase'] == 'first')) || $attrib['ucfirst']) {
595             return ucfirst($text);
596         }
597         else if ($attrib['uppercase']) {
598             return mb_strtoupper($text);
599         }
600         else if ($attrib['lowercase']) {
601             return mb_strtolower($text);
602         }
603
604         return strtr($text, array('\n' => "\n"));
0c2596 605     }
A 606
607
315418 608     /**
AM 609      * Check if the given text label exists
610      *
611      * @param string  $name       Label name
612      * @param string  $domain     Label domain (plugin) name or '*' for all domains
613      * @param string  $ref_domain Sets domain name if label is found
614      *
615      * @return boolean True if text exists (either in the current language or in en_US)
616      */
617     public function text_exists($name, $domain = null, &$ref_domain = null)
618     {
619         // load localization files if not done yet
620         if (empty($this->texts)) {
621             $this->load_language();
622         }
0c2596 623
315418 624         if (isset($this->texts[$name])) {
AM 625             $ref_domain = '';
626             return true;
627         }
0c2596 628
315418 629         // any of loaded domains (plugins)
AM 630         if ($domain == '*') {
631             foreach ($this->plugins->loaded_plugins() as $domain) {
632                 if (isset($this->texts[$domain.'.'.$name])) {
633                     $ref_domain = $domain;
634                     return true;
635                 }
636             }
637         }
638         // specified domain
639         else if ($domain) {
640             $ref_domain = $domain;
641             return isset($this->texts[$domain.'.'.$name]);
642         }
0c2596 643
315418 644         return false;
AM 645     }
646
647
648     /**
649      * Load a localization package
650      *
75a5c3 651      * @param string $lang  Language ID
AM 652      * @param array  $add   Additional text labels/messages
653      * @param array  $merge Additional text labels/messages to merge
315418 654      */
75a5c3 655     public function load_language($lang = null, $add = array(), $merge = array())
315418 656     {
AM 657         $lang = $this->language_prop(($lang ? $lang : $_SESSION['language']));
658
659         // load localized texts
660         if (empty($this->texts) || $lang != $_SESSION['language']) {
661             $this->texts = array();
662
663             // handle empty lines after closing PHP tag in localization files
664             ob_start();
665
666             // get english labels (these should be complete)
9be2f4 667             @include(RCUBE_LOCALIZATION_DIR . 'en_US/labels.inc');
TB 668             @include(RCUBE_LOCALIZATION_DIR . 'en_US/messages.inc');
315418 669
AM 670             if (is_array($labels))
671                 $this->texts = $labels;
672             if (is_array($messages))
673                 $this->texts = array_merge($this->texts, $messages);
674
675             // include user language files
9be2f4 676             if ($lang != 'en' && $lang != 'en_US' && is_dir(RCUBE_LOCALIZATION_DIR . $lang)) {
TB 677                 include_once(RCUBE_LOCALIZATION_DIR . $lang . '/labels.inc');
678                 include_once(RCUBE_LOCALIZATION_DIR . $lang . '/messages.inc');
315418 679
AM 680                 if (is_array($labels))
681                     $this->texts = array_merge($this->texts, $labels);
682                 if (is_array($messages))
683                     $this->texts = array_merge($this->texts, $messages);
684             }
685
686             ob_end_clean();
687
688             $_SESSION['language'] = $lang;
689         }
690
691         // append additional texts (from plugin)
692         if (is_array($add) && !empty($add)) {
693             $this->texts += $add;
694         }
75a5c3 695
AM 696         // merge additional texts (from plugin)
697         if (is_array($merge) && !empty($merge)) {
698             $this->texts = array_merge($this->texts, $merge);
699         }
315418 700     }
AM 701
702
703     /**
704      * Check the given string and return a valid language code
705      *
706      * @param string Language code
707      *
708      * @return string Valid language code
709      */
710     protected function language_prop($lang)
711     {
712         static $rcube_languages, $rcube_language_aliases;
713
714         // user HTTP_ACCEPT_LANGUAGE if no language is specified
715         if (empty($lang) || $lang == 'auto') {
716             $accept_langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
2c6a23 717             $lang         = $accept_langs[0];
AM 718
719             if (preg_match('/^([a-z]+)[_-]([a-z]+)$/i', $lang, $m)) {
720                 $lang = $m[1] . '_' . strtoupper($m[2]);
721             }
315418 722         }
AM 723
724         if (empty($rcube_languages)) {
9be2f4 725             @include(RCUBE_LOCALIZATION_DIR . 'index.inc');
315418 726         }
AM 727
728         // check if we have an alias for that language
729         if (!isset($rcube_languages[$lang]) && isset($rcube_language_aliases[$lang])) {
730             $lang = $rcube_language_aliases[$lang];
731         }
732         // try the first two chars
733         else if (!isset($rcube_languages[$lang])) {
734             $short = substr($lang, 0, 2);
735
736             // check if we have an alias for the short language code
737             if (!isset($rcube_languages[$short]) && isset($rcube_language_aliases[$short])) {
738                 $lang = $rcube_language_aliases[$short];
739             }
740             // expand 'nn' to 'nn_NN'
741             else if (!isset($rcube_languages[$short])) {
742                 $lang = $short.'_'.strtoupper($short);
743             }
744         }
745
9be2f4 746         if (!isset($rcube_languages[$lang]) || !is_dir(RCUBE_LOCALIZATION_DIR . $lang)) {
315418 747             $lang = 'en_US';
AM 748         }
749
750         return $lang;
751     }
752
753
754     /**
755      * Read directory program/localization and return a list of available languages
756      *
757      * @return array List of available localizations
758      */
759     public function list_languages()
760     {
761         static $sa_languages = array();
762
763         if (!sizeof($sa_languages)) {
9be2f4 764             @include(RCUBE_LOCALIZATION_DIR . 'index.inc');
315418 765
9be2f4 766             if ($dh = @opendir(RCUBE_LOCALIZATION_DIR)) {
315418 767                 while (($name = readdir($dh)) !== false) {
9be2f4 768                     if ($name[0] == '.' || !is_dir(RCUBE_LOCALIZATION_DIR . $name)) {
315418 769                         continue;
AM 770                     }
771
772                     if ($label = $rcube_languages[$name]) {
773                         $sa_languages[$name] = $label;
774                     }
775                 }
776                 closedir($dh);
777             }
778         }
779
780         return $sa_languages;
781     }
782
783
784     /**
785      * Encrypt using 3DES
786      *
787      * @param string $clear clear text input
788      * @param string $key encryption key to retrieve from the configuration, defaults to 'des_key'
789      * @param boolean $base64 whether or not to base64_encode() the result before returning
790      *
791      * @return string encrypted text
792      */
793     public function encrypt($clear, $key = 'des_key', $base64 = true)
794     {
795         if (!$clear) {
796             return '';
797         }
798
799         /*-
800          * Add a single canary byte to the end of the clear text, which
801          * will help find out how much of padding will need to be removed
802          * upon decryption; see http://php.net/mcrypt_generic#68082
803          */
804         $clear = pack("a*H2", $clear, "80");
805
806         if (function_exists('mcrypt_module_open') &&
807             ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_CBC, ""))
808         ) {
809             $iv = $this->create_iv(mcrypt_enc_get_iv_size($td));
810             mcrypt_generic_init($td, $this->config->get_crypto_key($key), $iv);
811             $cipher = $iv . mcrypt_generic($td, $clear);
812             mcrypt_generic_deinit($td);
813             mcrypt_module_close($td);
814         }
815         else {
816             @include_once 'des.inc';
817
818             if (function_exists('des')) {
819                 $des_iv_size = 8;
820                 $iv = $this->create_iv($des_iv_size);
821                 $cipher = $iv . des($this->config->get_crypto_key($key), $clear, 1, 1, $iv);
822             }
823             else {
824                 self::raise_error(array(
825                     'code' => 500, 'type' => 'php',
826                     'file' => __FILE__, 'line' => __LINE__,
827                     'message' => "Could not perform encryption; make sure Mcrypt is installed or lib/des.inc is available"
828                     ), true, true);
829             }
830         }
831
832         return $base64 ? base64_encode($cipher) : $cipher;
833     }
834
835
836     /**
837      * Decrypt 3DES-encrypted string
838      *
839      * @param string $cipher encrypted text
840      * @param string $key encryption key to retrieve from the configuration, defaults to 'des_key'
841      * @param boolean $base64 whether or not input is base64-encoded
842      *
843      * @return string decrypted text
844      */
845     public function decrypt($cipher, $key = 'des_key', $base64 = true)
846     {
847         if (!$cipher) {
848             return '';
849         }
850
851         $cipher = $base64 ? base64_decode($cipher) : $cipher;
852
853         if (function_exists('mcrypt_module_open') &&
854             ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_CBC, ""))
855         ) {
856             $iv_size = mcrypt_enc_get_iv_size($td);
857             $iv = substr($cipher, 0, $iv_size);
858
859             // session corruption? (#1485970)
860             if (strlen($iv) < $iv_size) {
861                 return '';
862             }
863
864             $cipher = substr($cipher, $iv_size);
865             mcrypt_generic_init($td, $this->config->get_crypto_key($key), $iv);
866             $clear = mdecrypt_generic($td, $cipher);
867             mcrypt_generic_deinit($td);
868             mcrypt_module_close($td);
869         }
870         else {
871             @include_once 'des.inc';
872
873             if (function_exists('des')) {
874                 $des_iv_size = 8;
875                 $iv = substr($cipher, 0, $des_iv_size);
876                 $cipher = substr($cipher, $des_iv_size);
877                 $clear = des($this->config->get_crypto_key($key), $cipher, 0, 1, $iv);
878             }
879             else {
880                 self::raise_error(array(
881                     'code' => 500, 'type' => 'php',
882                     'file' => __FILE__, 'line' => __LINE__,
883                     'message' => "Could not perform decryption; make sure Mcrypt is installed or lib/des.inc is available"
884                     ), true, true);
885             }
886         }
887
888         /*-
889          * Trim PHP's padding and the canary byte; see note in
890          * rcube::encrypt() and http://php.net/mcrypt_generic#68082
891          */
892         $clear = substr(rtrim($clear, "\0"), 0, -1);
893
894         return $clear;
895     }
896
897
898     /**
899      * Generates encryption initialization vector (IV)
900      *
901      * @param int Vector size
902      *
903      * @return string Vector string
904      */
905     private function create_iv($size)
906     {
907         // mcrypt_create_iv() can be slow when system lacks entrophy
908         // we'll generate IV vector manually
909         $iv = '';
910         for ($i = 0; $i < $size; $i++) {
911             $iv .= chr(mt_rand(0, 255));
912         }
913
914         return $iv;
915     }
916
917
918     /**
919      * Build a valid URL to this instance of Roundcube
920      *
921      * @param mixed Either a string with the action or url parameters as key-value pairs
922      * @return string Valid application URL
923      */
924     public function url($p)
925     {
926         // STUB: should be overloaded by the application
0c2596 927         return '';
A 928     }
929
315418 930
AM 931     /**
932      * Function to be executed in script shutdown
933      * Registered with register_shutdown_function()
0c2596 934      */
315418 935     public function shutdown()
AM 936     {
937         foreach ($this->shutdown_functions as $function) {
938             call_user_func($function);
0c2596 939         }
A 940
3dbe4f 941         // write session data as soon as possible and before
AM 942         // closing database connection, don't do this before
943         // registered shutdown functions, they may need the session
944         // Note: this will run registered gc handlers (ie. cache gc)
945         if ($_SERVER['REMOTE_ADDR'] && is_object($this->session)) {
946             $this->session->write_close();
315418 947         }
AM 948
3dbe4f 949         if (is_object($this->smtp)) {
AM 950             $this->smtp->disconnect();
ee73a7 951         }
AM 952
315418 953         foreach ($this->caches as $cache) {
AM 954             if (is_object($cache)) {
955                 $cache->close();
956             }
957         }
958
959         if (is_object($this->storage)) {
960             $this->storage->close();
961         }
0c2596 962     }
A 963
964
315418 965     /**
AM 966      * Registers shutdown function to be executed on shutdown.
967      * The functions will be executed before destroying any
968      * objects like smtp, imap, session, etc.
969      *
970      * @param callback Function callback
971      */
972     public function add_shutdown_function($function)
973     {
974         $this->shutdown_functions[] = $function;
975     }
976
977
978     /**
10da75 979      * Quote a given string.
TB 980      * Shortcut function for rcube_utils::rep_specialchars_output()
981      *
982      * @return string HTML-quoted string
983      */
984     public static function Q($str, $mode = 'strict', $newlines = true)
985     {
986         return rcube_utils::rep_specialchars_output($str, 'html', $mode, $newlines);
987     }
988
989
990     /**
991      * Quote a given string for javascript output.
992      * Shortcut function for rcube_utils::rep_specialchars_output()
993      *
994      * @return string JS-quoted string
995      */
996     public static function JQ($str)
997     {
998         return rcube_utils::rep_specialchars_output($str, 'js');
999     }
1000
1001
1002     /**
315418 1003      * Construct shell command, execute it and return output as string.
AM 1004      * Keywords {keyword} are replaced with arguments
1005      *
1006      * @param $cmd Format string with {keywords} to be replaced
1007      * @param $values (zero, one or more arrays can be passed)
1008      *
1009      * @return output of command. shell errors not detectable
1010      */
1011     public static function exec(/* $cmd, $values1 = array(), ... */)
1012     {
1013         $args   = func_get_args();
1014         $cmd    = array_shift($args);
1015         $values = $replacements = array();
1016
1017         // merge values into one array
1018         foreach ($args as $arg) {
1019             $values += (array)$arg;
1020         }
1021
1022         preg_match_all('/({(-?)([a-z]\w*)})/', $cmd, $matches, PREG_SET_ORDER);
1023         foreach ($matches as $tags) {
1024             list(, $tag, $option, $key) = $tags;
1025             $parts = array();
1026
1027             if ($option) {
1028                 foreach ((array)$values["-$key"] as $key => $value) {
1029                     if ($value === true || $value === false || $value === null) {
1030                         $parts[] = $value ? $key : "";
1031                     }
1032                     else {
1033                         foreach ((array)$value as $val) {
1034                             $parts[] = "$key " . escapeshellarg($val);
1035                         }
1036                     }
1037                 }
1038             }
1039             else {
1040                 foreach ((array)$values[$key] as $value) {
1041                     $parts[] = escapeshellarg($value);
1042                 }
1043             }
1044
1045             $replacements[$tag] = join(" ", $parts);
1046         }
1047
1048         // use strtr behaviour of going through source string once
1049         $cmd = strtr($cmd, $replacements);
1050
1051         return (string)shell_exec($cmd);
1052     }
0c2596 1053
A 1054
1055     /**
1056      * Print or write debug messages
1057      *
1058      * @param mixed Debug message or data
1059      */
1060     public static function console()
1061     {
1062         $args = func_get_args();
1063
be98df 1064         if (class_exists('rcube', false)) {
0c2596 1065             $rcube = self::get_instance();
be98df 1066             $plugin = $rcube->plugins->exec_hook('console', array('args' => $args));
A 1067             if ($plugin['abort']) {
1068                 return;
0c2596 1069             }
be98df 1070            $args = $plugin['args'];
0c2596 1071         }
A 1072
1073         $msg = array();
1074         foreach ($args as $arg) {
1075             $msg[] = !is_string($arg) ? var_export($arg, true) : $arg;
1076         }
1077
1078         self::write_log('console', join(";\n", $msg));
1079     }
1080
1081
1082     /**
1083      * Append a line to a logfile in the logs directory.
1084      * Date will be added automatically to the line.
1085      *
1086      * @param $name name of log file
1087      * @param line Line to append
1088      */
1089     public static function write_log($name, $line)
1090     {
1091         if (!is_string($line)) {
1092             $line = var_export($line, true);
1093         }
1094
1095         $date_format = self::$instance ? self::$instance->config->get('log_date_format') : null;
1096         $log_driver  = self::$instance ? self::$instance->config->get('log_driver') : null;
1097
1098         if (empty($date_format)) {
1099             $date_format = 'd-M-Y H:i:s O';
1100         }
1101
1102         $date = date($date_format);
1103
1104         // trigger logging hook
1105         if (is_object(self::$instance) && is_object(self::$instance->plugins)) {
1106             $log  = self::$instance->plugins->exec_hook('write_log', array('name' => $name, 'date' => $date, 'line' => $line));
1107             $name = $log['name'];
1108             $line = $log['line'];
1109             $date = $log['date'];
1110             if ($log['abort'])
1111                 return true;
1112         }
1113
1114         if ($log_driver == 'syslog') {
1115             $prio = $name == 'errors' ? LOG_ERR : LOG_INFO;
1116             syslog($prio, $line);
1117             return true;
1118         }
1119
1120         // log_driver == 'file' is assumed here
1121
1122         $line = sprintf("[%s]: %s\n", $date, $line);
3786a4 1123         $log_dir = null;
TB 1124
1125         // per-user logging is activated
1126         if (self::$instance && self::$instance->config->get('per_user_logging', false) && self::$instance->get_user_id()) {
1127             $log_dir = self::$instance->get_user_log_dir();
1128             if (empty($log_dir))
1129                 return false;
1130         }
1131         else if (!empty($log['dir'])) {
1132             $log_dir = $log['dir'];
1133         }
1134         else if (self::$instance) {
1135             $log_dir = self::$instance->config->get('log_dir');
1136         }
0c2596 1137
A 1138         if (empty($log_dir)) {
9be2f4 1139             $log_dir = RCUBE_INSTALL_PATH . 'logs';
0c2596 1140         }
A 1141
1142         // try to open specific log file for writing
1143         $logfile = $log_dir.'/'.$name;
1144
1145         if ($fp = @fopen($logfile, 'a')) {
1146             fwrite($fp, $line);
1147             fflush($fp);
1148             fclose($fp);
1149             return true;
1150         }
1151
1152         trigger_error("Error writing to log file $logfile; Please check permissions", E_USER_WARNING);
1153         return false;
1154     }
1155
1156
1157     /**
1158      * Throw system error (and show error page).
1159      *
1160      * @param array Named parameters
1161      *      - code:    Error code (required)
1162      *      - type:    Error type [php|db|imap|javascript] (required)
1163      *      - message: Error message
b3e259 1164      *      - file:    File where error occurred
AM 1165      *      - line:    Line where error occurred
0c2596 1166      * @param boolean True to log the error
A 1167      * @param boolean Terminate script execution
1168      */
1169     public static function raise_error($arg = array(), $log = false, $terminate = false)
1170     {
76e499 1171         // handle PHP exceptions
TB 1172         if (is_object($arg) && is_a($arg, 'Exception')) {
a39fd4 1173             $arg = array(
76e499 1174                 'code' => $arg->getCode(),
TB 1175                 'line' => $arg->getLine(),
1176                 'file' => $arg->getFile(),
1177                 'message' => $arg->getMessage(),
1178             );
a39fd4 1179         }
f23ef1 1180         else if (is_string($arg)) {
0301d9 1181             $arg = array('message' => $arg);
f23ef1 1182         }
a39fd4 1183
AM 1184         if (empty($arg['code'])) {
1185             $arg['code'] = 500;
76e499 1186         }
TB 1187
0c2596 1188         // installer
A 1189         if (class_exists('rcube_install', false)) {
1190             $rci = rcube_install::get_instance();
1191             $rci->raise_error($arg);
1192             return;
1193         }
1194
f23ef1 1195         $cli = php_sapi_name() == 'cli';
AM 1196
0301d9 1197         if (($log || $terminate) && !$cli && $arg['message']) {
819315 1198             $arg['fatal'] = $terminate;
0c2596 1199             self::log_bug($arg);
A 1200         }
1201
f23ef1 1202         // terminate script
AM 1203         if ($terminate) {
1204             // display error page
1205             if (is_object(self::$instance->output)) {
1206                 self::$instance->output->raise_error($arg['code'], $arg['message']);
1207             }
1208             else if ($cli) {
1209                 fwrite(STDERR, 'ERROR: ' . $arg['message']);
1210             }
1211
1212             exit(1);
0c2596 1213         }
A 1214     }
1215
1216
1217     /**
1218      * Report error according to configured debug_level
1219      *
1220      * @param array Named parameters
1221      * @see self::raise_error()
1222      */
1223     public static function log_bug($arg_arr)
1224     {
0301d9 1225         $program = strtoupper(!empty($arg_arr['type']) ? $arg_arr['type'] : 'php');
0c2596 1226         $level   = self::get_instance()->config->get('debug_level');
A 1227
1228         // disable errors for ajax requests, write to log instead (#1487831)
1229         if (($level & 4) && !empty($_REQUEST['_remote'])) {
1230             $level = ($level ^ 4) | 1;
1231         }
1232
1233         // write error to local log file
819315 1234         if (($level & 1) || !empty($arg_arr['fatal'])) {
0c2596 1235             if ($_SERVER['REQUEST_METHOD'] == 'POST') {
A 1236                 $post_query = '?_task='.urlencode($_POST['_task']).'&_action='.urlencode($_POST['_action']);
1237             }
1238             else {
1239                 $post_query = '';
1240             }
1241
1242             $log_entry = sprintf("%s Error: %s%s (%s %s)",
1243                 $program,
1244                 $arg_arr['message'],
1245                 $arg_arr['file'] ? sprintf(' in %s on line %d', $arg_arr['file'], $arg_arr['line']) : '',
1246                 $_SERVER['REQUEST_METHOD'],
1247                 $_SERVER['REQUEST_URI'] . $post_query);
1248
1249             if (!self::write_log('errors', $log_entry)) {
1250                 // send error to PHPs error handler if write_log didn't succeed
f23ef1 1251                 trigger_error($arg_arr['message'], E_USER_WARNING);
0c2596 1252             }
A 1253         }
1254
1255         // report the bug to the global bug reporting system
1256         if ($level & 2) {
1257             // TODO: Send error via HTTP
1258         }
1259
1260         // show error if debug_mode is on
1261         if ($level & 4) {
1262             print "<b>$program Error";
1263
1264             if (!empty($arg_arr['file']) && !empty($arg_arr['line'])) {
1265                 print " in $arg_arr[file] ($arg_arr[line])";
1266             }
1267
1268             print ':</b>&nbsp;';
1269             print nl2br($arg_arr['message']);
1270             print '<br />';
1271             flush();
1272         }
1273     }
1274
1275
1276     /**
1277      * Returns current time (with microseconds).
1278      *
1279      * @return float Current time in seconds since the Unix
1280      */
1281     public static function timer()
1282     {
1283         return microtime(true);
1284     }
1285
1286
1287     /**
1288      * Logs time difference according to provided timer
1289      *
1290      * @param float  $timer  Timer (self::timer() result)
1291      * @param string $label  Log line prefix
1292      * @param string $dest   Log file name
1293      *
1294      * @see self::timer()
1295      */
1296     public static function print_timer($timer, $label = 'Timer', $dest = 'console')
1297     {
1298         static $print_count = 0;
1299
1300         $print_count++;
1301         $now  = self::timer();
1302         $diff = $now - $timer;
1303
1304         if (empty($label)) {
1305             $label = 'Timer '.$print_count;
1306         }
1307
1308         self::write_log($dest, sprintf("%s: %0.4f sec", $label, $diff));
1309     }
1310
1311
1312     /**
1313      * Getter for logged user ID.
1314      *
1315      * @return mixed User identifier
1316      */
1317     public function get_user_id()
1318     {
1319         if (is_object($this->user)) {
1320             return $this->user->ID;
1321         }
a2f896 1322         else if (isset($_SESSION['user_id'])) {
A 1323             return $_SESSION['user_id'];
1324         }
0c2596 1325
A 1326         return null;
1327     }
1328
1329
1330     /**
1331      * Getter for logged user name.
1332      *
1333      * @return string User name
1334      */
1335     public function get_user_name()
1336     {
1337         if (is_object($this->user)) {
1338             return $this->user->get_username();
1339         }
789e59 1340         else if (isset($_SESSION['username'])) {
AM 1341             return $_SESSION['username'];
1342         }
1343     }
0c2596 1344
789e59 1345
AM 1346     /**
1347      * Getter for logged user email (derived from user name not identity).
1348      *
1349      * @return string User email address
1350      */
1351     public function get_user_email()
1352     {
1353         if (is_object($this->user)) {
1354             return $this->user->get_username('mail');
1355         }
0c2596 1356     }
5b06e2 1357
AM 1358
1359     /**
1360      * Getter for logged user password.
1361      *
1362      * @return string User password
1363      */
1364     public function get_user_password()
1365     {
1366         if ($this->password) {
1367             return $this->password;
1368         }
1369         else if ($_SESSION['password']) {
1370             return $this->decrypt($_SESSION['password']);
1371         }
1372     }
a5b8ef 1373
3786a4 1374     /**
TB 1375      * Get the per-user log directory
1376      */
1377     protected function get_user_log_dir()
1378     {
1379         $log_dir = $this->config->get('log_dir', RCUBE_INSTALL_PATH . 'logs');
1380         $user_name = $this->get_user_name();
1381         $user_log_dir = $log_dir . '/' . $user_name;
1382
1383         return !empty($user_name) && is_writable($user_log_dir) ? $user_log_dir : false;
1384     }
a5b8ef 1385
AM 1386     /**
1387      * Getter for logged user language code.
1388      *
1389      * @return string User language code
1390      */
1391     public function get_user_language()
1392     {
1393         if (is_object($this->user)) {
1394             return $this->user->language;
1395         }
1396         else if (isset($_SESSION['language'])) {
1397             return $_SESSION['language'];
1398         }
1399     }
0b9a7b 1400
TB 1401     /**
1402      * Unique Message-ID generator.
1403      *
1404      * @return string Message-ID
1405      */
1406     public function gen_message_id()
1407     {
1408         $local_part  = md5(uniqid('rcube'.mt_rand(), true));
1409         $domain_part = $this->user->get_username('domain');
1410
1411         // Try to find FQDN, some spamfilters doesn't like 'localhost' (#1486924)
1412         if (!preg_match('/\.[a-z]+$/i', $domain_part)) {
1413             foreach (array($_SERVER['HTTP_HOST'], $_SERVER['SERVER_NAME']) as $host) {
1414                 $host = preg_replace('/:[0-9]+$/', '', $host);
1415                 if ($host && preg_match('/\.[a-z]+$/i', $host)) {
1416                     $domain_part = $host;
1417                 }
1418             }
1419         }
1420
1421         return sprintf('<%s@%s>', $local_part, $domain_part);
1422     }
1423
1424     /**
1425      * Send the given message using the configured method.
1426      *
1427      * @param object $message    Reference to Mail_MIME object
1428      * @param string $from       Sender address string
1429      * @param array  $mailto     Array of recipient address strings
1430      * @param array  $error      SMTP error array (reference)
1431      * @param string $body_file  Location of file with saved message body (reference),
1432      *                           used when delay_file_io is enabled
1433      * @param array  $options    SMTP options (e.g. DSN request)
1434      *
1435      * @return boolean Send status.
1436      */
1437     public function deliver_message(&$message, $from, $mailto, &$error, &$body_file = null, $options = null)
1438     {
1439         $plugin = $this->plugins->exec_hook('message_before_send', array(
1440             'message' => $message,
1441             'from'    => $from,
1442             'mailto'  => $mailto,
1443             'options' => $options,
1444         ));
1445
6efadf 1446         if ($plugin['abort']) {
8b5d16 1447             if (!empty($plugin['error'])) {
AM 1448                 $error = $plugin['error'];
1449             }
1450             if (!empty($plugin['body_file'])) {
1451                 $body_file = $plugin['body_file'];
1452             }
1453
6efadf 1454             return isset($plugin['result']) ? $plugin['result'] : false;
AM 1455         }
1456
0b9a7b 1457         $from    = $plugin['from'];
TB 1458         $mailto  = $plugin['mailto'];
1459         $options = $plugin['options'];
1460         $message = $plugin['message'];
1461         $headers = $message->headers();
1462
1463         // send thru SMTP server using custom SMTP library
1464         if ($this->config->get('smtp_server')) {
1465             // generate list of recipients
4446ae 1466             $a_recipients = (array) $mailto;
0b9a7b 1467
TB 1468             if (strlen($headers['Cc']))
1469                 $a_recipients[] = $headers['Cc'];
1470             if (strlen($headers['Bcc']))
1471                 $a_recipients[] = $headers['Bcc'];
1472
eb3182 1473             // remove Bcc header and get the whole head of the message as string
AM 1474             $smtp_headers = $this->message_head($message, array('Bcc'));
0b9a7b 1475
TB 1476             if ($message->getParam('delay_file_io')) {
1477                 // use common temp dir
1478                 $temp_dir = $this->config->get('temp_dir');
1479                 $body_file = tempnam($temp_dir, 'rcmMsg');
1480                 if (PEAR::isError($mime_result = $message->saveMessageBody($body_file))) {
1481                     self::raise_error(array('code' => 650, 'type' => 'php',
1482                         'file' => __FILE__, 'line' => __LINE__,
1483                         'message' => "Could not create message: ".$mime_result->getMessage()),
1484                         TRUE, FALSE);
1485                     return false;
1486                 }
1487                 $msg_body = fopen($body_file, 'r');
1488             }
1489             else {
1490                 $msg_body = $message->get();
1491             }
1492
1493             // send message
1494             if (!is_object($this->smtp)) {
1495                 $this->smtp_init(true);
1496             }
1497
1498             $sent     = $this->smtp->send_mail($from, $a_recipients, $smtp_headers, $msg_body, $options);
1499             $response = $this->smtp->get_response();
1500             $error    = $this->smtp->get_error();
1501
1502             // log error
1503             if (!$sent) {
1504                 self::raise_error(array('code' => 800, 'type' => 'smtp',
1505                     'line' => __LINE__, 'file' => __FILE__,
78f948 1506                     'message' => join("\n", $response)), true, false);
0b9a7b 1507             }
TB 1508         }
1509         // send mail using PHP's mail() function
1510         else {
eb3182 1511             // unset To,Subject headers because they will be added by the mail() function
AM 1512             $header_str = $this->message_head($message, array('To', 'Subject'));
0b9a7b 1513
TB 1514             // #1485779
1515             if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
eb3182 1516                 if (preg_match_all('/<([^@]+@[^>]+)>/', $headers['To'], $m)) {
AM 1517                     $headers['To'] = implode(', ', $m[1]);
0b9a7b 1518                 }
TB 1519             }
1520
1521             $msg_body = $message->get();
1522
1523             if (PEAR::isError($msg_body)) {
1524                 self::raise_error(array('code' => 650, 'type' => 'php',
1525                     'file' => __FILE__, 'line' => __LINE__,
1526                     'message' => "Could not create message: ".$msg_body->getMessage()),
1527                     TRUE, FALSE);
1528             }
1529             else {
1530                 $delim   = $this->config->header_delimiter();
eb3182 1531                 $to      = $headers['To'];
AM 1532                 $subject = $headers['Subject'];
0b9a7b 1533                 $header_str = rtrim($header_str);
TB 1534
1535                 if ($delim != "\r\n") {
1536                     $header_str = str_replace("\r\n", $delim, $header_str);
1537                     $msg_body   = str_replace("\r\n", $delim, $msg_body);
1538                     $to         = str_replace("\r\n", $delim, $to);
1539                     $subject    = str_replace("\r\n", $delim, $subject);
1540                 }
1541
39b905 1542                 if (filter_var(ini_get('safe_mode'), FILTER_VALIDATE_BOOLEAN))
0b9a7b 1543                     $sent = mail($to, $subject, $msg_body, $header_str);
TB 1544                 else
1545                     $sent = mail($to, $subject, $msg_body, $header_str, "-f$from");
1546             }
1547         }
1548
1549         if ($sent) {
1550             $this->plugins->exec_hook('message_sent', array('headers' => $headers, 'body' => $msg_body));
1551
1552             // remove MDN headers after sending
1553             unset($headers['Return-Receipt-To'], $headers['Disposition-Notification-To']);
1554
1555             if ($this->config->get('smtp_log')) {
4446ae 1556                 // get all recipient addresses
AM 1557                 if (is_array($mailto)) {
1558                     $mailto = implode(',', $mailto);
1559                 }
1560                 if ($headers['Cc']) {
1561                     $mailto .= ',' . $headers['Cc'];
1562                 }
1563                 if ($headers['Bcc']) {
1564                     $mailto .= ',' . $headers['Bcc'];
1565                 }
1566
1567                 $mailto = rcube_mime::decode_address_list($mailto, null, false, null, true);
1568
0b9a7b 1569                 self::write_log('sendmail', sprintf("User %s [%s]; Message for %s; %s",
TB 1570                     $this->user->get_username(),
4446ae 1571                     rcube_utils::remote_addr(),
AM 1572                     implode(', ', $mailto),
0b9a7b 1573                     !empty($response) ? join('; ', $response) : ''));
TB 1574             }
1575         }
aef6ed 1576         else {
TB 1577             // allow plugins to catch sending errors with the same parameters as in 'message_before_send'
1578             $this->plugins->exec_hook('message_send_error', $plugin + array('error' => $error));
1579         }
0b9a7b 1580
TB 1581         if (is_resource($msg_body)) {
1582             fclose($msg_body);
1583         }
1584
eb3182 1585         $message->headers($headers, true);
0b9a7b 1586
TB 1587         return $sent;
1588     }
1589
eb3182 1590     /**
AM 1591      * Return message headers as a string
1592      */
1593     protected function message_head($message, $unset = array())
1594     {
1595         // Mail_mime >= 1.9.0
1596         if (method_exists($message, 'isMultipart')) {
1597             foreach ($unset as $header) {
1598                 $headers[$header] = null;
1599             }
1600         }
1601         else {
1602             $headers = $message->headers();
1603             foreach ($unset as $header) {
1604                 unset($headers[$header]);
1605             }
1606             $message->_headers = array();
1607         }
1608
1609         return $message->txtHeaders($headers, true);
1610     }
0c2596 1611 }
A 1612
1613
1614 /**
1615  * Lightweight plugin API class serving as a dummy if plugins are not enabled
1616  *
a07224 1617  * @package Framework
TB 1618  * @subpackage Core
0c2596 1619  */
A 1620 class rcube_dummy_plugin_api
1621 {
1622     /**
1623      * Triggers a plugin hook.
1624      * @see rcube_plugin_api::exec_hook()
1625      */
1626     public function exec_hook($hook, $args = array())
1627     {
1628         return $args;
1629     }
1630 }