Aleksander Machniak
2016-02-09 d66793f0af519ff68a1f785ed65e686a1341a79a
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         }
816
06fdaf 817         if ($absolute || $full) {
TB 818             // add base path to this Roundcube installation
819             if ($base_path == '') $base_path = '/';
5f5812 820             $prefix = $base_path;
AM 821
822             // prepend protocol://hostname:port
823             if ($full) {
824                 $prefix = rcube_utils::resolve_url($prefix);
825             }
826
827             $prefix = rtrim($prefix, '/') . '/';
06fdaf 828         }
TB 829         else {
830             $prefix = './';
831         }
832
833         return $prefix . $url;
0301d9 834     }
AM 835
836     /**
837      * Function to be executed in script shutdown
838      */
839     public function shutdown()
840     {
841         parent::shutdown();
842
843         foreach ($this->address_books as $book) {
844             if (is_object($book) && is_a($book, 'rcube_addressbook'))
845                 $book->close();
846         }
847
848         // write performance stats to logs/console
48e92f 849         if ($this->config->get('devel_mode') || $this->config->get('performance_stats')) {
70c0d2 850             // make sure logged numbers use unified format
AM 851             setlocale(LC_NUMERIC, 'en_US.utf8', 'en_US.UTF-8', 'en_US', 'C');
852
0301d9 853             if (function_exists('memory_get_usage'))
AM 854                 $mem = $this->show_bytes(memory_get_usage());
855             if (function_exists('memory_get_peak_usage'))
856                 $mem .= '/'.$this->show_bytes(memory_get_peak_usage());
857
858             $log = $this->task . ($this->action ? '/'.$this->action : '') . ($mem ? " [$mem]" : '');
859
860             if (defined('RCMAIL_START'))
861                 self::print_timer(RCMAIL_START, $log);
862             else
863                 self::console($log);
864         }
865     }
866
867     /**
681ba6 868      * CSRF attack prevention code
AM 869      *
870      * @param int Request mode
871      */
872     public function request_security_check($mode = rcube_utils::INPUT_POST)
873     {
874         // check request token
875         if (!$this->check_request($mode)) {
876             self::raise_error(array(
877                 'code' => 403, 'type' => 'php',
878                 'message' => "Request security check failed"), false, true);
879         }
880
881         // check referer if configured
882         if ($this->config->get('referer_check') && !rcube_utils::check_referer()) {
883             self::raise_error(array(
884                 'code' => 403, 'type' => 'php',
885                 'message' => "Referer check failed"), true, true);
886         }
887     }
888
889     /**
0301d9 890      * Registers action aliases for current task
AM 891      *
892      * @param array $map Alias-to-filename hash array
893      */
894     public function register_action_map($map)
895     {
896         if (is_array($map)) {
897             foreach ($map as $idx => $val) {
898                 $this->action_map[$idx] = $val;
899             }
900         }
901     }
902
903     /**
904      * Returns current action filename
905      *
906      * @param array $map Alias-to-filename hash array
907      */
908     public function get_action_file()
909     {
910         if (!empty($this->action_map[$this->action])) {
911             return $this->action_map[$this->action];
912         }
913
914         return strtr($this->action, '-', '_') . '.inc';
915     }
916
917     /**
918      * Fixes some user preferences according to namespace handling change.
919      * Old Roundcube versions were using folder names with removed namespace prefix.
920      * Now we need to add the prefix on servers where personal namespace has prefix.
921      *
922      * @param rcube_user $user User object
923      */
924     private function fix_namespace_settings($user)
925     {
926         $prefix     = $this->storage->get_namespace('prefix');
927         $prefix_len = strlen($prefix);
928
6d5a1b 929         if (!$prefix_len) {
0301d9 930             return;
6d5a1b 931         }
0301d9 932
6d5a1b 933         if ($this->config->get('namespace_fixed')) {
0301d9 934             return;
6d5a1b 935         }
AM 936
937         $prefs = array();
0301d9 938
AM 939         // Build namespace prefix regexp
940         $ns     = $this->storage->get_namespace();
941         $regexp = array();
942
943         foreach ($ns as $entry) {
944             if (!empty($entry)) {
945                 foreach ($entry as $item) {
946                     if (strlen($item[0])) {
947                         $regexp[] = preg_quote($item[0], '/');
948                     }
949                 }
950             }
951         }
952         $regexp = '/^('. implode('|', $regexp).')/';
953
954         // Fix preferences
955         $opts = array('drafts_mbox', 'junk_mbox', 'sent_mbox', 'trash_mbox', 'archive_mbox');
956         foreach ($opts as $opt) {
6d5a1b 957             if ($value = $this->config->get($opt)) {
0301d9 958                 if ($value != 'INBOX' && !preg_match($regexp, $value)) {
AM 959                     $prefs[$opt] = $prefix.$value;
960                 }
961             }
962         }
963
6d5a1b 964         if (($search_mods = $this->config->get('search_mods')) && !empty($search_mods)) {
0301d9 965             $folders = array();
6d5a1b 966             foreach ($search_mods as $idx => $value) {
0301d9 967                 if ($idx != 'INBOX' && $idx != '*' && !preg_match($regexp, $idx)) {
AM 968                     $idx = $prefix.$idx;
969                 }
970                 $folders[$idx] = $value;
971             }
972
973             $prefs['search_mods'] = $folders;
974         }
975
6d5a1b 976         if (($threading = $this->config->get('message_threading')) && !empty($threading)) {
0301d9 977             $folders = array();
6d5a1b 978             foreach ($threading as $idx => $value) {
0301d9 979                 if ($idx != 'INBOX' && !preg_match($regexp, $idx)) {
AM 980                     $idx = $prefix.$idx;
981                 }
982                 $folders[$prefix.$idx] = $value;
983             }
984
985             $prefs['message_threading'] = $folders;
986         }
987
6d5a1b 988         if ($collapsed = $this->config->get('collapsed_folders')) {
AM 989             $folders     = explode('&&', $collapsed);
0301d9 990             $count       = count($folders);
AM 991             $folders_str = '';
992
993             if ($count) {
994                 $folders[0]        = substr($folders[0], 1);
995                 $folders[$count-1] = substr($folders[$count-1], 0, -1);
996             }
997
998             foreach ($folders as $value) {
999                 if ($value != 'INBOX' && !preg_match($regexp, $value)) {
1000                     $value = $prefix.$value;
1001                 }
1002                 $folders_str .= '&'.$value.'&';
1003             }
1004
1005             $prefs['collapsed_folders'] = $folders_str;
1006         }
1007
1008         $prefs['namespace_fixed'] = true;
1009
1010         // save updated preferences and reset imap settings (default folders)
1011         $user->save_prefs($prefs);
1012         $this->set_storage_prop();
1013     }
0c2596 1014
A 1015     /**
1016      * Overwrite action variable
1017      *
1018      * @param string New action value
1019      */
1020     public function overwrite_action($action)
1021     {
1022         $this->action = $action;
1023         $this->output->set_env('action', $action);
1024     }
1025
1026     /**
f5d2ee 1027      * Set environment variables for specified config options
AM 1028      */
1029     public function set_env_config($options)
1030     {
1031         foreach ((array) $options as $option) {
1032             if ($this->config->get($option)) {
1033                 $this->output->set_env($option, true);
1034             }
1035         }
1036     }
1037
1038     /**
0c2596 1039      * Returns RFC2822 formatted current date in user's timezone
A 1040      *
1041      * @return string Date
1042      */
1043     public function user_date()
1044     {
1045         // get user's timezone
1046         try {
1047             $tz   = new DateTimeZone($this->config->get('timezone'));
1048             $date = new DateTime('now', $tz);
1049         }
1050         catch (Exception $e) {
1051             $date = new DateTime();
1052         }
1053
1054         return $date->format('r');
1055     }
1056
1057     /**
1058      * Write login data (name, ID, IP address) to the 'userlogins' log file.
1059      */
0f5574 1060     public function log_login($user = null, $failed_login = false, $error_code = 0)
0c2596 1061     {
A 1062         if (!$this->config->get('log_logins')) {
1063             return;
1064         }
1065
060467 1066         // failed login
AM 1067         if ($failed_login) {
1068             $message = sprintf('Failed login for %s from %s in session %s (error: %d)',
1069                 $user, rcube_utils::remote_ip(), session_id(), $error_code);
1070         }
1071         // successful login
1072         else {
1073             $user_name = $this->get_user_name();
1074             $user_id   = $this->get_user_id();
0c2596 1075
060467 1076             if (!$user_id) {
AM 1077                 return;
1078             }
1079
1080             $message = sprintf('Successful login for %s (ID: %d) from %s in session %s',
0301d9 1081                 $user_name, $user_id, rcube_utils::remote_ip(), session_id());
0c2596 1082         }
A 1083
060467 1084         // log login
AM 1085         self::write_log('userlogins', $message);
0c2596 1086     }
1aceb9 1087
A 1088     /**
1089      * Create a HTML table based on the given data
1090      *
1091      * @param  array  Named table attributes
1092      * @param  mixed  Table row data. Either a two-dimensional array or a valid SQL result set
1093      * @param  array  List of cols to show
1094      * @param  string Name of the identifier col
1095      *
1096      * @return string HTML table code
1097      */
1098     public function table_output($attrib, $table_data, $a_show_cols, $id_col)
1099     {
517dae 1100         $table = new html_table($attrib);
1aceb9 1101
A 1102         // add table header
1103         if (!$attrib['noheader']) {
1104             foreach ($a_show_cols as $col) {
1105                 $table->add_header($col, $this->Q($this->gettext($col)));
1106             }
1107         }
1108
1109         if (!is_array($table_data)) {
1110             $db = $this->get_dbh();
1111             while ($table_data && ($sql_arr = $db->fetch_assoc($table_data))) {
1112                 $table->add_row(array('id' => 'rcmrow' . rcube_utils::html_identifier($sql_arr[$id_col])));
1113
1114                 // format each col
1115                 foreach ($a_show_cols as $col) {
1116                     $table->add($col, $this->Q($sql_arr[$col]));
1117                 }
1118             }
1119         }
1120         else {
1121             foreach ($table_data as $row_data) {
77043f 1122                 $class = !empty($row_data['class']) ? $row_data['class'] : null;
TB 1123                 if (!empty($attrib['rowclass']))
1124                     $class = trim($class . ' ' . $attrib['rowclass']);
1aceb9 1125                 $rowid = 'rcmrow' . rcube_utils::html_identifier($row_data[$id_col]);
A 1126
1127                 $table->add_row(array('id' => $rowid, 'class' => $class));
1128
1129                 // format each col
1130                 foreach ($a_show_cols as $col) {
77043f 1131                     $val = is_array($row_data[$col]) ? $row_data[$col][0] : $row_data[$col];
TB 1132                     $table->add($col, empty($attrib['ishtml']) ? $this->Q($val) : $val);
1aceb9 1133                 }
A 1134             }
1135         }
1136
1137         return $table->show($attrib);
1138     }
1139
1140     /**
1141      * Convert the given date to a human readable form
1142      * This uses the date formatting properties from config
1143      *
1144      * @param mixed  Date representation (string, timestamp or DateTime object)
1145      * @param string Date format to use
1146      * @param bool   Enables date convertion according to user timezone
1147      *
1148      * @return string Formatted date string
1149      */
1150     public function format_date($date, $format = null, $convert = true)
1151     {
1152         if (is_object($date) && is_a($date, 'DateTime')) {
1153             $timestamp = $date->format('U');
1154         }
1155         else {
1156             if (!empty($date)) {
6075f0 1157                 $timestamp = rcube_utils::strtotime($date);
1aceb9 1158             }
A 1159
1160             if (empty($timestamp)) {
1161                 return '';
1162             }
1163
1164             try {
1165                 $date = new DateTime("@".$timestamp);
1166             }
1167             catch (Exception $e) {
1168                 return '';
1169             }
1170         }
1171
1172         if ($convert) {
1173             try {
1174                 // convert to the right timezone
1175                 $stz = date_default_timezone_get();
1176                 $tz = new DateTimeZone($this->config->get('timezone'));
1177                 $date->setTimezone($tz);
1178                 date_default_timezone_set($tz->getName());
1179
1180                 $timestamp = $date->format('U');
1181             }
1182             catch (Exception $e) {
1183             }
1184         }
1185
1186         // define date format depending on current time
1187         if (!$format) {
1188             $now         = time();
1189             $now_date    = getdate($now);
1190             $today_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday'], $now_date['year']);
1191             $week_limit  = mktime(0, 0, 0, $now_date['mon'], $now_date['mday']-6, $now_date['year']);
1192             $pretty_date = $this->config->get('prettydate');
1193
2b05c5 1194             if ($pretty_date && $timestamp > $today_limit && $timestamp <= $now) {
1aceb9 1195                 $format = $this->config->get('date_today', $this->config->get('time_format', 'H:i'));
A 1196                 $today  = true;
1197             }
2b05c5 1198             else if ($pretty_date && $timestamp > $week_limit && $timestamp <= $now) {
1aceb9 1199                 $format = $this->config->get('date_short', 'D H:i');
A 1200             }
1201             else {
1202                 $format = $this->config->get('date_long', 'Y-m-d H:i');
1203             }
1204         }
1205
1206         // strftime() format
1207         if (preg_match('/%[a-z]+/i', $format)) {
1208             $format = strftime($format, $timestamp);
1209             if ($stz) {
1210                 date_default_timezone_set($stz);
1211             }
1212             return $today ? ($this->gettext('today') . ' ' . $format) : $format;
1213         }
1214
1215         // parse format string manually in order to provide localized weekday and month names
1216         // an alternative would be to convert the date() format string to fit with strftime()
1217         $out = '';
1218         for ($i=0; $i<strlen($format); $i++) {
1219             if ($format[$i] == "\\") {  // skip escape chars
1220                 continue;
1221             }
1222
1223             // write char "as-is"
1224             if ($format[$i] == ' ' || $format[$i-1] == "\\") {
1225                 $out .= $format[$i];
1226             }
1227             // weekday (short)
1228             else if ($format[$i] == 'D') {
1229                 $out .= $this->gettext(strtolower(date('D', $timestamp)));
1230             }
1231             // weekday long
1232             else if ($format[$i] == 'l') {
1233                 $out .= $this->gettext(strtolower(date('l', $timestamp)));
1234             }
1235             // month name (short)
1236             else if ($format[$i] == 'M') {
1237                 $out .= $this->gettext(strtolower(date('M', $timestamp)));
1238             }
1239             // month name (long)
1240             else if ($format[$i] == 'F') {
1241                 $out .= $this->gettext('long'.strtolower(date('M', $timestamp)));
1242             }
1243             else if ($format[$i] == 'x') {
1244                 $out .= strftime('%x %X', $timestamp);
1245             }
1246             else {
1247                 $out .= date($format[$i], $timestamp);
1248             }
1249         }
1250
1251         if ($today) {
1252             $label = $this->gettext('today');
1253             // replcae $ character with "Today" label (#1486120)
1254             if (strpos($out, '$') !== false) {
1255                 $out = preg_replace('/\$/', $label, $out, 1);
1256             }
1257             else {
1258                 $out = $label . ' ' . $out;
1259             }
1260         }
1261
1262         if ($stz) {
1263             date_default_timezone_set($stz);
1264         }
1265
1266         return $out;
1267     }
1268
1269     /**
1270      * Return folders list in HTML
1271      *
1272      * @param array $attrib Named parameters
1273      *
1274      * @return string HTML code for the gui object
1275      */
1276     public function folder_list($attrib)
1277     {
1278         static $a_mailboxes;
1279
1280         $attrib += array('maxlength' => 100, 'realnames' => false, 'unreadwrap' => ' (%s)');
1281
1282         $rcmail  = rcmail::get_instance();
1283         $storage = $rcmail->get_storage();
1284
1285         // add some labels to client
1286         $rcmail->output->add_label('purgefolderconfirm', 'deletemessagesconfirm');
1287
1288         $type = $attrib['type'] ? $attrib['type'] : 'ul';
1289         unset($attrib['type']);
1290
1291         if ($type == 'ul' && !$attrib['id']) {
1292             $attrib['id'] = 'rcmboxlist';
1293         }
1294
1295         if (empty($attrib['folder_name'])) {
1296             $attrib['folder_name'] = '*';
1297         }
1298
1299         // get current folder
1300         $mbox_name = $storage->get_folder();
1301
1302         // build the folders tree
1303         if (empty($a_mailboxes)) {
1304             // get mailbox list
1305             $a_folders = $storage->list_folders_subscribed(
1306                 '', $attrib['folder_name'], $attrib['folder_filter']);
1307             $delimiter = $storage->get_hierarchy_delimiter();
1308             $a_mailboxes = array();
1309
1310             foreach ($a_folders as $folder) {
1311                 $rcmail->build_folder_tree($a_mailboxes, $folder, $delimiter);
1312             }
1313         }
1314
1315         // allow plugins to alter the folder tree or to localize folder names
1316         $hook = $rcmail->plugins->exec_hook('render_mailboxlist', array(
1317             'list'      => $a_mailboxes,
1318             'delimiter' => $delimiter,
1319             'type'      => $type,
1320             'attribs'   => $attrib,
1321         ));
1322
1323         $a_mailboxes = $hook['list'];
1324         $attrib      = $hook['attribs'];
1325
1326         if ($type == 'select') {
0a1dd5 1327             $attrib['is_escaped'] = true;
1aceb9 1328             $select = new html_select($attrib);
A 1329
1330             // add no-selection option
1331             if ($attrib['noselection']) {
0a1dd5 1332                 $select->add(html::quote($rcmail->gettext($attrib['noselection'])), '');
1aceb9 1333             }
A 1334
1335             $rcmail->render_folder_tree_select($a_mailboxes, $mbox_name, $attrib['maxlength'], $select, $attrib['realnames']);
1336             $out = $select->show($attrib['default']);
1337         }
1338         else {
1339             $js_mailboxlist = array();
9a0153 1340             $tree = $rcmail->render_folder_tree_html($a_mailboxes, $mbox_name, $js_mailboxlist, $attrib);
1aceb9 1341
9a0153 1342             if ($type != 'js') {
AM 1343                 $out = html::tag('ul', $attrib, $tree, html::$common_attrib);
1344
1345                 $rcmail->output->include_script('treelist.js');
1346                 $rcmail->output->add_gui_object('mailboxlist', $attrib['id']);
1347                 $rcmail->output->set_env('unreadwrap', $attrib['unreadwrap']);
1348                 $rcmail->output->set_env('collapsed_folders', (string)$rcmail->config->get('collapsed_folders'));
1349             }
1350
1aceb9 1351             $rcmail->output->set_env('mailboxes', $js_mailboxlist);
9a0153 1352
AM 1353             // we can't use object keys in javascript because they are unordered
1354             // we need sorted folders list for folder-selector widget
1355             $rcmail->output->set_env('mailboxes_list', array_keys($js_mailboxlist));
1aceb9 1356         }
A 1357
1358         return $out;
1359     }
1360
1361     /**
1362      * Return folders list as html_select object
1363      *
1364      * @param array $p  Named parameters
1365      *
1366      * @return html_select HTML drop-down object
1367      */
1368     public function folder_selector($p = array())
1369     {
4a9a0e 1370         $realnames = $this->config->get('show_real_foldernames');
DC 1371         $p += array('maxlength' => 100, 'realnames' => $realnames, 'is_escaped' => true);
1aceb9 1372         $a_mailboxes = array();
A 1373         $storage = $this->get_storage();
1374
1375         if (empty($p['folder_name'])) {
1376             $p['folder_name'] = '*';
1377         }
1378
1379         if ($p['unsubscribed']) {
1380             $list = $storage->list_folders('', $p['folder_name'], $p['folder_filter'], $p['folder_rights']);
1381         }
1382         else {
1383             $list = $storage->list_folders_subscribed('', $p['folder_name'], $p['folder_filter'], $p['folder_rights']);
1384         }
1385
1386         $delimiter = $storage->get_hierarchy_delimiter();
1387
1597c8 1388         if (!empty($p['exceptions'])) {
AM 1389             $list = array_diff($list, (array) $p['exceptions']);
1390         }
1391
1392         if (!empty($p['additional'])) {
1393             foreach ($p['additional'] as $add_folder) {
1394                 $add_items = explode($delimiter, $add_folder);
1395                 $folder    = '';
1396                 while (count($add_items)) {
1397                     $folder .= array_shift($add_items);
1398
1399                     // @TODO: sorting
1400                     if (!in_array($folder, $list)) {
1401                         $list[] = $folder;
1402                     }
1403
1404                     $folder .= $delimiter;
1405                 }
1aceb9 1406             }
A 1407         }
1408
1597c8 1409         foreach ($list as $folder) {
AM 1410             $this->build_folder_tree($a_mailboxes, $folder, $delimiter);
1411         }
1412
1aceb9 1413         $select = new html_select($p);
A 1414
1415         if ($p['noselection']) {
0a1dd5 1416             $select->add(html::quote($p['noselection']), '');
1aceb9 1417         }
A 1418
1419         $this->render_folder_tree_select($a_mailboxes, $mbox, $p['maxlength'], $select, $p['realnames'], 0, $p);
1420
1421         return $select;
1422     }
1423
1424     /**
1425      * Create a hierarchical array of the mailbox list
1426      */
1427     public function build_folder_tree(&$arrFolders, $folder, $delm = '/', $path = '')
1428     {
1429         // Handle namespace prefix
1430         $prefix = '';
1431         if (!$path) {
1432             $n_folder = $folder;
1433             $folder = $this->storage->mod_folder($folder);
1434
1435             if ($n_folder != $folder) {
1436                 $prefix = substr($n_folder, 0, -strlen($folder));
1437             }
1438         }
1439
1440         $pos = strpos($folder, $delm);
1441
1442         if ($pos !== false) {
1443             $subFolders    = substr($folder, $pos+1);
1444             $currentFolder = substr($folder, 0, $pos);
1445
1446             // sometimes folder has a delimiter as the last character
1447             if (!strlen($subFolders)) {
1448                 $virtual = false;
1449             }
1450             else if (!isset($arrFolders[$currentFolder])) {
1451                 $virtual = true;
1452             }
1453             else {
1454                 $virtual = $arrFolders[$currentFolder]['virtual'];
1455             }
1456         }
1457         else {
1458             $subFolders    = false;
1459             $currentFolder = $folder;
1460             $virtual       = false;
1461         }
1462
1463         $path .= $prefix . $currentFolder;
1464
1465         if (!isset($arrFolders[$currentFolder])) {
1466             $arrFolders[$currentFolder] = array(
1467                 'id' => $path,
1468                 'name' => rcube_charset::convert($currentFolder, 'UTF7-IMAP'),
1469                 'virtual' => $virtual,
1470                 'folders' => array());
1471         }
1472         else {
1473             $arrFolders[$currentFolder]['virtual'] = $virtual;
1474         }
1475
1476         if (strlen($subFolders)) {
1477             $this->build_folder_tree($arrFolders[$currentFolder]['folders'], $subFolders, $delm, $path.$delm);
1478         }
1479     }
1480
1481     /**
1482      * Return html for a structured list &lt;ul&gt; for the mailbox tree
1483      */
1484     public function render_folder_tree_html(&$arrFolders, &$mbox_name, &$jslist, $attrib, $nestLevel = 0)
1485     {
1486         $maxlength = intval($attrib['maxlength']);
1487         $realnames = (bool)$attrib['realnames'];
1488         $msgcounts = $this->storage->get_cache('messagecount');
1489         $collapsed = $this->config->get('collapsed_folders');
85e65c 1490         $realnames = $this->config->get('show_real_foldernames');
52deb1 1491
1aceb9 1492         $out = '';
3725cf 1493         foreach ($arrFolders as $folder) {
1aceb9 1494             $title        = null;
A 1495             $folder_class = $this->folder_classname($folder['id']);
1496             $is_collapsed = strpos($collapsed, '&'.rawurlencode($folder['id']).'&') !== false;
1497             $unread       = $msgcounts ? intval($msgcounts[$folder['id']]['UNSEEN']) : 0;
1498
1499             if ($folder_class && !$realnames) {
1500                 $foldername = $this->gettext($folder_class);
1501             }
1502             else {
1503                 $foldername = $folder['name'];
1504
1505                 // shorten the folder name to a given length
1506                 if ($maxlength && $maxlength > 1) {
1507                     $fname = abbreviate_string($foldername, $maxlength);
1508                     if ($fname != $foldername) {
1509                         $title = $foldername;
1510                     }
1511                     $foldername = $fname;
1512                 }
1513             }
1514
1515             // make folder name safe for ids and class names
1516             $folder_id = rcube_utils::html_identifier($folder['id'], true);
1517             $classes   = array('mailbox');
1518
1519             // set special class for Sent, Drafts, Trash and Junk
1520             if ($folder_class) {
1521                 $classes[] = $folder_class;
1522             }
1523
1524             if ($folder['id'] == $mbox_name) {
1525                 $classes[] = 'selected';
1526             }
1527
1528             if ($folder['virtual']) {
1529                 $classes[] = 'virtual';
1530             }
1531             else if ($unread) {
1532                 $classes[] = 'unread';
1533             }
1534
1535             $js_name = $this->JQ($folder['id']);
1536             $html_name = $this->Q($foldername) . ($unread ? html::span('unreadcount', sprintf($attrib['unreadwrap'], $unread)) : '');
1537             $link_attrib = $folder['virtual'] ? array() : array(
1538                 'href' => $this->url(array('_mbox' => $folder['id'])),
d58c39 1539                 'onclick' => sprintf("return %s.command('list','%s',this,event)", rcmail_output::JS_OBJECT_NAME, $js_name),
1aceb9 1540                 'rel' => $folder['id'],
A 1541                 'title' => $title,
1542             );
1543
1544             $out .= html::tag('li', array(
1545                 'id' => "rcmli".$folder_id,
1546                 'class' => join(' ', $classes),
1547                 'noclose' => true),
3c309a 1548                 html::a($link_attrib, $html_name));
1aceb9 1549
3c309a 1550             if (!empty($folder['folders'])) {
TB 1551                 $out .= html::div('treetoggle ' . ($is_collapsed ? 'collapsed' : 'expanded'), '&nbsp;');
1552             }
1553
1554             $jslist[$folder['id']] = array(
1aceb9 1555                 'id'      => $folder['id'],
A 1556                 'name'    => $foldername,
9a0153 1557                 'virtual' => $folder['virtual'],
1aceb9 1558             );
A 1559
9a0153 1560             if (!empty($folder_class)) {
AM 1561                 $jslist[$folder['id']]['class'] = $folder_class;
1562             }
1563
1aceb9 1564             if (!empty($folder['folders'])) {
A 1565                 $out .= html::tag('ul', array('style' => ($is_collapsed ? "display:none;" : null)),
1566                     $this->render_folder_tree_html($folder['folders'], $mbox_name, $jslist, $attrib, $nestLevel+1));
1567             }
1568
1569             $out .= "</li>\n";
1570         }
1571
1572         return $out;
1573     }
1574
1575     /**
1576      * Return html for a flat list <select> for the mailbox tree
1577      */
1578     public function render_folder_tree_select(&$arrFolders, &$mbox_name, $maxlength, &$select, $realnames = false, $nestLevel = 0, $opts = array())
1579     {
1580         $out = '';
1581
3725cf 1582         foreach ($arrFolders as $folder) {
1aceb9 1583             // skip exceptions (and its subfolders)
A 1584             if (!empty($opts['exceptions']) && in_array($folder['id'], $opts['exceptions'])) {
1585                 continue;
1586             }
1587
1588             // skip folders in which it isn't possible to create subfolders
1589             if (!empty($opts['skip_noinferiors'])) {
1590                 $attrs = $this->storage->folder_attributes($folder['id']);
19a618 1591                 if ($attrs && in_array_nocase('\\Noinferiors', $attrs)) {
1aceb9 1592                     continue;
A 1593                 }
1594             }
1595
1596             if (!$realnames && ($folder_class = $this->folder_classname($folder['id']))) {
1597                 $foldername = $this->gettext($folder_class);
1598             }
1599             else {
1600                 $foldername = $folder['name'];
1601
1602                 // shorten the folder name to a given length
1603                 if ($maxlength && $maxlength > 1) {
1604                     $foldername = abbreviate_string($foldername, $maxlength);
1605                 }
e7ca04 1606             }
1aceb9 1607
0a1dd5 1608             $select->add(str_repeat('&nbsp;', $nestLevel*4) . html::quote($foldername), $folder['id']);
1aceb9 1609
e7ca04 1610             if (!empty($folder['folders'])) {
A 1611                 $out .= $this->render_folder_tree_select($folder['folders'], $mbox_name, $maxlength,
1612                     $select, $realnames, $nestLevel+1, $opts);
1aceb9 1613             }
A 1614         }
1615
1616         return $out;
1617     }
1618
1619     /**
1620      * Return internal name for the given folder if it matches the configured special folders
1621      */
1622     public function folder_classname($folder_id)
1623     {
1624         if ($folder_id == 'INBOX') {
1625             return 'inbox';
1626         }
1627
1628         // for these mailboxes we have localized labels and css classes
1629         foreach (array('sent', 'drafts', 'trash', 'junk') as $smbx)
1630         {
1631             if ($folder_id === $this->config->get($smbx.'_mbox')) {
1632                 return $smbx;
1633             }
1634         }
1635     }
1636
1637     /**
1638      * Try to localize the given IMAP folder name.
1639      * UTF-7 decode it in case no localized text was found
1640      *
4d7964 1641      * @param string $name      Folder name
AM 1642      * @param bool   $with_path Enable path localization
1aceb9 1643      *
A 1644      * @return string Localized folder name in UTF-8 encoding
1645      */
cb29c9 1646     public function localize_foldername($name, $with_path = false)
1aceb9 1647     {
85e65c 1648         $realnames = $this->config->get('show_real_foldernames');
cb29c9 1649
AM 1650         if (!$realnames && ($folder_class = $this->folder_classname($name))) {
1651             return $this->gettext($folder_class);
1652         }
85e65c 1653
4d7964 1654         // try to localize path of the folder
85e65c 1655         if ($with_path && !$realnames) {
4d7964 1656             $storage   = $this->get_storage();
AM 1657             $delimiter = $storage->get_hierarchy_delimiter();
1658             $path      = explode($delimiter, $name);
1659             $count     = count($path);
1660
1661             if ($count > 1) {
a12bbb 1662                 for ($i = 1; $i < $count; $i++) {
4d7964 1663                     $folder = implode($delimiter, array_slice($path, 0, -$i));
85e65c 1664                     if ($folder_class = $this->folder_classname($folder)) {
4d7964 1665                         $name = implode($delimiter, array_slice($path, $count - $i));
AM 1666                         return $this->gettext($folder_class) . $delimiter . rcube_charset::convert($name, 'UTF7-IMAP');
1667                     }
1668                 }
1669             }
1aceb9 1670         }
85e65c 1671
AM 1672         return rcube_charset::convert($name, 'UTF7-IMAP');
1aceb9 1673     }
A 1674
1675
1676     public function localize_folderpath($path)
1677     {
1678         $protect_folders = $this->config->get('protect_default_folders');
1679         $delimiter       = $this->storage->get_hierarchy_delimiter();
1680         $path            = explode($delimiter, $path);
1681         $result          = array();
1682
1683         foreach ($path as $idx => $dir) {
1684             $directory = implode($delimiter, array_slice($path, 0, $idx+1));
dc0b50 1685             if ($protect_folders && $this->storage->is_special_folder($directory)) {
1aceb9 1686                 unset($result);
A 1687                 $result[] = $this->localize_foldername($directory);
1688             }
1689             else {
1690                 $result[] = rcube_charset::convert($dir, 'UTF7-IMAP');
1691             }
1692         }
1693
1694         return implode($delimiter, $result);
1695     }
1696
1697
1698     public static function quota_display($attrib)
1699     {
1700         $rcmail = rcmail::get_instance();
1701
1702         if (!$attrib['id']) {
1703             $attrib['id'] = 'rcmquotadisplay';
1704         }
1705
1706         $_SESSION['quota_display'] = !empty($attrib['display']) ? $attrib['display'] : 'text';
1707
1708         $rcmail->output->add_gui_object('quotadisplay', $attrib['id']);
1709
1710         $quota = $rcmail->quota_content($attrib);
1711
1712         $rcmail->output->add_script('rcmail.set_quota('.rcube_output::json_serialize($quota).');', 'docready');
1713
edca65 1714         return html::span($attrib, '&nbsp;');
1aceb9 1715     }
A 1716
1717
b8bcca 1718     public function quota_content($attrib = null, $folder = null)
1aceb9 1719     {
b8bcca 1720         $quota = $this->storage->get_quota($folder);
1aceb9 1721         $quota = $this->plugins->exec_hook('quota', $quota);
A 1722
1723         $quota_result = (array) $quota;
5312b7 1724         $quota_result['type']   = isset($_SESSION['quota_display']) ? $_SESSION['quota_display'] : '';
AM 1725         $quota_result['folder'] = $folder !== null && $folder !== '' ? $folder : 'INBOX';
1aceb9 1726
4fee77 1727         if ($quota['total'] > 0) {
1aceb9 1728             if (!isset($quota['percent'])) {
A 1729                 $quota_result['percent'] = min(100, round(($quota['used']/max(1,$quota['total']))*100));
1730             }
1731
1732             $title = sprintf('%s / %s (%.0f%%)',
1733                 $this->show_bytes($quota['used'] * 1024), $this->show_bytes($quota['total'] * 1024),
1734                 $quota_result['percent']);
1735
1736             $quota_result['title'] = $title;
1737
1738             if ($attrib['width']) {
1739                 $quota_result['width'] = $attrib['width'];
1740             }
1741             if ($attrib['height']) {
c5f068 1742                 $quota_result['height'] = $attrib['height'];
AM 1743             }
1744
1745             // build a table of quota types/roots info
1746             if (($root_cnt = count($quota_result['all'])) > 1 || count($quota_result['all'][key($quota_result['all'])]) > 1) {
1747                 $table = new html_table(array('cols' => 3, 'class' => 'quota-info'));
1748
1749                 $table->add_header(null, self::Q($this->gettext('quotatype')));
1750                 $table->add_header(null, self::Q($this->gettext('quotatotal')));
1751                 $table->add_header(null, self::Q($this->gettext('quotaused')));
1752
1753                 foreach ($quota_result['all'] as $root => $data) {
1754                     if ($root_cnt > 1 && $root) {
1755                         $table->add(array('colspan' => 3, 'class' => 'root'), self::Q($root));
1756                     }
1757
1758                     if ($storage = $data['storage']) {
1759                         $percent = min(100, round(($storage['used']/max(1,$storage['total']))*100));
1760
1761                         $table->add('name', self::Q($this->gettext('quotastorage')));
1762                         $table->add(null, $this->show_bytes($storage['total'] * 1024));
1763                         $table->add(null, sprintf('%s (%.0f%%)', $this->show_bytes($storage['used'] * 1024), $percent));
1764                     }
1765                     if ($message = $data['message']) {
1766                         $percent = min(100, round(($message['used']/max(1,$message['total']))*100));
1767
1768                         $table->add('name', self::Q($this->gettext('quotamessage')));
1769                         $table->add(null, intval($message['total']));
1770                         $table->add(null, sprintf('%d (%.0f%%)', $message['used'], $percent));
1771                     }
1772                 }
1773
1774                 $quota_result['table'] = $table->show();
1aceb9 1775             }
A 1776         }
1777         else {
4fee77 1778             $unlimited               = $this->config->get('quota_zero_as_unlimited');
AM 1779             $quota_result['title']   = $this->gettext($unlimited ? 'unlimited' : 'unknown');
1aceb9 1780             $quota_result['percent'] = 0;
A 1781         }
1782
c5f068 1783         // cleanup
AM 1784         unset($quota_result['abort']);
1785         if (empty($quota_result['table'])) {
1786             unset($quota_result['all']);
1787         }
1788
1aceb9 1789         return $quota_result;
A 1790     }
1791
1792     /**
1793      * Outputs error message according to server error/response codes
1794      *
1795      * @param string $fallback       Fallback message label
1796      * @param array  $fallback_args  Fallback message label arguments
e7c1aa 1797      * @param string $suffix         Message label suffix
bbbd02 1798      * @param array  $params         Additional parameters (type, prefix)
1aceb9 1799      */
bbbd02 1800     public function display_server_error($fallback = null, $fallback_args = null, $suffix = '', $params = array())
1aceb9 1801     {
A 1802         $err_code = $this->storage->get_error_code();
1803         $res_code = $this->storage->get_response_code();
e7c1aa 1804         $args     = array();
1aceb9 1805
524e48 1806         if ($res_code == rcube_storage::NOPERM) {
e7c1aa 1807             $error = 'errornoperm';
1aceb9 1808         }
A 1809         else if ($res_code == rcube_storage::READONLY) {
e7c1aa 1810             $error = 'errorreadonly';
1aceb9 1811         }
0bf724 1812         else if ($res_code == rcube_storage::OVERQUOTA) {
383724 1813             $error = 'erroroverquota';
0bf724 1814         }
1aceb9 1815         else if ($err_code && ($err_str = $this->storage->get_error_str())) {
A 1816             // try to detect access rights problem and display appropriate message
1817             if (stripos($err_str, 'Permission denied') !== false) {
e7c1aa 1818                 $error = 'errornoperm';
1aceb9 1819             }
0bf724 1820             // try to detect full mailbox problem and display appropriate message
bbbd02 1821             // there can be e.g. "Quota exceeded" / "quotum would exceed" / "Over quota"
AM 1822             else if (stripos($err_str, 'quot') !== false && preg_match('/exceed|over/i', $err_str)) {
e7c1aa 1823                 $error = 'erroroverquota';
0bf724 1824             }
1aceb9 1825             else {
e7c1aa 1826                 $error = 'servererrormsg';
15fd8f 1827                 $args  = array('msg' => rcube::Q($err_str));
1aceb9 1828             }
A 1829         }
524e48 1830         else if ($err_code < 0) {
e7c1aa 1831             $error = 'storageerror';
524e48 1832         }
1aceb9 1833         else if ($fallback) {
e7c1aa 1834             $error = $fallback;
AM 1835             $args  = $fallback_args;
bbbd02 1836             $params['prefix'] = false;
e7c1aa 1837         }
AM 1838
1839         if ($error) {
1840             if ($suffix && $this->text_exists($error . $suffix)) {
1841                 $error .= $suffix;
1842             }
bbbd02 1843
AM 1844             $msg = $this->gettext(array('name' => $error, 'vars' => $args));
1845
1846             if ($params['prefix'] && $fallback) {
1847                 $msg = $this->gettext(array('name' => $fallback, 'vars' => $fallback_args)) . ' ' . $msg;
1848             }
1849
1850             $this->output->show_message($msg, $params['type'] ?: 'error');
1aceb9 1851         }
A 1852     }
1853
1854     /**
1855      * Output HTML editor scripts
1856      *
1857      * @param string $mode  Editor mode
1858      */
1859     public function html_editor($mode = '')
1860     {
1861         $hook = $this->plugins->exec_hook('html_editor', array('mode' => $mode));
1862
1863         if ($hook['abort']) {
1864             return;
1865         }
1866
6fa5b4 1867         $lang_codes = array($_SESSION['language']);
1aceb9 1868
6fa5b4 1869         if ($pos = strpos($_SESSION['language'], '_')) {
AM 1870             $lang_codes[] = substr($_SESSION['language'], 0, $pos);
1aceb9 1871         }
A 1872
6fa5b4 1873         foreach ($lang_codes as $code) {
AM 1874             if (file_exists(INSTALL_PATH . 'program/js/tinymce/langs/'.$code.'.js')) {
1875                 $lang = $code;
1876                 break;
1877             }
1878         }
1879
1880         if (empty($lang)) {
1aceb9 1881             $lang = 'en';
A 1882         }
1883
646b64 1884         $config = array(
1aceb9 1885             'mode'       => $mode,
A 1886             'lang'       => $lang,
1887             'skin_path'  => $this->output->get_skin_path(),
1888             'spellcheck' => intval($this->config->get('enable_spellcheck')),
1889             'spelldict'  => intval($this->config->get('spellcheck_dictionary'))
646b64 1890         );
1aceb9 1891
c5bfe6 1892         $this->output->add_label('selectimage', 'addimage', 'selectmedia', 'addmedia');
646b64 1893         $this->output->set_env('editor_config', $config);
c5bfe6 1894         $this->output->include_css('program/js/tinymce/roundcube/browser.css');
6fa5b4 1895         $this->output->include_script('tinymce/tinymce.min.js');
1aceb9 1896         $this->output->include_script('editor.js');
A 1897     }
1898
1899     /**
1900      * Replaces TinyMCE's emoticon images with plain-text representation
1901      *
1902      * @param string $html  HTML content
1903      *
1904      * @return string HTML content
1905      */
1906     public static function replace_emoticons($html)
1907     {
1908         $emoticons = array(
1909             '8-)' => 'smiley-cool',
1910             ':-#' => 'smiley-foot-in-mouth',
1911             ':-*' => 'smiley-kiss',
1912             ':-X' => 'smiley-sealed',
1913             ':-P' => 'smiley-tongue-out',
1914             ':-@' => 'smiley-yell',
1915             ":'(" => 'smiley-cry',
1916             ':-(' => 'smiley-frown',
1917             ':-D' => 'smiley-laughing',
1918             ':-)' => 'smiley-smile',
1919             ':-S' => 'smiley-undecided',
1920             ':-$' => 'smiley-embarassed',
1921             'O:-)' => 'smiley-innocent',
1922             ':-|' => 'smiley-money-mouth',
1923             ':-O' => 'smiley-surprised',
1924             ';-)' => 'smiley-wink',
1925         );
1926
1927         foreach ($emoticons as $idx => $file) {
6fa5b4 1928             // <img title="Cry" src="http://.../program/js/tinymce/plugins/emoticons/img/smiley-cry.gif" border="0" alt="Cry" />
d66793 1929             $file      = preg_quote('program/js/tinymce/plugins/emoticons/img/' . $file . '.gif', '/');
AM 1930             $search[]  = '/<img (title="[a-z ]+" )?src="[^"]+' . $file . '"[^>]+\/>/i';
1aceb9 1931             $replace[] = $idx;
A 1932         }
1933
1934         return preg_replace($search, $replace, $html);
1935     }
1936
1937     /**
1938      * File upload progress handler.
1939      */
1940     public function upload_progress()
1941     {
1942         $params = array(
1943             'action' => $this->action,
93e12f 1944             'name'   => rcube_utils::get_input_value('_progress', rcube_utils::INPUT_GET),
1aceb9 1945         );
A 1946
93e12f 1947         if (function_exists('uploadprogress_get_info')) {
AM 1948             $status = uploadprogress_get_info($params['name']);
1aceb9 1949
A 1950             if (!empty($status)) {
93e12f 1951                 $params['current'] = $status['bytes_uploaded'];
AM 1952                 $params['total']   = $status['bytes_total'];
1aceb9 1953             }
A 1954         }
1955
93e12f 1956         if (!isset($status) && filter_var(ini_get('apc.rfc1867'), FILTER_VALIDATE_BOOLEAN)
AM 1957             && ini_get('apc.rfc1867_name')
1958         ) {
1959             $prefix = ini_get('apc.rfc1867_prefix');
1960             $status = apc_fetch($prefix . $params['name']);
1961
1962             if (!empty($status)) {
1963                 $params['current'] = $status['current'];
1964                 $params['total']   = $status['total'];
1965             }
1966         }
1967
1968         if (!isset($status) && filter_var(ini_get('session.upload_progress.enabled'), FILTER_VALIDATE_BOOLEAN)
1969             && ini_get('session.upload_progress.name')
1970         ) {
1971             $key = ini_get('session.upload_progress.prefix') . $params['name'];
1972
1973             $params['total']   = $_SESSION[$key]['content_length'];
1974             $params['current'] = $_SESSION[$key]['bytes_processed'];
1975         }
1976
1977         if (!empty($params['total'])) {
2dfad0 1978             $total = $this->show_bytes($params['total'], $unit);
AM 1979             switch ($unit) {
1980             case 'GB':
1981                 $gb      = $params['current']/1073741824;
1982                 $current = sprintf($gb >= 10 ? "%d" : "%.1f", $gb);
1983                 break;
1984             case 'MB':
1985                 $mb      = $params['current']/1048576;
1986                 $current = sprintf($mb >= 10 ? "%d" : "%.1f", $mb);
1987                 break;
1988             case 'KB':
1989                 $current = round($params['current']/1024);
1990                 break;
1991             case 'B':
1992             default:
1993                 $current = $params['current'];
1994                 break;
1995             }
1996
1997             $params['percent'] = round($params['current']/$params['total']*100);
93e12f 1998             $params['text']    = $this->gettext(array(
AM 1999                 'name' => 'uploadprogress',
2000                 'vars' => array(
2001                     'percent' => $params['percent'] . '%',
2dfad0 2002                     'current' => $current,
AM 2003                     'total'   => $total
93e12f 2004                 )
AM 2005             ));
2006         }
1aceb9 2007
A 2008         $this->output->command('upload_progress_update', $params);
2009         $this->output->send();
2010     }
2011
2012     /**
2013      * Initializes file uploading interface.
3cc1af 2014      *
AM 2015      * @param $int Optional maximum file size in bytes
1aceb9 2016      */
3cc1af 2017     public function upload_init($max_size = null)
1aceb9 2018     {
A 2019         // Enable upload progress bar
93e12f 2020         if ($seconds = $this->config->get('upload_progress')) {
AM 2021             if (function_exists('uploadprogress_get_info')) {
2022                 $field_name = 'UPLOAD_IDENTIFIER';
2023             }
2024             if (!$field_name && filter_var(ini_get('apc.rfc1867'), FILTER_VALIDATE_BOOLEAN)) {
2025                 $field_name = ini_get('apc.rfc1867_name');
2026             }
2027             if (!$field_name && filter_var(ini_get('session.upload_progress.enabled'), FILTER_VALIDATE_BOOLEAN)) {
2028                 $field_name = ini_get('session.upload_progress.name');
2029             }
2030
2031             if ($field_name) {
1aceb9 2032                 $this->output->set_env('upload_progress_name', $field_name);
A 2033                 $this->output->set_env('upload_progress_time', (int) $seconds);
2034             }
2035         }
2036
2037         // find max filesize value
2038         $max_filesize = parse_bytes(ini_get('upload_max_filesize'));
2039         $max_postsize = parse_bytes(ini_get('post_max_size'));
0301d9 2040
1aceb9 2041         if ($max_postsize && $max_postsize < $max_filesize) {
A 2042             $max_filesize = $max_postsize;
2043         }
2044
3cc1af 2045         if ($max_size && $max_size < $max_filesize) {
AM 2046             $max_filesize = $max_size;
2047         }
2048
1aceb9 2049         $this->output->set_env('max_filesize', $max_filesize);
6b2b2e 2050         $max_filesize = $this->show_bytes($max_filesize);
1aceb9 2051         $this->output->set_env('filesizeerror', $this->gettext(array(
A 2052             'name' => 'filesizeerror', 'vars' => array('size' => $max_filesize))));
2053
2054         return $max_filesize;
2055     }
2056
2057     /**
3cc1af 2058      * Outputs uploaded file content (with image thumbnails support
AM 2059      *
2060      * @param array $file Upload file data
2061      */
2062     public function display_uploaded_file($file)
2063     {
2064         if (empty($file)) {
2065             return;
2066         }
2067
2068         $file = $this->plugins->exec_hook('attachment_display', $file);
2069
2070         if ($file['status']) {
2071             if (empty($file['size'])) {
2072                 $file['size'] = $file['data'] ? strlen($file['data']) : @filesize($file['path']);
2073             }
2074
2075             // generate image thumbnail for file browser in HTML editor
2076             if (!empty($_GET['_thumbnail'])) {
2077                 $temp_dir       = $this->config->get('temp_dir');
2078                 $thumbnail_size = 80;
2079                 $mimetype       = $file['mimetype'];
2080                 $file_ident     = $file['id'] . ':' . $file['mimetype'] . ':' . $file['size'];
2081                 $cache_basename = $temp_dir . '/' . md5($file_ident . ':' . $this->user->ID . ':' . $thumbnail_size);
84af0d 2082                 $cache_file     = $cache_basename . '.thumb';
3cc1af 2083
AM 2084                 // render thumbnail image if not done yet
2085                 if (!is_file($cache_file)) {
2086                     if (!$file['path']) {
84af0d 2087                         $orig_name = $filename = $cache_basename . '.tmp';
3cc1af 2088                         file_put_contents($orig_name, $file['data']);
AM 2089                     }
2090                     else {
2091                         $filename = $file['path'];
2092                     }
2093
2094                     $image = new rcube_image($filename);
2095                     if ($imgtype = $image->resize($thumbnail_size, $cache_file, true)) {
2096                         $mimetype = 'image/' . $imgtype;
2097
2098                         if ($orig_name) {
2099                             unlink($orig_name);
2100                         }
2101                     }
2102                 }
2103
2104                 if (is_file($cache_file)) {
2105                     // cache for 1h
2106                     $this->output->future_expire_header(3600);
2107                     header('Content-Type: ' . $mimetype);
2108                     header('Content-Length: ' . filesize($cache_file));
2109
2110                     readfile($cache_file);
2111                     exit;
2112                 }
2113             }
2114
2115             header('Content-Type: ' . $file['mimetype']);
2116             header('Content-Length: ' . $file['size']);
2117
2118             if ($file['data']) {
2119                 echo $file['data'];
2120             }
2121             else if ($file['path']) {
2122                 readfile($file['path']);
2123             }
2124         }
2125     }
2126
2127     /**
1aceb9 2128      * Initializes client-side autocompletion.
A 2129      */
2130     public function autocomplete_init()
2131     {
2132         static $init;
2133
2134         if ($init) {
2135             return;
2136         }
2137
2138         $init = 1;
2139
2140         if (($threads = (int)$this->config->get('autocomplete_threads')) > 0) {
2141             $book_types = (array) $this->config->get('autocomplete_addressbooks', 'sql');
2142             if (count($book_types) > 1) {
2143                 $this->output->set_env('autocomplete_threads', $threads);
2144                 $this->output->set_env('autocomplete_sources', $book_types);
2145             }
2146         }
2147
2148         $this->output->set_env('autocomplete_max', (int)$this->config->get('autocomplete_max', 15));
2149         $this->output->set_env('autocomplete_min_length', $this->config->get('autocomplete_min_length'));
2150         $this->output->add_label('autocompletechars', 'autocompletemore');
2151     }
2152
2153     /**
2154      * Returns supported font-family specifications
2155      *
2156      * @param string $font  Font name
2157      *
2158      * @param string|array Font-family specification array or string (if $font is used)
2159      */
2160     public static function font_defs($font = null)
2161     {
2162         $fonts = array(
2163             'Andale Mono'   => '"Andale Mono",Times,monospace',
2164             'Arial'         => 'Arial,Helvetica,sans-serif',
2165             'Arial Black'   => '"Arial Black","Avant Garde",sans-serif',
2166             'Book Antiqua'  => '"Book Antiqua",Palatino,serif',
2167             'Courier New'   => '"Courier New",Courier,monospace',
2168             'Georgia'       => 'Georgia,Palatino,serif',
2169             'Helvetica'     => 'Helvetica,Arial,sans-serif',
2170             'Impact'        => 'Impact,Chicago,sans-serif',
2171             'Tahoma'        => 'Tahoma,Arial,Helvetica,sans-serif',
2172             'Terminal'      => 'Terminal,Monaco,monospace',
2173             'Times New Roman' => '"Times New Roman",Times,serif',
2174             'Trebuchet MS'  => '"Trebuchet MS",Geneva,sans-serif',
2175             'Verdana'       => 'Verdana,Geneva,sans-serif',
2176         );
2177
2178         if ($font) {
2179             return $fonts[$font];
2180         }
2181
2182         return $fonts;
2183     }
2184
2185     /**
2186      * Create a human readable string for a number of bytes
2187      *
2dfad0 2188      * @param int    Number of bytes
AM 2189      * @param string Size unit
1aceb9 2190      *
A 2191      * @return string Byte string
2192      */
2dfad0 2193     public function show_bytes($bytes, &$unit = null)
1aceb9 2194     {
A 2195         if ($bytes >= 1073741824) {
2dfad0 2196             $unit = 'GB';
AM 2197             $gb   = $bytes/1073741824;
2198             $str  = sprintf($gb >= 10 ? "%d " : "%.1f ", $gb) . $this->gettext($unit);
1aceb9 2199         }
A 2200         else if ($bytes >= 1048576) {
2dfad0 2201             $unit = 'MB';
AM 2202             $mb   = $bytes/1048576;
2203             $str  = sprintf($mb >= 10 ? "%d " : "%.1f ", $mb) . $this->gettext($unit);
1aceb9 2204         }
A 2205         else if ($bytes >= 1024) {
2dfad0 2206             $unit = 'KB';
AM 2207             $str  = sprintf("%d ",  round($bytes/1024)) . $this->gettext($unit);
1aceb9 2208         }
A 2209         else {
2dfad0 2210             $unit = 'B';
f7f467 2211             $str  = sprintf('%d ', $bytes) . $this->gettext($unit);
1aceb9 2212         }
A 2213
2214         return $str;
2215     }
2216
2217     /**
8749e9 2218      * Returns real size (calculated) of the message part
AM 2219      *
2220      * @param rcube_message_part  Message part
2221      *
2222      * @return string Part size (and unit)
2223      */
2224     public function message_part_size($part)
2225     {
2226         if (isset($part->d_parameters['size'])) {
2227             $size = $this->show_bytes((int)$part->d_parameters['size']);
2228         }
2229         else {
2230           $size = $part->size;
2231           if ($part->encoding == 'base64') {
2232             $size = $size / 1.33;
2233           }
2234
2235           $size = '~' . $this->show_bytes($size);
2236         }
2237
2238         return $size;
2239     }
2240
0456f7 2241     /**
TB 2242      * Returns message UID(s) and IMAP folder(s) from GET/POST data
2243      *
b8bcca 2244      * @param string UID value to decode
AM 2245      * @param string Default mailbox value (if not encoded in UIDs)
2246      * @param bool   Will be set to True if multi-folder request
2247      *
0456f7 2248      * @return array  List of message UIDs per folder
TB 2249      */
b8bcca 2250     public static function get_uids($uids = null, $mbox = null, &$is_multifolder = false)
0456f7 2251     {
TB 2252         // message UID (or comma-separated list of IDs) is provided in
2253         // the form of <ID>-<MBOX>[,<ID>-<MBOX>]*
2254
f0c94a 2255         $_uid  = $uids ?: rcube_utils::get_input_value('_uid', RCUBE_INPUT_GPC);
TB 2256         $_mbox = $mbox ?: (string)rcube_utils::get_input_value('_mbox', RCUBE_INPUT_GPC);
0456f7 2257
188247 2258         // already a hash array
TB 2259         if (is_array($_uid) && !isset($_uid[0])) {
2260             return $_uid;
0456f7 2261         }
TB 2262
2263         $result = array();
0f48e6 2264
TB 2265         // special case: *
2266         if ($_uid == '*' && is_object($_SESSION['search'][1]) && $_SESSION['search'][1]->multi) {
b8bcca 2267             $is_multifolder = true;
0f48e6 2268             // extract the full list of UIDs per folder from the search set
TB 2269             foreach ($_SESSION['search'][1]->sets as $subset) {
2270                 $mbox = $subset->get_parameters('MAILBOX');
2271                 $result[$mbox] = $subset->get();
2272             }
2273         }
2274         else {
188247 2275             if (is_string($_uid))
TB 2276                 $_uid = explode(',', $_uid);
2277
0f48e6 2278             // create a per-folder UIDs array
188247 2279             foreach ((array)$_uid as $uid) {
0f48e6 2280                 list($uid, $mbox) = explode('-', $uid, 2);
b8bcca 2281                 if (!strlen($mbox)) {
0f48e6 2282                     $mbox = $_mbox;
b8bcca 2283                 }
AM 2284                 else {
2285                     $is_multifolder = true;
2286                 }
2287
2288                 if ($uid == '*') {
518963 2289                     $result[$mbox] = $uid;
b8bcca 2290                 }
AM 2291                 else {
518963 2292                     $result[$mbox][] = $uid;
b8bcca 2293                 }
0f48e6 2294             }
0456f7 2295         }
TB 2296
2297         return $result;
2298     }
2299
c6efcf 2300     /**
AM 2301      * Get resource file content (with assets_dir support)
2302      *
2303      * @param string $name File name
2304      */
2305     public function get_resource_content($name)
2306     {
2307         if (!strpos($name, '/')) {
2308             $name = "program/resources/$name";
2309         }
2310
2311         $assets_dir = $this->config->get('assets_dir');
2312
2313         if ($assets_dir) {
2314             $path = slashify($assets_dir) . $name;
2315             if (@file_exists($path)) {
2316                 $name = $path;
2317             }
2318         }
2319
2320         return file_get_contents($name, false);
2321     }
2322
8749e9 2323
1aceb9 2324     /************************************************************************
A 2325      *********          Deprecated methods (to be removed)          *********
2326      ***********************************************************************/
2327
2328     public static function setcookie($name, $value, $exp = 0)
2329     {
2330         rcube_utils::setcookie($name, $value, $exp);
2331     }
38a08c 2332
AM 2333     public function imap_connect()
2334     {
2335         return $this->storage_connect();
2336     }
5a575b 2337
b97f21 2338     public function imap_init()
TB 2339     {
2340         return $this->storage_init();
2341     }
2342
5a575b 2343     /**
AM 2344      * Connect to the mail storage server with stored session data
2345      *
2346      * @return bool True on success, False on error
2347      */
2348     public function storage_connect()
2349     {
2350         $storage = $this->get_storage();
2351
2352         if ($_SESSION['storage_host'] && !$storage->is_connected()) {
2353             $host = $_SESSION['storage_host'];
2354             $user = $_SESSION['username'];
2355             $port = $_SESSION['storage_port'];
2356             $ssl  = $_SESSION['storage_ssl'];
2357             $pass = $this->decrypt($_SESSION['password']);
2358
2359             if (!$storage->connect($host, $user, $pass, $port, $ssl)) {
2360                 if (is_object($this->output)) {
7ea292 2361                     $this->output->show_message('storageerror', 'error');
5a575b 2362                 }
AM 2363             }
2364             else {
2365                 $this->set_storage_prop();
2366             }
2367         }
2368
5f6c71 2369         return $storage->is_connected();
5a575b 2370     }
197601 2371 }