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

Last change on this file since 4020 was 4020, checked in by alec, 3 years ago
  • Added line number for error message
  • Property svn:keywords set to Id
File size: 36.5 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-2010, Roundcube Dev. - Switzerland                 |
9 | Licensed under the GNU GPL                                            |
10 |                                                                       |
11 | PURPOSE:                                                              |
12 |   Application class providing core functions and holding              |
13 |   instances of all 'global' objects like db- and imap-connections     |
14 +-----------------------------------------------------------------------+
15 | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16 +-----------------------------------------------------------------------+
17
18 $Id$
19
20*/
21
22
23/**
24 * Application class of Roundcube Webmail
25 * implemented as singleton
26 *
27 * @package Core
28 */
29class rcmail
30{
31  /**
32   * Main tasks.
33   *
34   * @var array
35   */
36  static public $main_tasks = array('mail','settings','addressbook','login','logout','utils','dummy');
37
38  /**
39   * Singleton instace of rcmail
40   *
41   * @var rcmail
42   */
43  static private $instance;
44
45  /**
46   * Stores instance of rcube_config.
47   *
48   * @var rcube_config
49   */
50  public $config;
51
52  /**
53   * Stores rcube_user instance.
54   *
55   * @var rcube_user
56   */
57  public $user;
58
59  /**
60   * Instace of database class.
61   *
62   * @var rcube_mdb2
63   */
64  public $db;
65
66  /**
67   * Instace of rcube_session class.
68   *
69   * @var rcube_session
70   */
71  public $session;
72
73  /**
74   * Instance of rcube_smtp class.
75   *
76   * @var rcube_smtp
77   */
78  public $smtp;
79
80  /**
81   * Instance of rcube_imap class.
82   *
83   * @var rcube_imap
84   */
85  public $imap;
86
87  /**
88   * Instance of rcube_template class.
89   *
90   * @var rcube_template
91   */
92  public $output;
93
94  /**
95   * Instance of rcube_plugin_api.
96   *
97   * @var rcube_plugin_api
98   */
99  public $plugins;
100
101  /**
102   * Current task.
103   *
104   * @var string
105   */
106  public $task;
107
108  /**
109   * Current action.
110   *
111   * @var string
112   */
113  public $action = '';
114  public $comm_path = './';
115
116  private $texts;
117  private $books = array();
118
119
120  /**
121   * This implements the 'singleton' design pattern
122   *
123   * @return rcmail The one and only instance
124   */
125  static function get_instance()
126  {
127    if (!self::$instance) {
128      self::$instance = new rcmail();
129      self::$instance->startup();  // init AFTER object was linked with self::$instance
130    }
131
132    return self::$instance;
133  }
134
135
136  /**
137   * Private constructor
138   */
139  private function __construct()
140  {
141    // load configuration
142    $this->config = new rcube_config();
143
144    register_shutdown_function(array($this, 'shutdown'));
145  }
146
147
148  /**
149   * Initial startup function
150   * to register session, create database and imap connections
151   *
152   * @todo Remove global vars $DB, $USER
153   */
154  private function startup()
155  {
156    // initialize syslog
157    if ($this->config->get('log_driver') == 'syslog') {
158      $syslog_id = $this->config->get('syslog_id', 'roundcube');
159      $syslog_facility = $this->config->get('syslog_facility', LOG_USER);
160      openlog($syslog_id, LOG_ODELAY, $syslog_facility);
161    }
162
163    // connect to database
164    $GLOBALS['DB'] = $this->get_dbh();
165
166    // start session
167    $this->session_init();
168
169    // create user object
170    $this->set_user(new rcube_user($_SESSION['user_id']));
171
172    // configure session (after user config merge!)
173    $this->session_configure();
174
175    // set task and action properties
176    $this->set_task(get_input_value('_task', RCUBE_INPUT_GPC));
177    $this->action = asciiwords(get_input_value('_action', RCUBE_INPUT_GPC));
178
179    // reset some session parameters when changing task
180    if ($this->task != 'utils') {
181      if ($this->session && $_SESSION['task'] != $this->task)
182        $this->session->remove('page');
183      // set current task to session
184      $_SESSION['task'] = $this->task;
185    }
186
187    // init output class
188    if (!empty($_REQUEST['_remote']))
189      $GLOBALS['OUTPUT'] = $this->json_init();
190    else
191      $GLOBALS['OUTPUT'] = $this->load_gui(!empty($_REQUEST['_framed']));
192
193    // create plugin API and load plugins
194    $this->plugins = rcube_plugin_api::get_instance();
195
196    // init plugins
197    $this->plugins->init();
198  }
199
200
201  /**
202   * Setter for application task
203   *
204   * @param string Task to set
205   */
206  public function set_task($task)
207  {
208    $task = asciiwords($task);
209
210    if ($this->user && $this->user->ID)
211      $task = !$task || $task == 'login' ? 'mail' : $task;
212    else
213      $task = 'login';
214
215    $this->task = $task;
216    $this->comm_path = $this->url(array('task' => $this->task));
217
218    if ($this->output)
219      $this->output->set_env('task', $this->task);
220  }
221
222
223  /**
224   * Setter for system user object
225   *
226   * @param rcube_user Current user instance
227   */
228  public function set_user($user)
229  {
230    if (is_object($user)) {
231      $this->user = $user;
232      $GLOBALS['USER'] = $this->user;
233
234      // overwrite config with user preferences
235      $this->config->set_user_prefs((array)$this->user->get_prefs());
236    }
237
238    $_SESSION['language'] = $this->user->language = $this->language_prop($this->config->get('language', $_SESSION['language']));
239
240    // set localization
241    setlocale(LC_ALL, $_SESSION['language'] . '.utf8', 'en_US.utf8');
242
243    // workaround for http://bugs.php.net/bug.php?id=18556
244    if (in_array($_SESSION['language'], array('tr_TR', 'ku', 'az_AZ')))
245      setlocale(LC_CTYPE, 'en_US' . '.utf8');
246  }
247
248
249  /**
250   * Check the given string and return a valid language code
251   *
252   * @param string Language code
253   * @return string Valid language code
254   */
255  private function language_prop($lang)
256  {
257    static $rcube_languages, $rcube_language_aliases;
258
259    // user HTTP_ACCEPT_LANGUAGE if no language is specified
260    if (empty($lang) || $lang == 'auto') {
261       $accept_langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
262       $lang = str_replace('-', '_', $accept_langs[0]);
263     }
264
265    if (empty($rcube_languages)) {
266      @include(INSTALL_PATH . 'program/localization/index.inc');
267    }
268
269    // check if we have an alias for that language
270    if (!isset($rcube_languages[$lang]) && isset($rcube_language_aliases[$lang])) {
271      $lang = $rcube_language_aliases[$lang];
272    }
273    // try the first two chars
274    else if (!isset($rcube_languages[$lang])) {
275      $short = substr($lang, 0, 2);
276
277      // check if we have an alias for the short language code
278      if (!isset($rcube_languages[$short]) && isset($rcube_language_aliases[$short])) {
279        $lang = $rcube_language_aliases[$short];
280      }
281      // expand 'nn' to 'nn_NN'
282      else if (!isset($rcube_languages[$short])) {
283        $lang = $short.'_'.strtoupper($short);
284      }
285    }
286
287    if (!isset($rcube_languages[$lang]) || !is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
288      $lang = 'en_US';
289    }
290
291    return $lang;
292  }
293
294
295  /**
296   * Get the current database connection
297   *
298   * @return rcube_mdb2  Database connection object
299   */
300  public function get_dbh()
301  {
302    if (!$this->db) {
303      $config_all = $this->config->all();
304
305      $this->db = new rcube_mdb2($config_all['db_dsnw'], $config_all['db_dsnr'], $config_all['db_persistent']);
306      $this->db->sqlite_initials = INSTALL_PATH . 'SQL/sqlite.initial.sql';
307      $this->db->set_debug((bool)$config_all['sql_debug']);
308    }
309
310    return $this->db;
311  }
312
313
314  /**
315   * Return instance of the internal address book class
316   *
317   * @param string  Address book identifier
318   * @param boolean True if the address book needs to be writeable
319   * @return rcube_contacts Address book object
320   */
321  public function get_address_book($id, $writeable = false)
322  {
323    $contacts = null;
324    $ldap_config = (array)$this->config->get('ldap_public');
325    $abook_type = strtolower($this->config->get('address_book_type'));
326
327    $plugin = $this->plugins->exec_hook('addressbook_get', array('id' => $id, 'writeable' => $writeable));
328
329    // plugin returned instance of a rcube_addressbook
330    if ($plugin['instance'] instanceof rcube_addressbook) {
331      $contacts = $plugin['instance'];
332    }
333    else if ($id && $ldap_config[$id]) {
334      $contacts = new rcube_ldap($ldap_config[$id], $this->config->get('ldap_debug'), $this->config->mail_domain($_SESSION['imap_host']));
335    }
336    else if ($id === '0') {
337      $contacts = new rcube_contacts($this->db, $this->user->ID);
338    }
339    else if ($abook_type == 'ldap') {
340      // Use the first writable LDAP address book.
341      foreach ($ldap_config as $id => $prop) {
342        if (!$writeable || $prop['writable']) {
343          $contacts = new rcube_ldap($prop, $this->config->get('ldap_debug'), $this->config->mail_domain($_SESSION['imap_host']));
344          break;
345        }
346      }
347    }
348    else { // $id == 'sql'
349      $contacts = new rcube_contacts($this->db, $this->user->ID);
350    }
351
352    // add to the 'books' array for shutdown function
353    if (!in_array($contacts, $this->books))
354      $this->books[] = $contacts;
355
356    return $contacts;
357  }
358
359
360  /**
361   * Return address books list
362   *
363   * @param boolean True if the address book needs to be writeable
364   * @return array  Address books array
365   */
366  public function get_address_sources($writeable = false)
367  {
368    $abook_type = strtolower($this->config->get('address_book_type'));
369    $ldap_config = $this->config->get('ldap_public');
370    $autocomplete = (array) $this->config->get('autocomplete_addressbooks');
371    $list = array();
372
373    // We are using the DB address book
374    if ($abook_type != 'ldap') {
375      $contacts = new rcube_contacts($this->db, null);
376      $list['0'] = array(
377        'id' => 0,
378        'name' => rcube_label('personaladrbook'),
379        'groups' => $contacts->groups,
380        'readonly' => false,
381        'autocomplete' => in_array('sql', $autocomplete)
382      );
383    }
384
385    if ($ldap_config) {
386      $ldap_config = (array) $ldap_config;
387      foreach ($ldap_config as $id => $prop)
388        $list[$id] = array(
389          'id' => $id,
390          'name' => $prop['name'],
391          'groups' => false,
392          'readonly' => !$prop['writable'],
393          'autocomplete' => in_array('sql', $autocomplete)
394        );
395    }
396
397    $plugin = $this->plugins->exec_hook('addressbooks_list', array('sources' => $list));
398    $list = $plugin['sources'];
399
400    if ($writeable && !empty($list)) {
401      foreach ($list as $idx => $item) {
402        if ($item['readonly']) {
403          unset($list[$idx]);
404        }
405      }
406    }
407
408    return $list;
409  }
410
411
412  /**
413   * Init output object for GUI and add common scripts.
414   * This will instantiate a rcmail_template object and set
415   * environment vars according to the current session and configuration
416   *
417   * @param boolean True if this request is loaded in a (i)frame
418   * @return rcube_template Reference to HTML output object
419   */
420  public function load_gui($framed = false)
421  {
422    // init output page
423    if (!($this->output instanceof rcube_template))
424      $this->output = new rcube_template($this->task, $framed);
425
426    // set keep-alive/check-recent interval
427    if ($this->session && ($keep_alive = $this->session->get_keep_alive())) {
428      $this->output->set_env('keep_alive', $keep_alive);
429    }
430
431    if ($framed) {
432      $this->comm_path .= '&_framed=1';
433      $this->output->set_env('framed', true);
434    }
435
436    $this->output->set_env('task', $this->task);
437    $this->output->set_env('action', $this->action);
438    $this->output->set_env('comm_path', $this->comm_path);
439    $this->output->set_charset(RCMAIL_CHARSET);
440
441    // add some basic label to client
442    $this->output->add_label('loading', 'servererror');
443
444    return $this->output;
445  }
446
447
448  /**
449   * Create an output object for JSON responses
450   *
451   * @return rcube_json_output Reference to JSON output object
452   */
453  public function json_init()
454  {
455    if (!($this->output instanceof rcube_json_output))
456      $this->output = new rcube_json_output($this->task);
457
458    return $this->output;
459  }
460
461
462  /**
463   * Create SMTP object and connect to server
464   *
465   * @param boolean True if connection should be established
466   */
467  public function smtp_init($connect = false)
468  {
469    $this->smtp = new rcube_smtp();
470
471    if ($connect)
472      $this->smtp->connect();
473  }
474
475
476  /**
477   * Create global IMAP object and connect to server
478   *
479   * @param boolean True if connection should be established
480   * @todo Remove global $IMAP
481   */
482  public function imap_init($connect = false)
483  {
484    // already initialized
485    if (is_object($this->imap))
486      return;
487
488    $this->imap = new rcube_imap($this->db);
489    $this->imap->debug_level = $this->config->get('debug_level');
490    $this->imap->skip_deleted = $this->config->get('skip_deleted');
491
492    // enable caching of imap data
493    if ($this->config->get('enable_caching')) {
494      $this->imap->set_caching(true);
495    }
496
497    // set pagesize from config
498    $this->imap->set_pagesize($this->config->get('pagesize', 50));
499
500    // Setting root and delimiter before establishing the connection
501    // can save time detecting them using NAMESPACE and LIST
502    $options = array(
503      'auth_method' => $this->config->get('imap_auth_type', 'check'),
504      'delimiter'   => isset($_SESSION['imap_delimiter']) ? $_SESSION['imap_delimiter'] : $this->config->get('imap_delimiter'),
505      'rootdir'     => isset($_SESSION['imap_root']) ? $_SESSION['imap_root'] : $this->config->get('imap_root'),
506      'debug_mode'  => (bool) $this->config->get('imap_debug', 0),
507      'force_caps'  => (bool) $this->config->get('imap_force_caps'),
508      'timeout'     => (int) $this->config->get('imap_timeout', 0),
509    );
510
511    $this->imap->set_options($options);
512
513    // set global object for backward compatibility
514    $GLOBALS['IMAP'] = $this->imap;
515
516    $hook = $this->plugins->exec_hook('imap_init', array('fetch_headers' => $this->imap->fetch_add_headers));
517    if ($hook['fetch_headers'])
518      $this->imap->fetch_add_headers = $hook['fetch_headers'];
519
520    // support this parameter for backward compatibility but log warning
521    if ($connect) {
522      $this->imap_connect();
523      raise_error(array(
524        'code' => 800, 'type' => 'imap',
525        'file' => __FILE__, 'line' => __LINE__,
526        'message' => "rcube::imap_init(true) is deprecated, use rcube::imap_connect() instead"),
527        true, false);
528    }
529  }
530
531
532  /**
533   * Connect to IMAP server with stored session data
534   *
535   * @return bool True on success, false on error
536   */
537  public function imap_connect()
538  {
539    if (!$this->imap)
540      $this->imap_init();
541
542    if ($_SESSION['imap_host'] && !$this->imap->conn->connected()) {
543      if (!$this->imap->connect($_SESSION['imap_host'], $_SESSION['username'], $this->decrypt($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl'])) {
544        if ($this->output)
545          $this->output->show_message($this->imap->error_code == -1 ? 'imaperror' : 'sessionerror', 'error');
546      }
547      else {
548        $this->set_imap_prop();
549        return $this->imap->conn;
550      }
551    }
552
553    return false;
554  }
555
556
557  /**
558   * Create session object and start the session.
559   */
560  public function session_init()
561  {
562    // session started (Installer?)
563    if (session_id())
564      return;
565
566    $lifetime = $this->config->get('session_lifetime', 0) * 60;
567
568    // set session domain
569    if ($domain = $this->config->get('session_domain')) {
570      ini_set('session.cookie_domain', $domain);
571    }
572    // set session garbage collecting time according to session_lifetime
573    if ($lifetime) {
574      ini_set('session.gc_maxlifetime', $lifetime * 2);
575    }
576
577    ini_set('session.cookie_secure', rcube_https_check());
578    ini_set('session.name', 'roundcube_sessid');
579    ini_set('session.use_cookies', 1);
580    ini_set('session.use_only_cookies', 1);
581    ini_set('session.serialize_handler', 'php');
582
583    // use database for storing session data
584    $this->session = new rcube_session($this->get_dbh(), $lifetime);
585
586    $this->session->register_gc_handler('rcmail_temp_gc');
587    if ($this->config->get('enable_caching'))
588      $this->session->register_gc_handler('rcmail_cache_gc');
589
590    // start PHP session (if not in CLI mode)
591    if ($_SERVER['REMOTE_ADDR'])
592      session_start();
593
594    // set initial session vars
595    if (!isset($_SESSION['auth_time'])) {
596      $_SESSION['auth_time'] = time();
597      $_SESSION['temp'] = true;
598    }
599  }
600
601
602  /**
603   * Configure session object internals
604   */
605  public function session_configure()
606  {
607    if (!$this->session)
608      return;
609
610    $lifetime = $this->config->get('session_lifetime', 0) * 60;
611
612    // set keep-alive/check-recent interval
613    if ($keep_alive = $this->config->get('keep_alive')) {
614      // be sure that it's less than session lifetime
615      if ($lifetime)
616        $keep_alive = min($keep_alive, $lifetime - 30);
617      $keep_alive = max(60, $keep_alive);
618      $this->session->set_keep_alive($keep_alive);
619    }
620  }
621
622
623  /**
624   * Perfom login to the IMAP server and to the webmail service.
625   * This will also create a new user entry if auto_create_user is configured.
626   *
627   * @param string IMAP user name
628   * @param string IMAP password
629   * @param string IMAP host
630   * @return boolean True on success, False on failure
631   */
632  function login($username, $pass, $host=NULL)
633  {
634    $user = NULL;
635    $config = $this->config->all();
636
637    if (!$host)
638      $host = $config['default_host'];
639
640    // Validate that selected host is in the list of configured hosts
641    if (is_array($config['default_host'])) {
642      $allowed = false;
643      foreach ($config['default_host'] as $key => $host_allowed) {
644        if (!is_numeric($key))
645          $host_allowed = $key;
646        if ($host == $host_allowed) {
647          $allowed = true;
648          break;
649        }
650      }
651      if (!$allowed)
652        return false;
653      }
654    else if (!empty($config['default_host']) && $host != rcube_parse_host($config['default_host']))
655      return false;
656
657    // parse $host URL
658    $a_host = parse_url($host);
659    if ($a_host['host']) {
660      $host = $a_host['host'];
661      $imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? $a_host['scheme'] : null;
662      if (!empty($a_host['port']))
663        $imap_port = $a_host['port'];
664      else if ($imap_ssl && $imap_ssl != 'tls' && (!$config['default_port'] || $config['default_port'] == 143))
665        $imap_port = 993;
666    }
667
668    $imap_port = $imap_port ? $imap_port : $config['default_port'];
669
670    /* Modify username with domain if required
671       Inspired by Marco <P0L0_notspam_binware.org>
672    */
673    // Check if we need to add domain
674    if (!empty($config['username_domain']) && strpos($username, '@') === false) {
675      if (is_array($config['username_domain']) && isset($config['username_domain'][$host]))
676        $username .= '@'.rcube_parse_host($config['username_domain'][$host]);
677      else if (is_string($config['username_domain']))
678        $username .= '@'.rcube_parse_host($config['username_domain']);
679    }
680
681    // try to resolve email address from virtuser table
682    if (strpos($username, '@'))
683      if ($virtuser = rcube_user::email2user($username))
684        $username = $virtuser;
685
686    // user already registered -> overwrite username
687    if ($user = rcube_user::query($username, $host))
688      $username = $user->data['username'];
689
690    if (!$this->imap)
691      $this->imap_init();
692
693    // Here we need IDNA ASCII
694    // Only rcube_contacts class is using domain names in Unicode
695    $host = idn_to_ascii($host);
696    if (strpos($username, '@'))
697      $username = idn_to_ascii($username);
698
699    // try IMAP login
700    if (!($imap_login = $this->imap->connect($host, $username, $pass, $imap_port, $imap_ssl))) {
701      // lowercase username if it's an e-mail address (#1484473)
702      $username_lc = mb_strtolower($username);
703      if ($username_lc != $username && ($imap_login = $this->imap->connect($host, $username_lc, $pass, $imap_port, $imap_ssl)))
704        $username = $username_lc;
705    }
706
707    // exit if IMAP login failed
708    if (!$imap_login)
709      return false;
710
711    $this->set_imap_prop();
712
713    // user already registered -> update user's record
714    if (is_object($user)) {
715      // create default folders on first login
716      if (!$user->data['last_login'] && $config['create_default_folders'])
717        $this->imap->create_default_folders();
718      $user->touch();
719    }
720    // create new system user
721    else if ($config['auto_create_user']) {
722      if ($created = rcube_user::create($username, $host)) {
723        $user = $created;
724        // create default folders on first login
725        if ($config['create_default_folders'])
726          $this->imap->create_default_folders();
727      }
728      else {
729        raise_error(array(
730          'code' => 600, 'type' => 'php',
731          'file' => __FILE__, 'line' => __LINE__,
732          'message' => "Failed to create a user record. Maybe aborted by a plugin?"
733          ), true, false);
734      }
735    }
736    else {
737      raise_error(array(
738        'code' => 600, 'type' => 'php',
739        'file' => __FILE__, 'line' => __LINE__,
740        'message' => "Acces denied for new user $username. 'auto_create_user' is disabled"
741        ), true, false);
742    }
743
744    // login succeeded
745    if (is_object($user) && $user->ID) {
746      $this->set_user($user);
747
748      // set session vars
749      $_SESSION['user_id']   = $user->ID;
750      $_SESSION['username']  = $user->data['username'];
751      $_SESSION['imap_host'] = $host;
752      $_SESSION['imap_port'] = $imap_port;
753      $_SESSION['imap_ssl']  = $imap_ssl;
754      $_SESSION['password']  = $this->encrypt($pass);
755      $_SESSION['login_time'] = mktime();
756
757      if (isset($_REQUEST['_timezone']) && $_REQUEST['_timezone'] != '_default_')
758        $_SESSION['timezone'] = floatval($_REQUEST['_timezone']);
759
760      // force reloading complete list of subscribed mailboxes
761      $this->imap->clear_cache('mailboxes');
762
763      return true;
764    }
765
766    return false;
767  }
768
769
770  /**
771   * Set root dir and last stored mailbox
772   * This must be done AFTER connecting to the server!
773   */
774  public function set_imap_prop()
775  {
776    $this->imap->set_charset($this->config->get('default_charset', RCMAIL_CHARSET));
777
778    if ($default_folders = $this->config->get('default_imap_folders')) {
779      $this->imap->set_default_mailboxes($default_folders);
780    }
781    if (!empty($_SESSION['mbox'])) {
782      $this->imap->set_mailbox($_SESSION['mbox']);
783    }
784    if (isset($_SESSION['page'])) {
785      $this->imap->set_page($_SESSION['page']);
786    }
787
788    // cache IMAP root and delimiter in session for performance reasons
789    $_SESSION['imap_root'] = $this->imap->root_dir;
790    $_SESSION['imap_delimiter'] = $this->imap->delimiter;
791  }
792
793
794  /**
795   * Auto-select IMAP host based on the posted login information
796   *
797   * @return string Selected IMAP host
798   */
799  public function autoselect_host()
800  {
801    $default_host = $this->config->get('default_host');
802    $host = null;
803
804    if (is_array($default_host)) {
805      $post_host = get_input_value('_host', RCUBE_INPUT_POST);
806
807      // direct match in default_host array
808      if ($default_host[$post_host] || in_array($post_host, array_values($default_host))) {
809        $host = $post_host;
810      }
811
812      // try to select host by mail domain
813      list($user, $domain) = explode('@', get_input_value('_user', RCUBE_INPUT_POST));
814      if (!empty($domain)) {
815        foreach ($default_host as $imap_host => $mail_domains) {
816          if (is_array($mail_domains) && in_array($domain, $mail_domains)) {
817            $host = $imap_host;
818            break;
819          }
820        }
821      }
822
823      // take the first entry if $host is still an array
824      if (empty($host)) {
825        $host = array_shift($default_host);
826      }
827    }
828    else if (empty($default_host)) {
829      $host = get_input_value('_host', RCUBE_INPUT_POST);
830    }
831    else
832      $host = rcube_parse_host($default_host);
833
834    return $host;
835  }
836
837
838  /**
839   * Get localized text in the desired language
840   *
841   * @param mixed Named parameters array or label name
842   * @return string Localized text
843   */
844  public function gettext($attrib, $domain=null)
845  {
846    // load localization files if not done yet
847    if (empty($this->texts))
848      $this->load_language();
849
850    // extract attributes
851    if (is_string($attrib))
852      $attrib = array('name' => $attrib);
853
854    $nr = is_numeric($attrib['nr']) ? $attrib['nr'] : 1;
855    $name = $attrib['name'] ? $attrib['name'] : '';
856
857    // check for text with domain
858    if ($domain && ($text_item = $this->texts[$domain.'.'.$name]))
859      ;
860    // text does not exist
861    else if (!($text_item = $this->texts[$name])) {
862      return "[$name]";
863    }
864
865    // make text item array
866    $a_text_item = is_array($text_item) ? $text_item : array('single' => $text_item);
867
868    // decide which text to use
869    if ($nr == 1) {
870      $text = $a_text_item['single'];
871    }
872    else if ($nr > 0) {
873      $text = $a_text_item['multiple'];
874    }
875    else if ($nr == 0) {
876      if ($a_text_item['none'])
877        $text = $a_text_item['none'];
878      else if ($a_text_item['single'])
879        $text = $a_text_item['single'];
880      else if ($a_text_item['multiple'])
881        $text = $a_text_item['multiple'];
882    }
883
884    // default text is single
885    if ($text == '') {
886      $text = $a_text_item['single'];
887    }
888
889    // replace vars in text
890    if (is_array($attrib['vars'])) {
891      foreach ($attrib['vars'] as $var_key => $var_value)
892        $text = str_replace($var_key[0]!='$' ? '$'.$var_key : $var_key, $var_value, $text);
893    }
894
895    // format output
896    if (($attrib['uppercase'] && strtolower($attrib['uppercase']=='first')) || $attrib['ucfirst'])
897      return ucfirst($text);
898    else if ($attrib['uppercase'])
899      return mb_strtoupper($text);
900    else if ($attrib['lowercase'])
901      return mb_strtolower($text);
902
903    return $text;
904  }
905
906
907  /**
908   * Load a localization package
909   *
910   * @param string Language ID
911   */
912  public function load_language($lang = null, $add = array())
913  {
914    $lang = $this->language_prop(($lang ? $lang : $_SESSION['language']));
915
916    // load localized texts
917    if (empty($this->texts) || $lang != $_SESSION['language']) {
918      $this->texts = array();
919
920      // get english labels (these should be complete)
921      @include(INSTALL_PATH . 'program/localization/en_US/labels.inc');
922      @include(INSTALL_PATH . 'program/localization/en_US/messages.inc');
923
924      if (is_array($labels))
925        $this->texts = $labels;
926      if (is_array($messages))
927        $this->texts = array_merge($this->texts, $messages);
928
929      // include user language files
930      if ($lang != 'en' && is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
931        include_once(INSTALL_PATH . 'program/localization/' . $lang . '/labels.inc');
932        include_once(INSTALL_PATH . 'program/localization/' . $lang . '/messages.inc');
933
934        if (is_array($labels))
935          $this->texts = array_merge($this->texts, $labels);
936        if (is_array($messages))
937          $this->texts = array_merge($this->texts, $messages);
938      }
939
940      $_SESSION['language'] = $lang;
941    }
942
943    // append additional texts (from plugin)
944    if (is_array($add) && !empty($add))
945      $this->texts += $add;
946  }
947
948
949  /**
950   * Read directory program/localization and return a list of available languages
951   *
952   * @return array List of available localizations
953   */
954  public function list_languages()
955  {
956    static $sa_languages = array();
957
958    if (!sizeof($sa_languages)) {
959      @include(INSTALL_PATH . 'program/localization/index.inc');
960
961      if ($dh = @opendir(INSTALL_PATH . 'program/localization')) {
962        while (($name = readdir($dh)) !== false) {
963          if ($name[0] == '.' || !is_dir(INSTALL_PATH . 'program/localization/' . $name))
964            continue;
965
966          if ($label = $rcube_languages[$name])
967            $sa_languages[$name] = $label;
968        }
969        closedir($dh);
970      }
971    }
972
973    return $sa_languages;
974  }
975
976
977  /**
978   * Check the auth hash sent by the client against the local session credentials
979   *
980   * @return boolean True if valid, False if not
981   */
982  function authenticate_session()
983  {
984    // advanced session authentication
985    if ($this->config->get('double_auth')) {
986      $now = time();
987      $valid = ($_COOKIE['sessauth'] == $this->get_auth_hash(session_id(), $_SESSION['auth_time']) ||
988                $_COOKIE['sessauth'] == $this->get_auth_hash(session_id(), $_SESSION['last_auth']));
989
990      // renew auth cookie every 5 minutes (only for GET requests)
991      if (!$valid || ($_SERVER['REQUEST_METHOD']!='POST' && $now - $_SESSION['auth_time'] > 300)) {
992        $_SESSION['last_auth'] = $_SESSION['auth_time'];
993        $_SESSION['auth_time'] = $now;
994        rcmail::setcookie('sessauth', $this->get_auth_hash(session_id(), $now), 0);
995      }
996    }
997    else {
998      $valid = $this->config->get('ip_check') ? $_SERVER['REMOTE_ADDR'] == $this->session->get_ip() : true;
999    }
1000
1001    // check session filetime
1002    $lifetime = $this->config->get('session_lifetime');
1003    $sess_ts = $this->session->get_ts();
1004    if (!empty($lifetime) && !empty($sess_ts) && $sess_ts + $lifetime*60 < time()) {
1005      $valid = false;
1006    }
1007
1008    return $valid;
1009  }
1010
1011
1012  /**
1013   * Destroy session data and remove cookie
1014   */
1015  public function kill_session()
1016  {
1017    $this->plugins->exec_hook('session_destroy');
1018
1019    $this->session->remove();
1020    $_SESSION = array('language' => $this->user->language, 'auth_time' => time(), 'temp' => true);
1021    rcmail::setcookie('sessauth', '-del-', time() - 60);
1022    $this->user->reset();
1023  }
1024
1025
1026  /**
1027   * Do server side actions on logout
1028   */
1029  public function logout_actions()
1030  {
1031    $config = $this->config->all();
1032
1033    // on logout action we're not connected to imap server
1034    if (($config['logout_purge'] && !empty($config['trash_mbox'])) || $config['logout_expunge']) {
1035      if (!$this->authenticate_session())
1036        return;
1037
1038      $this->imap_connect();
1039    }
1040
1041    if ($config['logout_purge'] && !empty($config['trash_mbox'])) {
1042      $this->imap->clear_mailbox($config['trash_mbox']);
1043    }
1044
1045    if ($config['logout_expunge']) {
1046      $this->imap->expunge('INBOX');
1047    }
1048  }
1049
1050
1051  /**
1052   * Function to be executed in script shutdown
1053   * Registered with register_shutdown_function()
1054   */
1055  public function shutdown()
1056  {
1057    if (is_object($this->imap))
1058      $this->imap->close();
1059
1060    if (is_object($this->smtp))
1061      $this->smtp->disconnect();
1062
1063    foreach ($this->books as $book)
1064      if (is_object($book))
1065        $book->close();
1066
1067    // before closing the database connection, write session data
1068    if ($_SERVER['REMOTE_ADDR'])
1069      session_write_close();
1070
1071    // write performance stats to logs/console
1072    if ($this->config->get('devel_mode')) {
1073      if (function_exists('memory_get_usage'))
1074        $mem = show_bytes(memory_get_usage());
1075      if (function_exists('memory_get_peak_usage'))
1076        $mem .= '/'.show_bytes(memory_get_peak_usage());
1077
1078      $log = $this->task . ($this->action ? '/'.$this->action : '') . ($mem ? " [$mem]" : '');
1079      if (defined('RCMAIL_START'))
1080        rcube_print_time(RCMAIL_START, $log);
1081      else
1082        console($log);
1083    }
1084  }
1085
1086
1087  /**
1088   * Generate a unique token to be used in a form request
1089   *
1090   * @return string The request token
1091   */
1092  public function get_request_token()
1093  {
1094    $key = $this->task;
1095
1096    if (!$_SESSION['request_tokens'][$key])
1097      $_SESSION['request_tokens'][$key] = md5(uniqid($key . mt_rand(), true));
1098
1099    return $_SESSION['request_tokens'][$key];
1100  }
1101
1102
1103  /**
1104   * Check if the current request contains a valid token
1105   *
1106   * @param int Request method
1107   * @return boolean True if request token is valid false if not
1108   */
1109  public function check_request($mode = RCUBE_INPUT_POST)
1110  {
1111    $token = get_input_value('_token', $mode);
1112    return !empty($token) && $_SESSION['request_tokens'][$this->task] == $token;
1113  }
1114
1115
1116  /**
1117   * Create unique authorization hash
1118   *
1119   * @param string Session ID
1120   * @param int Timestamp
1121   * @return string The generated auth hash
1122   */
1123  private function get_auth_hash($sess_id, $ts)
1124  {
1125    $auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
1126      $sess_id,
1127      $ts,
1128      $this->config->get('ip_check') ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
1129      $_SERVER['HTTP_USER_AGENT']);
1130
1131    if (function_exists('sha1'))
1132      return sha1($auth_string);
1133    else
1134      return md5($auth_string);
1135  }
1136
1137
1138  /**
1139   * Encrypt using 3DES
1140   *
1141   * @param string $clear clear text input
1142   * @param string $key encryption key to retrieve from the configuration, defaults to 'des_key'
1143   * @param boolean $base64 whether or not to base64_encode() the result before returning
1144   *
1145   * @return string encrypted text
1146   */
1147  public function encrypt($clear, $key = 'des_key', $base64 = true)
1148  {
1149    if (!$clear)
1150      return '';
1151    /*-
1152     * Add a single canary byte to the end of the clear text, which
1153     * will help find out how much of padding will need to be removed
1154     * upon decryption; see http://php.net/mcrypt_generic#68082
1155     */
1156    $clear = pack("a*H2", $clear, "80");
1157
1158    if (function_exists('mcrypt_module_open') &&
1159        ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_CBC, "")))
1160    {
1161      $iv = $this->create_iv(mcrypt_enc_get_iv_size($td));
1162      mcrypt_generic_init($td, $this->config->get_crypto_key($key), $iv);
1163      $cipher = $iv . mcrypt_generic($td, $clear);
1164      mcrypt_generic_deinit($td);
1165      mcrypt_module_close($td);
1166    }
1167    else {
1168      @include_once('lib/des.inc');
1169
1170      if (function_exists('des')) {
1171        $des_iv_size = 8;
1172        $iv = $this->create_iv($des_iv_size);
1173        $cipher = $iv . des($this->config->get_crypto_key($key), $clear, 1, 1, $iv);
1174      }
1175      else {
1176        raise_error(array(
1177          'code' => 500, 'type' => 'php',
1178          'file' => __FILE__, 'line' => __LINE__,
1179          'message' => "Could not perform encryption; make sure Mcrypt is installed or lib/des.inc is available"
1180        ), true, true);
1181      }
1182    }
1183
1184    return $base64 ? base64_encode($cipher) : $cipher;
1185  }
1186
1187  /**
1188   * Decrypt 3DES-encrypted string
1189   *
1190   * @param string $cipher encrypted text
1191   * @param string $key encryption key to retrieve from the configuration, defaults to 'des_key'
1192   * @param boolean $base64 whether or not input is base64-encoded
1193   *
1194   * @return string decrypted text
1195   */
1196  public function decrypt($cipher, $key = 'des_key', $base64 = true)
1197  {
1198    if (!$cipher)
1199      return '';
1200
1201    $cipher = $base64 ? base64_decode($cipher) : $cipher;
1202
1203    if (function_exists('mcrypt_module_open') &&
1204        ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_CBC, "")))
1205    {
1206      $iv = substr($cipher, 0, mcrypt_enc_get_iv_size($td));
1207      $cipher = substr($cipher, mcrypt_enc_get_iv_size($td));
1208      mcrypt_generic_init($td, $this->config->get_crypto_key($key), $iv);
1209      $clear = mdecrypt_generic($td, $cipher);
1210      mcrypt_generic_deinit($td);
1211      mcrypt_module_close($td);
1212    }
1213    else {
1214      @include_once('lib/des.inc');
1215
1216      if (function_exists('des')) {
1217        $des_iv_size = 8;
1218        $iv = substr($cipher, 0, $des_iv_size);
1219        $cipher = substr($cipher, $des_iv_size);
1220        $clear = des($this->config->get_crypto_key($key), $cipher, 0, 1, $iv);
1221      }
1222      else {
1223        raise_error(array(
1224          'code' => 500, 'type' => 'php',
1225          'file' => __FILE__, 'line' => __LINE__,
1226          'message' => "Could not perform decryption; make sure Mcrypt is installed or lib/des.inc is available"
1227        ), true, true);
1228      }
1229    }
1230
1231    /*-
1232     * Trim PHP's padding and the canary byte; see note in
1233     * rcmail::encrypt() and http://php.net/mcrypt_generic#68082
1234     */
1235    $clear = substr(rtrim($clear, "\0"), 0, -1);
1236
1237    return $clear;
1238  }
1239
1240  /**
1241   * Generates encryption initialization vector (IV)
1242   *
1243   * @param int Vector size
1244   * @return string Vector string
1245   */
1246  private function create_iv($size)
1247  {
1248    // mcrypt_create_iv() can be slow when system lacks entrophy
1249    // we'll generate IV vector manually
1250    $iv = '';
1251    for ($i = 0; $i < $size; $i++)
1252        $iv .= chr(mt_rand(0, 255));
1253    return $iv;
1254  }
1255
1256  /**
1257   * Build a valid URL to this instance of Roundcube
1258   *
1259   * @param mixed Either a string with the action or url parameters as key-value pairs
1260   * @return string Valid application URL
1261   */
1262  public function url($p)
1263  {
1264    if (!is_array($p))
1265      $p = array('_action' => @func_get_arg(0));
1266
1267    $task = $p['_task'] ? $p['_task'] : ($p['task'] ? $p['task'] : $this->task);
1268    $p['_task'] = $task;
1269    unset($p['task']);
1270
1271    $url = './';
1272    $delm = '?';
1273    foreach (array_reverse($p) as $key => $val)
1274    {
1275      if (!empty($val)) {
1276        $par = $key[0] == '_' ? $key : '_'.$key;
1277        $url .= $delm.urlencode($par).'='.urlencode($val);
1278        $delm = '&';
1279      }
1280    }
1281    return $url;
1282  }
1283
1284
1285  /**
1286   * Helper method to set a cookie with the current path and host settings
1287   *
1288   * @param string Cookie name
1289   * @param string Cookie value
1290   * @param string Expiration time
1291   */
1292  public static function setcookie($name, $value, $exp = 0)
1293  {
1294    if (headers_sent())
1295      return;
1296
1297    $cookie = session_get_cookie_params();
1298
1299    setcookie($name, $value, $exp, $cookie['path'], $cookie['domain'],
1300      rcube_https_check(), true);
1301  }
1302}
1303
1304
Note: See TracBrowser for help on using the repository browser.