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

Last change on this file since 5177 was 5177, checked in by thomasb, 22 months ago

Improved memcache connection procedure from release-0.6; use call_user_func to trigger session gc handlers

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