source: github/program/include/rcmail.php @ b8ea160

HEADcourier-fixdev-browser-capabilitiespdorelease-0.8
Last change on this file since b8ea160 was b8ea160, checked in by thomascube <thomas@…>, 14 months ago

Always return the correct connection state

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