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

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