Aleksander Machniak
2016-04-12 a0f38f5fd87ca6e5a5cab916e48c15877d52b3b1
commit | author | age
197601 1 <?php
T 2
a95874 3 /**
197601 4  +-----------------------------------------------------------------------+
T 5  | program/include/rcmail.php                                            |
6  |                                                                       |
e019f2 7  | This file is part of the Roundcube Webmail client                     |
ce2019 8  | Copyright (C) 2008-2014, The Roundcube Dev Team                       |
TB 9  | Copyright (C) 2011-2014, Kolab Systems AG                             |
7fe381 10  |                                                                       |
T 11  | Licensed under the GNU General Public License version 3 or            |
12  | any later version with exceptions for skins & plugins.                |
13  | See the README file for a full license statement.                     |
197601 14  |                                                                       |
T 15  | PURPOSE:                                                              |
16  |   Application class providing core functions and holding              |
17  |   instances of all 'global' objects like db- and imap-connections     |
18  +-----------------------------------------------------------------------+
19  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
1aceb9 20  | Author: Aleksander Machniak <alec@alec.pl>                            |
197601 21  +-----------------------------------------------------------------------+
T 22 */
23
24 /**
e019f2 25  * Application class of Roundcube Webmail
197601 26  * implemented as singleton
T 27  *
9ba496 28  * @package Webmail
197601 29  */
0c2596 30 class rcmail extends rcube
197601 31 {
0301d9 32     /**
AM 33      * Main tasks.
34      *
35      * @var array
36      */
37     static public $main_tasks = array('mail','settings','addressbook','login','logout','utils','dummy');
5c461b 38
0301d9 39     /**
AM 40      * Current task.
41      *
42      * @var string
43      */
44     public $task;
5c461b 45
0301d9 46     /**
AM 47      * Current action.
48      *
49      * @var string
50      */
51     public $action    = '';
52     public $comm_path = './';
53     public $filename  = '';
677e1f 54
0301d9 55     private $address_books = array();
AM 56     private $action_map    = array();
677e1f 57
A 58
0301d9 59     const ERROR_STORAGE          = -2;
AM 60     const ERROR_INVALID_REQUEST  = 1;
61     const ERROR_INVALID_HOST     = 2;
62     const ERROR_COOKIES_DISABLED = 3;
a15d87 63     const ERROR_RATE_LIMIT       = 4;
7c8fd8 64
AM 65
0301d9 66     /**
AM 67      * This implements the 'singleton' design pattern
68      *
1b39d9 69      * @param integer $mode Ignored rcube::get_instance() argument
AM 70      * @param string  $env  Environment name to run (e.g. live, dev, test)
0301d9 71      *
AM 72      * @return rcmail The one and only instance
73      */
1b39d9 74     static function get_instance($mode = 0, $env = '')
0301d9 75     {
AM 76         if (!self::$instance || !is_a(self::$instance, 'rcmail')) {
77             self::$instance = new rcmail($env);
78             // init AFTER object was linked with self::$instance
79             self::$instance->startup();
65dff8 80         }
0301d9 81
AM 82         return self::$instance;
5ed119 83     }
A 84
0301d9 85     /**
AM 86      * Initial startup function
87      * to register session, create database and imap connections
88      */
89     protected function startup()
90     {
91         $this->init(self::INIT_WITH_DB | self::INIT_WITH_PLUGINS);
ae80b5 92
0301d9 93         // set filename if not index.php
AM 94         if (($basename = basename($_SERVER['SCRIPT_FILENAME'])) && $basename != 'index.php') {
95             $this->filename = $basename;
08b7b6 96         }
3704b7 97
de89d4 98         // load all configured plugins
1b39d9 99         $plugins          = (array) $this->config->get('plugins', array());
AM 100         $required_plugins = array('filesystem_attachments', 'jqueryui');
101         $this->plugins->load_plugins($plugins, $required_plugins);
de89d4 102
0301d9 103         // start session
AM 104         $this->session_init();
3704b7 105
0301d9 106         // create user object
AM 107         $this->set_user(new rcube_user($_SESSION['user_id']));
8c263e 108
0301d9 109         // set task and action properties
AM 110         $this->set_task(rcube_utils::get_input_value('_task', rcube_utils::INPUT_GPC));
111         $this->action = asciiwords(rcube_utils::get_input_value('_action', rcube_utils::INPUT_GPC));
b62a0d 112
0301d9 113         // reset some session parameters when changing task
AM 114         if ($this->task != 'utils') {
115             // we reset list page when switching to another task
71dbee 116             // but only to the main task interface - empty action (#1489076, #1490116)
0301d9 117             // this will prevent from unintentional page reset on cross-task requests
AM 118             if ($this->session && $_SESSION['task'] != $this->task && empty($this->action)) {
119                 $this->session->remove('page');
9c41ba 120
71dbee 121                 // set current task to session
AM 122                 $_SESSION['task'] = $this->task;
123             }
197601 124         }
0301d9 125
dcc446 126         // init output class (not in CLI mode)
AM 127         if (!empty($_REQUEST['_remote'])) {
0301d9 128             $GLOBALS['OUTPUT'] = $this->json_init();
dcc446 129         }
AM 130         else if ($_SERVER['REMOTE_ADDR']) {
0301d9 131             $GLOBALS['OUTPUT'] = $this->load_gui(!empty($_REQUEST['_framed']));
dcc446 132         }
0301d9 133
de89d4 134         // run init method on all the plugins
0301d9 135         $this->plugins->init($this, $this->task);
7c8fd8 136     }
AM 137
0301d9 138     /**
AM 139      * Setter for application task
140      *
141      * @param string Task to set
142      */
143     public function set_task($task)
144     {
145         $task = asciiwords($task, true);
197601 146
0301d9 147         if ($this->user && $this->user->ID)
AM 148             $task = !$task ? 'mail' : $task;
899211 149         else if (php_sapi_name() == 'cli')
TB 150             $task = 'cli';
0301d9 151         else
AM 152             $task = 'login';
b62a0d 153
0301d9 154         $this->task      = $task;
AM 155         $this->comm_path = $this->url(array('task' => $this->task));
197601 156
e35eab 157         if (!empty($_REQUEST['_framed'])) {
AM 158             $this->comm_path .= '&_framed=1';
159         }
160
0301d9 161         if ($this->output) {
AM 162             $this->output->set_env('task', $this->task);
e35eab 163             $this->output->set_env('comm_path', $this->comm_path);
96f59c 164         }
0301d9 165     }
AM 166
167     /**
168      * Setter for system user object
169      *
170      * @param rcube_user Current user instance
171      */
172     public function set_user($user)
173     {
ce2019 174         parent::set_user($user);
0301d9 175
AM 176         $lang = $this->language_prop($this->config->get('language', $_SESSION['language']));
177         $_SESSION['language'] = $this->user->language = $lang;
178
179         // set localization
180         setlocale(LC_ALL, $lang . '.utf8', $lang . '.UTF-8', 'en_US.utf8', 'en_US.UTF-8');
181
3c29c7 182         // Workaround for http://bugs.php.net/bug.php?id=18556
AM 183         // Also strtoupper/strtolower and other methods are locale-aware
184         // for these locales it is problematic (#1490519)
185         if (in_array($lang, array('tr_TR', 'ku', 'az_AZ'))) {
e2f605 186             setlocale(LC_CTYPE, 'en_US.utf8', 'en_US.UTF-8', 'C');
0301d9 187         }
197601 188     }
T 189
0301d9 190     /**
AM 191      * Return instance of the internal address book class
192      *
193      * @param string  Address book identifier (-1 for default addressbook)
194      * @param boolean True if the address book needs to be writeable
195      *
196      * @return rcube_contacts Address book object
197      */
198     public function get_address_book($id, $writeable = false)
199     {
200         $contacts    = null;
201         $ldap_config = (array)$this->config->get('ldap_public');
202
203         // 'sql' is the alias for '0' used by autocomplete
204         if ($id == 'sql')
205             $id = '0';
206         else if ($id == -1) {
207             $id = $this->config->get('default_addressbook');
208             $default = true;
209         }
210
211         // use existing instance
212         if (isset($this->address_books[$id]) && ($this->address_books[$id] instanceof rcube_addressbook)) {
213             $contacts = $this->address_books[$id];
214         }
215         else if ($id && $ldap_config[$id]) {
216             $domain   = $this->config->mail_domain($_SESSION['storage_host']);
217             $contacts = new rcube_ldap($ldap_config[$id], $this->config->get('ldap_debug'), $domain);
218         }
219         else if ($id === '0') {
220             $contacts = new rcube_contacts($this->db, $this->get_user_id());
221         }
222         else {
223             $plugin = $this->plugins->exec_hook('addressbook_get', array('id' => $id, 'writeable' => $writeable));
224
225             // plugin returned instance of a rcube_addressbook
226             if ($plugin['instance'] instanceof rcube_addressbook) {
227                 $contacts = $plugin['instance'];
228             }
229         }
230
231         // when user requested default writeable addressbook
232         // we need to check if default is writeable, if not we
233         // will return first writeable book (if any exist)
234         if ($contacts && $default && $contacts->readonly && $writeable) {
235             $contacts = null;
236         }
237
238         // Get first addressbook from the list if configured default doesn't exist
239         // This can happen when user deleted the addressbook (e.g. Kolab folder)
240         if (!$contacts && (!$id || $default)) {
241             $source = reset($this->get_address_sources($writeable, !$default));
242             if (!empty($source)) {
243                 $contacts = $this->get_address_book($source['id']);
244                 if ($contacts) {
245                     $id = $source['id'];
246                 }
247             }
248         }
249
250         if (!$contacts) {
251             // there's no default, just return
252             if ($default) {
253                 return null;
254             }
255
256             self::raise_error(array(
257                     'code'    => 700,
258                     'file'    => __FILE__,
259                     'line'    => __LINE__,
260                     'message' => "Addressbook source ($id) not found!"
261                 ),
262                 true, true);
263         }
264
265         // add to the 'books' array for shutdown function
266         $this->address_books[$id] = $contacts;
267
268         if ($writeable && $contacts->readonly) {
269             return null;
270         }
271
272         // set configured sort order
273         if ($sort_col = $this->config->get('addressbook_sort_col')) {
274             $contacts->set_sort_order($sort_col);
275         }
276
277         return $contacts;
df95e7 278     }
AM 279
0301d9 280     /**
AM 281      * Return identifier of the address book object
282      *
283      * @param rcube_addressbook Addressbook source object
284      *
285      * @return string Source identifier
286      */
287     public function get_address_book_id($object)
288     {
289         foreach ($this->address_books as $index => $book) {
290             if ($book === $object) {
291                 return $index;
292             }
293         }
e17553 294     }
A 295
0301d9 296     /**
AM 297      * Return address books list
298      *
299      * @param boolean True if the address book needs to be writeable
300      * @param boolean True if the address book needs to be not hidden
301      *
302      * @return array  Address books array
303      */
304     public function get_address_sources($writeable = false, $skip_hidden = false)
305     {
306         $abook_type   = (string) $this->config->get('address_book_type');
307         $ldap_config  = (array) $this->config->get('ldap_public');
308         $autocomplete = (array) $this->config->get('autocomplete_addressbooks');
309         $list         = array();
310
311         // We are using the DB address book or a plugin address book
312         if (!empty($abook_type) && strtolower($abook_type) != 'ldap') {
313             if (!isset($this->address_books['0'])) {
314                 $this->address_books['0'] = new rcube_contacts($this->db, $this->get_user_id());
315             }
316
317             $list['0'] = array(
318                 'id'       => '0',
319                 'name'     => $this->gettext('personaladrbook'),
320                 'groups'   => $this->address_books['0']->groups,
321                 'readonly' => $this->address_books['0']->readonly,
322                 'undelete' => $this->address_books['0']->undelete && $this->config->get('undo_timeout'),
323                 'autocomplete' => in_array('sql', $autocomplete),
324             );
325         }
326
327         if (!empty($ldap_config)) {
328             foreach ($ldap_config as $id => $prop) {
329                 // handle misconfiguration
330                 if (empty($prop) || !is_array($prop)) {
331                     continue;
332                 }
333
334                 $list[$id] = array(
335                     'id'       => $id,
336                     'name'     => html::quote($prop['name']),
337                     'groups'   => !empty($prop['groups']) || !empty($prop['group_filters']),
338                     'readonly' => !$prop['writable'],
339                     'hidden'   => $prop['hidden'],
340                     'autocomplete' => in_array($id, $autocomplete)
341                 );
342             }
343         }
344
345         $plugin = $this->plugins->exec_hook('addressbooks_list', array('sources' => $list));
346         $list   = $plugin['sources'];
347
348         foreach ($list as $idx => $item) {
349             // register source for shutdown function
350             if (!is_object($this->address_books[$item['id']])) {
351                 $this->address_books[$item['id']] = $item;
352             }
353             // remove from list if not writeable as requested
354             if ($writeable && $item['readonly']) {
355                 unset($list[$idx]);
356             }
357             // remove from list if hidden as requested
358             else if ($skip_hidden && $item['hidden']) {
359                 unset($list[$idx]);
360             }
361         }
362
363         return $list;
e17553 364     }
197601 365
0301d9 366     /**
AM 367      * Getter for compose responses.
368      * These are stored in local config and user preferences.
369      *
370      * @param boolean True to sort the list alphabetically
371      * @param boolean True if only this user's responses shall be listed
372      *
373      * @return array List of the current user's stored responses
374      */
375     public function get_compose_responses($sorted = false, $user_only = false)
376     {
377         $responses = array();
f1adbf 378
0301d9 379         if (!$user_only) {
AM 380             foreach ($this->config->get('compose_responses_static', array()) as $response) {
381                 if (empty($response['key'])) {
382                     $response['key']    = substr(md5($response['name']), 0, 16);
383                 }
384
385                 $response['static'] = true;
386                 $response['class']  = 'readonly';
387
388                 $k = $sorted ? '0000-' . strtolower($response['name']) : $response['key'];
389                 $responses[$k] = $response;
390             }
391         }
392
393         foreach ($this->config->get('compose_responses', array()) as $response) {
394             if (empty($response['key'])) {
395                 $response['key'] = substr(md5($response['name']), 0, 16);
396             }
397
398             $k = $sorted ? strtolower($response['name']) : $response['key'];
399             $responses[$k] = $response;
400         }
401
402         // sort list by name
403         if ($sorted) {
404             ksort($responses, SORT_LOCALE_STRING);
405         }
406
407         return array_values($responses);
c72325 408     }
197601 409
0301d9 410     /**
AM 411      * Init output object for GUI and add common scripts.
412      * This will instantiate a rcmail_output_html object and set
413      * environment vars according to the current session and configuration
414      *
415      * @param boolean True if this request is loaded in a (i)frame
416      *
417      * @return rcube_output Reference to HTML output object
418      */
419     public function load_gui($framed = false)
420     {
421         // init output page
422         if (!($this->output instanceof rcmail_output_html)) {
423             $this->output = new rcmail_output_html($this->task, $framed);
424         }
48bc52 425
0301d9 426         // set refresh interval
AM 427         $this->output->set_env('refresh_interval', $this->config->get('refresh_interval', 0));
428         $this->output->set_env('session_lifetime', $this->config->get('session_lifetime', 0) * 60);
429
430         if ($framed) {
431             $this->comm_path .= '&_framed=1';
432             $this->output->set_env('framed', true);
433         }
434
435         $this->output->set_env('task', $this->task);
436         $this->output->set_env('action', $this->action);
437         $this->output->set_env('comm_path', $this->comm_path);
438         $this->output->set_charset(RCUBE_CHARSET);
439
440         if ($this->user && $this->user->ID) {
441             $this->output->set_env('user_id', $this->user->get_hash());
442         }
443
d47833 444         // set compose mode for all tasks (message compose step can be triggered from everywhere)
TB 445         $this->output->set_env('compose_extwin', $this->config->get('compose_extwin',false));
446
0301d9 447         // add some basic labels to client
b408e0 448         $this->output->add_label('loading', 'servererror', 'connerror', 'requesttimedout',
0b36d1 449             'refreshing', 'windowopenerror', 'uploadingmany');
0301d9 450
AM 451         return $this->output;
c321a9 452     }
197601 453
0301d9 454     /**
AM 455      * Create an output object for JSON responses
456      *
457      * @return rcube_output Reference to JSON output object
458      */
459     public function json_init()
460     {
461         if (!($this->output instanceof rcmail_output_json)) {
462             $this->output = new rcmail_output_json($this->task);
463         }
464
465         return $this->output;
197601 466     }
T 467
0301d9 468     /**
AM 469      * Create session object and start the session.
470      */
471     public function session_init()
472     {
473         parent::session_init();
f53750 474
0301d9 475         // set initial session vars
AM 476         if (!$_SESSION['user_id']) {
477             $_SESSION['temp'] = true;
478         }
f53750 479
0301d9 480         // restore skin selection after logout
AM 481         if ($_SESSION['temp'] && !empty($_SESSION['skin'])) {
482             $this->config->set('skin', $_SESSION['skin']);
483         }
197601 484     }
T 485
0301d9 486     /**
AM 487      * Perfom login to the mail server and to the webmail service.
488      * This will also create a new user entry if auto_create_user is configured.
489      *
490      * @param string Mail storage (IMAP) user name
491      * @param string Mail storage (IMAP) password
492      * @param string Mail storage (IMAP) host
493      * @param bool   Enables cookie check
494      *
495      * @return boolean True on success, False on failure
496      */
a5c03d 497     function login($username, $password, $host = null, $cookiecheck = false)
0301d9 498     {
AM 499         $this->login_error = null;
197601 500
0301d9 501         if (empty($username)) {
AM 502             return false;
503         }
504
505         if ($cookiecheck && empty($_COOKIE)) {
506             $this->login_error = self::ERROR_COOKIES_DISABLED;
507             return false;
508         }
509
a5c03d 510         $username_filter = $this->config->get('login_username_filter');
AM 511         $username_maxlen = $this->config->get('login_username_maxlen', 1024);
512         $password_maxlen = $this->config->get('login_password_maxlen', 1024);
3509a8 513         $default_host    = $this->config->get('default_host');
AM 514         $default_port    = $this->config->get('default_port');
515         $username_domain = $this->config->get('username_domain');
516         $login_lc        = $this->config->get('login_lc', 2);
a5c03d 517
AM 518         // check input for security (#1490500)
519         if (($username_maxlen && strlen($username) > $username_maxlen)
520             || ($username_filter && !preg_match($username_filter, $username))
521             || ($password_maxlen && strlen($password) > $password_maxlen)
522         ) {
523             $this->login_error = self::ERROR_INVALID_REQUEST;
524             return false;
525         }
0301d9 526
204977 527         // host is validated in rcmail::autoselect_host(), so here
AM 528         // we'll only handle unset host (if possible)
529         if (!$host && !empty($default_host)) {
530             if (is_array($default_host)) {
531                 list($key, $val) = each($default_host);
532                 $host = is_numeric($key) ? $val : $key;
533             }
534             else {
535                 $host = $default_host;
0301d9 536             }
AM 537
204977 538             $host = rcube_utils::parse_host($host);
0301d9 539         }
AM 540
541         if (!$host) {
542             $this->login_error = self::ERROR_INVALID_HOST;
543             return false;
544         }
545
546         // parse $host URL
547         $a_host = parse_url($host);
548         if ($a_host['host']) {
549             $host = $a_host['host'];
550             $ssl  = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? $a_host['scheme'] : null;
551
552             if (!empty($a_host['port']))
553                 $port = $a_host['port'];
3509a8 554             else if ($ssl && $ssl != 'tls' && (!$default_port || $default_port == 143))
0301d9 555                 $port = 993;
AM 556         }
557
558         if (!$port) {
3509a8 559             $port = $default_port;
0301d9 560         }
AM 561
562         // Check if we need to add/force domain to username
3509a8 563         if (!empty($username_domain)) {
AM 564             $domain = is_array($username_domain) ? $username_domain[$host] : $username_domain;
0301d9 565
AM 566             if ($domain = rcube_utils::parse_host((string)$domain, $host)) {
567                 $pos = strpos($username, '@');
568
569                 // force configured domains
3509a8 570                 if ($pos !== false && $this->config->get('username_domain_forced')) {
0301d9 571                     $username = substr($username, 0, $pos) . '@' . $domain;
AM 572                 }
573                 // just add domain if not specified
574                 else if ($pos === false) {
575                     $username .= '@' . $domain;
576                 }
577             }
578         }
579
580         // Convert username to lowercase. If storage backend
581         // is case-insensitive we need to store always the same username (#1487113)
3509a8 582         if ($login_lc) {
AM 583             if ($login_lc == 2 || $login_lc === true) {
0301d9 584                 $username = mb_strtolower($username);
AM 585             }
586             else if (strpos($username, '@')) {
587                 // lowercase domain name
588                 list($local, $domain) = explode('@', $username);
589                 $username = $local . '@' . mb_strtolower($domain);
590             }
591         }
592
593         // try to resolve email address from virtuser table
594         if (strpos($username, '@') && ($virtuser = rcube_user::email2user($username))) {
595             $username = $virtuser;
596         }
597
598         // Here we need IDNA ASCII
599         // Only rcube_contacts class is using domain names in Unicode
600         $host     = rcube_utils::idn_to_ascii($host);
601         $username = rcube_utils::idn_to_ascii($username);
602
603         // user already registered -> overwrite username
604         if ($user = rcube_user::query($username, $host)) {
605             $username = $user->data['username'];
a15d87 606
AM 607             // Brute-force prevention
608             if ($user->is_locked()) {
609                 $this->login_error = self::ERROR_RATE_LIMIT;
610                 return false;
611             }
0301d9 612         }
AM 613
614         $storage = $this->get_storage();
615
616         // try to log in
a5c03d 617         if (!$storage->connect($host, $username, $password, $port, $ssl)) {
a15d87 618             if ($user) {
AM 619                 $user->failed_login();
620             }
621
c1bbf0 622             // Wait a second to slow down brute-force attacks (#1490549)
AM 623             sleep(1);
0301d9 624             return false;
AM 625         }
626
627         // user already registered -> update user's record
628         if (is_object($user)) {
629             // update last login timestamp
630             $user->touch();
631         }
632         // create new system user
3509a8 633         else if ($this->config->get('auto_create_user')) {
0301d9 634             if ($created = rcube_user::create($username, $host)) {
AM 635                 $user = $created;
636             }
637             else {
638                 self::raise_error(array(
639                         'code'    => 620,
640                         'file'    => __FILE__,
641                         'line'    => __LINE__,
642                         'message' => "Failed to create a user record. Maybe aborted by a plugin?"
643                     ),
644                     true, false);
645             }
646         }
647         else {
648             self::raise_error(array(
649                     'code'    => 621,
650                     'file'    => __FILE__,
651                     'line'    => __LINE__,
652                     'message' => "Access denied for new user $username. 'auto_create_user' is disabled"
653                 ),
654                 true, false);
655         }
656
657         // login succeeded
658         if (is_object($user) && $user->ID) {
659             // Configure environment
660             $this->set_user($user);
661             $this->set_storage_prop();
662
663             // set session vars
664             $_SESSION['user_id']      = $user->ID;
665             $_SESSION['username']     = $user->data['username'];
666             $_SESSION['storage_host'] = $host;
667             $_SESSION['storage_port'] = $port;
668             $_SESSION['storage_ssl']  = $ssl;
a5c03d 669             $_SESSION['password']     = $this->encrypt($password);
0301d9 670             $_SESSION['login_time']   = time();
AM 671
672             if (isset($_REQUEST['_timezone']) && $_REQUEST['_timezone'] != '_default_') {
673                 $_SESSION['timezone'] = rcube_utils::get_input_value('_timezone', rcube_utils::INPUT_GPC);
674             }
675
4da065 676             // fix some old settings according to namespace prefix
AM 677             $this->fix_namespace_settings($user);
678
dc0b50 679             // set/create special folders
AM 680             $this->set_special_folders();
4da065 681
AM 682             // clear all mailboxes related cache(s)
0301d9 683             $storage->clear_cache('mailboxes', true);
AM 684
685             return true;
686         }
687
688         return false;
689     }
197601 690
7c8fd8 691     /**
AM 692      * Returns error code of last login operation
693      *
694      * @return int Error code
695      */
696     public function login_error()
697     {
698         if ($this->login_error) {
699             return $this->login_error;
700         }
701
702         if ($this->storage && $this->storage->get_error_code() < -1) {
703             return self::ERROR_STORAGE;
704         }
705     }
706
0301d9 707     /**
AM 708      * Auto-select IMAP host based on the posted login information
709      *
710      * @return string Selected IMAP host
711      */
712     public function autoselect_host()
713     {
714         $default_host = $this->config->get('default_host');
715         $host         = null;
7c8fd8 716
0301d9 717         if (is_array($default_host)) {
AM 718             $post_host = rcube_utils::get_input_value('_host', rcube_utils::INPUT_POST);
719             $post_user = rcube_utils::get_input_value('_user', rcube_utils::INPUT_POST);
b62a0d 720
0301d9 721             list(, $domain) = explode('@', $post_user);
45dd7c 722
0301d9 723             // direct match in default_host array
AM 724             if ($default_host[$post_host] || in_array($post_host, array_values($default_host))) {
725                 $host = $post_host;
726             }
727             // try to select host by mail domain
728             else if (!empty($domain)) {
729                 foreach ($default_host as $storage_host => $mail_domains) {
730                     if (is_array($mail_domains) && in_array_nocase($domain, $mail_domains)) {
731                         $host = $storage_host;
732                         break;
733                     }
734                     else if (stripos($storage_host, $domain) !== false || stripos(strval($mail_domains), $domain) !== false) {
735                         $host = is_numeric($storage_host) ? $mail_domains : $storage_host;
736                         break;
737                     }
738                 }
739             }
b62a0d 740
0301d9 741             // take the first entry if $host is still not set
AM 742             if (empty($host)) {
743                 list($key, $val) = each($default_host);
744                 $host = is_numeric($key) ? $val : $key;
745             }
1854c4 746         }
0301d9 747         else if (empty($default_host)) {
AM 748             $host = rcube_utils::get_input_value('_host', rcube_utils::INPUT_POST);
d08333 749         }
0301d9 750         else {
AM 751             $host = rcube_utils::parse_host($default_host);
d08333 752         }
0301d9 753
AM 754         return $host;
d08333 755     }
A 756
0301d9 757     /**
AM 758      * Destroy session data and remove cookie
759      */
760     public function kill_session()
761     {
762         $this->plugins->exec_hook('session_destroy');
763
764         $this->session->kill();
765         $_SESSION = array('language' => $this->user->language, 'temp' => true, 'skin' => $this->config->get('skin'));
766         $this->user->reset();
767     }
768
769     /**
770      * Do server side actions on logout
771      */
772     public function logout_actions()
773     {
6d5a1b 774         $storage        = $this->get_storage();
AM 775         $logout_expunge = $this->config->get('logout_expunge');
776         $logout_purge   = $this->config->get('logout_purge');
777         $trash_mbox     = $this->config->get('trash_mbox');
0301d9 778
6d5a1b 779         if ($logout_purge && !empty($trash_mbox)) {
AM 780             $storage->clear_folder($trash_mbox);
d08333 781         }
A 782
6d5a1b 783         if ($logout_expunge) {
0301d9 784             $storage->expunge_folder('INBOX');
d08333 785         }
A 786
0301d9 787         // Try to save unsaved user preferences
AM 788         if (!empty($_SESSION['preferences'])) {
789             $this->user->save_prefs(unserialize($_SESSION['preferences']));
d08333 790         }
A 791     }
792
0301d9 793     /**
AM 794      * Build a valid URL to this instance of Roundcube
795      *
06fdaf 796      * @param mixed   Either a string with the action or url parameters as key-value pairs
TB 797      * @param boolean Build an URL absolute to document root
798      * @param boolean Create fully qualified URL including http(s):// and hostname
681ba6 799      * @param bool    Return absolute URL in secure location
0301d9 800      *
AM 801      * @return string Valid application URL
802      */
681ba6 803     public function url($p, $absolute = false, $full = false, $secure = false)
0301d9 804     {
AM 805         if (!is_array($p)) {
806             if (strpos($p, 'http') === 0) {
807                 return $p;
808             }
809
810             $p = array('_action' => @func_get_arg(0));
811         }
812
06fdaf 813         $pre = array();
TB 814         $task = $p['_task'] ?: ($p['task'] ?: $this->task);
815         $pre['_task'] = $task;
816         unset($p['task'], $p['_task']);
0301d9 817
06fdaf 818         $url  = $this->filename;
0301d9 819         $delm = '?';
AM 820
06fdaf 821         foreach (array_merge($pre, $p) as $key => $val) {
0301d9 822             if ($val !== '' && $val !== null) {
AM 823                 $par  = $key[0] == '_' ? $key : '_'.$key;
824                 $url .= $delm.urlencode($par).'='.urlencode($val);
825                 $delm = '&';
826             }
827         }
828
681ba6 829         $base_path = strval($_SERVER['REDIRECT_SCRIPT_URL'] ?: $_SERVER['SCRIPT_NAME']);
AM 830         $base_path = preg_replace('![^/]+$!', '', $base_path);
831
832         if ($secure && ($token = $this->get_secure_url_token(true))) {
833             // add token to the url
834             $url = $token . '/' . $url;
835
836             // remove old token from the path
837             $base_path = rtrim($base_path, '/');
260869 838             $base_path = preg_replace('/\/[a-zA-Z0-9]{' . strlen($token) . '}$/', '', $base_path);
681ba6 839
AM 840             // this need to be full url to make redirects work
841             $absolute = true;
842         }
4a4088 843         else if ($secure && ($token = $this->get_request_token()))
TB 844             $url .= $delm . '_token=' . urlencode($token);
681ba6 845
06fdaf 846         if ($absolute || $full) {
TB 847             // add base path to this Roundcube installation
848             if ($base_path == '') $base_path = '/';
5f5812 849             $prefix = $base_path;
AM 850
851             // prepend protocol://hostname:port
852             if ($full) {
853                 $prefix = rcube_utils::resolve_url($prefix);
854             }
855
856             $prefix = rtrim($prefix, '/') . '/';
06fdaf 857         }
TB 858         else {
859             $prefix = './';
860         }
861
862         return $prefix . $url;
0301d9 863     }
AM 864
865     /**
866      * Function to be executed in script shutdown
867      */
868     public function shutdown()
869     {
870         parent::shutdown();
871
872         foreach ($this->address_books as $book) {
873             if (is_object($book) && is_a($book, 'rcube_addressbook'))
874                 $book->close();
875         }
876
877         // write performance stats to logs/console
48e92f 878         if ($this->config->get('devel_mode') || $this->config->get('performance_stats')) {
70c0d2 879             // make sure logged numbers use unified format
AM 880             setlocale(LC_NUMERIC, 'en_US.utf8', 'en_US.UTF-8', 'en_US', 'C');
881
0301d9 882             if (function_exists('memory_get_usage'))
AM 883                 $mem = $this->show_bytes(memory_get_usage());
884             if (function_exists('memory_get_peak_usage'))
885                 $mem .= '/'.$this->show_bytes(memory_get_peak_usage());
886
887             $log = $this->task . ($this->action ? '/'.$this->action : '') . ($mem ? " [$mem]" : '');
888
889             if (defined('RCMAIL_START'))
890                 self::print_timer(RCMAIL_START, $log);
891             else
892                 self::console($log);
893         }
894     }
895
896     /**
681ba6 897      * CSRF attack prevention code
AM 898      *
899      * @param int Request mode
900      */
901     public function request_security_check($mode = rcube_utils::INPUT_POST)
902     {
903         // check request token
904         if (!$this->check_request($mode)) {
905             self::raise_error(array(
906                 'code' => 403, 'type' => 'php',
907                 'message' => "Request security check failed"), false, true);
908         }
909
910         // check referer if configured
911         if ($this->config->get('referer_check') && !rcube_utils::check_referer()) {
912             self::raise_error(array(
913                 'code' => 403, 'type' => 'php',
914                 'message' => "Referer check failed"), true, true);
915         }
916     }
917
918     /**
0301d9 919      * Registers action aliases for current task
AM 920      *
921      * @param array $map Alias-to-filename hash array
922      */
923     public function register_action_map($map)
924     {
925         if (is_array($map)) {
926             foreach ($map as $idx => $val) {
927                 $this->action_map[$idx] = $val;
928             }
929         }
930     }
931
932     /**
933      * Returns current action filename
934      *
935      * @param array $map Alias-to-filename hash array
936      */
937     public function get_action_file()
938     {
939         if (!empty($this->action_map[$this->action])) {
940             return $this->action_map[$this->action];
941         }
942
943         return strtr($this->action, '-', '_') . '.inc';
944     }
945
946     /**
947      * Fixes some user preferences according to namespace handling change.
948      * Old Roundcube versions were using folder names with removed namespace prefix.
949      * Now we need to add the prefix on servers where personal namespace has prefix.
950      *
951      * @param rcube_user $user User object
952      */
953     private function fix_namespace_settings($user)
954     {
955         $prefix     = $this->storage->get_namespace('prefix');
956         $prefix_len = strlen($prefix);
957
6d5a1b 958         if (!$prefix_len) {
0301d9 959             return;
6d5a1b 960         }
0301d9 961
6d5a1b 962         if ($this->config->get('namespace_fixed')) {
0301d9 963             return;
6d5a1b 964         }
AM 965
966         $prefs = array();
0301d9 967
AM 968         // Build namespace prefix regexp
969         $ns     = $this->storage->get_namespace();
970         $regexp = array();
971
972         foreach ($ns as $entry) {
973             if (!empty($entry)) {
974                 foreach ($entry as $item) {
975                     if (strlen($item[0])) {
976                         $regexp[] = preg_quote($item[0], '/');
977                     }
978                 }
979             }
980         }
981         $regexp = '/^('. implode('|', $regexp).')/';
982
983         // Fix preferences
984         $opts = array('drafts_mbox', 'junk_mbox', 'sent_mbox', 'trash_mbox', 'archive_mbox');
985         foreach ($opts as $opt) {
6d5a1b 986             if ($value = $this->config->get($opt)) {
0301d9 987                 if ($value != 'INBOX' && !preg_match($regexp, $value)) {
AM 988                     $prefs[$opt] = $prefix.$value;
989                 }
990             }
991         }
992
6d5a1b 993         if (($search_mods = $this->config->get('search_mods')) && !empty($search_mods)) {
0301d9 994             $folders = array();
6d5a1b 995             foreach ($search_mods as $idx => $value) {
0301d9 996                 if ($idx != 'INBOX' && $idx != '*' && !preg_match($regexp, $idx)) {
AM 997                     $idx = $prefix.$idx;
998                 }
999                 $folders[$idx] = $value;
1000             }
1001
1002             $prefs['search_mods'] = $folders;
1003         }
1004
6d5a1b 1005         if (($threading = $this->config->get('message_threading')) && !empty($threading)) {
0301d9 1006             $folders = array();
6d5a1b 1007             foreach ($threading as $idx => $value) {
0301d9 1008                 if ($idx != 'INBOX' && !preg_match($regexp, $idx)) {
AM 1009                     $idx = $prefix.$idx;
1010                 }
1011                 $folders[$prefix.$idx] = $value;
1012             }
1013
1014             $prefs['message_threading'] = $folders;
1015         }
1016
6d5a1b 1017         if ($collapsed = $this->config->get('collapsed_folders')) {
AM 1018             $folders     = explode('&&', $collapsed);
0301d9 1019             $count       = count($folders);
AM 1020             $folders_str = '';
1021
1022             if ($count) {
1023                 $folders[0]        = substr($folders[0], 1);
1024                 $folders[$count-1] = substr($folders[$count-1], 0, -1);
1025             }
1026
1027             foreach ($folders as $value) {
1028                 if ($value != 'INBOX' && !preg_match($regexp, $value)) {
1029                     $value = $prefix.$value;
1030                 }
1031                 $folders_str .= '&'.$value.'&';
1032             }
1033
1034             $prefs['collapsed_folders'] = $folders_str;
1035         }
1036
1037         $prefs['namespace_fixed'] = true;
1038
1039         // save updated preferences and reset imap settings (default folders)
1040         $user->save_prefs($prefs);
1041         $this->set_storage_prop();
1042     }
0c2596 1043
A 1044     /**
1045      * Overwrite action variable
1046      *
1047      * @param string New action value
1048      */
1049     public function overwrite_action($action)
1050     {
1051         $this->action = $action;
1052         $this->output->set_env('action', $action);
1053     }
1054
1055     /**
f5d2ee 1056      * Set environment variables for specified config options
AM 1057      */
1058     public function set_env_config($options)
1059     {
1060         foreach ((array) $options as $option) {
1061             if ($this->config->get($option)) {
1062                 $this->output->set_env($option, true);
1063             }
1064         }
1065     }
1066
1067     /**
0c2596 1068      * Returns RFC2822 formatted current date in user's timezone
A 1069      *
1070      * @return string Date
1071      */
1072     public function user_date()
1073     {
1074         // get user's timezone
1075         try {
1076             $tz   = new DateTimeZone($this->config->get('timezone'));
1077             $date = new DateTime('now', $tz);
1078         }
1079         catch (Exception $e) {
1080             $date = new DateTime();
1081         }
1082
1083         return $date->format('r');
1084     }
1085
1086     /**
1087      * Write login data (name, ID, IP address) to the 'userlogins' log file.
1088      */
0f5574 1089     public function log_login($user = null, $failed_login = false, $error_code = 0)
0c2596 1090     {
A 1091         if (!$this->config->get('log_logins')) {
1092             return;
1093         }
1094
060467 1095         // failed login
AM 1096         if ($failed_login) {
a5c03d 1097             // don't fill the log with complete input, which could
AM 1098             // have been prepared by a hacker
1099             if (strlen($user) > 256) {
1100                 $user = substr($user, 0, 256) . '...';
1101             }
1102
060467 1103             $message = sprintf('Failed login for %s from %s in session %s (error: %d)',
AM 1104                 $user, rcube_utils::remote_ip(), session_id(), $error_code);
1105         }
1106         // successful login
1107         else {
1108             $user_name = $this->get_user_name();
1109             $user_id   = $this->get_user_id();
0c2596 1110
060467 1111             if (!$user_id) {
AM 1112                 return;
1113             }
1114
1115             $message = sprintf('Successful login for %s (ID: %d) from %s in session %s',
0301d9 1116                 $user_name, $user_id, rcube_utils::remote_ip(), session_id());
0c2596 1117         }
A 1118
060467 1119         // log login
AM 1120         self::write_log('userlogins', $message);
0c2596 1121     }
1aceb9 1122
A 1123     /**
1124      * Create a HTML table based on the given data
1125      *
1126      * @param  array  Named table attributes
1127      * @param  mixed  Table row data. Either a two-dimensional array or a valid SQL result set
1128      * @param  array  List of cols to show
1129      * @param  string Name of the identifier col
1130      *
1131      * @return string HTML table code
1132      */
1133     public function table_output($attrib, $table_data, $a_show_cols, $id_col)
1134     {
517dae 1135         $table = new html_table($attrib);
1aceb9 1136
A 1137         // add table header
1138         if (!$attrib['noheader']) {
1139             foreach ($a_show_cols as $col) {
1140                 $table->add_header($col, $this->Q($this->gettext($col)));
1141             }
1142         }
1143
1144         if (!is_array($table_data)) {
1145             $db = $this->get_dbh();
1146             while ($table_data && ($sql_arr = $db->fetch_assoc($table_data))) {
1147                 $table->add_row(array('id' => 'rcmrow' . rcube_utils::html_identifier($sql_arr[$id_col])));
1148
1149                 // format each col
1150                 foreach ($a_show_cols as $col) {
1151                     $table->add($col, $this->Q($sql_arr[$col]));
1152                 }
1153             }
1154         }
1155         else {
1156             foreach ($table_data as $row_data) {
77043f 1157                 $class = !empty($row_data['class']) ? $row_data['class'] : null;
TB 1158                 if (!empty($attrib['rowclass']))
1159                     $class = trim($class . ' ' . $attrib['rowclass']);
1aceb9 1160                 $rowid = 'rcmrow' . rcube_utils::html_identifier($row_data[$id_col]);
A 1161
1162                 $table->add_row(array('id' => $rowid, 'class' => $class));
1163
1164                 // format each col
1165                 foreach ($a_show_cols as $col) {
77043f 1166                     $val = is_array($row_data[$col]) ? $row_data[$col][0] : $row_data[$col];
TB 1167                     $table->add($col, empty($attrib['ishtml']) ? $this->Q($val) : $val);
1aceb9 1168                 }
A 1169             }
1170         }
1171
1172         return $table->show($attrib);
1173     }
1174
1175     /**
1176      * Convert the given date to a human readable form
1177      * This uses the date formatting properties from config
1178      *
1179      * @param mixed  Date representation (string, timestamp or DateTime object)
1180      * @param string Date format to use
1181      * @param bool   Enables date convertion according to user timezone
1182      *
1183      * @return string Formatted date string
1184      */
1185     public function format_date($date, $format = null, $convert = true)
1186     {
1187         if (is_object($date) && is_a($date, 'DateTime')) {
1188             $timestamp = $date->format('U');
1189         }
1190         else {
1191             if (!empty($date)) {
6075f0 1192                 $timestamp = rcube_utils::strtotime($date);
1aceb9 1193             }
A 1194
1195             if (empty($timestamp)) {
1196                 return '';
1197             }
1198
1199             try {
1200                 $date = new DateTime("@".$timestamp);
1201             }
1202             catch (Exception $e) {
1203                 return '';
1204             }
1205         }
1206
1207         if ($convert) {
1208             try {
1209                 // convert to the right timezone
1210                 $stz = date_default_timezone_get();
1211                 $tz = new DateTimeZone($this->config->get('timezone'));
1212                 $date->setTimezone($tz);
1213                 date_default_timezone_set($tz->getName());
1214
1215                 $timestamp = $date->format('U');
1216             }
1217             catch (Exception $e) {
1218             }
1219         }
1220
1221         // define date format depending on current time
1222         if (!$format) {
1223             $now         = time();
1224             $now_date    = getdate($now);
1225             $today_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday'], $now_date['year']);
1226             $week_limit  = mktime(0, 0, 0, $now_date['mon'], $now_date['mday']-6, $now_date['year']);
1227             $pretty_date = $this->config->get('prettydate');
1228
2b05c5 1229             if ($pretty_date && $timestamp > $today_limit && $timestamp <= $now) {
1aceb9 1230                 $format = $this->config->get('date_today', $this->config->get('time_format', 'H:i'));
A 1231                 $today  = true;
1232             }
2b05c5 1233             else if ($pretty_date && $timestamp > $week_limit && $timestamp <= $now) {
1aceb9 1234                 $format = $this->config->get('date_short', 'D H:i');
A 1235             }
1236             else {
1237                 $format = $this->config->get('date_long', 'Y-m-d H:i');
1238             }
1239         }
1240
1241         // strftime() format
1242         if (preg_match('/%[a-z]+/i', $format)) {
1243             $format = strftime($format, $timestamp);
1244             if ($stz) {
1245                 date_default_timezone_set($stz);
1246             }
1247             return $today ? ($this->gettext('today') . ' ' . $format) : $format;
1248         }
1249
1250         // parse format string manually in order to provide localized weekday and month names
1251         // an alternative would be to convert the date() format string to fit with strftime()
1252         $out = '';
1253         for ($i=0; $i<strlen($format); $i++) {
1254             if ($format[$i] == "\\") {  // skip escape chars
1255                 continue;
1256             }
1257
1258             // write char "as-is"
1259             if ($format[$i] == ' ' || $format[$i-1] == "\\") {
1260                 $out .= $format[$i];
1261             }
1262             // weekday (short)
1263             else if ($format[$i] == 'D') {
1264                 $out .= $this->gettext(strtolower(date('D', $timestamp)));
1265             }
1266             // weekday long
1267             else if ($format[$i] == 'l') {
1268                 $out .= $this->gettext(strtolower(date('l', $timestamp)));
1269             }
1270             // month name (short)
1271             else if ($format[$i] == 'M') {
1272                 $out .= $this->gettext(strtolower(date('M', $timestamp)));
1273             }
1274             // month name (long)
1275             else if ($format[$i] == 'F') {
1276                 $out .= $this->gettext('long'.strtolower(date('M', $timestamp)));
1277             }
1278             else if ($format[$i] == 'x') {
1279                 $out .= strftime('%x %X', $timestamp);
1280             }
1281             else {
1282                 $out .= date($format[$i], $timestamp);
1283             }
1284         }
1285
1286         if ($today) {
1287             $label = $this->gettext('today');
1288             // replcae $ character with "Today" label (#1486120)
1289             if (strpos($out, '$') !== false) {
1290                 $out = preg_replace('/\$/', $label, $out, 1);
1291             }
1292             else {
1293                 $out = $label . ' ' . $out;
1294             }
1295         }
1296
1297         if ($stz) {
1298             date_default_timezone_set($stz);
1299         }
1300
1301         return $out;
1302     }
1303
1304     /**
1305      * Return folders list in HTML
1306      *
1307      * @param array $attrib Named parameters
1308      *
1309      * @return string HTML code for the gui object
1310      */
1311     public function folder_list($attrib)
1312     {
1313         static $a_mailboxes;
1314
1315         $attrib += array('maxlength' => 100, 'realnames' => false, 'unreadwrap' => ' (%s)');
1316
1317         $rcmail  = rcmail::get_instance();
1318         $storage = $rcmail->get_storage();
1319
1320         // add some labels to client
1321         $rcmail->output->add_label('purgefolderconfirm', 'deletemessagesconfirm');
1322
1323         $type = $attrib['type'] ? $attrib['type'] : 'ul';
1324         unset($attrib['type']);
1325
1326         if ($type == 'ul' && !$attrib['id']) {
1327             $attrib['id'] = 'rcmboxlist';
1328         }
1329
1330         if (empty($attrib['folder_name'])) {
1331             $attrib['folder_name'] = '*';
1332         }
1333
1334         // get current folder
1335         $mbox_name = $storage->get_folder();
1336
1337         // build the folders tree
1338         if (empty($a_mailboxes)) {
1339             // get mailbox list
1340             $a_folders = $storage->list_folders_subscribed(
1341                 '', $attrib['folder_name'], $attrib['folder_filter']);
1342             $delimiter = $storage->get_hierarchy_delimiter();
1343             $a_mailboxes = array();
1344
1345             foreach ($a_folders as $folder) {
1346                 $rcmail->build_folder_tree($a_mailboxes, $folder, $delimiter);
1347             }
1348         }
1349
1350         // allow plugins to alter the folder tree or to localize folder names
1351         $hook = $rcmail->plugins->exec_hook('render_mailboxlist', array(
1352             'list'      => $a_mailboxes,
1353             'delimiter' => $delimiter,
1354             'type'      => $type,
1355             'attribs'   => $attrib,
1356         ));
1357
1358         $a_mailboxes = $hook['list'];
1359         $attrib      = $hook['attribs'];
1360
1361         if ($type == 'select') {
0a1dd5 1362             $attrib['is_escaped'] = true;
1aceb9 1363             $select = new html_select($attrib);
A 1364
1365             // add no-selection option
1366             if ($attrib['noselection']) {
0a1dd5 1367                 $select->add(html::quote($rcmail->gettext($attrib['noselection'])), '');
1aceb9 1368             }
A 1369
1370             $rcmail->render_folder_tree_select($a_mailboxes, $mbox_name, $attrib['maxlength'], $select, $attrib['realnames']);
1371             $out = $select->show($attrib['default']);
1372         }
1373         else {
1374             $js_mailboxlist = array();
9a0153 1375             $tree = $rcmail->render_folder_tree_html($a_mailboxes, $mbox_name, $js_mailboxlist, $attrib);
1aceb9 1376
9a0153 1377             if ($type != 'js') {
AM 1378                 $out = html::tag('ul', $attrib, $tree, html::$common_attrib);
1379
1380                 $rcmail->output->include_script('treelist.js');
1381                 $rcmail->output->add_gui_object('mailboxlist', $attrib['id']);
1382                 $rcmail->output->set_env('unreadwrap', $attrib['unreadwrap']);
1383                 $rcmail->output->set_env('collapsed_folders', (string)$rcmail->config->get('collapsed_folders'));
1384             }
1385
1aceb9 1386             $rcmail->output->set_env('mailboxes', $js_mailboxlist);
9a0153 1387
AM 1388             // we can't use object keys in javascript because they are unordered
1389             // we need sorted folders list for folder-selector widget
1390             $rcmail->output->set_env('mailboxes_list', array_keys($js_mailboxlist));
1aceb9 1391         }
A 1392
1393         return $out;
1394     }
1395
1396     /**
1397      * Return folders list as html_select object
1398      *
1399      * @param array $p  Named parameters
1400      *
1401      * @return html_select HTML drop-down object
1402      */
1403     public function folder_selector($p = array())
1404     {
4a9a0e 1405         $realnames = $this->config->get('show_real_foldernames');
DC 1406         $p += array('maxlength' => 100, 'realnames' => $realnames, 'is_escaped' => true);
1aceb9 1407         $a_mailboxes = array();
A 1408         $storage = $this->get_storage();
1409
1410         if (empty($p['folder_name'])) {
1411             $p['folder_name'] = '*';
1412         }
1413
1414         if ($p['unsubscribed']) {
1415             $list = $storage->list_folders('', $p['folder_name'], $p['folder_filter'], $p['folder_rights']);
1416         }
1417         else {
1418             $list = $storage->list_folders_subscribed('', $p['folder_name'], $p['folder_filter'], $p['folder_rights']);
1419         }
1420
1421         $delimiter = $storage->get_hierarchy_delimiter();
1422
1597c8 1423         if (!empty($p['exceptions'])) {
AM 1424             $list = array_diff($list, (array) $p['exceptions']);
1425         }
1426
1427         if (!empty($p['additional'])) {
1428             foreach ($p['additional'] as $add_folder) {
1429                 $add_items = explode($delimiter, $add_folder);
1430                 $folder    = '';
1431                 while (count($add_items)) {
1432                     $folder .= array_shift($add_items);
1433
1434                     // @TODO: sorting
1435                     if (!in_array($folder, $list)) {
1436                         $list[] = $folder;
1437                     }
1438
1439                     $folder .= $delimiter;
1440                 }
1aceb9 1441             }
A 1442         }
1443
1597c8 1444         foreach ($list as $folder) {
AM 1445             $this->build_folder_tree($a_mailboxes, $folder, $delimiter);
1446         }
1447
1aceb9 1448         $select = new html_select($p);
A 1449
1450         if ($p['noselection']) {
0a1dd5 1451             $select->add(html::quote($p['noselection']), '');
1aceb9 1452         }
A 1453
1454         $this->render_folder_tree_select($a_mailboxes, $mbox, $p['maxlength'], $select, $p['realnames'], 0, $p);
1455
1456         return $select;
1457     }
1458
1459     /**
1460      * Create a hierarchical array of the mailbox list
1461      */
1462     public function build_folder_tree(&$arrFolders, $folder, $delm = '/', $path = '')
1463     {
1464         // Handle namespace prefix
1465         $prefix = '';
1466         if (!$path) {
1467             $n_folder = $folder;
1468             $folder = $this->storage->mod_folder($folder);
1469
1470             if ($n_folder != $folder) {
1471                 $prefix = substr($n_folder, 0, -strlen($folder));
1472             }
1473         }
1474
1475         $pos = strpos($folder, $delm);
1476
1477         if ($pos !== false) {
1478             $subFolders    = substr($folder, $pos+1);
1479             $currentFolder = substr($folder, 0, $pos);
1480
1481             // sometimes folder has a delimiter as the last character
1482             if (!strlen($subFolders)) {
1483                 $virtual = false;
1484             }
1485             else if (!isset($arrFolders[$currentFolder])) {
1486                 $virtual = true;
1487             }
1488             else {
1489                 $virtual = $arrFolders[$currentFolder]['virtual'];
1490             }
1491         }
1492         else {
1493             $subFolders    = false;
1494             $currentFolder = $folder;
1495             $virtual       = false;
1496         }
1497
1498         $path .= $prefix . $currentFolder;
1499
1500         if (!isset($arrFolders[$currentFolder])) {
1501             $arrFolders[$currentFolder] = array(
1502                 'id' => $path,
1503                 'name' => rcube_charset::convert($currentFolder, 'UTF7-IMAP'),
1504                 'virtual' => $virtual,
1505                 'folders' => array());
1506         }
1507         else {
1508             $arrFolders[$currentFolder]['virtual'] = $virtual;
1509         }
1510
1511         if (strlen($subFolders)) {
1512             $this->build_folder_tree($arrFolders[$currentFolder]['folders'], $subFolders, $delm, $path.$delm);
1513         }
1514     }
1515
1516     /**
1517      * Return html for a structured list &lt;ul&gt; for the mailbox tree
1518      */
1519     public function render_folder_tree_html(&$arrFolders, &$mbox_name, &$jslist, $attrib, $nestLevel = 0)
1520     {
1521         $maxlength = intval($attrib['maxlength']);
1522         $realnames = (bool)$attrib['realnames'];
1523         $msgcounts = $this->storage->get_cache('messagecount');
1524         $collapsed = $this->config->get('collapsed_folders');
85e65c 1525         $realnames = $this->config->get('show_real_foldernames');
52deb1 1526
1aceb9 1527         $out = '';
3725cf 1528         foreach ($arrFolders as $folder) {
1aceb9 1529             $title        = null;
A 1530             $folder_class = $this->folder_classname($folder['id']);
1531             $is_collapsed = strpos($collapsed, '&'.rawurlencode($folder['id']).'&') !== false;
1532             $unread       = $msgcounts ? intval($msgcounts[$folder['id']]['UNSEEN']) : 0;
1533
1534             if ($folder_class && !$realnames) {
1535                 $foldername = $this->gettext($folder_class);
1536             }
1537             else {
1538                 $foldername = $folder['name'];
1539
1540                 // shorten the folder name to a given length
1541                 if ($maxlength && $maxlength > 1) {
1542                     $fname = abbreviate_string($foldername, $maxlength);
1543                     if ($fname != $foldername) {
1544                         $title = $foldername;
1545                     }
1546                     $foldername = $fname;
1547                 }
1548             }
1549
1550             // make folder name safe for ids and class names
1551             $folder_id = rcube_utils::html_identifier($folder['id'], true);
1552             $classes   = array('mailbox');
1553
1554             // set special class for Sent, Drafts, Trash and Junk
1555             if ($folder_class) {
1556                 $classes[] = $folder_class;
1557             }
1558
1559             if ($folder['id'] == $mbox_name) {
1560                 $classes[] = 'selected';
1561             }
1562
1563             if ($folder['virtual']) {
1564                 $classes[] = 'virtual';
1565             }
1566             else if ($unread) {
1567                 $classes[] = 'unread';
1568             }
1569
1570             $js_name = $this->JQ($folder['id']);
1571             $html_name = $this->Q($foldername) . ($unread ? html::span('unreadcount', sprintf($attrib['unreadwrap'], $unread)) : '');
1572             $link_attrib = $folder['virtual'] ? array() : array(
1573                 'href' => $this->url(array('_mbox' => $folder['id'])),
d58c39 1574                 'onclick' => sprintf("return %s.command('list','%s',this,event)", rcmail_output::JS_OBJECT_NAME, $js_name),
1aceb9 1575                 'rel' => $folder['id'],
A 1576                 'title' => $title,
1577             );
1578
1579             $out .= html::tag('li', array(
1580                 'id' => "rcmli".$folder_id,
1581                 'class' => join(' ', $classes),
1582                 'noclose' => true),
3c309a 1583                 html::a($link_attrib, $html_name));
1aceb9 1584
3c309a 1585             if (!empty($folder['folders'])) {
TB 1586                 $out .= html::div('treetoggle ' . ($is_collapsed ? 'collapsed' : 'expanded'), '&nbsp;');
1587             }
1588
1589             $jslist[$folder['id']] = array(
1aceb9 1590                 'id'      => $folder['id'],
A 1591                 'name'    => $foldername,
9a0153 1592                 'virtual' => $folder['virtual'],
1aceb9 1593             );
A 1594
9a0153 1595             if (!empty($folder_class)) {
AM 1596                 $jslist[$folder['id']]['class'] = $folder_class;
1597             }
1598
1aceb9 1599             if (!empty($folder['folders'])) {
A 1600                 $out .= html::tag('ul', array('style' => ($is_collapsed ? "display:none;" : null)),
1601                     $this->render_folder_tree_html($folder['folders'], $mbox_name, $jslist, $attrib, $nestLevel+1));
1602             }
1603
1604             $out .= "</li>\n";
1605         }
1606
1607         return $out;
1608     }
1609
1610     /**
1611      * Return html for a flat list <select> for the mailbox tree
1612      */
1613     public function render_folder_tree_select(&$arrFolders, &$mbox_name, $maxlength, &$select, $realnames = false, $nestLevel = 0, $opts = array())
1614     {
1615         $out = '';
1616
3725cf 1617         foreach ($arrFolders as $folder) {
1aceb9 1618             // skip exceptions (and its subfolders)
A 1619             if (!empty($opts['exceptions']) && in_array($folder['id'], $opts['exceptions'])) {
1620                 continue;
1621             }
1622
1623             // skip folders in which it isn't possible to create subfolders
1624             if (!empty($opts['skip_noinferiors'])) {
1625                 $attrs = $this->storage->folder_attributes($folder['id']);
9d78c6 1626                 if ($attrs && in_array_nocase('\\Noinferiors', $attrs)) {
1aceb9 1627                     continue;
A 1628                 }
1629             }
1630
1631             if (!$realnames && ($folder_class = $this->folder_classname($folder['id']))) {
1632                 $foldername = $this->gettext($folder_class);
1633             }
1634             else {
1635                 $foldername = $folder['name'];
1636
1637                 // shorten the folder name to a given length
1638                 if ($maxlength && $maxlength > 1) {
1639                     $foldername = abbreviate_string($foldername, $maxlength);
1640                 }
e7ca04 1641             }
1aceb9 1642
0a1dd5 1643             $select->add(str_repeat('&nbsp;', $nestLevel*4) . html::quote($foldername), $folder['id']);
1aceb9 1644
e7ca04 1645             if (!empty($folder['folders'])) {
A 1646                 $out .= $this->render_folder_tree_select($folder['folders'], $mbox_name, $maxlength,
1647                     $select, $realnames, $nestLevel+1, $opts);
1aceb9 1648             }
A 1649         }
1650
1651         return $out;
1652     }
1653
1654     /**
1655      * Return internal name for the given folder if it matches the configured special folders
1656      */
1657     public function folder_classname($folder_id)
1658     {
1659         if ($folder_id == 'INBOX') {
1660             return 'inbox';
1661         }
1662
1663         // for these mailboxes we have localized labels and css classes
1664         foreach (array('sent', 'drafts', 'trash', 'junk') as $smbx)
1665         {
1666             if ($folder_id === $this->config->get($smbx.'_mbox')) {
1667                 return $smbx;
1668             }
1669         }
1670     }
1671
1672     /**
1673      * Try to localize the given IMAP folder name.
1674      * UTF-7 decode it in case no localized text was found
1675      *
4d7964 1676      * @param string $name      Folder name
AM 1677      * @param bool   $with_path Enable path localization
1aceb9 1678      *
A 1679      * @return string Localized folder name in UTF-8 encoding
1680      */
cb29c9 1681     public function localize_foldername($name, $with_path = false)
1aceb9 1682     {
85e65c 1683         $realnames = $this->config->get('show_real_foldernames');
cb29c9 1684
AM 1685         if (!$realnames && ($folder_class = $this->folder_classname($name))) {
1686             return $this->gettext($folder_class);
1687         }
85e65c 1688
4d7964 1689         // try to localize path of the folder
85e65c 1690         if ($with_path && !$realnames) {
4d7964 1691             $storage   = $this->get_storage();
AM 1692             $delimiter = $storage->get_hierarchy_delimiter();
1693             $path      = explode($delimiter, $name);
1694             $count     = count($path);
1695
1696             if ($count > 1) {
a12bbb 1697                 for ($i = 1; $i < $count; $i++) {
4d7964 1698                     $folder = implode($delimiter, array_slice($path, 0, -$i));
85e65c 1699                     if ($folder_class = $this->folder_classname($folder)) {
4d7964 1700                         $name = implode($delimiter, array_slice($path, $count - $i));
AM 1701                         return $this->gettext($folder_class) . $delimiter . rcube_charset::convert($name, 'UTF7-IMAP');
1702                     }
1703                 }
1704             }
1aceb9 1705         }
85e65c 1706
AM 1707         return rcube_charset::convert($name, 'UTF7-IMAP');
1aceb9 1708     }
A 1709
1710
1711     public function localize_folderpath($path)
1712     {
1713         $protect_folders = $this->config->get('protect_default_folders');
1714         $delimiter       = $this->storage->get_hierarchy_delimiter();
1715         $path            = explode($delimiter, $path);
1716         $result          = array();
1717
1718         foreach ($path as $idx => $dir) {
1719             $directory = implode($delimiter, array_slice($path, 0, $idx+1));
dc0b50 1720             if ($protect_folders && $this->storage->is_special_folder($directory)) {
1aceb9 1721                 unset($result);
A 1722                 $result[] = $this->localize_foldername($directory);
1723             }
1724             else {
1725                 $result[] = rcube_charset::convert($dir, 'UTF7-IMAP');
1726             }
1727         }
1728
1729         return implode($delimiter, $result);
1730     }
1731
1732
1733     public static function quota_display($attrib)
1734     {
1735         $rcmail = rcmail::get_instance();
1736
1737         if (!$attrib['id']) {
1738             $attrib['id'] = 'rcmquotadisplay';
1739         }
1740
1741         $_SESSION['quota_display'] = !empty($attrib['display']) ? $attrib['display'] : 'text';
1742
1743         $rcmail->output->add_gui_object('quotadisplay', $attrib['id']);
1744
1745         $quota = $rcmail->quota_content($attrib);
1746
1747         $rcmail->output->add_script('rcmail.set_quota('.rcube_output::json_serialize($quota).');', 'docready');
1748
edca65 1749         return html::span($attrib, '&nbsp;');
1aceb9 1750     }
A 1751
1752
b8bcca 1753     public function quota_content($attrib = null, $folder = null)
1aceb9 1754     {
b8bcca 1755         $quota = $this->storage->get_quota($folder);
1aceb9 1756         $quota = $this->plugins->exec_hook('quota', $quota);
A 1757
1758         $quota_result = (array) $quota;
5312b7 1759         $quota_result['type']   = isset($_SESSION['quota_display']) ? $_SESSION['quota_display'] : '';
AM 1760         $quota_result['folder'] = $folder !== null && $folder !== '' ? $folder : 'INBOX';
1aceb9 1761
4fee77 1762         if ($quota['total'] > 0) {
1aceb9 1763             if (!isset($quota['percent'])) {
A 1764                 $quota_result['percent'] = min(100, round(($quota['used']/max(1,$quota['total']))*100));
1765             }
1766
1767             $title = sprintf('%s / %s (%.0f%%)',
1768                 $this->show_bytes($quota['used'] * 1024), $this->show_bytes($quota['total'] * 1024),
1769                 $quota_result['percent']);
1770
1771             $quota_result['title'] = $title;
1772
1773             if ($attrib['width']) {
1774                 $quota_result['width'] = $attrib['width'];
1775             }
1776             if ($attrib['height']) {
c5f068 1777                 $quota_result['height'] = $attrib['height'];
AM 1778             }
1779
1780             // build a table of quota types/roots info
1781             if (($root_cnt = count($quota_result['all'])) > 1 || count($quota_result['all'][key($quota_result['all'])]) > 1) {
1782                 $table = new html_table(array('cols' => 3, 'class' => 'quota-info'));
1783
1784                 $table->add_header(null, self::Q($this->gettext('quotatype')));
1785                 $table->add_header(null, self::Q($this->gettext('quotatotal')));
1786                 $table->add_header(null, self::Q($this->gettext('quotaused')));
1787
1788                 foreach ($quota_result['all'] as $root => $data) {
1789                     if ($root_cnt > 1 && $root) {
1790                         $table->add(array('colspan' => 3, 'class' => 'root'), self::Q($root));
1791                     }
1792
1793                     if ($storage = $data['storage']) {
1794                         $percent = min(100, round(($storage['used']/max(1,$storage['total']))*100));
1795
1796                         $table->add('name', self::Q($this->gettext('quotastorage')));
1797                         $table->add(null, $this->show_bytes($storage['total'] * 1024));
1798                         $table->add(null, sprintf('%s (%.0f%%)', $this->show_bytes($storage['used'] * 1024), $percent));
1799                     }
1800                     if ($message = $data['message']) {
1801                         $percent = min(100, round(($message['used']/max(1,$message['total']))*100));
1802
1803                         $table->add('name', self::Q($this->gettext('quotamessage')));
1804                         $table->add(null, intval($message['total']));
1805                         $table->add(null, sprintf('%d (%.0f%%)', $message['used'], $percent));
1806                     }
1807                 }
1808
1809                 $quota_result['table'] = $table->show();
1aceb9 1810             }
A 1811         }
1812         else {
4fee77 1813             $unlimited               = $this->config->get('quota_zero_as_unlimited');
AM 1814             $quota_result['title']   = $this->gettext($unlimited ? 'unlimited' : 'unknown');
1aceb9 1815             $quota_result['percent'] = 0;
A 1816         }
1817
c5f068 1818         // cleanup
AM 1819         unset($quota_result['abort']);
1820         if (empty($quota_result['table'])) {
1821             unset($quota_result['all']);
1822         }
1823
1aceb9 1824         return $quota_result;
A 1825     }
1826
1827     /**
1828      * Outputs error message according to server error/response codes
1829      *
1830      * @param string $fallback       Fallback message label
1831      * @param array  $fallback_args  Fallback message label arguments
e7c1aa 1832      * @param string $suffix         Message label suffix
216b31 1833      * @param array  $params         Additional parameters (type, prefix)
1aceb9 1834      */
216b31 1835     public function display_server_error($fallback = null, $fallback_args = null, $suffix = '', $params = array())
1aceb9 1836     {
A 1837         $err_code = $this->storage->get_error_code();
1838         $res_code = $this->storage->get_response_code();
e7c1aa 1839         $args     = array();
1aceb9 1840
524e48 1841         if ($res_code == rcube_storage::NOPERM) {
e7c1aa 1842             $error = 'errornoperm';
1aceb9 1843         }
A 1844         else if ($res_code == rcube_storage::READONLY) {
e7c1aa 1845             $error = 'errorreadonly';
1aceb9 1846         }
0bf724 1847         else if ($res_code == rcube_storage::OVERQUOTA) {
383724 1848             $error = 'erroroverquota';
0bf724 1849         }
1aceb9 1850         else if ($err_code && ($err_str = $this->storage->get_error_str())) {
A 1851             // try to detect access rights problem and display appropriate message
1852             if (stripos($err_str, 'Permission denied') !== false) {
e7c1aa 1853                 $error = 'errornoperm';
1aceb9 1854             }
0bf724 1855             // try to detect full mailbox problem and display appropriate message
216b31 1856             // there can be e.g. "Quota exceeded" / "quotum would exceed" / "Over quota"
AM 1857             else if (stripos($err_str, 'quot') !== false && preg_match('/exceed|over/i', $err_str)) {
e7c1aa 1858                 $error = 'erroroverquota';
0bf724 1859             }
1aceb9 1860             else {
e7c1aa 1861                 $error = 'servererrormsg';
b78281 1862                 $args  = array('msg' => rcube::Q($err_str));
1aceb9 1863             }
A 1864         }
524e48 1865         else if ($err_code < 0) {
e7c1aa 1866             $error = 'storageerror';
524e48 1867         }
1aceb9 1868         else if ($fallback) {
e7c1aa 1869             $error = $fallback;
AM 1870             $args  = $fallback_args;
216b31 1871             $params['prefix'] = false;
e7c1aa 1872         }
AM 1873
1874         if ($error) {
1875             if ($suffix && $this->text_exists($error . $suffix)) {
1876                 $error .= $suffix;
1877             }
216b31 1878
AM 1879             $msg = $this->gettext(array('name' => $error, 'vars' => $args));
1880
1881             if ($params['prefix'] && $fallback) {
1882                 $msg = $this->gettext(array('name' => $fallback, 'vars' => $fallback_args)) . ' ' . $msg;
1883             }
1884
1885             $this->output->show_message($msg, $params['type'] ?: 'error');
1aceb9 1886         }
A 1887     }
1888
1889     /**
1890      * Output HTML editor scripts
1891      *
1892      * @param string $mode  Editor mode
1893      */
1894     public function html_editor($mode = '')
1895     {
a63f14 1896         $spellcheck       = intval($this->config->get('enable_spellcheck'));
AM 1897         $spelldict        = intval($this->config->get('spellcheck_dictionary'));
1898         $disabled_plugins = array();
1899         $disabled_buttons = array();
2aa9ee 1900         $extra_plugins    = array();
AM 1901         $extra_buttons    = array();
a63f14 1902
AM 1903         if (!$spellcheck) {
1904             $disabled_plugins[] = 'spellchecker';
1905         }
1906
1907         $hook = $this->plugins->exec_hook('html_editor', array(
1908                 'mode'             => $mode,
1909                 'disabled_plugins' => $disabled_plugins,
1910                 'disabled_buttons' => $disabled_buttons,
2aa9ee 1911                 'extra_plugins' => $extra_plugins,
AM 1912                 'extra_buttons' => $extra_buttons,
a63f14 1913         ));
1aceb9 1914
A 1915         if ($hook['abort']) {
1916             return;
1917         }
1918
6fa5b4 1919         $lang_codes = array($_SESSION['language']);
1aceb9 1920
6fa5b4 1921         if ($pos = strpos($_SESSION['language'], '_')) {
AM 1922             $lang_codes[] = substr($_SESSION['language'], 0, $pos);
1aceb9 1923         }
A 1924
6fa5b4 1925         foreach ($lang_codes as $code) {
AM 1926             if (file_exists(INSTALL_PATH . 'program/js/tinymce/langs/'.$code.'.js')) {
1927                 $lang = $code;
1928                 break;
1929             }
1930         }
1931
1932         if (empty($lang)) {
1aceb9 1933             $lang = 'en';
A 1934         }
1935
646b64 1936         $config = array(
1aceb9 1937             'mode'       => $mode,
A 1938             'lang'       => $lang,
1939             'skin_path'  => $this->output->get_skin_path(),
a63f14 1940             'spellcheck' => $spellcheck, // deprecated
AM 1941             'spelldict'  => $spelldict,
1942             'disabled_plugins' => $hook['disabled_plugins'],
1943             'disabled_buttons' => $hook['disabled_buttons'],
2aa9ee 1944             'extra_plugins'    => $hook['extra_plugins'],
AM 1945             'extra_buttons'    => $hook['extra_buttons'],
646b64 1946         );
1aceb9 1947
c5bfe6 1948         $this->output->add_label('selectimage', 'addimage', 'selectmedia', 'addmedia');
646b64 1949         $this->output->set_env('editor_config', $config);
c5bfe6 1950         $this->output->include_css('program/js/tinymce/roundcube/browser.css');
6fa5b4 1951         $this->output->include_script('tinymce/tinymce.min.js');
1aceb9 1952         $this->output->include_script('editor.js');
A 1953     }
1954
1955     /**
1956      * File upload progress handler.
1957      */
1958     public function upload_progress()
1959     {
1960         $params = array(
1961             'action' => $this->action,
93e12f 1962             'name'   => rcube_utils::get_input_value('_progress', rcube_utils::INPUT_GET),
1aceb9 1963         );
A 1964
93e12f 1965         if (function_exists('uploadprogress_get_info')) {
AM 1966             $status = uploadprogress_get_info($params['name']);
1aceb9 1967
A 1968             if (!empty($status)) {
93e12f 1969                 $params['current'] = $status['bytes_uploaded'];
AM 1970                 $params['total']   = $status['bytes_total'];
1aceb9 1971             }
A 1972         }
1973
93e12f 1974         if (!isset($status) && filter_var(ini_get('apc.rfc1867'), FILTER_VALIDATE_BOOLEAN)
AM 1975             && ini_get('apc.rfc1867_name')
1976         ) {
1977             $prefix = ini_get('apc.rfc1867_prefix');
1978             $status = apc_fetch($prefix . $params['name']);
1979
1980             if (!empty($status)) {
1981                 $params['current'] = $status['current'];
1982                 $params['total']   = $status['total'];
1983             }
1984         }
1985
1986         if (!isset($status) && filter_var(ini_get('session.upload_progress.enabled'), FILTER_VALIDATE_BOOLEAN)
1987             && ini_get('session.upload_progress.name')
1988         ) {
1989             $key = ini_get('session.upload_progress.prefix') . $params['name'];
1990
1991             $params['total']   = $_SESSION[$key]['content_length'];
1992             $params['current'] = $_SESSION[$key]['bytes_processed'];
1993         }
1994
1995         if (!empty($params['total'])) {
2dfad0 1996             $total = $this->show_bytes($params['total'], $unit);
AM 1997             switch ($unit) {
1998             case 'GB':
1999                 $gb      = $params['current']/1073741824;
2000                 $current = sprintf($gb >= 10 ? "%d" : "%.1f", $gb);
2001                 break;
2002             case 'MB':
2003                 $mb      = $params['current']/1048576;
2004                 $current = sprintf($mb >= 10 ? "%d" : "%.1f", $mb);
2005                 break;
2006             case 'KB':
2007                 $current = round($params['current']/1024);
2008                 break;
2009             case 'B':
2010             default:
2011                 $current = $params['current'];
2012                 break;
2013             }
2014
2015             $params['percent'] = round($params['current']/$params['total']*100);
93e12f 2016             $params['text']    = $this->gettext(array(
AM 2017                 'name' => 'uploadprogress',
2018                 'vars' => array(
2019                     'percent' => $params['percent'] . '%',
2dfad0 2020                     'current' => $current,
AM 2021                     'total'   => $total
93e12f 2022                 )
AM 2023             ));
2024         }
1aceb9 2025
A 2026         $this->output->command('upload_progress_update', $params);
2027         $this->output->send();
2028     }
2029
2030     /**
2031      * Initializes file uploading interface.
3cc1af 2032      *
AM 2033      * @param $int Optional maximum file size in bytes
1aceb9 2034      */
3cc1af 2035     public function upload_init($max_size = null)
1aceb9 2036     {
A 2037         // Enable upload progress bar
93e12f 2038         if ($seconds = $this->config->get('upload_progress')) {
AM 2039             if (function_exists('uploadprogress_get_info')) {
2040                 $field_name = 'UPLOAD_IDENTIFIER';
2041             }
2042             if (!$field_name && filter_var(ini_get('apc.rfc1867'), FILTER_VALIDATE_BOOLEAN)) {
2043                 $field_name = ini_get('apc.rfc1867_name');
2044             }
2045             if (!$field_name && filter_var(ini_get('session.upload_progress.enabled'), FILTER_VALIDATE_BOOLEAN)) {
2046                 $field_name = ini_get('session.upload_progress.name');
2047             }
2048
2049             if ($field_name) {
1aceb9 2050                 $this->output->set_env('upload_progress_name', $field_name);
A 2051                 $this->output->set_env('upload_progress_time', (int) $seconds);
2052             }
2053         }
2054
2055         // find max filesize value
2056         $max_filesize = parse_bytes(ini_get('upload_max_filesize'));
2057         $max_postsize = parse_bytes(ini_get('post_max_size'));
0301d9 2058
1aceb9 2059         if ($max_postsize && $max_postsize < $max_filesize) {
A 2060             $max_filesize = $max_postsize;
2061         }
2062
3cc1af 2063         if ($max_size && $max_size < $max_filesize) {
AM 2064             $max_filesize = $max_size;
2065         }
2066
1aceb9 2067         $this->output->set_env('max_filesize', $max_filesize);
6b2b2e 2068         $max_filesize = $this->show_bytes($max_filesize);
1aceb9 2069         $this->output->set_env('filesizeerror', $this->gettext(array(
A 2070             'name' => 'filesizeerror', 'vars' => array('size' => $max_filesize))));
2071
2072         return $max_filesize;
2073     }
2074
2075     /**
3cc1af 2076      * Outputs uploaded file content (with image thumbnails support
AM 2077      *
2078      * @param array $file Upload file data
2079      */
2080     public function display_uploaded_file($file)
2081     {
2082         if (empty($file)) {
2083             return;
2084         }
2085
2086         $file = $this->plugins->exec_hook('attachment_display', $file);
2087
2088         if ($file['status']) {
2089             if (empty($file['size'])) {
2090                 $file['size'] = $file['data'] ? strlen($file['data']) : @filesize($file['path']);
2091             }
2092
2093             // generate image thumbnail for file browser in HTML editor
2094             if (!empty($_GET['_thumbnail'])) {
2095                 $temp_dir       = $this->config->get('temp_dir');
2096                 $thumbnail_size = 80;
2097                 $mimetype       = $file['mimetype'];
2098                 $file_ident     = $file['id'] . ':' . $file['mimetype'] . ':' . $file['size'];
2099                 $cache_basename = $temp_dir . '/' . md5($file_ident . ':' . $this->user->ID . ':' . $thumbnail_size);
03aa84 2100                 $cache_file     = $cache_basename . '.thumb';
3cc1af 2101
AM 2102                 // render thumbnail image if not done yet
2103                 if (!is_file($cache_file)) {
2104                     if (!$file['path']) {
03aa84 2105                         $orig_name = $filename = $cache_basename . '.tmp';
3cc1af 2106                         file_put_contents($orig_name, $file['data']);
AM 2107                     }
2108                     else {
2109                         $filename = $file['path'];
2110                     }
2111
2112                     $image = new rcube_image($filename);
2113                     if ($imgtype = $image->resize($thumbnail_size, $cache_file, true)) {
2114                         $mimetype = 'image/' . $imgtype;
2115
2116                         if ($orig_name) {
2117                             unlink($orig_name);
2118                         }
2119                     }
2120                 }
2121
2122                 if (is_file($cache_file)) {
2123                     // cache for 1h
2124                     $this->output->future_expire_header(3600);
2125                     header('Content-Type: ' . $mimetype);
2126                     header('Content-Length: ' . filesize($cache_file));
2127
2128                     readfile($cache_file);
2129                     exit;
2130                 }
2131             }
2132
2133             header('Content-Type: ' . $file['mimetype']);
2134             header('Content-Length: ' . $file['size']);
2135
2136             if ($file['data']) {
2137                 echo $file['data'];
2138             }
2139             else if ($file['path']) {
2140                 readfile($file['path']);
2141             }
2142         }
2143     }
2144
2145     /**
1aceb9 2146      * Initializes client-side autocompletion.
A 2147      */
2148     public function autocomplete_init()
2149     {
2150         static $init;
2151
2152         if ($init) {
2153             return;
2154         }
2155
2156         $init = 1;
2157
2158         if (($threads = (int)$this->config->get('autocomplete_threads')) > 0) {
2159             $book_types = (array) $this->config->get('autocomplete_addressbooks', 'sql');
2160             if (count($book_types) > 1) {
2161                 $this->output->set_env('autocomplete_threads', $threads);
2162                 $this->output->set_env('autocomplete_sources', $book_types);
2163             }
2164         }
2165
2166         $this->output->set_env('autocomplete_max', (int)$this->config->get('autocomplete_max', 15));
2167         $this->output->set_env('autocomplete_min_length', $this->config->get('autocomplete_min_length'));
2168         $this->output->add_label('autocompletechars', 'autocompletemore');
2169     }
2170
2171     /**
2172      * Returns supported font-family specifications
2173      *
a0f38f 2174      * @param string $font Font name
1aceb9 2175      *
A 2176      * @param string|array Font-family specification array or string (if $font is used)
2177      */
2178     public static function font_defs($font = null)
2179     {
2180         $fonts = array(
2181             'Andale Mono'   => '"Andale Mono",Times,monospace',
2182             'Arial'         => 'Arial,Helvetica,sans-serif',
2183             'Arial Black'   => '"Arial Black","Avant Garde",sans-serif',
2184             'Book Antiqua'  => '"Book Antiqua",Palatino,serif',
2185             'Courier New'   => '"Courier New",Courier,monospace',
2186             'Georgia'       => 'Georgia,Palatino,serif',
2187             'Helvetica'     => 'Helvetica,Arial,sans-serif',
2188             'Impact'        => 'Impact,Chicago,sans-serif',
2189             'Tahoma'        => 'Tahoma,Arial,Helvetica,sans-serif',
2190             'Terminal'      => 'Terminal,Monaco,monospace',
2191             'Times New Roman' => '"Times New Roman",Times,serif',
2192             'Trebuchet MS'  => '"Trebuchet MS",Geneva,sans-serif',
2193             'Verdana'       => 'Verdana,Geneva,sans-serif',
2194         );
2195
2196         if ($font) {
2197             return $fonts[$font];
2198         }
2199
2200         return $fonts;
2201     }
2202
2203     /**
2204      * Create a human readable string for a number of bytes
2205      *
a0f38f 2206      * @param int    $bytes Number of bytes
AM 2207      * @param string &$unit Size unit
1aceb9 2208      *
A 2209      * @return string Byte string
2210      */
2dfad0 2211     public function show_bytes($bytes, &$unit = null)
1aceb9 2212     {
A 2213         if ($bytes >= 1073741824) {
2dfad0 2214             $unit = 'GB';
AM 2215             $gb   = $bytes/1073741824;
2216             $str  = sprintf($gb >= 10 ? "%d " : "%.1f ", $gb) . $this->gettext($unit);
1aceb9 2217         }
A 2218         else if ($bytes >= 1048576) {
2dfad0 2219             $unit = 'MB';
AM 2220             $mb   = $bytes/1048576;
2221             $str  = sprintf($mb >= 10 ? "%d " : "%.1f ", $mb) . $this->gettext($unit);
1aceb9 2222         }
A 2223         else if ($bytes >= 1024) {
2dfad0 2224             $unit = 'KB';
AM 2225             $str  = sprintf("%d ",  round($bytes/1024)) . $this->gettext($unit);
1aceb9 2226         }
A 2227         else {
2dfad0 2228             $unit = 'B';
f7f467 2229             $str  = sprintf('%d ', $bytes) . $this->gettext($unit);
1aceb9 2230         }
A 2231
2232         return $str;
2233     }
2234
2235     /**
8749e9 2236      * Returns real size (calculated) of the message part
AM 2237      *
a0f38f 2238      * @param rcube_message_part $part Message part
8749e9 2239      *
AM 2240      * @return string Part size (and unit)
2241      */
2242     public function message_part_size($part)
2243     {
2244         if (isset($part->d_parameters['size'])) {
2245             $size = $this->show_bytes((int)$part->d_parameters['size']);
2246         }
2247         else {
4e6f30 2248             $size = $part->size;
AM 2249             if ($part->encoding == 'base64') {
2250                 $size = $size / 1.33;
2251             }
8749e9 2252
4e6f30 2253             $size = '~' . $this->show_bytes($size);
8749e9 2254         }
AM 2255
2256         return $size;
2257     }
2258
0456f7 2259     /**
TB 2260      * Returns message UID(s) and IMAP folder(s) from GET/POST data
2261      *
b8bcca 2262      * @param string UID value to decode
AM 2263      * @param string Default mailbox value (if not encoded in UIDs)
2264      * @param bool   Will be set to True if multi-folder request
2265      *
0456f7 2266      * @return array  List of message UIDs per folder
TB 2267      */
b8bcca 2268     public static function get_uids($uids = null, $mbox = null, &$is_multifolder = false)
0456f7 2269     {
TB 2270         // message UID (or comma-separated list of IDs) is provided in
2271         // the form of <ID>-<MBOX>[,<ID>-<MBOX>]*
2272
08bb20 2273         $_uid  = $uids ?: rcube_utils::get_input_value('_uid', rcube_utils::INPUT_GPC);
AM 2274         $_mbox = $mbox ?: (string) rcube_utils::get_input_value('_mbox', rcube_utils::INPUT_GPC);
0456f7 2275
188247 2276         // already a hash array
TB 2277         if (is_array($_uid) && !isset($_uid[0])) {
2278             return $_uid;
0456f7 2279         }
TB 2280
2281         $result = array();
0f48e6 2282
TB 2283         // special case: *
2284         if ($_uid == '*' && is_object($_SESSION['search'][1]) && $_SESSION['search'][1]->multi) {
b8bcca 2285             $is_multifolder = true;
0f48e6 2286             // extract the full list of UIDs per folder from the search set
TB 2287             foreach ($_SESSION['search'][1]->sets as $subset) {
2288                 $mbox = $subset->get_parameters('MAILBOX');
2289                 $result[$mbox] = $subset->get();
2290             }
2291         }
2292         else {
188247 2293             if (is_string($_uid))
TB 2294                 $_uid = explode(',', $_uid);
2295
0f48e6 2296             // create a per-folder UIDs array
188247 2297             foreach ((array)$_uid as $uid) {
0f48e6 2298                 list($uid, $mbox) = explode('-', $uid, 2);
b8bcca 2299                 if (!strlen($mbox)) {
0f48e6 2300                     $mbox = $_mbox;
b8bcca 2301                 }
AM 2302                 else {
2303                     $is_multifolder = true;
2304                 }
2305
2306                 if ($uid == '*') {
518963 2307                     $result[$mbox] = $uid;
b8bcca 2308                 }
AM 2309                 else {
518963 2310                     $result[$mbox][] = $uid;
b8bcca 2311                 }
0f48e6 2312             }
0456f7 2313         }
TB 2314
2315         return $result;
2316     }
2317
c6efcf 2318     /**
AM 2319      * Get resource file content (with assets_dir support)
2320      *
2321      * @param string $name File name
a0f38f 2322      *
AM 2323      * @return string File content
c6efcf 2324      */
AM 2325     public function get_resource_content($name)
2326     {
2327         if (!strpos($name, '/')) {
2328             $name = "program/resources/$name";
2329         }
2330
2331         $assets_dir = $this->config->get('assets_dir');
2332
2333         if ($assets_dir) {
2334             $path = slashify($assets_dir) . $name;
2335             if (@file_exists($path)) {
2336                 $name = $path;
2337             }
2338         }
2339
2340         return file_get_contents($name, false);
2341     }
2342
a63f14 2343     /**
AM 2344      * Converts HTML content into plain text
2345      *
2346      * @param string $html    HTML content
2347      * @param array  $options Conversion parameters (width, links, charset)
2348      *
2349      * @return string Plain text
2350      */
c4daf3 2351     public function html2text($html, $options = array())
a63f14 2352     {
AM 2353         $default_options = array(
2354             'links'   => true,
2355             'width'   => 75,
2356             'body'    => $html,
2357             'charset' => RCUBE_CHARSET,
2358         );
2359
c4daf3 2360         $options = array_merge($default_options, (array) $options);
a63f14 2361
AM 2362         // Plugins may want to modify HTML in another/additional way
2363         $options = $this->plugins->exec_hook('html2text', $options);
2364
2365         // Convert to text
2366         if (!$options['abort']) {
2367             $converter = new rcube_html2text($options['body'],
2368                 false, $options['links'], $options['width'], $options['charset']);
2369
2370             $options['body'] = rtrim($converter->get_text());
2371         }
2372
2373         return $options['body'];
2374     }
2375
5a575b 2376     /**
AM 2377      * Connect to the mail storage server with stored session data
2378      *
2379      * @return bool True on success, False on error
2380      */
2381     public function storage_connect()
2382     {
2383         $storage = $this->get_storage();
2384
2385         if ($_SESSION['storage_host'] && !$storage->is_connected()) {
2386             $host = $_SESSION['storage_host'];
2387             $user = $_SESSION['username'];
2388             $port = $_SESSION['storage_port'];
2389             $ssl  = $_SESSION['storage_ssl'];
2390             $pass = $this->decrypt($_SESSION['password']);
2391
2392             if (!$storage->connect($host, $user, $pass, $port, $ssl)) {
2393                 if (is_object($this->output)) {
7ea292 2394                     $this->output->show_message('storageerror', 'error');
5a575b 2395                 }
AM 2396             }
2397             else {
2398                 $this->set_storage_prop();
2399             }
2400         }
2401
5f6c71 2402         return $storage->is_connected();
5a575b 2403     }
197601 2404 }