source: github/program/include/rcmail.php @ 68d2d54

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