source: github/program/include/rcmail.php @ 08ffd939

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