source: subversion/trunk/roundcubemail/program/include/rcmail.php @ 4981

Last change on this file since 4981 was 4981, checked in by alec, 22 months ago
  • Performance fix: don't create addressbook object to close() it if it wasn't created before, skipping unneeded LDAP connection
  • Property svn:keywords set to Id
File size: 47.4 KB
Line 
1<?php
2
3/*
4 +-----------------------------------------------------------------------+
5 | program/include/rcmail.php                                            |
6 |                                                                       |
7 | This file is part of the Roundcube Webmail client                     |
8 | Copyright (C) 2008-2011, The Roundcube Dev Team                       |
9 | Licensed under the GNU GPL                                            |
10 |                                                                       |
11 | PURPOSE:                                                              |
12 |   Application class providing core functions and holding              |
13 |   instances of all 'global' objects like db- and imap-connections     |
14 +-----------------------------------------------------------------------+
15 | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16 +-----------------------------------------------------------------------+
17
18 $Id$
19
20*/
21
22
23/**
24 * Application class of Roundcube Webmail
25 * implemented as singleton
26 *
27 * @package Core
28 */
29class rcmail
30{
31  /**
32   * Main tasks.
33   *
34   * @var array
35   */
36  static public $main_tasks = array('mail','settings','addressbook','login','logout','utils','dummy');
37
38  /**
39   * Singleton instace of rcmail
40   *
41   * @var rcmail
42   */
43  static private $instance;
44
45  /**
46   * Stores instance of rcube_config.
47   *
48   * @var rcube_config
49   */
50  public $config;
51
52  /**
53   * Stores rcube_user instance.
54   *
55   * @var rcube_user
56   */
57  public $user;
58
59  /**
60   * Instace of database class.
61   *
62   * @var rcube_mdb2
63   */
64  public $db;
65
66  /**
67   * Instace of Memcache class.
68   *
69   * @var rcube_mdb2
70   */
71  public $memcache;
72
73  /**
74   * Instace of rcube_session class.
75   *
76   * @var rcube_session
77   */
78  public $session;
79
80  /**
81   * Instance of rcube_smtp class.
82   *
83   * @var rcube_smtp
84   */
85  public $smtp;
86
87  /**
88   * Instance of rcube_imap class.
89   *
90   * @var rcube_imap
91   */
92  public $imap;
93
94  /**
95   * Instance of rcube_template class.
96   *
97   * @var rcube_template
98   */
99  public $output;
100
101  /**
102   * Instance of rcube_plugin_api.
103   *
104   * @var rcube_plugin_api
105   */
106  public $plugins;
107
108  /**
109   * Current task.
110   *
111   * @var string
112   */
113  public $task;
114
115  /**
116   * Current action.
117   *
118   * @var string
119   */
120  public $action = '';
121  public $comm_path = './';
122
123  private $texts;
124  private $address_books = array();
125  private $caches = array();
126  private $action_map = array();
127  private $shutdown_functions = array();
128
129
130  /**
131   * This implements the 'singleton' design pattern
132   *
133   * @return rcmail The one and only instance
134   */
135  static function get_instance()
136  {
137    if (!self::$instance) {
138      self::$instance = new rcmail();
139      self::$instance->startup();  // init AFTER object was linked with self::$instance
140    }
141
142    return self::$instance;
143  }
144
145
146  /**
147   * Private constructor
148   */
149  private function __construct()
150  {
151    // load configuration
152    $this->config = new rcube_config();
153
154    register_shutdown_function(array($this, 'shutdown'));
155  }
156
157
158  /**
159   * Initial startup function
160   * to register session, create database and imap connections
161   *
162   * @todo Remove global vars $DB, $USER
163   */
164  private function startup()
165  {
166    // initialize syslog
167    if ($this->config->get('log_driver') == 'syslog') {
168      $syslog_id = $this->config->get('syslog_id', 'roundcube');
169      $syslog_facility = $this->config->get('syslog_facility', LOG_USER);
170      openlog($syslog_id, LOG_ODELAY, $syslog_facility);
171    }
172
173    // connect to database
174    $GLOBALS['DB'] = $this->get_dbh();
175
176    // start session
177    $this->session_init();
178
179    // create user object
180    $this->set_user(new rcube_user($_SESSION['user_id']));
181
182    // configure session (after user config merge!)
183    $this->session_configure();
184
185    // set task and action properties
186    $this->set_task(get_input_value('_task', RCUBE_INPUT_GPC));
187    $this->action = asciiwords(get_input_value('_action', RCUBE_INPUT_GPC));
188
189    // reset some session parameters when changing task
190    if ($this->task != 'utils') {
191      if ($this->session && $_SESSION['task'] != $this->task)
192        $this->session->remove('page');
193      // set current task to session
194      $_SESSION['task'] = $this->task;
195    }
196
197    // init output class
198    if (!empty($_REQUEST['_remote']))
199      $GLOBALS['OUTPUT'] = $this->json_init();
200    else
201      $GLOBALS['OUTPUT'] = $this->load_gui(!empty($_REQUEST['_framed']));
202
203    // create plugin API and load plugins
204    $this->plugins = rcube_plugin_api::get_instance();
205
206    // init plugins
207    $this->plugins->init();
208  }
209
210
211  /**
212   * Setter for application task
213   *
214   * @param string Task to set
215   */
216  public function set_task($task)
217  {
218    $task = asciiwords($task);
219
220    if ($this->user && $this->user->ID)
221      $task = !$task ? 'mail' : $task;
222    else
223      $task = 'login';
224
225    $this->task = $task;
226    $this->comm_path = $this->url(array('task' => $this->task));
227
228    if ($this->output)
229      $this->output->set_env('task', $this->task);
230  }
231
232
233  /**
234   * Setter for system user object
235   *
236   * @param rcube_user Current user instance
237   */
238  public function set_user($user)
239  {
240    if (is_object($user)) {
241      $this->user = $user;
242      $GLOBALS['USER'] = $this->user;
243
244      // overwrite config with user preferences
245      $this->config->set_user_prefs((array)$this->user->get_prefs());
246    }
247
248    $_SESSION['language'] = $this->user->language = $this->language_prop($this->config->get('language', $_SESSION['language']));
249
250    // set localization
251    setlocale(LC_ALL, $_SESSION['language'] . '.utf8', 'en_US.utf8');
252
253    // workaround for http://bugs.php.net/bug.php?id=18556
254    if (in_array($_SESSION['language'], array('tr_TR', 'ku', 'az_AZ')))
255      setlocale(LC_CTYPE, 'en_US' . '.utf8');
256  }
257
258
259  /**
260   * Check the given string and return a valid language code
261   *
262   * @param string Language code
263   * @return string Valid language code
264   */
265  private function language_prop($lang)
266  {
267    static $rcube_languages, $rcube_language_aliases;
268
269    // user HTTP_ACCEPT_LANGUAGE if no language is specified
270    if (empty($lang) || $lang == 'auto') {
271       $accept_langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
272       $lang = str_replace('-', '_', $accept_langs[0]);
273     }
274
275    if (empty($rcube_languages)) {
276      @include(INSTALL_PATH . 'program/localization/index.inc');
277    }
278
279    // check if we have an alias for that language
280    if (!isset($rcube_languages[$lang]) && isset($rcube_language_aliases[$lang])) {
281      $lang = $rcube_language_aliases[$lang];
282    }
283    // try the first two chars
284    else if (!isset($rcube_languages[$lang])) {
285      $short = substr($lang, 0, 2);
286
287      // check if we have an alias for the short language code
288      if (!isset($rcube_languages[$short]) && isset($rcube_language_aliases[$short])) {
289        $lang = $rcube_language_aliases[$short];
290      }
291      // expand 'nn' to 'nn_NN'
292      else if (!isset($rcube_languages[$short])) {
293        $lang = $short.'_'.strtoupper($short);
294      }
295    }
296
297    if (!isset($rcube_languages[$lang]) || !is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
298      $lang = 'en_US';
299    }
300
301    return $lang;
302  }
303
304
305  /**
306   * Get the current database connection
307   *
308   * @return rcube_mdb2  Database connection object
309   */
310  public function get_dbh()
311  {
312    if (!$this->db) {
313      $config_all = $this->config->all();
314
315      $this->db = new rcube_mdb2($config_all['db_dsnw'], $config_all['db_dsnr'], $config_all['db_persistent']);
316      $this->db->sqlite_initials = INSTALL_PATH . 'SQL/sqlite.initial.sql';
317      $this->db->set_debug((bool)$config_all['sql_debug']);
318    }
319
320    return $this->db;
321  }
322 
323 
324  /**
325   * Get global handle for memcache access
326   *
327   * @return object Memcache
328   */
329  public function get_memcache()
330  {
331    if (!isset($this->memcache)) {
332      // no memcache support in PHP
333      if (!class_exists('Memcache')) {
334        $this->memcache = false;
335        return false;
336      }
337
338      $this->memcache = new Memcache;
339      $mc_available = 0;
340      foreach ($this->config->get('memcache_hosts', array()) as $host) {
341        list($host, $port) = explode(':', $host);
342        if (!$port) $port = 11211;
343        // add server and attempt to connect if not already done yet
344        if ($this->memcache->addServer($host, $port) && !$mc_available)
345          $mc_available += intval($this->memcache->connect($host, $port));
346      }
347
348      if (!$mc_available)
349        $this->memcache = false;
350    }
351
352    return $this->memcache;
353  }
354
355
356  /**
357   * Initialize and get cache object
358   *
359   * @param string $name   Cache identifier
360   * @param string $type   Cache type ('db', 'apc' or 'memcache')
361   * @param int    $ttl    Expiration time for cache items in seconds
362   * @param bool   $packed Enables/disables data serialization
363   *
364   * @return rcube_cache Cache object
365   */
366  public function get_cache($name, $type='db', $ttl=0, $packed=true)
367  {
368    if (!isset($this->caches[$name])) {
369      $this->caches[$name] = new rcube_cache($type, $_SESSION['user_id'], $name, $ttl, $packed);
370    }
371
372    return $this->caches[$name];
373  }
374
375
376  /**
377   * Return instance of the internal address book class
378   *
379   * @param string  Address book identifier
380   * @param boolean True if the address book needs to be writeable
381   * @return rcube_contacts Address book object
382   */
383  public function get_address_book($id, $writeable = false)
384  {
385    $contacts    = null;
386    $ldap_config = (array)$this->config->get('ldap_public');
387    $abook_type  = strtolower($this->config->get('address_book_type'));
388
389    // use existing instance
390    if (isset($this->address_books[$id]) && is_a($this->address_books[$id], 'rcube_addressbook') && (!$writeable || !$this->address_books[$id]->readonly)) {
391      $contacts = $this->address_books[$id];
392    }
393    else if ($id && $ldap_config[$id]) {
394      $contacts = new rcube_ldap($ldap_config[$id], $this->config->get('ldap_debug'), $this->config->mail_domain($_SESSION['imap_host']));
395    }
396    else if ($id === '0') {
397      $contacts = new rcube_contacts($this->db, $this->user->ID);
398    }
399    else {
400      $plugin = $this->plugins->exec_hook('addressbook_get', array('id' => $id, 'writeable' => $writeable));
401
402      // plugin returned instance of a rcube_addressbook
403      if ($plugin['instance'] instanceof rcube_addressbook) {
404        $contacts = $plugin['instance'];
405      }
406      else if (!$id) {
407        if ($abook_type == 'ldap') {
408          // Use the first writable LDAP address book.
409          foreach ($ldap_config as $id => $prop) {
410            if (!$writeable || $prop['writable']) {
411              $contacts = new rcube_ldap($prop, $this->config->get('ldap_debug'), $this->config->mail_domain($_SESSION['imap_host']));
412              break;
413            }
414          }
415        }
416        else { // $id == 'sql'
417          $contacts = new rcube_contacts($this->db, $this->user->ID);
418        }
419      }
420    }
421
422    if (!$contacts) {
423      raise_error(array(
424        'code' => 600, 'type' => 'php',
425        'file' => __FILE__, 'line' => __LINE__,
426        'message' => "Addressbook source ($id) not found!"),
427        true, true);
428    }
429
430    // add to the 'books' array for shutdown function
431    if (!isset($this->address_books[$id]))
432      $this->address_books[$id] = $contacts;
433
434    return $contacts;
435  }
436
437
438  /**
439   * Return address books list
440   *
441   * @param boolean True if the address book needs to be writeable
442   * @return array  Address books array
443   */
444  public function get_address_sources($writeable = false)
445  {
446    $abook_type = strtolower($this->config->get('address_book_type'));
447    $ldap_config = $this->config->get('ldap_public');
448    $autocomplete = (array) $this->config->get('autocomplete_addressbooks');
449    $list = array();
450
451    // We are using the DB address book
452    if ($abook_type != 'ldap') {
453      if (!isset($this->address_books['0']))
454        $this->address_books['0'] = new rcube_contacts($this->db, $this->user->ID);
455      $list['0'] = array(
456        'id' => '0',
457        'name' => rcube_label('personaladrbook'),
458        'groups' => $this->address_books['0']->groups,
459        'readonly' => $this->address_books['0']->readonly,
460        'autocomplete' => in_array('sql', $autocomplete)
461      );
462    }
463
464    if ($ldap_config) {
465      $ldap_config = (array) $ldap_config;
466      foreach ($ldap_config as $id => $prop)
467        $list[$id] = array(
468          'id' => $id,
469          'name' => $prop['name'],
470          'groups' => is_array($prop['groups']),
471          'readonly' => !$prop['writable'],
472          'autocomplete' => in_array('sql', $autocomplete)
473        );
474    }
475
476    $plugin = $this->plugins->exec_hook('addressbooks_list', array('sources' => $list));
477    $list = $plugin['sources'];
478
479    foreach ($list as $idx => $item) {
480      // register source for shutdown function
481      if (!is_object($this->address_books[$item['id']]))
482        $this->address_books[$item['id']] = $item;
483      // remove from list if not writeable as requested
484      if ($writeable && $item['readonly'])
485          unset($list[$idx]);
486    }
487
488    return $list;
489  }
490
491
492  /**
493   * Init output object for GUI and add common scripts.
494   * This will instantiate a rcmail_template object and set
495   * environment vars according to the current session and configuration
496   *
497   * @param boolean True if this request is loaded in a (i)frame
498   * @return rcube_template Reference to HTML output object
499   */
500  public function load_gui($framed = false)
501  {
502    // init output page
503    if (!($this->output instanceof rcube_template))
504      $this->output = new rcube_template($this->task, $framed);
505
506    // set keep-alive/check-recent interval
507    if ($this->session && ($keep_alive = $this->session->get_keep_alive())) {
508      $this->output->set_env('keep_alive', $keep_alive);
509    }
510
511    if ($framed) {
512      $this->comm_path .= '&_framed=1';
513      $this->output->set_env('framed', true);
514    }
515
516    $this->output->set_env('task', $this->task);
517    $this->output->set_env('action', $this->action);
518    $this->output->set_env('comm_path', $this->comm_path);
519    $this->output->set_charset(RCMAIL_CHARSET);
520
521    // add some basic labels to client
522    $this->output->add_label('loading', 'servererror');
523
524    return $this->output;
525  }
526
527
528  /**
529   * Create an output object for JSON responses
530   *
531   * @return rcube_json_output Reference to JSON output object
532   */
533  public function json_init()
534  {
535    if (!($this->output instanceof rcube_json_output))
536      $this->output = new rcube_json_output($this->task);
537
538    return $this->output;
539  }
540
541
542  /**
543   * Create SMTP object and connect to server
544   *
545   * @param boolean True if connection should be established
546   */
547  public function smtp_init($connect = false)
548  {
549    $this->smtp = new rcube_smtp();
550
551    if ($connect)
552      $this->smtp->connect();
553  }
554
555
556  /**
557   * Create global IMAP object and connect to server
558   *
559   * @param boolean True if connection should be established
560   * @todo Remove global $IMAP
561   */
562  public function imap_init($connect = false)
563  {
564    // already initialized
565    if (is_object($this->imap))
566      return;
567
568    $this->imap = new rcube_imap();
569    $this->imap->debug_level = $this->config->get('debug_level');
570    $this->imap->skip_deleted = $this->config->get('skip_deleted');
571
572    // enable caching of imap data
573    $imap_cache = $this->config->get('imap_cache');
574    $messages_cache = $this->config->get('messages_cache');
575    // for backward compatybility
576    if ($imap_cache === null && $messages_cache === null && $this->config->get('enable_caching')) {
577        $imap_cache     = 'db';
578        $messages_cache = true;
579    }
580    if ($imap_cache)
581        $this->imap->set_caching($imap_cache);
582    if ($messages_cache)
583        $this->imap->set_messages_caching(true);
584
585    // set pagesize from config
586    $this->imap->set_pagesize($this->config->get('pagesize', 50));
587
588    // Setting root and delimiter before establishing the connection
589    // can save time detecting them using NAMESPACE and LIST
590    $options = array(
591      'auth_method' => $this->config->get('imap_auth_type', 'check'),
592      'auth_cid'    => $this->config->get('imap_auth_cid'),
593      'auth_pw'     => $this->config->get('imap_auth_pw'),
594      'debug'       => (bool) $this->config->get('imap_debug', 0),
595      'force_caps'  => (bool) $this->config->get('imap_force_caps'),
596      'timeout'     => (int) $this->config->get('imap_timeout', 0),
597    );
598
599    $this->imap->set_options($options);
600
601    // set global object for backward compatibility
602    $GLOBALS['IMAP'] = $this->imap;
603
604    $hook = $this->plugins->exec_hook('imap_init', array('fetch_headers' => $this->imap->fetch_add_headers));
605    if ($hook['fetch_headers'])
606      $this->imap->fetch_add_headers = $hook['fetch_headers'];
607
608    // support this parameter for backward compatibility but log warning
609    if ($connect) {
610      $this->imap_connect();
611      raise_error(array(
612        'code' => 800, 'type' => 'imap',
613        'file' => __FILE__, 'line' => __LINE__,
614        'message' => "rcube::imap_init(true) is deprecated, use rcube::imap_connect() instead"),
615        true, false);
616    }
617  }
618
619
620  /**
621   * Connect to IMAP server with stored session data
622   *
623   * @return bool True on success, false on error
624   */
625  public function imap_connect()
626  {
627    if (!$this->imap)
628      $this->imap_init();
629
630    if ($_SESSION['imap_host'] && !$this->imap->conn->connected()) {
631      if (!$this->imap->connect($_SESSION['imap_host'], $_SESSION['username'], $this->decrypt($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl'])) {
632        if ($this->output)
633          $this->output->show_message($this->imap->get_error_code() == -1 ? 'imaperror' : 'sessionerror', 'error');
634      }
635      else {
636        $this->set_imap_prop();
637        return $this->imap->conn;
638      }
639    }
640
641    return false;
642  }
643
644
645  /**
646   * Create session object and start the session.
647   */
648  public function session_init()
649  {
650    // session started (Installer?)
651    if (session_id())
652      return;
653
654    // set session domain
655    if ($domain = $this->config->get('session_domain')) {
656      ini_set('session.cookie_domain', $domain);
657    }
658    // set session garbage collecting time according to session_lifetime
659    $lifetime = $this->config->get('session_lifetime', 0) * 60;
660    if ($lifetime) {
661      ini_set('session.gc_maxlifetime', $lifetime * 2);
662    }
663
664    ini_set('session.cookie_secure', rcube_https_check());
665    ini_set('session.name', 'roundcube_sessid');
666    ini_set('session.use_cookies', 1);
667    ini_set('session.use_only_cookies', 1);
668    ini_set('session.serialize_handler', 'php');
669
670    // use database for storing session data
671    $this->session = new rcube_session($this->get_dbh(), $this->config);
672
673    $this->session->register_gc_handler('rcmail_temp_gc');
674    if ($this->config->get('enable_caching'))
675      $this->session->register_gc_handler('rcmail_cache_gc');
676
677    // start PHP session (if not in CLI mode)
678    if ($_SERVER['REMOTE_ADDR'])
679      session_start();
680
681    // set initial session vars
682    if (!$_SESSION['user_id'])
683      $_SESSION['temp'] = true;
684  }
685
686
687  /**
688   * Configure session object internals
689   */
690  public function session_configure()
691  {
692    if (!$this->session)
693      return;
694
695    $lifetime = $this->config->get('session_lifetime', 0) * 60;
696
697    // set keep-alive/check-recent interval
698    if ($keep_alive = $this->config->get('keep_alive')) {
699      // be sure that it's less than session lifetime
700      if ($lifetime)
701        $keep_alive = min($keep_alive, $lifetime - 30);
702      $keep_alive = max(60, $keep_alive);
703      $this->session->set_keep_alive($keep_alive);
704    }
705   
706    $this->session->set_secret($this->config->get('des_key') . $_SERVER['HTTP_USER_AGENT']);
707    $this->session->set_ip_check($this->config->get('ip_check'));
708  }
709
710
711  /**
712   * Perfom login to the IMAP server and to the webmail service.
713   * This will also create a new user entry if auto_create_user is configured.
714   *
715   * @param string IMAP user name
716   * @param string IMAP password
717   * @param string IMAP host
718   * @return boolean True on success, False on failure
719   */
720  function login($username, $pass, $host=NULL)
721  {
722    $user = NULL;
723    $config = $this->config->all();
724
725    if (!$host)
726      $host = $config['default_host'];
727
728    // Validate that selected host is in the list of configured hosts
729    if (is_array($config['default_host'])) {
730      $allowed = false;
731      foreach ($config['default_host'] as $key => $host_allowed) {
732        if (!is_numeric($key))
733          $host_allowed = $key;
734        if ($host == $host_allowed) {
735          $allowed = true;
736          break;
737        }
738      }
739      if (!$allowed)
740        return false;
741      }
742    else if (!empty($config['default_host']) && $host != rcube_parse_host($config['default_host']))
743      return false;
744
745    // parse $host URL
746    $a_host = parse_url($host);
747    if ($a_host['host']) {
748      $host = $a_host['host'];
749      $imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? $a_host['scheme'] : null;
750      if (!empty($a_host['port']))
751        $imap_port = $a_host['port'];
752      else if ($imap_ssl && $imap_ssl != 'tls' && (!$config['default_port'] || $config['default_port'] == 143))
753        $imap_port = 993;
754    }
755
756    $imap_port = $imap_port ? $imap_port : $config['default_port'];
757
758    /* Modify username with domain if required
759       Inspired by Marco <P0L0_notspam_binware.org>
760    */
761    // Check if we need to add domain
762    if (!empty($config['username_domain']) && strpos($username, '@') === false) {
763      if (is_array($config['username_domain']) && isset($config['username_domain'][$host]))
764        $username .= '@'.rcube_parse_host($config['username_domain'][$host], $host);
765      else if (is_string($config['username_domain']))
766        $username .= '@'.rcube_parse_host($config['username_domain'], $host);
767    }
768
769    // Convert username to lowercase. If IMAP backend
770    // is case-insensitive we need to store always the same username (#1487113)
771    if ($config['login_lc']) {
772      $username = mb_strtolower($username);
773    }
774
775    // try to resolve email address from virtuser table
776    if (strpos($username, '@') && ($virtuser = rcube_user::email2user($username))) {
777      $username = $virtuser;
778    }
779
780    // Here we need IDNA ASCII
781    // Only rcube_contacts class is using domain names in Unicode
782    $host = rcube_idn_to_ascii($host);
783    if (strpos($username, '@')) {
784      // lowercase domain name
785      list($local, $domain) = explode('@', $username);
786      $username = $local . '@' . mb_strtolower($domain);
787      $username = rcube_idn_to_ascii($username);
788    }
789
790    // user already registered -> overwrite username
791    if ($user = rcube_user::query($username, $host))
792      $username = $user->data['username'];
793
794    if (!$this->imap)
795      $this->imap_init();
796
797    // try IMAP login
798    if (!($imap_login = $this->imap->connect($host, $username, $pass, $imap_port, $imap_ssl))) {
799      // try with lowercase
800      $username_lc = mb_strtolower($username);
801      if ($username_lc != $username) {
802        // try to find user record again -> overwrite username
803        if (!$user && ($user = rcube_user::query($username_lc, $host)))
804          $username_lc = $user->data['username'];
805
806        if ($imap_login = $this->imap->connect($host, $username_lc, $pass, $imap_port, $imap_ssl))
807          $username = $username_lc;
808      }
809    }
810
811    // exit if IMAP login failed
812    if (!$imap_login)
813      return false;
814
815    $this->set_imap_prop();
816
817    // user already registered -> update user's record
818    if (is_object($user)) {
819      // fix some old settings according to namespace prefix
820      $this->fix_namespace_settings($user);
821
822      // create default folders on first login
823      if (!$user->data['last_login'] && $config['create_default_folders'])
824        $this->imap->create_default_folders();
825      // update last login timestamp
826      $user->touch();
827    }
828    // create new system user
829    else if ($config['auto_create_user']) {
830      if ($created = rcube_user::create($username, $host)) {
831        $user = $created;
832        // create default folders on first login
833        if ($config['create_default_folders'])
834          $this->imap->create_default_folders();
835      }
836      else {
837        raise_error(array(
838          'code' => 600, 'type' => 'php',
839          'file' => __FILE__, 'line' => __LINE__,
840          'message' => "Failed to create a user record. Maybe aborted by a plugin?"
841          ), true, false);
842      }
843    }
844    else {
845      raise_error(array(
846        'code' => 600, 'type' => 'php',
847        'file' => __FILE__, 'line' => __LINE__,
848        'message' => "Acces denied for new user $username. 'auto_create_user' is disabled"
849        ), true, false);
850    }
851
852    // login succeeded
853    if (is_object($user) && $user->ID) {
854      $this->set_user($user);
855      $this->session_configure();
856
857      // set session vars
858      $_SESSION['user_id']   = $user->ID;
859      $_SESSION['username']  = $user->data['username'];
860      $_SESSION['imap_host'] = $host;
861      $_SESSION['imap_port'] = $imap_port;
862      $_SESSION['imap_ssl']  = $imap_ssl;
863      $_SESSION['password']  = $this->encrypt($pass);
864      $_SESSION['login_time'] = mktime();
865     
866      if (isset($_REQUEST['_timezone']) && $_REQUEST['_timezone'] != '_default_')
867        $_SESSION['timezone'] = floatval($_REQUEST['_timezone']);
868
869      // force reloading complete list of subscribed mailboxes
870      $this->imap->clear_cache('mailboxes', true);
871
872      return true;
873    }
874
875    return false;
876  }
877
878
879  /**
880   * Set root dir and last stored mailbox
881   * This must be done AFTER connecting to the server!
882   */
883  public function set_imap_prop()
884  {
885    $this->imap->set_charset($this->config->get('default_charset', RCMAIL_CHARSET));
886
887    if ($default_folders = $this->config->get('default_imap_folders')) {
888      $this->imap->set_default_mailboxes($default_folders);
889    }
890    if (isset($_SESSION['mbox'])) {
891      $this->imap->set_mailbox($_SESSION['mbox']);
892    }
893    if (isset($_SESSION['page'])) {
894      $this->imap->set_page($_SESSION['page']);
895    }
896  }
897
898
899  /**
900   * Auto-select IMAP host based on the posted login information
901   *
902   * @return string Selected IMAP host
903   */
904  public function autoselect_host()
905  {
906    $default_host = $this->config->get('default_host');
907    $host = null;
908
909    if (is_array($default_host)) {
910      $post_host = get_input_value('_host', RCUBE_INPUT_POST);
911
912      // direct match in default_host array
913      if ($default_host[$post_host] || in_array($post_host, array_values($default_host))) {
914        $host = $post_host;
915      }
916
917      // try to select host by mail domain
918      list($user, $domain) = explode('@', get_input_value('_user', RCUBE_INPUT_POST));
919      if (!empty($domain)) {
920        foreach ($default_host as $imap_host => $mail_domains) {
921          if (is_array($mail_domains) && in_array($domain, $mail_domains)) {
922            $host = $imap_host;
923            break;
924          }
925        }
926      }
927
928      // take the first entry if $host is still an array
929      if (empty($host)) {
930        $host = array_shift($default_host);
931      }
932    }
933    else if (empty($default_host)) {
934      $host = get_input_value('_host', RCUBE_INPUT_POST);
935    }
936    else
937      $host = rcube_parse_host($default_host);
938
939    return $host;
940  }
941
942
943  /**
944   * Get localized text in the desired language
945   *
946   * @param mixed Named parameters array or label name
947   * @return string Localized text
948   */
949  public function gettext($attrib, $domain=null)
950  {
951    // load localization files if not done yet
952    if (empty($this->texts))
953      $this->load_language();
954
955    // extract attributes
956    if (is_string($attrib))
957      $attrib = array('name' => $attrib);
958
959    $nr = is_numeric($attrib['nr']) ? $attrib['nr'] : 1;
960    $name = $attrib['name'] ? $attrib['name'] : '';
961   
962    // attrib contain text values: use them from now
963    if (($setval = $attrib[strtolower($_SESSION['language'])]) || ($setval = $attrib['en_us']))
964        $this->texts[$name] = $setval;
965
966    // check for text with domain
967    if ($domain && ($text_item = $this->texts[$domain.'.'.$name]))
968      ;
969    // text does not exist
970    else if (!($text_item = $this->texts[$name])) {
971      return "[$name]";
972    }
973
974    // make text item array
975    $a_text_item = is_array($text_item) ? $text_item : array('single' => $text_item);
976
977    // decide which text to use
978    if ($nr == 1) {
979      $text = $a_text_item['single'];
980    }
981    else if ($nr > 0) {
982      $text = $a_text_item['multiple'];
983    }
984    else if ($nr == 0) {
985      if ($a_text_item['none'])
986        $text = $a_text_item['none'];
987      else if ($a_text_item['single'])
988        $text = $a_text_item['single'];
989      else if ($a_text_item['multiple'])
990        $text = $a_text_item['multiple'];
991    }
992
993    // default text is single
994    if ($text == '') {
995      $text = $a_text_item['single'];
996    }
997
998    // replace vars in text
999    if (is_array($attrib['vars'])) {
1000      foreach ($attrib['vars'] as $var_key => $var_value)
1001        $text = str_replace($var_key[0]!='$' ? '$'.$var_key : $var_key, $var_value, $text);
1002    }
1003
1004    // format output
1005    if (($attrib['uppercase'] && strtolower($attrib['uppercase']=='first')) || $attrib['ucfirst'])
1006      return ucfirst($text);
1007    else if ($attrib['uppercase'])
1008      return mb_strtoupper($text);
1009    else if ($attrib['lowercase'])
1010      return mb_strtolower($text);
1011
1012    return $text;
1013  }
1014
1015
1016  /**
1017   * Check if the given text lable exists
1018   *
1019   * @param string Label name
1020   * @return boolean True if text exists (either in the current language or in en_US)
1021   */
1022  public function text_exists($name, $domain=null)
1023  {
1024    // load localization files if not done yet
1025    if (empty($this->texts))
1026      $this->load_language();
1027
1028    // check for text with domain first
1029    return ($domain && isset($this->texts[$domain.'.'.$name])) || isset($this->texts[$name]);
1030  }
1031
1032  /**
1033   * Load a localization package
1034   *
1035   * @param string Language ID
1036   */
1037  public function load_language($lang = null, $add = array())
1038  {
1039    $lang = $this->language_prop(($lang ? $lang : $_SESSION['language']));
1040
1041    // load localized texts
1042    if (empty($this->texts) || $lang != $_SESSION['language']) {
1043      $this->texts = array();
1044
1045      // handle empty lines after closing PHP tag in localization files
1046      ob_start();
1047
1048      // get english labels (these should be complete)
1049      @include(INSTALL_PATH . 'program/localization/en_US/labels.inc');
1050      @include(INSTALL_PATH . 'program/localization/en_US/messages.inc');
1051
1052      if (is_array($labels))
1053        $this->texts = $labels;
1054      if (is_array($messages))
1055        $this->texts = array_merge($this->texts, $messages);
1056
1057      // include user language files
1058      if ($lang != 'en' && is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
1059        include_once(INSTALL_PATH . 'program/localization/' . $lang . '/labels.inc');
1060        include_once(INSTALL_PATH . 'program/localization/' . $lang . '/messages.inc');
1061
1062        if (is_array($labels))
1063          $this->texts = array_merge($this->texts, $labels);
1064        if (is_array($messages))
1065          $this->texts = array_merge($this->texts, $messages);
1066      }
1067
1068      ob_end_clean();
1069
1070      $_SESSION['language'] = $lang;
1071    }
1072
1073    // append additional texts (from plugin)
1074    if (is_array($add) && !empty($add))
1075      $this->texts += $add;
1076  }
1077
1078
1079  /**
1080   * Read directory program/localization and return a list of available languages
1081   *
1082   * @return array List of available localizations
1083   */
1084  public function list_languages()
1085  {
1086    static $sa_languages = array();
1087
1088    if (!sizeof($sa_languages)) {
1089      @include(INSTALL_PATH . 'program/localization/index.inc');
1090
1091      if ($dh = @opendir(INSTALL_PATH . 'program/localization')) {
1092        while (($name = readdir($dh)) !== false) {
1093          if ($name[0] == '.' || !is_dir(INSTALL_PATH . 'program/localization/' . $name))
1094            continue;
1095
1096          if ($label = $rcube_languages[$name])
1097            $sa_languages[$name] = $label;
1098        }
1099        closedir($dh);
1100      }
1101    }
1102
1103    return $sa_languages;
1104  }
1105
1106
1107  /**
1108   * Destroy session data and remove cookie
1109   */
1110  public function kill_session()
1111  {
1112    $this->plugins->exec_hook('session_destroy');
1113
1114    $this->session->kill();
1115    $_SESSION = array('language' => $this->user->language, 'temp' => true);
1116    $this->user->reset();
1117  }
1118
1119
1120  /**
1121   * Do server side actions on logout
1122   */
1123  public function logout_actions()
1124  {
1125    $config = $this->config->all();
1126
1127    // on logout action we're not connected to imap server
1128    if (($config['logout_purge'] && !empty($config['trash_mbox'])) || $config['logout_expunge']) {
1129      if (!$this->session->check_auth())
1130        return;
1131
1132      $this->imap_connect();
1133    }
1134
1135    if ($config['logout_purge'] && !empty($config['trash_mbox'])) {
1136      $this->imap->clear_mailbox($config['trash_mbox']);
1137    }
1138
1139    if ($config['logout_expunge']) {
1140      $this->imap->expunge('INBOX');
1141    }
1142
1143    // Try to save unsaved user preferences
1144    if (!empty($_SESSION['preferences'])) {
1145      $this->user->save_prefs(unserialize($_SESSION['preferences']));
1146    }
1147  }
1148
1149
1150  /**
1151   * Function to be executed in script shutdown
1152   * Registered with register_shutdown_function()
1153   */
1154  public function shutdown()
1155  {
1156    foreach ($this->shutdown_functions as $function)
1157      call_user_func($function);
1158
1159    if (is_object($this->smtp))
1160      $this->smtp->disconnect();
1161
1162    foreach ($this->address_books as $book) {
1163      if (is_a($book, 'rcube_addressbook'))
1164        $book->close();
1165    }
1166
1167    foreach ($this->caches as $cache) {
1168        if (is_object($cache))
1169            $cache->close();
1170    }
1171
1172    if (is_object($this->imap))
1173      $this->imap->close();
1174
1175    // before closing the database connection, write session data
1176    if ($_SERVER['REMOTE_ADDR'] && is_object($this->session)) {
1177      $this->session->cleanup();
1178      session_write_close();
1179    }
1180
1181    // write performance stats to logs/console
1182    if ($this->config->get('devel_mode')) {
1183      if (function_exists('memory_get_usage'))
1184        $mem = show_bytes(memory_get_usage());
1185      if (function_exists('memory_get_peak_usage'))
1186        $mem .= '/'.show_bytes(memory_get_peak_usage());
1187
1188      $log = $this->task . ($this->action ? '/'.$this->action : '') . ($mem ? " [$mem]" : '');
1189      if (defined('RCMAIL_START'))
1190        rcube_print_time(RCMAIL_START, $log);
1191      else
1192        console($log);
1193    }
1194  }
1195
1196
1197  /**
1198   * Registers shutdown function to be executed on shutdown.
1199   * The functions will be executed before destroying any
1200   * objects like smtp, imap, session, etc.
1201   *
1202   * @param callback Function callback
1203   */
1204  public function add_shutdown_function($function)
1205  {
1206    $this->shutdown_functions[] = $function;
1207  }
1208
1209
1210  /**
1211   * Generate a unique token to be used in a form request
1212   *
1213   * @return string The request token
1214   */
1215  public function get_request_token()
1216  {
1217    $sess_id = $_COOKIE[ini_get('session.name')];
1218    if (!$sess_id) $sess_id = session_id();
1219    $plugin = $this->plugins->exec_hook('request_token', array('value' => md5('RT' . $this->task . $this->config->get('des_key') . $sess_id)));
1220    return $plugin['value'];
1221  }
1222
1223
1224  /**
1225   * Check if the current request contains a valid token
1226   *
1227   * @param int Request method
1228   * @return boolean True if request token is valid false if not
1229   */
1230  public function check_request($mode = RCUBE_INPUT_POST)
1231  {
1232    $token = get_input_value('_token', $mode);
1233    $sess_id = $_COOKIE[ini_get('session.name')];
1234    return !empty($sess_id) && $token == $this->get_request_token();
1235  }
1236
1237
1238  /**
1239   * Create unique authorization hash
1240   *
1241   * @param string Session ID
1242   * @param int Timestamp
1243   * @return string The generated auth hash
1244   */
1245  private function get_auth_hash($sess_id, $ts)
1246  {
1247    $auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
1248      $sess_id,
1249      $ts,
1250      $this->config->get('ip_check') ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
1251      $_SERVER['HTTP_USER_AGENT']);
1252
1253    if (function_exists('sha1'))
1254      return sha1($auth_string);
1255    else
1256      return md5($auth_string);
1257  }
1258
1259
1260  /**
1261   * Encrypt using 3DES
1262   *
1263   * @param string $clear clear text input
1264   * @param string $key encryption key to retrieve from the configuration, defaults to 'des_key'
1265   * @param boolean $base64 whether or not to base64_encode() the result before returning
1266   *
1267   * @return string encrypted text
1268   */
1269  public function encrypt($clear, $key = 'des_key', $base64 = true)
1270  {
1271    if (!$clear)
1272      return '';
1273    /*-
1274     * Add a single canary byte to the end of the clear text, which
1275     * will help find out how much of padding will need to be removed
1276     * upon decryption; see http://php.net/mcrypt_generic#68082
1277     */
1278    $clear = pack("a*H2", $clear, "80");
1279
1280    if (function_exists('mcrypt_module_open') &&
1281        ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_CBC, "")))
1282    {
1283      $iv = $this->create_iv(mcrypt_enc_get_iv_size($td));
1284      mcrypt_generic_init($td, $this->config->get_crypto_key($key), $iv);
1285      $cipher = $iv . mcrypt_generic($td, $clear);
1286      mcrypt_generic_deinit($td);
1287      mcrypt_module_close($td);
1288    }
1289    else {
1290      @include_once 'des.inc';
1291
1292      if (function_exists('des')) {
1293        $des_iv_size = 8;
1294        $iv = $this->create_iv($des_iv_size);
1295        $cipher = $iv . des($this->config->get_crypto_key($key), $clear, 1, 1, $iv);
1296      }
1297      else {
1298        raise_error(array(
1299          'code' => 500, 'type' => 'php',
1300          'file' => __FILE__, 'line' => __LINE__,
1301          'message' => "Could not perform encryption; make sure Mcrypt is installed or lib/des.inc is available"
1302        ), true, true);
1303      }
1304    }
1305
1306    return $base64 ? base64_encode($cipher) : $cipher;
1307  }
1308
1309  /**
1310   * Decrypt 3DES-encrypted string
1311   *
1312   * @param string $cipher encrypted text
1313   * @param string $key encryption key to retrieve from the configuration, defaults to 'des_key'
1314   * @param boolean $base64 whether or not input is base64-encoded
1315   *
1316   * @return string decrypted text
1317   */
1318  public function decrypt($cipher, $key = 'des_key', $base64 = true)
1319  {
1320    if (!$cipher)
1321      return '';
1322
1323    $cipher = $base64 ? base64_decode($cipher) : $cipher;
1324
1325    if (function_exists('mcrypt_module_open') &&
1326        ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_CBC, "")))
1327    {
1328      $iv_size = mcrypt_enc_get_iv_size($td);
1329      $iv = substr($cipher, 0, $iv_size);
1330
1331      // session corruption? (#1485970)
1332      if (strlen($iv) < $iv_size)
1333        return '';
1334
1335      $cipher = substr($cipher, $iv_size);
1336      mcrypt_generic_init($td, $this->config->get_crypto_key($key), $iv);
1337      $clear = mdecrypt_generic($td, $cipher);
1338      mcrypt_generic_deinit($td);
1339      mcrypt_module_close($td);
1340    }
1341    else {
1342      @include_once 'des.inc';
1343
1344      if (function_exists('des')) {
1345        $des_iv_size = 8;
1346        $iv = substr($cipher, 0, $des_iv_size);
1347        $cipher = substr($cipher, $des_iv_size);
1348        $clear = des($this->config->get_crypto_key($key), $cipher, 0, 1, $iv);
1349      }
1350      else {
1351        raise_error(array(
1352          'code' => 500, 'type' => 'php',
1353          'file' => __FILE__, 'line' => __LINE__,
1354          'message' => "Could not perform decryption; make sure Mcrypt is installed or lib/des.inc is available"
1355        ), true, true);
1356      }
1357    }
1358
1359    /*-
1360     * Trim PHP's padding and the canary byte; see note in
1361     * rcmail::encrypt() and http://php.net/mcrypt_generic#68082
1362     */
1363    $clear = substr(rtrim($clear, "\0"), 0, -1);
1364
1365    return $clear;
1366  }
1367
1368  /**
1369   * Generates encryption initialization vector (IV)
1370   *
1371   * @param int Vector size
1372   * @return string Vector string
1373   */
1374  private function create_iv($size)
1375  {
1376    // mcrypt_create_iv() can be slow when system lacks entrophy
1377    // we'll generate IV vector manually
1378    $iv = '';
1379    for ($i = 0; $i < $size; $i++)
1380        $iv .= chr(mt_rand(0, 255));
1381    return $iv;
1382  }
1383
1384  /**
1385   * Build a valid URL to this instance of Roundcube
1386   *
1387   * @param mixed Either a string with the action or url parameters as key-value pairs
1388   * @return string Valid application URL
1389   */
1390  public function url($p)
1391  {
1392    if (!is_array($p))
1393      $p = array('_action' => @func_get_arg(0));
1394
1395    $task = $p['_task'] ? $p['_task'] : ($p['task'] ? $p['task'] : $this->task);
1396    $p['_task'] = $task;
1397    unset($p['task']);
1398
1399    $url = './';
1400    $delm = '?';
1401    foreach (array_reverse($p) as $key => $val) {
1402      if ($val !== '') {
1403        $par = $key[0] == '_' ? $key : '_'.$key;
1404        $url .= $delm.urlencode($par).'='.urlencode($val);
1405        $delm = '&';
1406      }
1407    }
1408    return $url;
1409  }
1410
1411
1412  /**
1413   * Use imagemagick or GD lib to read image properties
1414   *
1415   * @param string Absolute file path
1416   * @return mixed Hash array with image props like type, width, height or False on error
1417   */
1418  public static function imageprops($filepath)
1419  {
1420    $rcmail = rcmail::get_instance();
1421    if ($cmd = $rcmail->config->get('im_identify_path', false)) {
1422      list(, $type, $size) = explode(' ', strtolower(rcmail::exec($cmd. ' 2>/dev/null {in}', array('in' => $filepath))));
1423      if ($size)
1424        list($width, $height) = explode('x', $size);
1425    }
1426    else if (function_exists('getimagesize')) {
1427      $imsize = @getimagesize($filepath);
1428      $width = $imsize[0];
1429      $height = $imsize[1];
1430      $type = preg_replace('!image/!', '', $imsize['mime']);
1431    }
1432
1433    return $type ? array('type' => $type, 'width' => $width, 'height' => $height) : false;
1434  }
1435
1436
1437  /**
1438   * Convert an image to a given size and type using imagemagick (ensures input is an image)
1439   *
1440   * @param $p['in']  Input filename (mandatory)
1441   * @param $p['out'] Output filename (mandatory)
1442   * @param $p['size']  Width x height of resulting image, e.g. "160x60"
1443   * @param $p['type']  Output file type, e.g. "jpg"
1444   * @param $p['-opts'] Custom command line options to ImageMagick convert
1445   * @return Success of convert as true/false
1446   */
1447  public static function imageconvert($p)
1448  {
1449    $result = false;
1450    $rcmail = rcmail::get_instance();
1451    $convert  = $rcmail->config->get('im_convert_path', false);
1452    $identify = $rcmail->config->get('im_identify_path', false);
1453
1454    // imagemagick is required for this
1455    if (!$convert)
1456        return false;
1457
1458    if (!(($imagetype = @exif_imagetype($p['in'])) && ($type = image_type_to_extension($imagetype, false))))
1459      list(, $type) = explode(' ', strtolower(rcmail::exec($identify . ' 2>/dev/null {in}', $p))); # for things like eps
1460
1461    $type = strtr($type, array("jpeg" => "jpg", "tiff" => "tif", "ps" => "eps", "ept" => "eps"));
1462    $p += array('type' => $type, 'types' => "bmp,eps,gif,jp2,jpg,png,svg,tif", 'quality' => 75);
1463    $p['-opts'] = array('-resize' => $p['size'].'>') + (array)$p['-opts'];
1464
1465    if (in_array($type, explode(',', $p['types']))) # Valid type?
1466      $result = rcmail::exec($convert . ' 2>&1 -flatten -auto-orient -colorspace RGB -quality {quality} {-opts} {in} {type}:{out}', $p) === "";
1467
1468    return $result;
1469  }
1470
1471
1472  /**
1473   * Construct shell command, execute it and return output as string.
1474   * Keywords {keyword} are replaced with arguments
1475   *
1476   * @param $cmd Format string with {keywords} to be replaced
1477   * @param $values (zero, one or more arrays can be passed)
1478   * @return output of command. shell errors not detectable
1479   */
1480  public static function exec(/* $cmd, $values1 = array(), ... */)
1481  {
1482    $args = func_get_args();
1483    $cmd = array_shift($args);
1484    $values = $replacements = array();
1485
1486    // merge values into one array
1487    foreach ($args as $arg)
1488      $values += (array)$arg;
1489
1490    preg_match_all('/({(-?)([a-z]\w*)})/', $cmd, $matches, PREG_SET_ORDER);
1491    foreach ($matches as $tags) {
1492      list(, $tag, $option, $key) = $tags;
1493      $parts = array();
1494
1495      if ($option) {
1496        foreach ((array)$values["-$key"] as $key => $value) {
1497          if ($value === true || $value === false || $value === null)
1498            $parts[] = $value ? $key : "";
1499          else foreach ((array)$value as $val)
1500            $parts[] = "$key " . escapeshellarg($val);
1501        }
1502      }
1503      else {
1504        foreach ((array)$values[$key] as $value)
1505          $parts[] = escapeshellarg($value);
1506      }
1507
1508      $replacements[$tag] = join(" ", $parts);
1509    }
1510
1511    // use strtr behaviour of going through source string once
1512    $cmd = strtr($cmd, $replacements);
1513   
1514    return (string)shell_exec($cmd);
1515  }
1516
1517
1518  /**
1519   * Helper method to set a cookie with the current path and host settings
1520   *
1521   * @param string Cookie name
1522   * @param string Cookie value
1523   * @param string Expiration time
1524   */
1525  public static function setcookie($name, $value, $exp = 0)
1526  {
1527    if (headers_sent())
1528      return;
1529
1530    $cookie = session_get_cookie_params();
1531
1532    setcookie($name, $value, $exp, $cookie['path'], $cookie['domain'],
1533      rcube_https_check(), true);
1534  }
1535
1536  /**
1537   * Registers action aliases for current task
1538   *
1539   * @param array $map Alias-to-filename hash array
1540   */
1541  public function register_action_map($map)
1542  {
1543    if (is_array($map)) {
1544      foreach ($map as $idx => $val) {
1545        $this->action_map[$idx] = $val;
1546      }
1547    }
1548  }
1549 
1550  /**
1551   * Returns current action filename
1552   *
1553   * @param array $map Alias-to-filename hash array
1554   */
1555  public function get_action_file()
1556  {
1557    if (!empty($this->action_map[$this->action])) {
1558      return $this->action_map[$this->action];
1559    }
1560
1561    return strtr($this->action, '-', '_') . '.inc';
1562  }
1563
1564  /**
1565   * Fixes some user preferences according to namespace handling change.
1566   * Old Roundcube versions were using folder names with removed namespace prefix.
1567   * Now we need to add the prefix on servers where personal namespace has prefix.
1568   *
1569   * @param rcube_user $user User object
1570   */
1571  private function fix_namespace_settings($user)
1572  {
1573    $prefix     = $this->imap->get_namespace('prefix');
1574    $prefix_len = strlen($prefix);
1575
1576    if (!$prefix_len)
1577      return;
1578
1579    $prefs = $user->get_prefs();
1580    if (empty($prefs) || $prefs['namespace_fixed'])
1581      return;
1582
1583    // Build namespace prefix regexp
1584    $ns     = $this->imap->get_namespace();
1585    $regexp = array();
1586
1587    foreach ($ns as $entry) {
1588      if (!empty($entry)) {
1589        foreach ($entry as $item) {
1590          if (strlen($item[0])) {
1591            $regexp[] = preg_quote($item[0], '/');
1592          }
1593        }
1594      }
1595    }
1596    $regexp = '/^('. implode('|', $regexp).')/';
1597
1598    // Fix preferences
1599    $opts = array('drafts_mbox', 'junk_mbox', 'sent_mbox', 'trash_mbox', 'archive_mbox');
1600    foreach ($opts as $opt) {
1601      if ($value = $prefs[$opt]) {
1602        if ($value != 'INBOX' && !preg_match($regexp, $value)) {
1603          $prefs[$opt] = $prefix.$value;
1604        }
1605      }
1606    }
1607
1608    if (!empty($prefs['default_imap_folders'])) {
1609      foreach ($prefs['default_imap_folders'] as $idx => $name) {
1610        if ($name != 'INBOX' && !preg_match($regexp, $name)) {
1611          $prefs['default_imap_folders'][$idx] = $prefix.$name;
1612        }
1613      }
1614    }
1615
1616    if (!empty($prefs['search_mods'])) {
1617      $folders = array();
1618      foreach ($prefs['search_mods'] as $idx => $value) {
1619        if ($idx != 'INBOX' && $idx != '*' && !preg_match($regexp, $idx)) {
1620          $idx = $prefix.$idx;
1621        }
1622        $folders[$idx] = $value;
1623      }
1624      $prefs['search_mods'] = $folders;
1625    }
1626
1627    if (!empty($prefs['message_threading'])) {
1628      $folders = array();
1629      foreach ($prefs['message_threading'] as $idx => $value) {
1630        if ($idx != 'INBOX' && !preg_match($regexp, $idx)) {
1631          $idx = $prefix.$idx;
1632        }
1633        $folders[$prefix.$idx] = $value;
1634      }
1635      $prefs['message_threading'] = $folders;
1636    }
1637
1638    if (!empty($prefs['collapsed_folders'])) {
1639      $folders     = explode('&&', $prefs['collapsed_folders']);
1640      $count       = count($folders);
1641      $folders_str = '';
1642
1643      if ($count) {
1644          $folders[0]        = substr($folders[0], 1);
1645          $folders[$count-1] = substr($folders[$count-1], 0, -1);
1646      }
1647
1648      foreach ($folders as $value) {
1649        if ($value != 'INBOX' && !preg_match($regexp, $value)) {
1650          $value = $prefix.$value;
1651        }
1652        $folders_str .= '&'.$value.'&';
1653      }
1654      $prefs['collapsed_folders'] = $folders_str;
1655    }
1656
1657    $prefs['namespace_fixed'] = true;
1658
1659    // save updated preferences and reset imap settings (default folders)
1660    $user->save_prefs($prefs);
1661    $this->set_imap_prop();
1662  }
1663
1664}
Note: See TracBrowser for help on using the repository browser.