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