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