source: subversion/branches/devel-addressbook/program/include/rcmail.php @ 4283

Last change on this file since 4283 was 4283, checked in by thomasb, 2 years ago

Make sure to call rcube_addressbook::close() on every instance ever created

  • Property svn:keywords set to Id
File size: 37.1 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 $address_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 (!isset($this->address_books[$id]))
354      $this->address_books[$id] = $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    foreach ($list as $idx => $item) {
401      // register source for shutdown function
402      if (!is_object($this->address_books[$item['id']]))
403        $this->address_books[$item['id']] = $item;
404      // remove from list if not writeable as requested
405      if ($writeable && $item['readonly'])
406          unset($list[$idx]);
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      'delimiter'   => isset($_SESSION['imap_delimiter']) ? $_SESSION['imap_delimiter'] : $this->config->get('imap_delimiter'),
508      'rootdir'     => isset($_SESSION['imap_root']) ? $_SESSION['imap_root'] : $this->config->get('imap_root'),
509      'debug_mode'  => (bool) $this->config->get('imap_debug', 0),
510      'force_caps'  => (bool) $this->config->get('imap_force_caps'),
511      'timeout'     => (int) $this->config->get('imap_timeout', 0),
512    );
513
514    $this->imap->set_options($options);
515
516    // set global object for backward compatibility
517    $GLOBALS['IMAP'] = $this->imap;
518
519    $hook = $this->plugins->exec_hook('imap_init', array('fetch_headers' => $this->imap->fetch_add_headers));
520    if ($hook['fetch_headers'])
521      $this->imap->fetch_add_headers = $hook['fetch_headers'];
522
523    // support this parameter for backward compatibility but log warning
524    if ($connect) {
525      $this->imap_connect();
526      raise_error(array(
527        'code' => 800, 'type' => 'imap',
528        'file' => __FILE__, 'line' => __LINE__,
529        'message' => "rcube::imap_init(true) is deprecated, use rcube::imap_connect() instead"),
530        true, false);
531    }
532  }
533
534
535  /**
536   * Connect to IMAP server with stored session data
537   *
538   * @return bool True on success, false on error
539   */
540  public function imap_connect()
541  {
542    if (!$this->imap)
543      $this->imap_init();
544
545    if ($_SESSION['imap_host'] && !$this->imap->conn->connected()) {
546      if (!$this->imap->connect($_SESSION['imap_host'], $_SESSION['username'], $this->decrypt($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl'])) {
547        if ($this->output)
548          $this->output->show_message($this->imap->get_error_code() == -1 ? 'imaperror' : 'sessionerror', 'error');
549      }
550      else {
551        $this->set_imap_prop();
552        return $this->imap->conn;
553      }
554    }
555
556    return false;
557  }
558
559
560  /**
561   * Create session object and start the session.
562   */
563  public function session_init()
564  {
565    // session started (Installer?)
566    if (session_id())
567      return;
568
569    $lifetime = $this->config->get('session_lifetime', 0) * 60;
570
571    // set session domain
572    if ($domain = $this->config->get('session_domain')) {
573      ini_set('session.cookie_domain', $domain);
574    }
575    // set session garbage collecting time according to session_lifetime
576    if ($lifetime) {
577      ini_set('session.gc_maxlifetime', $lifetime * 2);
578    }
579
580    ini_set('session.cookie_secure', rcube_https_check());
581    ini_set('session.name', 'roundcube_sessid');
582    ini_set('session.use_cookies', 1);
583    ini_set('session.use_only_cookies', 1);
584    ini_set('session.serialize_handler', 'php');
585
586    // use database for storing session data
587    $this->session = new rcube_session($this->get_dbh(), $lifetime);
588
589    $this->session->register_gc_handler('rcmail_temp_gc');
590    if ($this->config->get('enable_caching'))
591      $this->session->register_gc_handler('rcmail_cache_gc');
592
593    // start PHP session (if not in CLI mode)
594    if ($_SERVER['REMOTE_ADDR'])
595      session_start();
596
597    // set initial session vars
598    if (!isset($_SESSION['auth_time'])) {
599      $_SESSION['auth_time'] = time();
600      $_SESSION['temp'] = true;
601    }
602  }
603
604
605  /**
606   * Configure session object internals
607   */
608  public function session_configure()
609  {
610    if (!$this->session)
611      return;
612
613    $lifetime = $this->config->get('session_lifetime', 0) * 60;
614
615    // set keep-alive/check-recent interval
616    if ($keep_alive = $this->config->get('keep_alive')) {
617      // be sure that it's less than session lifetime
618      if ($lifetime)
619        $keep_alive = min($keep_alive, $lifetime - 30);
620      $keep_alive = max(60, $keep_alive);
621      $this->session->set_keep_alive($keep_alive);
622    }
623  }
624
625
626  /**
627   * Perfom login to the IMAP server and to the webmail service.
628   * This will also create a new user entry if auto_create_user is configured.
629   *
630   * @param string IMAP user name
631   * @param string IMAP password
632   * @param string IMAP host
633   * @return boolean True on success, False on failure
634   */
635  function login($username, $pass, $host=NULL)
636  {
637    $user = NULL;
638    $config = $this->config->all();
639
640    if (!$host)
641      $host = $config['default_host'];
642
643    // Validate that selected host is in the list of configured hosts
644    if (is_array($config['default_host'])) {
645      $allowed = false;
646      foreach ($config['default_host'] as $key => $host_allowed) {
647        if (!is_numeric($key))
648          $host_allowed = $key;
649        if ($host == $host_allowed) {
650          $allowed = true;
651          break;
652        }
653      }
654      if (!$allowed)
655        return false;
656      }
657    else if (!empty($config['default_host']) && $host != rcube_parse_host($config['default_host']))
658      return false;
659
660    // parse $host URL
661    $a_host = parse_url($host);
662    if ($a_host['host']) {
663      $host = $a_host['host'];
664      $imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? $a_host['scheme'] : null;
665      if (!empty($a_host['port']))
666        $imap_port = $a_host['port'];
667      else if ($imap_ssl && $imap_ssl != 'tls' && (!$config['default_port'] || $config['default_port'] == 143))
668        $imap_port = 993;
669    }
670
671    $imap_port = $imap_port ? $imap_port : $config['default_port'];
672
673    /* Modify username with domain if required
674       Inspired by Marco <P0L0_notspam_binware.org>
675    */
676    // Check if we need to add domain
677    if (!empty($config['username_domain']) && strpos($username, '@') === false) {
678      if (is_array($config['username_domain']) && isset($config['username_domain'][$host]))
679        $username .= '@'.rcube_parse_host($config['username_domain'][$host]);
680      else if (is_string($config['username_domain']))
681        $username .= '@'.rcube_parse_host($config['username_domain']);
682    }
683
684    // try to resolve email address from virtuser table
685    if (strpos($username, '@'))
686      if ($virtuser = rcube_user::email2user($username))
687        $username = $virtuser;
688
689    // Here we need IDNA ASCII
690    // Only rcube_contacts class is using domain names in Unicode
691    $host = idn_to_ascii($host);
692    if (strpos($username, '@')) {
693      // lowercase domain name
694      list($local, $domain) = explode('@', $username);
695      $username = $local . '@' . mb_strtolower($domain);
696      $username = idn_to_ascii($username);
697    }
698
699    // user already registered -> overwrite username
700    if ($user = rcube_user::query($username, $host))
701      $username = $user->data['username'];
702
703    if (!$this->imap)
704      $this->imap_init();
705
706    // try IMAP login
707    if (!($imap_login = $this->imap->connect($host, $username, $pass, $imap_port, $imap_ssl))) {
708      // try with lowercase
709      $username_lc = mb_strtolower($username);
710      if ($username_lc != $username && ($imap_login = $this->imap->connect($host, $username_lc, $pass, $imap_port, $imap_ssl)))
711        $username = $username_lc;
712    }
713
714    // exit if IMAP login failed
715    if (!$imap_login)
716      return false;
717
718    $this->set_imap_prop();
719
720    // user already registered -> update user's record
721    if (is_object($user)) {
722      // create default folders on first login
723      if (!$user->data['last_login'] && $config['create_default_folders'])
724        $this->imap->create_default_folders();
725      $user->touch();
726    }
727    // create new system user
728    else if ($config['auto_create_user']) {
729      if ($created = rcube_user::create($username, $host)) {
730        $user = $created;
731        // create default folders on first login
732        if ($config['create_default_folders'])
733          $this->imap->create_default_folders();
734      }
735      else {
736        raise_error(array(
737          'code' => 600, 'type' => 'php',
738          'file' => __FILE__, 'line' => __LINE__,
739          'message' => "Failed to create a user record. Maybe aborted by a plugin?"
740          ), true, false);
741      }
742    }
743    else {
744      raise_error(array(
745        'code' => 600, 'type' => 'php',
746        'file' => __FILE__, 'line' => __LINE__,
747        'message' => "Acces denied for new user $username. 'auto_create_user' is disabled"
748        ), true, false);
749    }
750
751    // login succeeded
752    if (is_object($user) && $user->ID) {
753      $this->set_user($user);
754
755      // set session vars
756      $_SESSION['user_id']   = $user->ID;
757      $_SESSION['username']  = $user->data['username'];
758      $_SESSION['imap_host'] = $host;
759      $_SESSION['imap_port'] = $imap_port;
760      $_SESSION['imap_ssl']  = $imap_ssl;
761      $_SESSION['password']  = $this->encrypt($pass);
762      $_SESSION['login_time'] = mktime();
763
764      if (isset($_REQUEST['_timezone']) && $_REQUEST['_timezone'] != '_default_')
765        $_SESSION['timezone'] = floatval($_REQUEST['_timezone']);
766
767      // force reloading complete list of subscribed mailboxes
768      $this->imap->clear_cache('mailboxes');
769
770      return true;
771    }
772
773    return false;
774  }
775
776
777  /**
778   * Set root dir and last stored mailbox
779   * This must be done AFTER connecting to the server!
780   */
781  public function set_imap_prop()
782  {
783    $this->imap->set_charset($this->config->get('default_charset', RCMAIL_CHARSET));
784
785    if ($default_folders = $this->config->get('default_imap_folders')) {
786      $this->imap->set_default_mailboxes($default_folders);
787    }
788    if (!empty($_SESSION['mbox'])) {
789      $this->imap->set_mailbox($_SESSION['mbox']);
790    }
791    if (isset($_SESSION['page'])) {
792      $this->imap->set_page($_SESSION['page']);
793    }
794
795    // cache IMAP root and delimiter in session for performance reasons
796    $_SESSION['imap_root'] = $this->imap->root_dir;
797    $_SESSION['imap_delimiter'] = $this->imap->delimiter;
798  }
799
800
801  /**
802   * Auto-select IMAP host based on the posted login information
803   *
804   * @return string Selected IMAP host
805   */
806  public function autoselect_host()
807  {
808    $default_host = $this->config->get('default_host');
809    $host = null;
810
811    if (is_array($default_host)) {
812      $post_host = get_input_value('_host', RCUBE_INPUT_POST);
813
814      // direct match in default_host array
815      if ($default_host[$post_host] || in_array($post_host, array_values($default_host))) {
816        $host = $post_host;
817      }
818
819      // try to select host by mail domain
820      list($user, $domain) = explode('@', get_input_value('_user', RCUBE_INPUT_POST));
821      if (!empty($domain)) {
822        foreach ($default_host as $imap_host => $mail_domains) {
823          if (is_array($mail_domains) && in_array($domain, $mail_domains)) {
824            $host = $imap_host;
825            break;
826          }
827        }
828      }
829
830      // take the first entry if $host is still an array
831      if (empty($host)) {
832        $host = array_shift($default_host);
833      }
834    }
835    else if (empty($default_host)) {
836      $host = get_input_value('_host', RCUBE_INPUT_POST);
837    }
838    else
839      $host = rcube_parse_host($default_host);
840
841    return $host;
842  }
843
844
845  /**
846   * Get localized text in the desired language
847   *
848   * @param mixed Named parameters array or label name
849   * @return string Localized text
850   */
851  public function gettext($attrib, $domain=null)
852  {
853    // load localization files if not done yet
854    if (empty($this->texts))
855      $this->load_language();
856
857    // extract attributes
858    if (is_string($attrib))
859      $attrib = array('name' => $attrib);
860
861    $nr = is_numeric($attrib['nr']) ? $attrib['nr'] : 1;
862    $name = $attrib['name'] ? $attrib['name'] : '';
863
864    // check for text with domain
865    if ($domain && ($text_item = $this->texts[$domain.'.'.$name]))
866      ;
867    // text does not exist
868    else if (!($text_item = $this->texts[$name])) {
869      return "[$name]";
870    }
871
872    // make text item array
873    $a_text_item = is_array($text_item) ? $text_item : array('single' => $text_item);
874
875    // decide which text to use
876    if ($nr == 1) {
877      $text = $a_text_item['single'];
878    }
879    else if ($nr > 0) {
880      $text = $a_text_item['multiple'];
881    }
882    else if ($nr == 0) {
883      if ($a_text_item['none'])
884        $text = $a_text_item['none'];
885      else if ($a_text_item['single'])
886        $text = $a_text_item['single'];
887      else if ($a_text_item['multiple'])
888        $text = $a_text_item['multiple'];
889    }
890
891    // default text is single
892    if ($text == '') {
893      $text = $a_text_item['single'];
894    }
895
896    // replace vars in text
897    if (is_array($attrib['vars'])) {
898      foreach ($attrib['vars'] as $var_key => $var_value)
899        $text = str_replace($var_key[0]!='$' ? '$'.$var_key : $var_key, $var_value, $text);
900    }
901
902    // format output
903    if (($attrib['uppercase'] && strtolower($attrib['uppercase']=='first')) || $attrib['ucfirst'])
904      return ucfirst($text);
905    else if ($attrib['uppercase'])
906      return mb_strtoupper($text);
907    else if ($attrib['lowercase'])
908      return mb_strtolower($text);
909
910    return $text;
911  }
912
913
914  /**
915   * Load a localization package
916   *
917   * @param string Language ID
918   */
919  public function load_language($lang = null, $add = array())
920  {
921    $lang = $this->language_prop(($lang ? $lang : $_SESSION['language']));
922
923    // load localized texts
924    if (empty($this->texts) || $lang != $_SESSION['language']) {
925      $this->texts = array();
926
927      // get english labels (these should be complete)
928      @include(INSTALL_PATH . 'program/localization/en_US/labels.inc');
929      @include(INSTALL_PATH . 'program/localization/en_US/messages.inc');
930
931      if (is_array($labels))
932        $this->texts = $labels;
933      if (is_array($messages))
934        $this->texts = array_merge($this->texts, $messages);
935
936      // include user language files
937      if ($lang != 'en' && is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
938        include_once(INSTALL_PATH . 'program/localization/' . $lang . '/labels.inc');
939        include_once(INSTALL_PATH . 'program/localization/' . $lang . '/messages.inc');
940
941        if (is_array($labels))
942          $this->texts = array_merge($this->texts, $labels);
943        if (is_array($messages))
944          $this->texts = array_merge($this->texts, $messages);
945      }
946
947      $_SESSION['language'] = $lang;
948    }
949
950    // append additional texts (from plugin)
951    if (is_array($add) && !empty($add))
952      $this->texts += $add;
953  }
954
955
956  /**
957   * Read directory program/localization and return a list of available languages
958   *
959   * @return array List of available localizations
960   */
961  public function list_languages()
962  {
963    static $sa_languages = array();
964
965    if (!sizeof($sa_languages)) {
966      @include(INSTALL_PATH . 'program/localization/index.inc');
967
968      if ($dh = @opendir(INSTALL_PATH . 'program/localization')) {
969        while (($name = readdir($dh)) !== false) {
970          if ($name[0] == '.' || !is_dir(INSTALL_PATH . 'program/localization/' . $name))
971            continue;
972
973          if ($label = $rcube_languages[$name])
974            $sa_languages[$name] = $label;
975        }
976        closedir($dh);
977      }
978    }
979
980    return $sa_languages;
981  }
982
983
984  /**
985   * Check the auth hash sent by the client against the local session credentials
986   *
987   * @return boolean True if valid, False if not
988   */
989  function authenticate_session()
990  {
991    // advanced session authentication
992    if ($this->config->get('double_auth')) {
993      $now = time();
994      $valid = ($_COOKIE['sessauth'] == $this->get_auth_hash(session_id(), $_SESSION['auth_time']) ||
995                $_COOKIE['sessauth'] == $this->get_auth_hash(session_id(), $_SESSION['last_auth']));
996
997      // renew auth cookie every 5 minutes (only for GET requests)
998      if (!$valid || ($_SERVER['REQUEST_METHOD']!='POST' && $now - $_SESSION['auth_time'] > 300)) {
999        $_SESSION['last_auth'] = $_SESSION['auth_time'];
1000        $_SESSION['auth_time'] = $now;
1001        rcmail::setcookie('sessauth', $this->get_auth_hash(session_id(), $now), 0);
1002      }
1003    }
1004    else {
1005      $valid = $this->config->get('ip_check') ? $_SERVER['REMOTE_ADDR'] == $this->session->get_ip() : true;
1006    }
1007
1008    // check session filetime
1009    $lifetime = $this->config->get('session_lifetime');
1010    $sess_ts = $this->session->get_ts();
1011    if (!empty($lifetime) && !empty($sess_ts) && $sess_ts + $lifetime*60 < time()) {
1012      $valid = false;
1013    }
1014
1015    return $valid;
1016  }
1017
1018
1019  /**
1020   * Destroy session data and remove cookie
1021   */
1022  public function kill_session()
1023  {
1024    $this->plugins->exec_hook('session_destroy');
1025
1026    $this->session->remove();
1027    $_SESSION = array('language' => $this->user->language, 'auth_time' => time(), 'temp' => true);
1028    rcmail::setcookie('sessauth', '-del-', time() - 60);
1029    $this->user->reset();
1030  }
1031
1032
1033  /**
1034   * Do server side actions on logout
1035   */
1036  public function logout_actions()
1037  {
1038    $config = $this->config->all();
1039
1040    // on logout action we're not connected to imap server
1041    if (($config['logout_purge'] && !empty($config['trash_mbox'])) || $config['logout_expunge']) {
1042      if (!$this->authenticate_session())
1043        return;
1044
1045      $this->imap_connect();
1046    }
1047
1048    if ($config['logout_purge'] && !empty($config['trash_mbox'])) {
1049      $this->imap->clear_mailbox($config['trash_mbox']);
1050    }
1051
1052    if ($config['logout_expunge']) {
1053      $this->imap->expunge('INBOX');
1054    }
1055  }
1056
1057
1058  /**
1059   * Function to be executed in script shutdown
1060   * Registered with register_shutdown_function()
1061   */
1062  public function shutdown()
1063  {
1064    if (is_object($this->imap))
1065      $this->imap->close();
1066
1067    if (is_object($this->smtp))
1068      $this->smtp->disconnect();
1069
1070    foreach ($this->address_books as $book) {
1071      if (!is_object($book))  // maybe an address book instance wasn't fetched using get_address_book() yet
1072        $book = $this->get_address_book($book['id']);
1073      if (is_a($book, 'rcube_addressbook'))
1074        $book->close();
1075    }
1076
1077    // before closing the database connection, write session data
1078    if ($_SERVER['REMOTE_ADDR'])
1079      session_write_close();
1080
1081    // write performance stats to logs/console
1082    if ($this->config->get('devel_mode')) {
1083      if (function_exists('memory_get_usage'))
1084        $mem = show_bytes(memory_get_usage());
1085      if (function_exists('memory_get_peak_usage'))
1086        $mem .= '/'.show_bytes(memory_get_peak_usage());
1087
1088      $log = $this->task . ($this->action ? '/'.$this->action : '') . ($mem ? " [$mem]" : '');
1089      if (defined('RCMAIL_START'))
1090        rcube_print_time(RCMAIL_START, $log);
1091      else
1092        console($log);
1093    }
1094  }
1095
1096
1097  /**
1098   * Generate a unique token to be used in a form request
1099   *
1100   * @return string The request token
1101   */
1102  public function get_request_token()
1103  {
1104    $key = $this->task;
1105
1106    if (!$_SESSION['request_tokens'][$key])
1107      $_SESSION['request_tokens'][$key] = md5(uniqid($key . mt_rand(), true));
1108
1109    return $_SESSION['request_tokens'][$key];
1110  }
1111
1112
1113  /**
1114   * Check if the current request contains a valid token
1115   *
1116   * @param int Request method
1117   * @return boolean True if request token is valid false if not
1118   */
1119  public function check_request($mode = RCUBE_INPUT_POST)
1120  {
1121    $token = get_input_value('_token', $mode);
1122    return !empty($token) && $_SESSION['request_tokens'][$this->task] == $token;
1123  }
1124
1125
1126  /**
1127   * Create unique authorization hash
1128   *
1129   * @param string Session ID
1130   * @param int Timestamp
1131   * @return string The generated auth hash
1132   */
1133  private function get_auth_hash($sess_id, $ts)
1134  {
1135    $auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
1136      $sess_id,
1137      $ts,
1138      $this->config->get('ip_check') ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
1139      $_SERVER['HTTP_USER_AGENT']);
1140
1141    if (function_exists('sha1'))
1142      return sha1($auth_string);
1143    else
1144      return md5($auth_string);
1145  }
1146
1147
1148  /**
1149   * Encrypt using 3DES
1150   *
1151   * @param string $clear clear text input
1152   * @param string $key encryption key to retrieve from the configuration, defaults to 'des_key'
1153   * @param boolean $base64 whether or not to base64_encode() the result before returning
1154   *
1155   * @return string encrypted text
1156   */
1157  public function encrypt($clear, $key = 'des_key', $base64 = true)
1158  {
1159    if (!$clear)
1160      return '';
1161    /*-
1162     * Add a single canary byte to the end of the clear text, which
1163     * will help find out how much of padding will need to be removed
1164     * upon decryption; see http://php.net/mcrypt_generic#68082
1165     */
1166    $clear = pack("a*H2", $clear, "80");
1167
1168    if (function_exists('mcrypt_module_open') &&
1169        ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_CBC, "")))
1170    {
1171      $iv = $this->create_iv(mcrypt_enc_get_iv_size($td));
1172      mcrypt_generic_init($td, $this->config->get_crypto_key($key), $iv);
1173      $cipher = $iv . mcrypt_generic($td, $clear);
1174      mcrypt_generic_deinit($td);
1175      mcrypt_module_close($td);
1176    }
1177    else {
1178      @include_once('lib/des.inc');
1179
1180      if (function_exists('des')) {
1181        $des_iv_size = 8;
1182        $iv = $this->create_iv($des_iv_size);
1183        $cipher = $iv . des($this->config->get_crypto_key($key), $clear, 1, 1, $iv);
1184      }
1185      else {
1186        raise_error(array(
1187          'code' => 500, 'type' => 'php',
1188          'file' => __FILE__, 'line' => __LINE__,
1189          'message' => "Could not perform encryption; make sure Mcrypt is installed or lib/des.inc is available"
1190        ), true, true);
1191      }
1192    }
1193
1194    return $base64 ? base64_encode($cipher) : $cipher;
1195  }
1196
1197  /**
1198   * Decrypt 3DES-encrypted string
1199   *
1200   * @param string $cipher encrypted text
1201   * @param string $key encryption key to retrieve from the configuration, defaults to 'des_key'
1202   * @param boolean $base64 whether or not input is base64-encoded
1203   *
1204   * @return string decrypted text
1205   */
1206  public function decrypt($cipher, $key = 'des_key', $base64 = true)
1207  {
1208    if (!$cipher)
1209      return '';
1210
1211    $cipher = $base64 ? base64_decode($cipher) : $cipher;
1212
1213    if (function_exists('mcrypt_module_open') &&
1214        ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_CBC, "")))
1215    {
1216      $iv = substr($cipher, 0, mcrypt_enc_get_iv_size($td));
1217      $cipher = substr($cipher, mcrypt_enc_get_iv_size($td));
1218      mcrypt_generic_init($td, $this->config->get_crypto_key($key), $iv);
1219      $clear = mdecrypt_generic($td, $cipher);
1220      mcrypt_generic_deinit($td);
1221      mcrypt_module_close($td);
1222    }
1223    else {
1224      @include_once('lib/des.inc');
1225
1226      if (function_exists('des')) {
1227        $des_iv_size = 8;
1228        $iv = substr($cipher, 0, $des_iv_size);
1229        $cipher = substr($cipher, $des_iv_size);
1230        $clear = des($this->config->get_crypto_key($key), $cipher, 0, 1, $iv);
1231      }
1232      else {
1233        raise_error(array(
1234          'code' => 500, 'type' => 'php',
1235          'file' => __FILE__, 'line' => __LINE__,
1236          'message' => "Could not perform decryption; make sure Mcrypt is installed or lib/des.inc is available"
1237        ), true, true);
1238      }
1239    }
1240
1241    /*-
1242     * Trim PHP's padding and the canary byte; see note in
1243     * rcmail::encrypt() and http://php.net/mcrypt_generic#68082
1244     */
1245    $clear = substr(rtrim($clear, "\0"), 0, -1);
1246
1247    return $clear;
1248  }
1249
1250  /**
1251   * Generates encryption initialization vector (IV)
1252   *
1253   * @param int Vector size
1254   * @return string Vector string
1255   */
1256  private function create_iv($size)
1257  {
1258    // mcrypt_create_iv() can be slow when system lacks entrophy
1259    // we'll generate IV vector manually
1260    $iv = '';
1261    for ($i = 0; $i < $size; $i++)
1262        $iv .= chr(mt_rand(0, 255));
1263    return $iv;
1264  }
1265
1266  /**
1267   * Build a valid URL to this instance of Roundcube
1268   *
1269   * @param mixed Either a string with the action or url parameters as key-value pairs
1270   * @return string Valid application URL
1271   */
1272  public function url($p)
1273  {
1274    if (!is_array($p))
1275      $p = array('_action' => @func_get_arg(0));
1276
1277    $task = $p['_task'] ? $p['_task'] : ($p['task'] ? $p['task'] : $this->task);
1278    $p['_task'] = $task;
1279    unset($p['task']);
1280
1281    $url = './';
1282    $delm = '?';
1283    foreach (array_reverse($p) as $key => $val)
1284    {
1285      if (!empty($val)) {
1286        $par = $key[0] == '_' ? $key : '_'.$key;
1287        $url .= $delm.urlencode($par).'='.urlencode($val);
1288        $delm = '&';
1289      }
1290    }
1291    return $url;
1292  }
1293
1294
1295  /**
1296   * Helper method to set a cookie with the current path and host settings
1297   *
1298   * @param string Cookie name
1299   * @param string Cookie value
1300   * @param string Expiration time
1301   */
1302  public static function setcookie($name, $value, $exp = 0)
1303  {
1304    if (headers_sent())
1305      return;
1306
1307    $cookie = session_get_cookie_params();
1308
1309    setcookie($name, $value, $exp, $cookie['path'], $cookie['domain'],
1310      rcube_https_check(), true);
1311  }
1312}
1313
1314
Note: See TracBrowser for help on using the repository browser.