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