Aleksander Machniak
2015-08-18 eb318205fcebe671f20a62a6e5e1d81622e0586f
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
3dbe4f 467         $this->session->register_gc_handler(array($this, 'gc'));
c442f8 468         $this->session->set_secret($this->config->get('des_key') . dirname($_SERVER['SCRIPT_NAME']));
AM 469         $this->session->set_ip_check($this->config->get('ip_check'));
470
8d2963 471         if ($this->config->get('session_auth_name')) {
TB 472             $this->session->set_cookiename($this->config->get('session_auth_name'));
473         }
474
963a10 475         // start PHP session (if not in CLI mode)
A 476         if ($_SERVER['REMOTE_ADDR']) {
42de33 477             $this->session->start();
963a10 478         }
A 479     }
480
481
482     /**
ee73a7 483      * Garbage collector - cache/temp cleaner
AM 484      */
485     public function gc()
486     {
60b6d7 487         rcube_cache::gc();
AM 488         rcube_cache_shared::gc();
489         $this->get_storage()->cache_gc();
ee73a7 490
AM 491         $this->gc_temp();
492     }
493
494
495     /**
963a10 496      * Garbage collector function for temp files.
A 497      * Remove temp files older than two days
498      */
ee73a7 499     public function gc_temp()
963a10 500     {
A 501         $tmp = unslashify($this->config->get('temp_dir'));
de8687 502
DC 503         // expire in 48 hours by default
504         $temp_dir_ttl = $this->config->get('temp_dir_ttl', '48h');
505         $temp_dir_ttl = get_offset_sec($temp_dir_ttl);
506         if ($temp_dir_ttl < 6*3600)
507             $temp_dir_ttl = 6*3600;   // 6 hours sensible lower bound.
508
509         $expire = time() - $temp_dir_ttl;
963a10 510
A 511         if ($tmp && ($dir = opendir($tmp))) {
512             while (($fname = readdir($dir)) !== false) {
311d87 513                 if ($fname[0] == '.') {
963a10 514                     continue;
A 515                 }
516
311d87 517                 if (@filemtime($tmp.'/'.$fname) < $expire) {
963a10 518                     @unlink($tmp.'/'.$fname);
A 519                 }
520             }
521
522             closedir($dir);
523         }
ee73a7 524     }
AM 525
526
527     /**
528      * Runs garbage collector with probability based on
529      * session settings. This is intended for environments
530      * without a session.
531      */
532     public function gc_run()
533     {
534         $probability = (int) ini_get('session.gc_probability');
535         $divisor     = (int) ini_get('session.gc_divisor');
536
537         if ($divisor > 0 && $probability > 0) {
538             $random = mt_rand(1, $divisor);
539             if ($random <= $probability) {
540                 $this->gc();
541             }
542         }
963a10 543     }
A 544
545
315418 546     /**
AM 547      * Get localized text in the desired language
548      *
549      * @param mixed   $attrib  Named parameters array or label name
550      * @param string  $domain  Label domain (plugin) name
551      *
552      * @return string Localized text
0c2596 553      */
315418 554     public function gettext($attrib, $domain=null)
AM 555     {
556         // load localization files if not done yet
557         if (empty($this->texts)) {
558             $this->load_language();
559         }
0c2596 560
315418 561         // extract attributes
AM 562         if (is_string($attrib)) {
563             $attrib = array('name' => $attrib);
564         }
0c2596 565
315418 566         $name = $attrib['name'] ? $attrib['name'] : '';
AM 567
568         // attrib contain text values: use them from now
569         if (($setval = $attrib[strtolower($_SESSION['language'])]) || ($setval = $attrib['en_us'])) {
570             $this->texts[$name] = $setval;
571         }
572
573         // check for text with domain
574         if ($domain && ($text = $this->texts[$domain.'.'.$name])) {
575         }
576         // text does not exist
577         else if (!($text = $this->texts[$name])) {
578             return "[$name]";
579         }
580
581         // replace vars in text
582         if (is_array($attrib['vars'])) {
583             foreach ($attrib['vars'] as $var_key => $var_value) {
584                 $text = str_replace($var_key[0]!='$' ? '$'.$var_key : $var_key, $var_value, $text);
585             }
586         }
587
588         // format output
589         if (($attrib['uppercase'] && strtolower($attrib['uppercase'] == 'first')) || $attrib['ucfirst']) {
590             return ucfirst($text);
591         }
592         else if ($attrib['uppercase']) {
593             return mb_strtoupper($text);
594         }
595         else if ($attrib['lowercase']) {
596             return mb_strtolower($text);
597         }
598
599         return strtr($text, array('\n' => "\n"));
0c2596 600     }
A 601
602
315418 603     /**
AM 604      * Check if the given text label exists
605      *
606      * @param string  $name       Label name
607      * @param string  $domain     Label domain (plugin) name or '*' for all domains
608      * @param string  $ref_domain Sets domain name if label is found
609      *
610      * @return boolean True if text exists (either in the current language or in en_US)
611      */
612     public function text_exists($name, $domain = null, &$ref_domain = null)
613     {
614         // load localization files if not done yet
615         if (empty($this->texts)) {
616             $this->load_language();
617         }
0c2596 618
315418 619         if (isset($this->texts[$name])) {
AM 620             $ref_domain = '';
621             return true;
622         }
0c2596 623
315418 624         // any of loaded domains (plugins)
AM 625         if ($domain == '*') {
626             foreach ($this->plugins->loaded_plugins() as $domain) {
627                 if (isset($this->texts[$domain.'.'.$name])) {
628                     $ref_domain = $domain;
629                     return true;
630                 }
631             }
632         }
633         // specified domain
634         else if ($domain) {
635             $ref_domain = $domain;
636             return isset($this->texts[$domain.'.'.$name]);
637         }
0c2596 638
315418 639         return false;
AM 640     }
641
642
643     /**
644      * Load a localization package
645      *
75a5c3 646      * @param string $lang  Language ID
AM 647      * @param array  $add   Additional text labels/messages
648      * @param array  $merge Additional text labels/messages to merge
315418 649      */
75a5c3 650     public function load_language($lang = null, $add = array(), $merge = array())
315418 651     {
AM 652         $lang = $this->language_prop(($lang ? $lang : $_SESSION['language']));
653
654         // load localized texts
655         if (empty($this->texts) || $lang != $_SESSION['language']) {
656             $this->texts = array();
657
658             // handle empty lines after closing PHP tag in localization files
659             ob_start();
660
661             // get english labels (these should be complete)
9be2f4 662             @include(RCUBE_LOCALIZATION_DIR . 'en_US/labels.inc');
TB 663             @include(RCUBE_LOCALIZATION_DIR . 'en_US/messages.inc');
315418 664
AM 665             if (is_array($labels))
666                 $this->texts = $labels;
667             if (is_array($messages))
668                 $this->texts = array_merge($this->texts, $messages);
669
670             // include user language files
9be2f4 671             if ($lang != 'en' && $lang != 'en_US' && is_dir(RCUBE_LOCALIZATION_DIR . $lang)) {
TB 672                 include_once(RCUBE_LOCALIZATION_DIR . $lang . '/labels.inc');
673                 include_once(RCUBE_LOCALIZATION_DIR . $lang . '/messages.inc');
315418 674
AM 675                 if (is_array($labels))
676                     $this->texts = array_merge($this->texts, $labels);
677                 if (is_array($messages))
678                     $this->texts = array_merge($this->texts, $messages);
679             }
680
681             ob_end_clean();
682
683             $_SESSION['language'] = $lang;
684         }
685
686         // append additional texts (from plugin)
687         if (is_array($add) && !empty($add)) {
688             $this->texts += $add;
689         }
75a5c3 690
AM 691         // merge additional texts (from plugin)
692         if (is_array($merge) && !empty($merge)) {
693             $this->texts = array_merge($this->texts, $merge);
694         }
315418 695     }
AM 696
697
698     /**
699      * Check the given string and return a valid language code
700      *
701      * @param string Language code
702      *
703      * @return string Valid language code
704      */
705     protected function language_prop($lang)
706     {
707         static $rcube_languages, $rcube_language_aliases;
708
709         // user HTTP_ACCEPT_LANGUAGE if no language is specified
710         if (empty($lang) || $lang == 'auto') {
711             $accept_langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
2c6a23 712             $lang         = $accept_langs[0];
AM 713
714             if (preg_match('/^([a-z]+)[_-]([a-z]+)$/i', $lang, $m)) {
715                 $lang = $m[1] . '_' . strtoupper($m[2]);
716             }
315418 717         }
AM 718
719         if (empty($rcube_languages)) {
9be2f4 720             @include(RCUBE_LOCALIZATION_DIR . 'index.inc');
315418 721         }
AM 722
723         // check if we have an alias for that language
724         if (!isset($rcube_languages[$lang]) && isset($rcube_language_aliases[$lang])) {
725             $lang = $rcube_language_aliases[$lang];
726         }
727         // try the first two chars
728         else if (!isset($rcube_languages[$lang])) {
729             $short = substr($lang, 0, 2);
730
731             // check if we have an alias for the short language code
732             if (!isset($rcube_languages[$short]) && isset($rcube_language_aliases[$short])) {
733                 $lang = $rcube_language_aliases[$short];
734             }
735             // expand 'nn' to 'nn_NN'
736             else if (!isset($rcube_languages[$short])) {
737                 $lang = $short.'_'.strtoupper($short);
738             }
739         }
740
9be2f4 741         if (!isset($rcube_languages[$lang]) || !is_dir(RCUBE_LOCALIZATION_DIR . $lang)) {
315418 742             $lang = 'en_US';
AM 743         }
744
745         return $lang;
746     }
747
748
749     /**
750      * Read directory program/localization and return a list of available languages
751      *
752      * @return array List of available localizations
753      */
754     public function list_languages()
755     {
756         static $sa_languages = array();
757
758         if (!sizeof($sa_languages)) {
9be2f4 759             @include(RCUBE_LOCALIZATION_DIR . 'index.inc');
315418 760
9be2f4 761             if ($dh = @opendir(RCUBE_LOCALIZATION_DIR)) {
315418 762                 while (($name = readdir($dh)) !== false) {
9be2f4 763                     if ($name[0] == '.' || !is_dir(RCUBE_LOCALIZATION_DIR . $name)) {
315418 764                         continue;
AM 765                     }
766
767                     if ($label = $rcube_languages[$name]) {
768                         $sa_languages[$name] = $label;
769                     }
770                 }
771                 closedir($dh);
772             }
773         }
774
775         return $sa_languages;
776     }
777
778
779     /**
780      * Encrypt using 3DES
781      *
782      * @param string $clear clear text input
783      * @param string $key encryption key to retrieve from the configuration, defaults to 'des_key'
784      * @param boolean $base64 whether or not to base64_encode() the result before returning
785      *
786      * @return string encrypted text
787      */
788     public function encrypt($clear, $key = 'des_key', $base64 = true)
789     {
790         if (!$clear) {
791             return '';
792         }
793
794         /*-
795          * Add a single canary byte to the end of the clear text, which
796          * will help find out how much of padding will need to be removed
797          * upon decryption; see http://php.net/mcrypt_generic#68082
798          */
799         $clear = pack("a*H2", $clear, "80");
800
801         if (function_exists('mcrypt_module_open') &&
802             ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_CBC, ""))
803         ) {
804             $iv = $this->create_iv(mcrypt_enc_get_iv_size($td));
805             mcrypt_generic_init($td, $this->config->get_crypto_key($key), $iv);
806             $cipher = $iv . mcrypt_generic($td, $clear);
807             mcrypt_generic_deinit($td);
808             mcrypt_module_close($td);
809         }
810         else {
811             @include_once 'des.inc';
812
813             if (function_exists('des')) {
814                 $des_iv_size = 8;
815                 $iv = $this->create_iv($des_iv_size);
816                 $cipher = $iv . des($this->config->get_crypto_key($key), $clear, 1, 1, $iv);
817             }
818             else {
819                 self::raise_error(array(
820                     'code' => 500, 'type' => 'php',
821                     'file' => __FILE__, 'line' => __LINE__,
822                     'message' => "Could not perform encryption; make sure Mcrypt is installed or lib/des.inc is available"
823                     ), true, true);
824             }
825         }
826
827         return $base64 ? base64_encode($cipher) : $cipher;
828     }
829
830
831     /**
832      * Decrypt 3DES-encrypted string
833      *
834      * @param string $cipher encrypted text
835      * @param string $key encryption key to retrieve from the configuration, defaults to 'des_key'
836      * @param boolean $base64 whether or not input is base64-encoded
837      *
838      * @return string decrypted text
839      */
840     public function decrypt($cipher, $key = 'des_key', $base64 = true)
841     {
842         if (!$cipher) {
843             return '';
844         }
845
846         $cipher = $base64 ? base64_decode($cipher) : $cipher;
847
848         if (function_exists('mcrypt_module_open') &&
849             ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_CBC, ""))
850         ) {
851             $iv_size = mcrypt_enc_get_iv_size($td);
852             $iv = substr($cipher, 0, $iv_size);
853
854             // session corruption? (#1485970)
855             if (strlen($iv) < $iv_size) {
856                 return '';
857             }
858
859             $cipher = substr($cipher, $iv_size);
860             mcrypt_generic_init($td, $this->config->get_crypto_key($key), $iv);
861             $clear = mdecrypt_generic($td, $cipher);
862             mcrypt_generic_deinit($td);
863             mcrypt_module_close($td);
864         }
865         else {
866             @include_once 'des.inc';
867
868             if (function_exists('des')) {
869                 $des_iv_size = 8;
870                 $iv = substr($cipher, 0, $des_iv_size);
871                 $cipher = substr($cipher, $des_iv_size);
872                 $clear = des($this->config->get_crypto_key($key), $cipher, 0, 1, $iv);
873             }
874             else {
875                 self::raise_error(array(
876                     'code' => 500, 'type' => 'php',
877                     'file' => __FILE__, 'line' => __LINE__,
878                     'message' => "Could not perform decryption; make sure Mcrypt is installed or lib/des.inc is available"
879                     ), true, true);
880             }
881         }
882
883         /*-
884          * Trim PHP's padding and the canary byte; see note in
885          * rcube::encrypt() and http://php.net/mcrypt_generic#68082
886          */
887         $clear = substr(rtrim($clear, "\0"), 0, -1);
888
889         return $clear;
890     }
891
892
893     /**
894      * Generates encryption initialization vector (IV)
895      *
896      * @param int Vector size
897      *
898      * @return string Vector string
899      */
900     private function create_iv($size)
901     {
902         // mcrypt_create_iv() can be slow when system lacks entrophy
903         // we'll generate IV vector manually
904         $iv = '';
905         for ($i = 0; $i < $size; $i++) {
906             $iv .= chr(mt_rand(0, 255));
907         }
908
909         return $iv;
910     }
911
912
913     /**
914      * Build a valid URL to this instance of Roundcube
915      *
916      * @param mixed Either a string with the action or url parameters as key-value pairs
917      * @return string Valid application URL
918      */
919     public function url($p)
920     {
921         // STUB: should be overloaded by the application
0c2596 922         return '';
A 923     }
924
315418 925
AM 926     /**
927      * Function to be executed in script shutdown
928      * Registered with register_shutdown_function()
0c2596 929      */
315418 930     public function shutdown()
AM 931     {
932         foreach ($this->shutdown_functions as $function) {
933             call_user_func($function);
0c2596 934         }
A 935
3dbe4f 936         // write session data as soon as possible and before
AM 937         // closing database connection, don't do this before
938         // registered shutdown functions, they may need the session
939         // Note: this will run registered gc handlers (ie. cache gc)
940         if ($_SERVER['REMOTE_ADDR'] && is_object($this->session)) {
941             $this->session->write_close();
315418 942         }
AM 943
3dbe4f 944         if (is_object($this->smtp)) {
AM 945             $this->smtp->disconnect();
ee73a7 946         }
AM 947
315418 948         foreach ($this->caches as $cache) {
AM 949             if (is_object($cache)) {
950                 $cache->close();
951             }
952         }
953
954         if (is_object($this->storage)) {
955             $this->storage->close();
956         }
0c2596 957     }
A 958
959
315418 960     /**
AM 961      * Registers shutdown function to be executed on shutdown.
962      * The functions will be executed before destroying any
963      * objects like smtp, imap, session, etc.
964      *
965      * @param callback Function callback
966      */
967     public function add_shutdown_function($function)
968     {
969         $this->shutdown_functions[] = $function;
970     }
971
972
973     /**
10da75 974      * Quote a given string.
TB 975      * Shortcut function for rcube_utils::rep_specialchars_output()
976      *
977      * @return string HTML-quoted string
978      */
979     public static function Q($str, $mode = 'strict', $newlines = true)
980     {
981         return rcube_utils::rep_specialchars_output($str, 'html', $mode, $newlines);
982     }
983
984
985     /**
986      * Quote a given string for javascript output.
987      * Shortcut function for rcube_utils::rep_specialchars_output()
988      *
989      * @return string JS-quoted string
990      */
991     public static function JQ($str)
992     {
993         return rcube_utils::rep_specialchars_output($str, 'js');
994     }
995
996
997     /**
315418 998      * Construct shell command, execute it and return output as string.
AM 999      * Keywords {keyword} are replaced with arguments
1000      *
1001      * @param $cmd Format string with {keywords} to be replaced
1002      * @param $values (zero, one or more arrays can be passed)
1003      *
1004      * @return output of command. shell errors not detectable
1005      */
1006     public static function exec(/* $cmd, $values1 = array(), ... */)
1007     {
1008         $args   = func_get_args();
1009         $cmd    = array_shift($args);
1010         $values = $replacements = array();
1011
1012         // merge values into one array
1013         foreach ($args as $arg) {
1014             $values += (array)$arg;
1015         }
1016
1017         preg_match_all('/({(-?)([a-z]\w*)})/', $cmd, $matches, PREG_SET_ORDER);
1018         foreach ($matches as $tags) {
1019             list(, $tag, $option, $key) = $tags;
1020             $parts = array();
1021
1022             if ($option) {
1023                 foreach ((array)$values["-$key"] as $key => $value) {
1024                     if ($value === true || $value === false || $value === null) {
1025                         $parts[] = $value ? $key : "";
1026                     }
1027                     else {
1028                         foreach ((array)$value as $val) {
1029                             $parts[] = "$key " . escapeshellarg($val);
1030                         }
1031                     }
1032                 }
1033             }
1034             else {
1035                 foreach ((array)$values[$key] as $value) {
1036                     $parts[] = escapeshellarg($value);
1037                 }
1038             }
1039
1040             $replacements[$tag] = join(" ", $parts);
1041         }
1042
1043         // use strtr behaviour of going through source string once
1044         $cmd = strtr($cmd, $replacements);
1045
1046         return (string)shell_exec($cmd);
1047     }
0c2596 1048
A 1049
1050     /**
1051      * Print or write debug messages
1052      *
1053      * @param mixed Debug message or data
1054      */
1055     public static function console()
1056     {
1057         $args = func_get_args();
1058
be98df 1059         if (class_exists('rcube', false)) {
0c2596 1060             $rcube = self::get_instance();
be98df 1061             $plugin = $rcube->plugins->exec_hook('console', array('args' => $args));
A 1062             if ($plugin['abort']) {
1063                 return;
0c2596 1064             }
be98df 1065            $args = $plugin['args'];
0c2596 1066         }
A 1067
1068         $msg = array();
1069         foreach ($args as $arg) {
1070             $msg[] = !is_string($arg) ? var_export($arg, true) : $arg;
1071         }
1072
1073         self::write_log('console', join(";\n", $msg));
1074     }
1075
1076
1077     /**
1078      * Append a line to a logfile in the logs directory.
1079      * Date will be added automatically to the line.
1080      *
1081      * @param $name name of log file
1082      * @param line Line to append
1083      */
1084     public static function write_log($name, $line)
1085     {
1086         if (!is_string($line)) {
1087             $line = var_export($line, true);
1088         }
1089
1090         $date_format = self::$instance ? self::$instance->config->get('log_date_format') : null;
1091         $log_driver  = self::$instance ? self::$instance->config->get('log_driver') : null;
1092
1093         if (empty($date_format)) {
1094             $date_format = 'd-M-Y H:i:s O';
1095         }
1096
1097         $date = date($date_format);
1098
1099         // trigger logging hook
1100         if (is_object(self::$instance) && is_object(self::$instance->plugins)) {
1101             $log  = self::$instance->plugins->exec_hook('write_log', array('name' => $name, 'date' => $date, 'line' => $line));
1102             $name = $log['name'];
1103             $line = $log['line'];
1104             $date = $log['date'];
1105             if ($log['abort'])
1106                 return true;
1107         }
1108
1109         if ($log_driver == 'syslog') {
1110             $prio = $name == 'errors' ? LOG_ERR : LOG_INFO;
1111             syslog($prio, $line);
1112             return true;
1113         }
1114
1115         // log_driver == 'file' is assumed here
1116
1117         $line = sprintf("[%s]: %s\n", $date, $line);
3786a4 1118         $log_dir = null;
TB 1119
1120         // per-user logging is activated
1121         if (self::$instance && self::$instance->config->get('per_user_logging', false) && self::$instance->get_user_id()) {
1122             $log_dir = self::$instance->get_user_log_dir();
1123             if (empty($log_dir))
1124                 return false;
1125         }
1126         else if (!empty($log['dir'])) {
1127             $log_dir = $log['dir'];
1128         }
1129         else if (self::$instance) {
1130             $log_dir = self::$instance->config->get('log_dir');
1131         }
0c2596 1132
A 1133         if (empty($log_dir)) {
9be2f4 1134             $log_dir = RCUBE_INSTALL_PATH . 'logs';
0c2596 1135         }
A 1136
1137         // try to open specific log file for writing
1138         $logfile = $log_dir.'/'.$name;
1139
1140         if ($fp = @fopen($logfile, 'a')) {
1141             fwrite($fp, $line);
1142             fflush($fp);
1143             fclose($fp);
1144             return true;
1145         }
1146
1147         trigger_error("Error writing to log file $logfile; Please check permissions", E_USER_WARNING);
1148         return false;
1149     }
1150
1151
1152     /**
1153      * Throw system error (and show error page).
1154      *
1155      * @param array Named parameters
1156      *      - code:    Error code (required)
1157      *      - type:    Error type [php|db|imap|javascript] (required)
1158      *      - message: Error message
b3e259 1159      *      - file:    File where error occurred
AM 1160      *      - line:    Line where error occurred
0c2596 1161      * @param boolean True to log the error
A 1162      * @param boolean Terminate script execution
1163      */
1164     public static function raise_error($arg = array(), $log = false, $terminate = false)
1165     {
76e499 1166         // handle PHP exceptions
TB 1167         if (is_object($arg) && is_a($arg, 'Exception')) {
a39fd4 1168             $arg = array(
76e499 1169                 'code' => $arg->getCode(),
TB 1170                 'line' => $arg->getLine(),
1171                 'file' => $arg->getFile(),
1172                 'message' => $arg->getMessage(),
1173             );
a39fd4 1174         }
f23ef1 1175         else if (is_string($arg)) {
0301d9 1176             $arg = array('message' => $arg);
f23ef1 1177         }
a39fd4 1178
AM 1179         if (empty($arg['code'])) {
1180             $arg['code'] = 500;
76e499 1181         }
TB 1182
0c2596 1183         // installer
A 1184         if (class_exists('rcube_install', false)) {
1185             $rci = rcube_install::get_instance();
1186             $rci->raise_error($arg);
1187             return;
1188         }
1189
f23ef1 1190         $cli = php_sapi_name() == 'cli';
AM 1191
0301d9 1192         if (($log || $terminate) && !$cli && $arg['message']) {
819315 1193             $arg['fatal'] = $terminate;
0c2596 1194             self::log_bug($arg);
A 1195         }
1196
f23ef1 1197         // terminate script
AM 1198         if ($terminate) {
1199             // display error page
1200             if (is_object(self::$instance->output)) {
1201                 self::$instance->output->raise_error($arg['code'], $arg['message']);
1202             }
1203             else if ($cli) {
1204                 fwrite(STDERR, 'ERROR: ' . $arg['message']);
1205             }
1206
1207             exit(1);
0c2596 1208         }
A 1209     }
1210
1211
1212     /**
1213      * Report error according to configured debug_level
1214      *
1215      * @param array Named parameters
1216      * @see self::raise_error()
1217      */
1218     public static function log_bug($arg_arr)
1219     {
0301d9 1220         $program = strtoupper(!empty($arg_arr['type']) ? $arg_arr['type'] : 'php');
0c2596 1221         $level   = self::get_instance()->config->get('debug_level');
A 1222
1223         // disable errors for ajax requests, write to log instead (#1487831)
1224         if (($level & 4) && !empty($_REQUEST['_remote'])) {
1225             $level = ($level ^ 4) | 1;
1226         }
1227
1228         // write error to local log file
819315 1229         if (($level & 1) || !empty($arg_arr['fatal'])) {
0c2596 1230             if ($_SERVER['REQUEST_METHOD'] == 'POST') {
A 1231                 $post_query = '?_task='.urlencode($_POST['_task']).'&_action='.urlencode($_POST['_action']);
1232             }
1233             else {
1234                 $post_query = '';
1235             }
1236
1237             $log_entry = sprintf("%s Error: %s%s (%s %s)",
1238                 $program,
1239                 $arg_arr['message'],
1240                 $arg_arr['file'] ? sprintf(' in %s on line %d', $arg_arr['file'], $arg_arr['line']) : '',
1241                 $_SERVER['REQUEST_METHOD'],
1242                 $_SERVER['REQUEST_URI'] . $post_query);
1243
1244             if (!self::write_log('errors', $log_entry)) {
1245                 // send error to PHPs error handler if write_log didn't succeed
f23ef1 1246                 trigger_error($arg_arr['message'], E_USER_WARNING);
0c2596 1247             }
A 1248         }
1249
1250         // report the bug to the global bug reporting system
1251         if ($level & 2) {
1252             // TODO: Send error via HTTP
1253         }
1254
1255         // show error if debug_mode is on
1256         if ($level & 4) {
1257             print "<b>$program Error";
1258
1259             if (!empty($arg_arr['file']) && !empty($arg_arr['line'])) {
1260                 print " in $arg_arr[file] ($arg_arr[line])";
1261             }
1262
1263             print ':</b>&nbsp;';
1264             print nl2br($arg_arr['message']);
1265             print '<br />';
1266             flush();
1267         }
1268     }
1269
1270
1271     /**
1272      * Returns current time (with microseconds).
1273      *
1274      * @return float Current time in seconds since the Unix
1275      */
1276     public static function timer()
1277     {
1278         return microtime(true);
1279     }
1280
1281
1282     /**
1283      * Logs time difference according to provided timer
1284      *
1285      * @param float  $timer  Timer (self::timer() result)
1286      * @param string $label  Log line prefix
1287      * @param string $dest   Log file name
1288      *
1289      * @see self::timer()
1290      */
1291     public static function print_timer($timer, $label = 'Timer', $dest = 'console')
1292     {
1293         static $print_count = 0;
1294
1295         $print_count++;
1296         $now  = self::timer();
1297         $diff = $now - $timer;
1298
1299         if (empty($label)) {
1300             $label = 'Timer '.$print_count;
1301         }
1302
1303         self::write_log($dest, sprintf("%s: %0.4f sec", $label, $diff));
1304     }
1305
1306
1307     /**
1308      * Getter for logged user ID.
1309      *
1310      * @return mixed User identifier
1311      */
1312     public function get_user_id()
1313     {
1314         if (is_object($this->user)) {
1315             return $this->user->ID;
1316         }
a2f896 1317         else if (isset($_SESSION['user_id'])) {
A 1318             return $_SESSION['user_id'];
1319         }
0c2596 1320
A 1321         return null;
1322     }
1323
1324
1325     /**
1326      * Getter for logged user name.
1327      *
1328      * @return string User name
1329      */
1330     public function get_user_name()
1331     {
1332         if (is_object($this->user)) {
1333             return $this->user->get_username();
1334         }
789e59 1335         else if (isset($_SESSION['username'])) {
AM 1336             return $_SESSION['username'];
1337         }
1338     }
0c2596 1339
789e59 1340
AM 1341     /**
1342      * Getter for logged user email (derived from user name not identity).
1343      *
1344      * @return string User email address
1345      */
1346     public function get_user_email()
1347     {
1348         if (is_object($this->user)) {
1349             return $this->user->get_username('mail');
1350         }
0c2596 1351     }
5b06e2 1352
AM 1353
1354     /**
1355      * Getter for logged user password.
1356      *
1357      * @return string User password
1358      */
1359     public function get_user_password()
1360     {
1361         if ($this->password) {
1362             return $this->password;
1363         }
1364         else if ($_SESSION['password']) {
1365             return $this->decrypt($_SESSION['password']);
1366         }
1367     }
a5b8ef 1368
3786a4 1369     /**
TB 1370      * Get the per-user log directory
1371      */
1372     protected function get_user_log_dir()
1373     {
1374         $log_dir = $this->config->get('log_dir', RCUBE_INSTALL_PATH . 'logs');
1375         $user_name = $this->get_user_name();
1376         $user_log_dir = $log_dir . '/' . $user_name;
1377
1378         return !empty($user_name) && is_writable($user_log_dir) ? $user_log_dir : false;
1379     }
a5b8ef 1380
AM 1381     /**
1382      * Getter for logged user language code.
1383      *
1384      * @return string User language code
1385      */
1386     public function get_user_language()
1387     {
1388         if (is_object($this->user)) {
1389             return $this->user->language;
1390         }
1391         else if (isset($_SESSION['language'])) {
1392             return $_SESSION['language'];
1393         }
1394     }
0b9a7b 1395
TB 1396     /**
1397      * Unique Message-ID generator.
1398      *
1399      * @return string Message-ID
1400      */
1401     public function gen_message_id()
1402     {
1403         $local_part  = md5(uniqid('rcube'.mt_rand(), true));
1404         $domain_part = $this->user->get_username('domain');
1405
1406         // Try to find FQDN, some spamfilters doesn't like 'localhost' (#1486924)
1407         if (!preg_match('/\.[a-z]+$/i', $domain_part)) {
1408             foreach (array($_SERVER['HTTP_HOST'], $_SERVER['SERVER_NAME']) as $host) {
1409                 $host = preg_replace('/:[0-9]+$/', '', $host);
1410                 if ($host && preg_match('/\.[a-z]+$/i', $host)) {
1411                     $domain_part = $host;
1412                 }
1413             }
1414         }
1415
1416         return sprintf('<%s@%s>', $local_part, $domain_part);
1417     }
1418
1419     /**
1420      * Send the given message using the configured method.
1421      *
1422      * @param object $message    Reference to Mail_MIME object
1423      * @param string $from       Sender address string
1424      * @param array  $mailto     Array of recipient address strings
1425      * @param array  $error      SMTP error array (reference)
1426      * @param string $body_file  Location of file with saved message body (reference),
1427      *                           used when delay_file_io is enabled
1428      * @param array  $options    SMTP options (e.g. DSN request)
1429      *
1430      * @return boolean Send status.
1431      */
1432     public function deliver_message(&$message, $from, $mailto, &$error, &$body_file = null, $options = null)
1433     {
1434         $plugin = $this->plugins->exec_hook('message_before_send', array(
1435             'message' => $message,
1436             'from'    => $from,
1437             'mailto'  => $mailto,
1438             'options' => $options,
1439         ));
1440
6efadf 1441         if ($plugin['abort']) {
8b5d16 1442             if (!empty($plugin['error'])) {
AM 1443                 $error = $plugin['error'];
1444             }
1445             if (!empty($plugin['body_file'])) {
1446                 $body_file = $plugin['body_file'];
1447             }
1448
6efadf 1449             return isset($plugin['result']) ? $plugin['result'] : false;
AM 1450         }
1451
0b9a7b 1452         $from    = $plugin['from'];
TB 1453         $mailto  = $plugin['mailto'];
1454         $options = $plugin['options'];
1455         $message = $plugin['message'];
1456         $headers = $message->headers();
1457
1458         // send thru SMTP server using custom SMTP library
1459         if ($this->config->get('smtp_server')) {
1460             // generate list of recipients
4446ae 1461             $a_recipients = (array) $mailto;
0b9a7b 1462
TB 1463             if (strlen($headers['Cc']))
1464                 $a_recipients[] = $headers['Cc'];
1465             if (strlen($headers['Bcc']))
1466                 $a_recipients[] = $headers['Bcc'];
1467
eb3182 1468             // remove Bcc header and get the whole head of the message as string
AM 1469             $smtp_headers = $this->message_head($message, array('Bcc'));
0b9a7b 1470
TB 1471             if ($message->getParam('delay_file_io')) {
1472                 // use common temp dir
1473                 $temp_dir = $this->config->get('temp_dir');
1474                 $body_file = tempnam($temp_dir, 'rcmMsg');
1475                 if (PEAR::isError($mime_result = $message->saveMessageBody($body_file))) {
1476                     self::raise_error(array('code' => 650, 'type' => 'php',
1477                         'file' => __FILE__, 'line' => __LINE__,
1478                         'message' => "Could not create message: ".$mime_result->getMessage()),
1479                         TRUE, FALSE);
1480                     return false;
1481                 }
1482                 $msg_body = fopen($body_file, 'r');
1483             }
1484             else {
1485                 $msg_body = $message->get();
1486             }
1487
1488             // send message
1489             if (!is_object($this->smtp)) {
1490                 $this->smtp_init(true);
1491             }
1492
1493             $sent     = $this->smtp->send_mail($from, $a_recipients, $smtp_headers, $msg_body, $options);
1494             $response = $this->smtp->get_response();
1495             $error    = $this->smtp->get_error();
1496
1497             // log error
1498             if (!$sent) {
1499                 self::raise_error(array('code' => 800, 'type' => 'smtp',
1500                     'line' => __LINE__, 'file' => __FILE__,
78f948 1501                     'message' => join("\n", $response)), true, false);
0b9a7b 1502             }
TB 1503         }
1504         // send mail using PHP's mail() function
1505         else {
eb3182 1506             // unset To,Subject headers because they will be added by the mail() function
AM 1507             $header_str = $this->message_head($message, array('To', 'Subject'));
0b9a7b 1508
TB 1509             // #1485779
1510             if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
eb3182 1511                 if (preg_match_all('/<([^@]+@[^>]+)>/', $headers['To'], $m)) {
AM 1512                     $headers['To'] = implode(', ', $m[1]);
0b9a7b 1513                 }
TB 1514             }
1515
1516             $msg_body = $message->get();
1517
1518             if (PEAR::isError($msg_body)) {
1519                 self::raise_error(array('code' => 650, 'type' => 'php',
1520                     'file' => __FILE__, 'line' => __LINE__,
1521                     'message' => "Could not create message: ".$msg_body->getMessage()),
1522                     TRUE, FALSE);
1523             }
1524             else {
1525                 $delim   = $this->config->header_delimiter();
eb3182 1526                 $to      = $headers['To'];
AM 1527                 $subject = $headers['Subject'];
0b9a7b 1528                 $header_str = rtrim($header_str);
TB 1529
1530                 if ($delim != "\r\n") {
1531                     $header_str = str_replace("\r\n", $delim, $header_str);
1532                     $msg_body   = str_replace("\r\n", $delim, $msg_body);
1533                     $to         = str_replace("\r\n", $delim, $to);
1534                     $subject    = str_replace("\r\n", $delim, $subject);
1535                 }
1536
39b905 1537                 if (filter_var(ini_get('safe_mode'), FILTER_VALIDATE_BOOLEAN))
0b9a7b 1538                     $sent = mail($to, $subject, $msg_body, $header_str);
TB 1539                 else
1540                     $sent = mail($to, $subject, $msg_body, $header_str, "-f$from");
1541             }
1542         }
1543
1544         if ($sent) {
1545             $this->plugins->exec_hook('message_sent', array('headers' => $headers, 'body' => $msg_body));
1546
1547             // remove MDN headers after sending
1548             unset($headers['Return-Receipt-To'], $headers['Disposition-Notification-To']);
1549
1550             if ($this->config->get('smtp_log')) {
4446ae 1551                 // get all recipient addresses
AM 1552                 if (is_array($mailto)) {
1553                     $mailto = implode(',', $mailto);
1554                 }
1555                 if ($headers['Cc']) {
1556                     $mailto .= ',' . $headers['Cc'];
1557                 }
1558                 if ($headers['Bcc']) {
1559                     $mailto .= ',' . $headers['Bcc'];
1560                 }
1561
1562                 $mailto = rcube_mime::decode_address_list($mailto, null, false, null, true);
1563
0b9a7b 1564                 self::write_log('sendmail', sprintf("User %s [%s]; Message for %s; %s",
TB 1565                     $this->user->get_username(),
4446ae 1566                     rcube_utils::remote_addr(),
AM 1567                     implode(', ', $mailto),
0b9a7b 1568                     !empty($response) ? join('; ', $response) : ''));
TB 1569             }
1570         }
aef6ed 1571         else {
TB 1572             // allow plugins to catch sending errors with the same parameters as in 'message_before_send'
1573             $this->plugins->exec_hook('message_send_error', $plugin + array('error' => $error));
1574         }
0b9a7b 1575
TB 1576         if (is_resource($msg_body)) {
1577             fclose($msg_body);
1578         }
1579
eb3182 1580         $message->headers($headers, true);
0b9a7b 1581
TB 1582         return $sent;
1583     }
1584
eb3182 1585     /**
AM 1586      * Return message headers as a string
1587      */
1588     protected function message_head($message, $unset = array())
1589     {
1590         // Mail_mime >= 1.9.0
1591         if (method_exists($message, 'isMultipart')) {
1592             foreach ($unset as $header) {
1593                 $headers[$header] = null;
1594             }
1595         }
1596         else {
1597             $headers = $message->headers();
1598             foreach ($unset as $header) {
1599                 unset($headers[$header]);
1600             }
1601             $message->_headers = array();
1602         }
1603
1604         return $message->txtHeaders($headers, true);
1605     }
0c2596 1606 }
A 1607
1608
1609 /**
1610  * Lightweight plugin API class serving as a dummy if plugins are not enabled
1611  *
a07224 1612  * @package Framework
TB 1613  * @subpackage Core
0c2596 1614  */
A 1615 class rcube_dummy_plugin_api
1616 {
1617     /**
1618      * Triggers a plugin hook.
1619      * @see rcube_plugin_api::exec_hook()
1620      */
1621     public function exec_hook($hook, $args = array())
1622     {
1623         return $args;
1624     }
1625 }