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