source: github/program/include/rcmail.php @ 6a642d1

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