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