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