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

HEADcourier-fixdev-browser-capabilitiespdorelease-0.8
Last change on this file since a71a97f was a71a97f, checked in by alecpl <alec@…>, 15 months ago
  • Image resize with GD extension (#1488383)
  • 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        return $storage->is_connected();
732      }
733    }
734
735    return false;
736  }
737
738
739  /**
740   * Create session object and start the session.
741   */
742  public function session_init()
743  {
744    // session started (Installer?)
745    if (session_id())
746      return;
747
748    $sess_name   = $this->config->get('session_name');
749    $sess_domain = $this->config->get('session_domain');
750    $lifetime    = $this->config->get('session_lifetime', 0) * 60;
751
752    // set session domain
753    if ($sess_domain) {
754      ini_set('session.cookie_domain', $sess_domain);
755    }
756    // set session garbage collecting time according to session_lifetime
757    if ($lifetime) {
758      ini_set('session.gc_maxlifetime', $lifetime * 2);
759    }
760
761    ini_set('session.cookie_secure', rcube_https_check());
762    ini_set('session.name', $sess_name ? $sess_name : 'roundcube_sessid');
763    ini_set('session.use_cookies', 1);
764    ini_set('session.use_only_cookies', 1);
765    ini_set('session.serialize_handler', 'php');
766
767    // use database for storing session data
768    $this->session = new rcube_session($this->get_dbh(), $this->config);
769
770    $this->session->register_gc_handler('rcmail_temp_gc');
771    $this->session->register_gc_handler(array($this, 'cache_gc'));
772
773    // start PHP session (if not in CLI mode)
774    if ($_SERVER['REMOTE_ADDR'])
775      session_start();
776
777    // set initial session vars
778    if (!$_SESSION['user_id'])
779      $_SESSION['temp'] = true;
780
781    // restore skin selection after logout
782    if ($_SESSION['temp'] && !empty($_SESSION['skin']))
783      $this->config->set('skin', $_SESSION['skin']);
784  }
785
786
787  /**
788   * Configure session object internals
789   */
790  public function session_configure()
791  {
792    if (!$this->session)
793      return;
794
795    $lifetime = $this->config->get('session_lifetime', 0) * 60;
796
797    // set keep-alive/check-recent interval
798    if ($keep_alive = $this->config->get('keep_alive')) {
799      // be sure that it's less than session lifetime
800      if ($lifetime)
801        $keep_alive = min($keep_alive, $lifetime - 30);
802      $keep_alive = max(60, $keep_alive);
803      $this->session->set_keep_alive($keep_alive);
804    }
805
806    $this->session->set_secret($this->config->get('des_key') . $_SERVER['HTTP_USER_AGENT']);
807    $this->session->set_ip_check($this->config->get('ip_check'));
808  }
809
810
811  /**
812   * Perfom login to the mail server and to the webmail service.
813   * This will also create a new user entry if auto_create_user is configured.
814   *
815   * @param string Mail storage (IMAP) user name
816   * @param string Mail storage (IMAP) password
817   * @param string Mail storage (IMAP) host
818   *
819   * @return boolean True on success, False on failure
820   */
821  function login($username, $pass, $host=NULL)
822  {
823    if (empty($username)) {
824      return false;
825    }
826
827    $config = $this->config->all();
828
829    if (!$host)
830      $host = $config['default_host'];
831
832    // Validate that selected host is in the list of configured hosts
833    if (is_array($config['default_host'])) {
834      $allowed = false;
835      foreach ($config['default_host'] as $key => $host_allowed) {
836        if (!is_numeric($key))
837          $host_allowed = $key;
838        if ($host == $host_allowed) {
839          $allowed = true;
840          break;
841        }
842      }
843      if (!$allowed)
844        return false;
845      }
846    else if (!empty($config['default_host']) && $host != rcube_parse_host($config['default_host']))
847      return false;
848
849    // parse $host URL
850    $a_host = parse_url($host);
851    if ($a_host['host']) {
852      $host = $a_host['host'];
853      $ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? $a_host['scheme'] : null;
854      if (!empty($a_host['port']))
855        $port = $a_host['port'];
856      else if ($ssl && $ssl != 'tls' && (!$config['default_port'] || $config['default_port'] == 143))
857        $port = 993;
858    }
859
860    if (!$port) {
861        $port = $config['default_port'];
862    }
863
864    /* Modify username with domain if required
865       Inspired by Marco <P0L0_notspam_binware.org>
866    */
867    // Check if we need to add domain
868    if (!empty($config['username_domain']) && strpos($username, '@') === false) {
869      if (is_array($config['username_domain']) && isset($config['username_domain'][$host]))
870        $username .= '@'.rcube_parse_host($config['username_domain'][$host], $host);
871      else if (is_string($config['username_domain']))
872        $username .= '@'.rcube_parse_host($config['username_domain'], $host);
873    }
874
875    // Convert username to lowercase. If storage backend
876    // is case-insensitive we need to store always the same username (#1487113)
877    if ($config['login_lc']) {
878      $username = mb_strtolower($username);
879    }
880
881    // try to resolve email address from virtuser table
882    if (strpos($username, '@') && ($virtuser = rcube_user::email2user($username))) {
883      $username = $virtuser;
884    }
885
886    // Here we need IDNA ASCII
887    // Only rcube_contacts class is using domain names in Unicode
888    $host = rcube_idn_to_ascii($host);
889    if (strpos($username, '@')) {
890      // lowercase domain name
891      list($local, $domain) = explode('@', $username);
892      $username = $local . '@' . mb_strtolower($domain);
893      $username = rcube_idn_to_ascii($username);
894    }
895
896    // user already registered -> overwrite username
897    if ($user = rcube_user::query($username, $host))
898      $username = $user->data['username'];
899
900    if (!$this->storage)
901      $this->storage_init();
902
903    // try to log in
904    if (!($login = $this->storage->connect($host, $username, $pass, $port, $ssl))) {
905      // try with lowercase
906      $username_lc = mb_strtolower($username);
907      if ($username_lc != $username) {
908        // try to find user record again -> overwrite username
909        if (!$user && ($user = rcube_user::query($username_lc, $host)))
910          $username_lc = $user->data['username'];
911
912        if ($login = $this->storage->connect($host, $username_lc, $pass, $port, $ssl))
913          $username = $username_lc;
914      }
915    }
916
917    // exit if login failed
918    if (!$login) {
919      return false;
920    }
921
922    // user already registered -> update user's record
923    if (is_object($user)) {
924      // update last login timestamp
925      $user->touch();
926    }
927    // create new system user
928    else if ($config['auto_create_user']) {
929      if ($created = rcube_user::create($username, $host)) {
930        $user = $created;
931      }
932      else {
933        raise_error(array(
934          'code' => 620, 'type' => 'php',
935          'file' => __FILE__, 'line' => __LINE__,
936          'message' => "Failed to create a user record. Maybe aborted by a plugin?"
937          ), true, false);
938      }
939    }
940    else {
941      raise_error(array(
942        'code' => 621, 'type' => 'php',
943        'file' => __FILE__, 'line' => __LINE__,
944        'message' => "Access denied for new user $username. 'auto_create_user' is disabled"
945        ), true, false);
946    }
947
948    // login succeeded
949    if (is_object($user) && $user->ID) {
950      // Configure environment
951      $this->set_user($user);
952      $this->set_storage_prop();
953      $this->session_configure();
954
955      // fix some old settings according to namespace prefix
956      $this->fix_namespace_settings($user);
957
958      // create default folders on first login
959      if ($config['create_default_folders'] && (!empty($created) || empty($user->data['last_login']))) {
960        $this->storage->create_default_folders();
961      }
962
963      // set session vars
964      $_SESSION['user_id']      = $user->ID;
965      $_SESSION['username']     = $user->data['username'];
966      $_SESSION['storage_host'] = $host;
967      $_SESSION['storage_port'] = $port;
968      $_SESSION['storage_ssl']  = $ssl;
969      $_SESSION['password']     = $this->encrypt($pass);
970      $_SESSION['login_time']   = mktime();
971
972      if (isset($_REQUEST['_timezone']) && $_REQUEST['_timezone'] != '_default_')
973        $_SESSION['timezone'] = floatval($_REQUEST['_timezone']);
974      if (isset($_REQUEST['_dstactive']) && $_REQUEST['_dstactive'] != '_default_')
975        $_SESSION['dst_active'] = intval($_REQUEST['_dstactive']);
976
977      // force reloading complete list of subscribed mailboxes
978      $this->storage->clear_cache('mailboxes', true);
979
980      return true;
981    }
982
983    return false;
984  }
985
986
987  /**
988   * Set storage parameters.
989   * This must be done AFTER connecting to the server!
990   */
991  private function set_storage_prop()
992  {
993    $storage = $this->get_storage();
994
995    $storage->set_charset($this->config->get('default_charset', RCMAIL_CHARSET));
996
997    if ($default_folders = $this->config->get('default_folders')) {
998      $storage->set_default_folders($default_folders);
999    }
1000    if (isset($_SESSION['mbox'])) {
1001      $storage->set_folder($_SESSION['mbox']);
1002    }
1003    if (isset($_SESSION['page'])) {
1004      $storage->set_page($_SESSION['page']);
1005    }
1006  }
1007
1008
1009  /**
1010   * Auto-select IMAP host based on the posted login information
1011   *
1012   * @return string Selected IMAP host
1013   */
1014  public function autoselect_host()
1015  {
1016    $default_host = $this->config->get('default_host');
1017    $host = null;
1018
1019    if (is_array($default_host)) {
1020      $post_host = get_input_value('_host', RCUBE_INPUT_POST);
1021
1022      // direct match in default_host array
1023      if ($default_host[$post_host] || in_array($post_host, array_values($default_host))) {
1024        $host = $post_host;
1025      }
1026
1027      // try to select host by mail domain
1028      list($user, $domain) = explode('@', get_input_value('_user', RCUBE_INPUT_POST));
1029      if (!empty($domain)) {
1030        foreach ($default_host as $storage_host => $mail_domains) {
1031          if (is_array($mail_domains) && in_array_nocase($domain, $mail_domains)) {
1032            $host = $storage_host;
1033            break;
1034          }
1035          else if (stripos($storage_host, $domain) !== false || stripos(strval($mail_domains), $domain) !== false) {
1036            $host = is_numeric($storage_host) ? $mail_domains : $storage_host;
1037            break;
1038          }
1039        }
1040      }
1041
1042      // take the first entry if $host is still not set
1043      if (empty($host)) {
1044        list($key, $val) = each($default_host);
1045        $host = is_numeric($key) ? $val : $key;
1046      }
1047    }
1048    else if (empty($default_host)) {
1049      $host = get_input_value('_host', RCUBE_INPUT_POST);
1050    }
1051    else
1052      $host = rcube_parse_host($default_host);
1053
1054    return $host;
1055  }
1056
1057
1058  /**
1059   * Get localized text in the desired language
1060   *
1061   * @param mixed   $attrib  Named parameters array or label name
1062   * @param string  $domain  Label domain (plugin) name
1063   *
1064   * @return string Localized text
1065   */
1066  public function gettext($attrib, $domain=null)
1067  {
1068    // load localization files if not done yet
1069    if (empty($this->texts))
1070      $this->load_language();
1071
1072    // extract attributes
1073    if (is_string($attrib))
1074      $attrib = array('name' => $attrib);
1075
1076    $name = $attrib['name'] ? $attrib['name'] : '';
1077
1078    // attrib contain text values: use them from now
1079    if (($setval = $attrib[strtolower($_SESSION['language'])]) || ($setval = $attrib['en_us']))
1080        $this->texts[$name] = $setval;
1081
1082    // check for text with domain
1083    if ($domain && ($text = $this->texts[$domain.'.'.$name]))
1084      ;
1085    // text does not exist
1086    else if (!($text = $this->texts[$name])) {
1087      return "[$name]";
1088    }
1089
1090    // replace vars in text
1091    if (is_array($attrib['vars'])) {
1092      foreach ($attrib['vars'] as $var_key => $var_value)
1093        $text = str_replace($var_key[0]!='$' ? '$'.$var_key : $var_key, $var_value, $text);
1094    }
1095
1096    // format output
1097    if (($attrib['uppercase'] && strtolower($attrib['uppercase']=='first')) || $attrib['ucfirst'])
1098      return ucfirst($text);
1099    else if ($attrib['uppercase'])
1100      return mb_strtoupper($text);
1101    else if ($attrib['lowercase'])
1102      return mb_strtolower($text);
1103
1104    return strtr($text, array('\n' => "\n"));
1105  }
1106
1107
1108  /**
1109   * Check if the given text label exists
1110   *
1111   * @param string  $name       Label name
1112   * @param string  $domain     Label domain (plugin) name or '*' for all domains
1113   * @param string  $ref_domain Sets domain name if label is found
1114   *
1115   * @return boolean True if text exists (either in the current language or in en_US)
1116   */
1117  public function text_exists($name, $domain = null, &$ref_domain = null)
1118  {
1119    // load localization files if not done yet
1120    if (empty($this->texts))
1121      $this->load_language();
1122
1123    if (isset($this->texts[$name])) {
1124        $ref_domain = '';
1125        return true;
1126    }
1127
1128    // any of loaded domains (plugins)
1129    if ($domain == '*') {
1130      foreach ($this->plugins->loaded_plugins() as $domain)
1131        if (isset($this->texts[$domain.'.'.$name])) {
1132          $ref_domain = $domain;
1133          return true;
1134        }
1135    }
1136    // specified domain
1137    else if ($domain) {
1138      $ref_domain = $domain;
1139      return isset($this->texts[$domain.'.'.$name]);
1140    }
1141
1142    return false;
1143  }
1144
1145  /**
1146   * Load a localization package
1147   *
1148   * @param string Language ID
1149   */
1150  public function load_language($lang = null, $add = array())
1151  {
1152    $lang = $this->language_prop(($lang ? $lang : $_SESSION['language']));
1153
1154    // load localized texts
1155    if (empty($this->texts) || $lang != $_SESSION['language']) {
1156      $this->texts = array();
1157
1158      // handle empty lines after closing PHP tag in localization files
1159      ob_start();
1160
1161      // get english labels (these should be complete)
1162      @include(INSTALL_PATH . 'program/localization/en_US/labels.inc');
1163      @include(INSTALL_PATH . 'program/localization/en_US/messages.inc');
1164
1165      if (is_array($labels))
1166        $this->texts = $labels;
1167      if (is_array($messages))
1168        $this->texts = array_merge($this->texts, $messages);
1169
1170      // include user language files
1171      if ($lang != 'en' && is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
1172        include_once(INSTALL_PATH . 'program/localization/' . $lang . '/labels.inc');
1173        include_once(INSTALL_PATH . 'program/localization/' . $lang . '/messages.inc');
1174
1175        if (is_array($labels))
1176          $this->texts = array_merge($this->texts, $labels);
1177        if (is_array($messages))
1178          $this->texts = array_merge($this->texts, $messages);
1179      }
1180
1181      ob_end_clean();
1182
1183      $_SESSION['language'] = $lang;
1184    }
1185
1186    // append additional texts (from plugin)
1187    if (is_array($add) && !empty($add))
1188      $this->texts += $add;
1189  }
1190
1191
1192  /**
1193   * Read directory program/localization and return a list of available languages
1194   *
1195   * @return array List of available localizations
1196   */
1197  public function list_languages()
1198  {
1199    static $sa_languages = array();
1200
1201    if (!sizeof($sa_languages)) {
1202      @include(INSTALL_PATH . 'program/localization/index.inc');
1203
1204      if ($dh = @opendir(INSTALL_PATH . 'program/localization')) {
1205        while (($name = readdir($dh)) !== false) {
1206          if ($name[0] == '.' || !is_dir(INSTALL_PATH . 'program/localization/' . $name))
1207            continue;
1208
1209          if ($label = $rcube_languages[$name])
1210            $sa_languages[$name] = $label;
1211        }
1212        closedir($dh);
1213      }
1214    }
1215
1216    return $sa_languages;
1217  }
1218
1219
1220  /**
1221   * Destroy session data and remove cookie
1222   */
1223  public function kill_session()
1224  {
1225    $this->plugins->exec_hook('session_destroy');
1226
1227    $this->session->kill();
1228    $_SESSION = array('language' => $this->user->language, 'temp' => true, 'skin' => $this->config->get('skin'));
1229    $this->user->reset();
1230  }
1231
1232
1233  /**
1234   * Do server side actions on logout
1235   */
1236  public function logout_actions()
1237  {
1238    $config = $this->config->all();
1239
1240    // on logout action we're not connected to imap server
1241    if (($config['logout_purge'] && !empty($config['trash_mbox'])) || $config['logout_expunge']) {
1242      if (!$this->session->check_auth())
1243        return;
1244
1245      $this->storage_connect();
1246    }
1247
1248    if ($config['logout_purge'] && !empty($config['trash_mbox'])) {
1249      $this->storage->clear_folder($config['trash_mbox']);
1250    }
1251
1252    if ($config['logout_expunge']) {
1253      $this->storage->expunge_folder('INBOX');
1254    }
1255
1256    // Try to save unsaved user preferences
1257    if (!empty($_SESSION['preferences'])) {
1258      $this->user->save_prefs(unserialize($_SESSION['preferences']));
1259    }
1260  }
1261
1262
1263  /**
1264   * Function to be executed in script shutdown
1265   * Registered with register_shutdown_function()
1266   */
1267  public function shutdown()
1268  {
1269    foreach ($this->shutdown_functions as $function)
1270      call_user_func($function);
1271
1272    if (is_object($this->smtp))
1273      $this->smtp->disconnect();
1274
1275    foreach ($this->address_books as $book) {
1276      if (is_object($book) && is_a($book, 'rcube_addressbook'))
1277        $book->close();
1278    }
1279
1280    foreach ($this->caches as $cache) {
1281        if (is_object($cache))
1282            $cache->close();
1283    }
1284
1285    if (is_object($this->storage)) {
1286        if ($this->expunge_cache)
1287            $this->storage->expunge_cache();
1288      $this->storage->close();
1289  }
1290
1291    // before closing the database connection, write session data
1292    if ($_SERVER['REMOTE_ADDR'] && is_object($this->session)) {
1293      session_write_close();
1294    }
1295
1296    // write performance stats to logs/console
1297    if ($this->config->get('devel_mode')) {
1298      if (function_exists('memory_get_usage'))
1299        $mem = show_bytes(memory_get_usage());
1300      if (function_exists('memory_get_peak_usage'))
1301        $mem .= '/'.show_bytes(memory_get_peak_usage());
1302
1303      $log = $this->task . ($this->action ? '/'.$this->action : '') . ($mem ? " [$mem]" : '');
1304      if (defined('RCMAIL_START'))
1305        rcube_print_time(RCMAIL_START, $log);
1306      else
1307        console($log);
1308    }
1309  }
1310
1311
1312  /**
1313   * Registers shutdown function to be executed on shutdown.
1314   * The functions will be executed before destroying any
1315   * objects like smtp, imap, session, etc.
1316   *
1317   * @param callback Function callback
1318   */
1319  public function add_shutdown_function($function)
1320  {
1321    $this->shutdown_functions[] = $function;
1322  }
1323
1324
1325  /**
1326   * Garbage collector for cache entries.
1327   * Set flag to expunge caches on shutdown
1328   */
1329  function cache_gc()
1330  {
1331    // because this gc function is called before storage is initialized,
1332    // we just set a flag to expunge storage cache on shutdown.
1333    $this->expunge_cache = true;
1334  }
1335
1336
1337  /**
1338   * Generate a unique token to be used in a form request
1339   *
1340   * @return string The request token
1341   */
1342  public function get_request_token()
1343  {
1344    $sess_id = $_COOKIE[ini_get('session.name')];
1345    if (!$sess_id) $sess_id = session_id();
1346    $plugin = $this->plugins->exec_hook('request_token', array('value' => md5('RT' . $this->user->ID . $this->config->get('des_key') . $sess_id)));
1347    return $plugin['value'];
1348  }
1349
1350
1351  /**
1352   * Check if the current request contains a valid token
1353   *
1354   * @param int Request method
1355   * @return boolean True if request token is valid false if not
1356   */
1357  public function check_request($mode = RCUBE_INPUT_POST)
1358  {
1359    $token = get_input_value('_token', $mode);
1360    $sess_id = $_COOKIE[ini_get('session.name')];
1361    return !empty($sess_id) && $token == $this->get_request_token();
1362  }
1363
1364
1365  /**
1366   * Create unique authorization hash
1367   *
1368   * @param string Session ID
1369   * @param int Timestamp
1370   * @return string The generated auth hash
1371   */
1372  private function get_auth_hash($sess_id, $ts)
1373  {
1374    $auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
1375      $sess_id,
1376      $ts,
1377      $this->config->get('ip_check') ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
1378      $_SERVER['HTTP_USER_AGENT']);
1379
1380    if (function_exists('sha1'))
1381      return sha1($auth_string);
1382    else
1383      return md5($auth_string);
1384  }
1385
1386
1387  /**
1388   * Encrypt using 3DES
1389   *
1390   * @param string $clear clear text input
1391   * @param string $key encryption key to retrieve from the configuration, defaults to 'des_key'
1392   * @param boolean $base64 whether or not to base64_encode() the result before returning
1393   *
1394   * @return string encrypted text
1395   */
1396  public function encrypt($clear, $key = 'des_key', $base64 = true)
1397  {
1398    if (!$clear)
1399      return '';
1400    /*-
1401     * Add a single canary byte to the end of the clear text, which
1402     * will help find out how much of padding will need to be removed
1403     * upon decryption; see http://php.net/mcrypt_generic#68082
1404     */
1405    $clear = pack("a*H2", $clear, "80");
1406
1407    if (function_exists('mcrypt_module_open') &&
1408        ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_CBC, "")))
1409    {
1410      $iv = $this->create_iv(mcrypt_enc_get_iv_size($td));
1411      mcrypt_generic_init($td, $this->config->get_crypto_key($key), $iv);
1412      $cipher = $iv . mcrypt_generic($td, $clear);
1413      mcrypt_generic_deinit($td);
1414      mcrypt_module_close($td);
1415    }
1416    else {
1417      @include_once 'des.inc';
1418
1419      if (function_exists('des')) {
1420        $des_iv_size = 8;
1421        $iv = $this->create_iv($des_iv_size);
1422        $cipher = $iv . des($this->config->get_crypto_key($key), $clear, 1, 1, $iv);
1423      }
1424      else {
1425        raise_error(array(
1426          'code' => 500, 'type' => 'php',
1427          'file' => __FILE__, 'line' => __LINE__,
1428          'message' => "Could not perform encryption; make sure Mcrypt is installed or lib/des.inc is available"
1429        ), true, true);
1430      }
1431    }
1432
1433    return $base64 ? base64_encode($cipher) : $cipher;
1434  }
1435
1436  /**
1437   * Decrypt 3DES-encrypted string
1438   *
1439   * @param string $cipher encrypted text
1440   * @param string $key encryption key to retrieve from the configuration, defaults to 'des_key'
1441   * @param boolean $base64 whether or not input is base64-encoded
1442   *
1443   * @return string decrypted text
1444   */
1445  public function decrypt($cipher, $key = 'des_key', $base64 = true)
1446  {
1447    if (!$cipher)
1448      return '';
1449
1450    $cipher = $base64 ? base64_decode($cipher) : $cipher;
1451
1452    if (function_exists('mcrypt_module_open') &&
1453        ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_CBC, "")))
1454    {
1455      $iv_size = mcrypt_enc_get_iv_size($td);
1456      $iv = substr($cipher, 0, $iv_size);
1457
1458      // session corruption? (#1485970)
1459      if (strlen($iv) < $iv_size)
1460        return '';
1461
1462      $cipher = substr($cipher, $iv_size);
1463      mcrypt_generic_init($td, $this->config->get_crypto_key($key), $iv);
1464      $clear = mdecrypt_generic($td, $cipher);
1465      mcrypt_generic_deinit($td);
1466      mcrypt_module_close($td);
1467    }
1468    else {
1469      @include_once 'des.inc';
1470
1471      if (function_exists('des')) {
1472        $des_iv_size = 8;
1473        $iv = substr($cipher, 0, $des_iv_size);
1474        $cipher = substr($cipher, $des_iv_size);
1475        $clear = des($this->config->get_crypto_key($key), $cipher, 0, 1, $iv);
1476      }
1477      else {
1478        raise_error(array(
1479          'code' => 500, 'type' => 'php',
1480          'file' => __FILE__, 'line' => __LINE__,
1481          'message' => "Could not perform decryption; make sure Mcrypt is installed or lib/des.inc is available"
1482        ), true, true);
1483      }
1484    }
1485
1486    /*-
1487     * Trim PHP's padding and the canary byte; see note in
1488     * rcmail::encrypt() and http://php.net/mcrypt_generic#68082
1489     */
1490    $clear = substr(rtrim($clear, "\0"), 0, -1);
1491
1492    return $clear;
1493  }
1494
1495  /**
1496   * Generates encryption initialization vector (IV)
1497   *
1498   * @param int Vector size
1499   * @return string Vector string
1500   */
1501  private function create_iv($size)
1502  {
1503    // mcrypt_create_iv() can be slow when system lacks entrophy
1504    // we'll generate IV vector manually
1505    $iv = '';
1506    for ($i = 0; $i < $size; $i++)
1507        $iv .= chr(mt_rand(0, 255));
1508    return $iv;
1509  }
1510
1511  /**
1512   * Build a valid URL to this instance of Roundcube
1513   *
1514   * @param mixed Either a string with the action or url parameters as key-value pairs
1515   * @return string Valid application URL
1516   */
1517  public function url($p)
1518  {
1519    if (!is_array($p))
1520      $p = array('_action' => @func_get_arg(0));
1521
1522    $task = $p['_task'] ? $p['_task'] : ($p['task'] ? $p['task'] : $this->task);
1523    $p['_task'] = $task;
1524    unset($p['task']);
1525
1526    $url = './';
1527    $delm = '?';
1528    foreach (array_reverse($p) as $key => $val) {
1529      if ($val !== '' && $val !== null) {
1530        $par = $key[0] == '_' ? $key : '_'.$key;
1531        $url .= $delm.urlencode($par).'='.urlencode($val);
1532        $delm = '&';
1533      }
1534    }
1535    return $url;
1536  }
1537
1538
1539  /**
1540   * Construct shell command, execute it and return output as string.
1541   * Keywords {keyword} are replaced with arguments
1542   *
1543   * @param $cmd Format string with {keywords} to be replaced
1544   * @param $values (zero, one or more arrays can be passed)
1545   * @return output of command. shell errors not detectable
1546   */
1547  public static function exec(/* $cmd, $values1 = array(), ... */)
1548  {
1549    $args = func_get_args();
1550    $cmd = array_shift($args);
1551    $values = $replacements = array();
1552
1553    // merge values into one array
1554    foreach ($args as $arg)
1555      $values += (array)$arg;
1556
1557    preg_match_all('/({(-?)([a-z]\w*)})/', $cmd, $matches, PREG_SET_ORDER);
1558    foreach ($matches as $tags) {
1559      list(, $tag, $option, $key) = $tags;
1560      $parts = array();
1561
1562      if ($option) {
1563        foreach ((array)$values["-$key"] as $key => $value) {
1564          if ($value === true || $value === false || $value === null)
1565            $parts[] = $value ? $key : "";
1566          else foreach ((array)$value as $val)
1567            $parts[] = "$key " . escapeshellarg($val);
1568        }
1569      }
1570      else {
1571        foreach ((array)$values[$key] as $value)
1572          $parts[] = escapeshellarg($value);
1573      }
1574
1575      $replacements[$tag] = join(" ", $parts);
1576    }
1577
1578    // use strtr behaviour of going through source string once
1579    $cmd = strtr($cmd, $replacements);
1580
1581    return (string)shell_exec($cmd);
1582  }
1583
1584
1585  /**
1586   * Helper method to set a cookie with the current path and host settings
1587   *
1588   * @param string Cookie name
1589   * @param string Cookie value
1590   * @param string Expiration time
1591   */
1592  public static function setcookie($name, $value, $exp = 0)
1593  {
1594    if (headers_sent())
1595      return;
1596
1597    $cookie = session_get_cookie_params();
1598
1599    setcookie($name, $value, $exp, $cookie['path'], $cookie['domain'],
1600      rcube_https_check(), true);
1601  }
1602
1603  /**
1604   * Registers action aliases for current task
1605   *
1606   * @param array $map Alias-to-filename hash array
1607   */
1608  public function register_action_map($map)
1609  {
1610    if (is_array($map)) {
1611      foreach ($map as $idx => $val) {
1612        $this->action_map[$idx] = $val;
1613      }
1614    }
1615  }
1616
1617  /**
1618   * Returns current action filename
1619   *
1620   * @param array $map Alias-to-filename hash array
1621   */
1622  public function get_action_file()
1623  {
1624    if (!empty($this->action_map[$this->action])) {
1625      return $this->action_map[$this->action];
1626    }
1627
1628    return strtr($this->action, '-', '_') . '.inc';
1629  }
1630
1631  /**
1632   * Fixes some user preferences according to namespace handling change.
1633   * Old Roundcube versions were using folder names with removed namespace prefix.
1634   * Now we need to add the prefix on servers where personal namespace has prefix.
1635   *
1636   * @param rcube_user $user User object
1637   */
1638  private function fix_namespace_settings($user)
1639  {
1640    $prefix     = $this->storage->get_namespace('prefix');
1641    $prefix_len = strlen($prefix);
1642
1643    if (!$prefix_len)
1644      return;
1645
1646    $prefs = $this->config->all();
1647    if (!empty($prefs['namespace_fixed']))
1648      return;
1649
1650    // Build namespace prefix regexp
1651    $ns     = $this->storage->get_namespace();
1652    $regexp = array();
1653
1654    foreach ($ns as $entry) {
1655      if (!empty($entry)) {
1656        foreach ($entry as $item) {
1657          if (strlen($item[0])) {
1658            $regexp[] = preg_quote($item[0], '/');
1659          }
1660        }
1661      }
1662    }
1663    $regexp = '/^('. implode('|', $regexp).')/';
1664
1665    // Fix preferences
1666    $opts = array('drafts_mbox', 'junk_mbox', 'sent_mbox', 'trash_mbox', 'archive_mbox');
1667    foreach ($opts as $opt) {
1668      if ($value = $prefs[$opt]) {
1669        if ($value != 'INBOX' && !preg_match($regexp, $value)) {
1670          $prefs[$opt] = $prefix.$value;
1671        }
1672      }
1673    }
1674
1675    if (!empty($prefs['default_folders'])) {
1676      foreach ($prefs['default_folders'] as $idx => $name) {
1677        if ($name != 'INBOX' && !preg_match($regexp, $name)) {
1678          $prefs['default_folders'][$idx] = $prefix.$name;
1679        }
1680      }
1681    }
1682
1683    if (!empty($prefs['search_mods'])) {
1684      $folders = array();
1685      foreach ($prefs['search_mods'] as $idx => $value) {
1686        if ($idx != 'INBOX' && $idx != '*' && !preg_match($regexp, $idx)) {
1687          $idx = $prefix.$idx;
1688        }
1689        $folders[$idx] = $value;
1690      }
1691      $prefs['search_mods'] = $folders;
1692    }
1693
1694    if (!empty($prefs['message_threading'])) {
1695      $folders = array();
1696      foreach ($prefs['message_threading'] as $idx => $value) {
1697        if ($idx != 'INBOX' && !preg_match($regexp, $idx)) {
1698          $idx = $prefix.$idx;
1699        }
1700        $folders[$prefix.$idx] = $value;
1701      }
1702      $prefs['message_threading'] = $folders;
1703    }
1704
1705    if (!empty($prefs['collapsed_folders'])) {
1706      $folders     = explode('&&', $prefs['collapsed_folders']);
1707      $count       = count($folders);
1708      $folders_str = '';
1709
1710      if ($count) {
1711          $folders[0]        = substr($folders[0], 1);
1712          $folders[$count-1] = substr($folders[$count-1], 0, -1);
1713      }
1714
1715      foreach ($folders as $value) {
1716        if ($value != 'INBOX' && !preg_match($regexp, $value)) {
1717          $value = $prefix.$value;
1718        }
1719        $folders_str .= '&'.$value.'&';
1720      }
1721      $prefs['collapsed_folders'] = $folders_str;
1722    }
1723
1724    $prefs['namespace_fixed'] = true;
1725
1726    // save updated preferences and reset imap settings (default folders)
1727    $user->save_prefs($prefs);
1728    $this->set_storage_prop();
1729  }
1730
1731}
Note: See TracBrowser for help on using the repository browser.