source: subversion/branches/devel-api/program/include/rcmail.php @ 2279

Last change on this file since 2279 was 2279, checked in by thomasb, 4 years ago

Add localization functions to plugin API

File size: 27.9 KB
RevLine 
[1344]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, 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
[1722]18 $Id: rcmail.php 328 2006-08-30 17:41:21Z thomasb $
[1344]19
20*/
21
22
23/**
24 * Application class of RoundCube Webmail
25 * implemented as singleton
26 *
27 * @package Core
28 */
29class rcmail
30{
[1360]31  static public $main_tasks = array('mail','settings','addressbook','login','logout');
[1344]32 
33  static private $instance;
34 
35  public $config;
36  public $user;
37  public $db;
38  public $imap;
39  public $output;
[2209]40  public $plugins;
[1344]41  public $task = 'mail';
42  public $action = '';
43  public $comm_path = './';
44 
45  private $texts;
46 
47 
48  /**
49   * This implements the 'singleton' design pattern
50   *
[2209]51   * @return object rcmail The one and only instance
[1344]52   */
53  static function get_instance()
54  {
55    if (!self::$instance) {
56      self::$instance = new rcmail();
57      self::$instance->startup();  // init AFTER object was linked with self::$instance
58    }
59
60    return self::$instance;
61  }
62 
63 
64  /**
65   * Private constructor
66   */
67  private function __construct()
68  {
69    // load configuration
70    $this->config = new rcube_config();
71   
72    register_shutdown_function(array($this, 'shutdown'));
73  }
74 
75 
76  /**
77   * Initial startup function
78   * to register session, create database and imap connections
79   *
80   * @todo Remove global vars $DB, $USER
81   */
82  private function startup()
83  {
84    $config_all = $this->config->all();
85
[1683]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    }
[2209]92
[1344]93    // set task and action properties
94    $this->set_task(strip_quotes(get_input_value('_task', RCUBE_INPUT_GPC)));
[1560]95    $this->action = asciiwords(get_input_value('_action', RCUBE_INPUT_GPC));
[1344]96
97    // connect to database
98    $GLOBALS['DB'] = $this->get_dbh();
99
100    // use database for storing session data
101    include_once('include/session.inc');
102
103    // set session domain
104    if (!empty($config_all['session_domain'])) {
105      ini_set('session.cookie_domain', $config_all['session_domain']);
106    }
107    // set session garbage collecting time according to session_lifetime
108    if (!empty($config_all['session_lifetime'])) {
109      ini_set('session.gc_maxlifetime', ($config_all['session_lifetime']) * 120);
110    }
111
[1450]112    // start PHP session (if not in CLI mode)
113    if ($_SERVER['REMOTE_ADDR'])
114      session_start();
[1344]115
116    // set initial session vars
117    if (!isset($_SESSION['auth_time'])) {
118      $_SESSION['auth_time'] = time();
119      $_SESSION['temp'] = true;
120    }
121
122    // create user object
123    $this->set_user(new rcube_user($_SESSION['user_id']));
124
125    // reset some session parameters when changing task
126    if ($_SESSION['task'] != $this->task)
127      unset($_SESSION['page']);
128
129    // set current task to session
130    $_SESSION['task'] = $this->task;
131
132    // create IMAP object
133    if ($this->task == 'mail')
134      $this->imap_init();
[2209]135     
136    // create plugin API and load plugins
137    $this->plugins = rcube_plugin_api::get_instance();
[1344]138  }
139 
140 
141  /**
142   * Setter for application task
143   *
144   * @param string Task to set
145   */
146  public function set_task($task)
147  {
148    if (!in_array($task, self::$main_tasks))
149      $task = 'mail';
150   
151    $this->task = $task;
[1562]152    $this->comm_path = $this->url(array('task' => $task));
[1344]153   
154    if ($this->output)
155      $this->output->set_env('task', $task);
156  }
157 
158 
159  /**
160   * Setter for system user object
161   *
162   * @param object rcube_user Current user instance
163   */
164  public function set_user($user)
165  {
166    if (is_object($user)) {
167      $this->user = $user;
168      $GLOBALS['USER'] = $this->user;
169     
170      // overwrite config with user preferences
171      $this->config->merge((array)$this->user->get_prefs());
172    }
173   
[1722]174    $_SESSION['language'] = $this->user->language = $this->language_prop($this->config->get('language', $_SESSION['language']));
[1449]175
[1344]176    // set localization
[1895]177    setlocale(LC_ALL, $_SESSION['language'] . '.utf8', 'en_US.utf8');
[2060]178
179    // workaround for http://bugs.php.net/bug.php?id=18556
180    if (in_array($_SESSION['language'], array('tr_TR', 'ku', 'az_AZ'))) 
181      setlocale(LC_CTYPE, 'en_US' . '.utf8'); 
[1344]182  }
183 
184 
185  /**
186   * Check the given string and return a valid language code
187   *
188   * @param string Language code
189   * @return string Valid language code
190   */
191  private function language_prop($lang)
192  {
193    static $rcube_languages, $rcube_language_aliases;
[1722]194   
195    // user HTTP_ACCEPT_LANGUAGE if no language is specified
196    if (empty($lang) || $lang == 'auto') {
197       $accept_langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
198       $lang = str_replace('-', '_', $accept_langs[0]);
199     }
200     
[1344]201    if (empty($rcube_languages)) {
202      @include(INSTALL_PATH . 'program/localization/index.inc');
203    }
[1486]204   
[1344]205    // check if we have an alias for that language
206    if (!isset($rcube_languages[$lang]) && isset($rcube_language_aliases[$lang])) {
207      $lang = $rcube_language_aliases[$lang];
208    }
209    // try the first two chars
[1486]210    else if (!isset($rcube_languages[$lang])) {
[1492]211      $short = substr($lang, 0, 2);
212     
[1485]213      // check if we have an alias for the short language code
214      if (!isset($rcube_languages[$short]) && isset($rcube_language_aliases[$short])) {
215        $lang = $rcube_language_aliases[$short];
216      }
[1486]217      // expand 'nn' to 'nn_NN'
218      else if (!isset($rcube_languages[$short])) {
[1485]219        $lang = $short.'_'.strtoupper($short);
220      }
[1344]221    }
222
[1360]223    if (!isset($rcube_languages[$lang]) || !is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
[1344]224      $lang = 'en_US';
225    }
226
227    return $lang;
228  }
229 
230 
231  /**
232   * Get the current database connection
233   *
[1872]234   * @return object rcube_mdb2  Database connection object
[1344]235   */
236  public function get_dbh()
237  {
238    if (!$this->db) {
239      $config_all = $this->config->all();
240
[1681]241      $this->db = new rcube_mdb2($config_all['db_dsnw'], $config_all['db_dsnr'], $config_all['db_persistent']);
[1344]242      $this->db->sqlite_initials = INSTALL_PATH . 'SQL/sqlite.initial.sql';
243      $this->db->set_debug((bool)$config_all['sql_debug']);
244      $this->db->db_connect('w');
245    }
246
247    return $this->db;
248  }
249 
250 
251  /**
[1712]252   * Return instance of the internal address book class
253   *
254   * @param boolean True if the address book needs to be writeable
255   * @return object rcube_contacts Address book object
256   */
257  public function get_address_book($id, $writeable = false)
258  {
259    $contacts = null;
260    $ldap_config = (array)$this->config->get('ldap_public');
261    $abook_type = strtolower($this->config->get('address_book_type'));
262   
263    if ($id && $ldap_config[$id]) {
264      $contacts = new rcube_ldap($ldap_config[$id]);
265    }
266    else if ($abook_type == 'ldap') {
267      // Use the first writable LDAP address book.
268      foreach ($ldap_config as $id => $prop) {
269        if (!$writeable || $prop['writable']) {
270          $contacts = new rcube_ldap($prop);
271          break;
272        }
273      }
274    }
275    else {
276      $contacts = new rcube_contacts($this->db, $this->user->ID);
277    }
278   
279    return $contacts;
280  }
281 
282 
283  /**
[1344]284   * Init output object for GUI and add common scripts.
285   * This will instantiate a rcmail_template object and set
286   * environment vars according to the current session and configuration
[1613]287   *
288   * @param boolean True if this request is loaded in a (i)frame
289   * @return object rcube_template Reference to HTML output object
[1344]290   */
291  public function load_gui($framed = false)
292  {
293    // init output page
[1613]294    if (!($this->output instanceof rcube_template))
295      $this->output = new rcube_template($this->task, $framed);
[1344]296
[1617]297    foreach (array('flag_for_deletion','read_when_deleted') as $js_config_var) {
[1344]298      $this->output->set_env($js_config_var, $this->config->get($js_config_var));
299    }
[2013]300   
301    // set keep-alive/check-recent interval
302    if ($keep_alive = $this->config->get('keep_alive')) {
303      // be sure that it's less than session lifetime
304      if ($session_lifetime = $this->config->get('session_lifetime'))
305        $keep_alive = min($keep_alive, $session_lifetime * 60 - 30);
306      $this->output->set_env('keep_alive', max(60, $keep_alive));
307    }
[1344]308
309    if ($framed) {
310      $this->comm_path .= '&_framed=1';
311      $this->output->set_env('framed', true);
312    }
313
314    $this->output->set_env('task', $this->task);
315    $this->output->set_env('action', $this->action);
316    $this->output->set_env('comm_path', $this->comm_path);
317    $this->output->set_charset($this->config->get('charset', RCMAIL_CHARSET));
318
319    // add some basic label to client
320    $this->output->add_label('loading');
321   
[2266]322    // load plugins stuff
323    $this->plugins->init_gui($this->output);
324   
[1344]325    return $this->output;
326  }
327 
328 
329  /**
330   * Create an output object for JSON responses
[1613]331   *
332   * @return object rcube_json_output Reference to JSON output object
[1344]333   */
334  public function init_json()
335  {
[1613]336    if (!($this->output instanceof rcube_json_output))
337      $this->output = new rcube_json_output($this->task);
[1344]338   
339    return $this->output;
340  }
341 
342 
343  /**
344   * Create global IMAP object and connect to server
345   *
346   * @param boolean True if connection should be established
347   * @todo Remove global $IMAP
348   */
[1360]349  public function imap_init($connect = false)
[1344]350  {
351    $this->imap = new rcube_imap($this->db);
352    $this->imap->debug_level = $this->config->get('debug_level');
353    $this->imap->skip_deleted = $this->config->get('skip_deleted');
354
355    // enable caching of imap data
356    if ($this->config->get('enable_caching')) {
357      $this->imap->set_caching(true);
358    }
359
360    // set pagesize from config
361    $this->imap->set_pagesize($this->config->get('pagesize', 50));
[2188]362   
363    // Setting root and delimiter before iil_Connect can save time detecting them
364    // using NAMESPACE and LIST
365    $options = array(
366      'imap' => $this->config->get('imap_auth_type', 'check'),
367      'delimiter' => isset($_SESSION['imap_delimiter']) ? $_SESSION['imap_delimiter'] : $this->config->get('imap_delimiter'),
368    );
369   
370    if (isset($_SESSION['imap_root']))
371      $options['rootdir'] = $_SESSION['imap_root'];
372    else if ($imap_root = $this->config->get('imap_root'))
373      $options['rootdir'] = $imap_root;
374   
375    $this->imap->set_options($options);
[1360]376 
[1344]377    // set global object for backward compatibility
378    $GLOBALS['IMAP'] = $this->imap;
[1360]379   
380    if ($connect)
381      $this->imap_connect();
[1344]382  }
383
384
385  /**
[1360]386   * Connect to IMAP server with stored session data
387   *
388   * @return bool True on success, false on error
389   */
390  public function imap_connect()
391  {
392    $conn = false;
393   
[1613]394    if ($_SESSION['imap_host'] && !$this->imap->conn) {
[2188]395      if (!($conn = $this->imap->connect($_SESSION['imap_host'], $_SESSION['username'], $this->decrypt_passwd($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl']))) {
[1360]396        if ($this->output)
397          $this->output->show_message($this->imap->error_code == -1 ? 'imaperror' : 'sessionerror', 'error');
398      }
399
400      $this->set_imap_prop();
401    }
402
[1613]403    return $conn;
[1360]404  }
405
406
407  /**
[1344]408   * Perfom login to the IMAP server and to the webmail service.
409   * This will also create a new user entry if auto_create_user is configured.
410   *
411   * @param string IMAP user name
412   * @param string IMAP password
413   * @param string IMAP host
414   * @return boolean True on success, False on failure
415   */
416  function login($username, $pass, $host=NULL)
417  {
418    $user = NULL;
419    $config = $this->config->all();
420
421    if (!$host)
422      $host = $config['default_host'];
423
424    // Validate that selected host is in the list of configured hosts
425    if (is_array($config['default_host'])) {
426      $allowed = false;
427      foreach ($config['default_host'] as $key => $host_allowed) {
428        if (!is_numeric($key))
429          $host_allowed = $key;
430        if ($host == $host_allowed) {
431          $allowed = true;
432          break;
433        }
434      }
435      if (!$allowed)
436        return false;
437      }
438    else if (!empty($config['default_host']) && $host != $config['default_host'])
439      return false;
440
441    // parse $host URL
442    $a_host = parse_url($host);
443    if ($a_host['host']) {
444      $host = $a_host['host'];
445      $imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? $a_host['scheme'] : null;
446      $imap_port = isset($a_host['port']) ? $a_host['port'] : ($imap_ssl ? 993 : $config['default_port']);
447    }
448    else
449      $imap_port = $config['default_port'];
450
451
452    /* Modify username with domain if required 
453       Inspired by Marco <P0L0_notspam_binware.org>
454    */
455    // Check if we need to add domain
456    if (!empty($config['username_domain']) && !strpos($username, '@')) {
457      if (is_array($config['username_domain']) && isset($config['username_domain'][$host]))
458        $username .= '@'.$config['username_domain'][$host];
459      else if (is_string($config['username_domain']))
460        $username .= '@'.$config['username_domain'];
461    }
462
463    // try to resolve email address from virtuser table   
464    if (!empty($config['virtuser_file']) && strpos($username, '@'))
465      $username = rcube_user::email2user($username);
466
467    // lowercase username if it's an e-mail address (#1484473)
468    if (strpos($username, '@'))
[2006]469      $username = rc_strtolower($username);
[1344]470
471    // user already registered -> overwrite username
472    if ($user = rcube_user::query($username, $host))
473      $username = $user->data['username'];
474
475    // exit if IMAP login failed
[2188]476    if (!($imap_login  = $this->imap->connect($host, $username, $pass, $imap_port, $imap_ssl)))
[1344]477      return false;
478
479    // user already registered -> update user's record
480    if (is_object($user)) {
481      $user->touch();
482    }
483    // create new system user
484    else if ($config['auto_create_user']) {
485      if ($created = rcube_user::create($username, $host)) {
486        $user = $created;
487
488        // get existing mailboxes (but why?)
489        // $a_mailboxes = $this->imap->list_mailboxes();
490      }
491    }
492    else {
493      raise_error(array(
494        'code' => 600,
495        'type' => 'php',
[1854]496        'file' => RCMAIL_CONFIG_DIR."/main.inc.php",
[1344]497        'message' => "Acces denied for new user $username. 'auto_create_user' is disabled"
498        ), true, false);
499    }
500
501    // login succeeded
502    if (is_object($user) && $user->ID) {
503      $this->set_user($user);
504
505      // set session vars
506      $_SESSION['user_id']   = $user->ID;
507      $_SESSION['username']  = $user->data['username'];
508      $_SESSION['imap_host'] = $host;
509      $_SESSION['imap_port'] = $imap_port;
510      $_SESSION['imap_ssl']  = $imap_ssl;
[1360]511      $_SESSION['password']  = $this->encrypt_passwd($pass);
[1344]512      $_SESSION['login_time'] = mktime();
[1722]513     
514      if ($_REQUEST['_timezone'] != '_default_')
515        $_SESSION['timezone'] = floatval($_REQUEST['_timezone']);
[1344]516
517      // force reloading complete list of subscribed mailboxes
518      $this->set_imap_prop();
519      $this->imap->clear_cache('mailboxes');
520
521      if ($config['create_default_folders'])
522          $this->imap->create_default_folders();
523
524      return true;
525    }
526
527    return false;
528  }
529
530
531  /**
532   * Set root dir and last stored mailbox
533   * This must be done AFTER connecting to the server!
534   */
535  public function set_imap_prop()
536  {
537    $this->imap->set_charset($this->config->get('default_charset', RCMAIL_CHARSET));
538
539    if ($default_folders = $this->config->get('default_imap_folders')) {
540      $this->imap->set_default_mailboxes($default_folders);
541    }
542    if (!empty($_SESSION['mbox'])) {
543      $this->imap->set_mailbox($_SESSION['mbox']);
544    }
545    if (isset($_SESSION['page'])) {
546      $this->imap->set_page($_SESSION['page']);
547    }
[2188]548   
549    // cache IMAP root and delimiter in session for performance reasons
550    $_SESSION['imap_root'] = $this->imap->root_dir;
551    $_SESSION['imap_delimiter'] = $this->imap->delimiter;
[1344]552  }
553
[1360]554
555  /**
556   * Auto-select IMAP host based on the posted login information
557   *
558   * @return string Selected IMAP host
559   */
560  public function autoselect_host()
561  {
562    $default_host = $this->config->get('default_host');
[1573]563    $host = null;
[1360]564   
[1573]565    if (is_array($default_host)) {
566      $post_host = get_input_value('_host', RCUBE_INPUT_POST);
567     
568      // direct match in default_host array
569      if ($default_host[$post_host] || in_array($post_host, array_values($default_host))) {
570        $host = $post_host;
571      }
572     
573      // try to select host by mail domain
[1360]574      list($user, $domain) = explode('@', get_input_value('_user', RCUBE_INPUT_POST));
575      if (!empty($domain)) {
[1573]576        foreach ($default_host as $imap_host => $mail_domains) {
[1360]577          if (is_array($mail_domains) && in_array($domain, $mail_domains)) {
578            $host = $imap_host;
579            break;
580          }
581        }
582      }
583
584      // take the first entry if $host is still an array
[1573]585      if (empty($host)) {
586        $host = array_shift($default_host);
587      }
[1360]588    }
[1573]589    else if (empty($default_host)) {
590      $host = get_input_value('_host', RCUBE_INPUT_POST);
591    }
[1574]592    else
593      $host = $default_host;
[1360]594
595    return $host;
596  }
597
598
599  /**
600   * Get localized text in the desired language
601   *
602   * @param mixed Named parameters array or label name
603   * @return string Localized text
604   */
[2279]605  public function gettext($attrib, $domain=null)
[1360]606  {
607    // load localization files if not done yet
608    if (empty($this->texts))
609      $this->load_language();
610   
611    // extract attributes
612    if (is_string($attrib))
613      $attrib = array('name' => $attrib);
614
615    $nr = is_numeric($attrib['nr']) ? $attrib['nr'] : 1;
616    $vars = isset($attrib['vars']) ? $attrib['vars'] : '';
617
618    $command_name = !empty($attrib['command']) ? $attrib['command'] : NULL;
619    $alias = $attrib['name'] ? $attrib['name'] : ($command_name && $command_label_map[$command_name] ? $command_label_map[$command_name] : '');
[2279]620   
621    // check for text with domain
622    if ($domain && ($text_item = $this->texts[$domain.'.'.$alias]))
623      ;
[1360]624    // text does not exist
[2279]625    else if (!($text_item = $this->texts[$alias])) {
[1360]626      /*
627      raise_error(array(
628        'code' => 500,
629        'type' => 'php',
630        'line' => __LINE__,
631        'file' => __FILE__,
632        'message' => "Missing localized text for '$alias' in '$sess_user_lang'"), TRUE, FALSE);
633      */
634      return "[$alias]";
635    }
636
637    // make text item array
638    $a_text_item = is_array($text_item) ? $text_item : array('single' => $text_item);
639
640    // decide which text to use
641    if ($nr == 1) {
642      $text = $a_text_item['single'];
643    }
644    else if ($nr > 0) {
645      $text = $a_text_item['multiple'];
646    }
647    else if ($nr == 0) {
648      if ($a_text_item['none'])
649        $text = $a_text_item['none'];
650      else if ($a_text_item['single'])
651        $text = $a_text_item['single'];
652      else if ($a_text_item['multiple'])
653        $text = $a_text_item['multiple'];
654    }
655
656    // default text is single
657    if ($text == '') {
658      $text = $a_text_item['single'];
659    }
660
661    // replace vars in text
662    if (is_array($attrib['vars'])) {
663      foreach ($attrib['vars'] as $var_key => $var_value)
664        $a_replace_vars[$var_key{0}=='$' ? substr($var_key, 1) : $var_key] = $var_value;
665    }
666
667    if ($a_replace_vars)
668      $text = preg_replace('/\$\{?([_a-z]{1}[_a-z0-9]*)\}?/ei', '$a_replace_vars["\1"]', $text);
669
670    // format output
671    if (($attrib['uppercase'] && strtolower($attrib['uppercase']=='first')) || $attrib['ucfirst'])
672      return ucfirst($text);
673    else if ($attrib['uppercase'])
674      return strtoupper($text);
675    else if ($attrib['lowercase'])
676      return strtolower($text);
677
678    return $text;
679  }
680
681
682  /**
683   * Load a localization package
684   *
685   * @param string Language ID
686   */
[2279]687  public function load_language($lang = null, $add = array())
[1360]688  {
[1722]689    $lang = $this->language_prop(($lang ? $lang : $_SESSION['language']));
[1360]690   
691    // load localized texts
692    if (empty($this->texts) || $lang != $_SESSION['language']) {
693      $this->texts = array();
694
695      // get english labels (these should be complete)
696      @include(INSTALL_PATH . 'program/localization/en_US/labels.inc');
697      @include(INSTALL_PATH . 'program/localization/en_US/messages.inc');
698
699      if (is_array($labels))
[1372]700        $this->texts = $labels;
[1360]701      if (is_array($messages))
[1372]702        $this->texts = array_merge($this->texts, $messages);
[1360]703
704      // include user language files
705      if ($lang != 'en' && is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
706        include_once(INSTALL_PATH . 'program/localization/' . $lang . '/labels.inc');
707        include_once(INSTALL_PATH . 'program/localization/' . $lang . '/messages.inc');
708
709        if (is_array($labels))
710          $this->texts = array_merge($this->texts, $labels);
711        if (is_array($messages))
712          $this->texts = array_merge($this->texts, $messages);
713      }
714     
715      $_SESSION['language'] = $lang;
716    }
[2279]717
718    // append additional texts (from plugin)
719    if (is_array($add) && !empty($add))
720      $this->texts += $add;
[1360]721  }
722
723
724  /**
725   * Read directory program/localization and return a list of available languages
726   *
727   * @return array List of available localizations
728   */
729  public function list_languages()
730  {
731    static $sa_languages = array();
732
733    if (!sizeof($sa_languages)) {
734      @include(INSTALL_PATH . 'program/localization/index.inc');
735
736      if ($dh = @opendir(INSTALL_PATH . 'program/localization')) {
737        while (($name = readdir($dh)) !== false) {
738          if ($name{0}=='.' || !is_dir(INSTALL_PATH . 'program/localization/' . $name))
739            continue;
740
741          if ($label = $rcube_languages[$name])
742            $sa_languages[$name] = $label ? $label : $name;
743        }
744        closedir($dh);
745      }
746    }
747
748    return $sa_languages;
749  }
750
751
752  /**
753   * Check the auth hash sent by the client against the local session credentials
754   *
755   * @return boolean True if valid, False if not
756   */
757  function authenticate_session()
758  {
759    global $SESS_CLIENT_IP, $SESS_CHANGED;
760
761    // advanced session authentication
762    if ($this->config->get('double_auth')) {
763      $now = time();
764      $valid = ($_COOKIE['sessauth'] == $this->get_auth_hash(session_id(), $_SESSION['auth_time']) ||
765                $_COOKIE['sessauth'] == $this->get_auth_hash(session_id(), $_SESSION['last_auth']));
766
767      // renew auth cookie every 5 minutes (only for GET requests)
768      if (!$valid || ($_SERVER['REQUEST_METHOD']!='POST' && $now - $_SESSION['auth_time'] > 300)) {
769        $_SESSION['last_auth'] = $_SESSION['auth_time'];
770        $_SESSION['auth_time'] = $now;
[1890]771        rcmail::setcookie('sessauth', $this->get_auth_hash(session_id(), $now), 0);
[1360]772      }
773    }
774    else {
775      $valid = $this->config->get('ip_check') ? $_SERVER['REMOTE_ADDR'] == $SESS_CLIENT_IP : true;
776    }
777
778    // check session filetime
779    $lifetime = $this->config->get('session_lifetime');
780    if (!empty($lifetime) && isset($SESS_CHANGED) && $SESS_CHANGED + $lifetime*60 < time()) {
781      $valid = false;
782    }
783
784    return $valid;
785  }
786
787
788  /**
789   * Destroy session data and remove cookie
790   */
791  public function kill_session()
792  {
[1722]793    $_SESSION = array('language' => $this->user->language, 'auth_time' => time(), 'temp' => true);
[1890]794    rcmail::setcookie('sessauth', '-del-', time() - 60);
[1360]795    $this->user->reset();
796  }
797
798
799  /**
800   * Do server side actions on logout
801   */
802  public function logout_actions()
803  {
804    $config = $this->config->all();
805   
806    // on logout action we're not connected to imap server 
807    if (($config['logout_purge'] && !empty($config['trash_mbox'])) || $config['logout_expunge']) {
808      if (!$this->authenticate_session())
809        return;
810
811      $this->imap_init(true);
812    }
813
814    if ($config['logout_purge'] && !empty($config['trash_mbox'])) {
815      $this->imap->clear_mailbox($config['trash_mbox']);
816    }
817
818    if ($config['logout_expunge']) {
819      $this->imap->expunge('INBOX');
820    }
821  }
822
823
824  /**
825   * Function to be executed in script shutdown
826   * Registered with register_shutdown_function()
827   */
[1344]828  public function shutdown()
829  {
830    if (is_object($this->imap)) {
831      $this->imap->close();
832      $this->imap->write_cache();
833    }
834
835    if (is_object($this->contacts))
836      $this->contacts->close();
837
838    // before closing the database connection, write session data
[1450]839    if ($_SERVER['REMOTE_ADDR'])
840      session_write_close();
[1344]841  }
842 
[1360]843 
844  /**
845   * Create unique authorization hash
846   *
847   * @param string Session ID
848   * @param int Timestamp
849   * @return string The generated auth hash
850   */
851  private function get_auth_hash($sess_id, $ts)
852  {
853    $auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
854      $sess_id,
855      $ts,
856      $this->config->get('ip_check') ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
857      $_SERVER['HTTP_USER_AGENT']);
858
859    if (function_exists('sha1'))
860      return sha1($auth_string);
861    else
862      return md5($auth_string);
863  }
864
865  /**
866   * Encrypt IMAP password using DES encryption
867   *
868   * @param string Password to encrypt
869   * @return string Encryprted string
870   */
[1401]871  public function encrypt_passwd($pass)
[1360]872  {
873    if (function_exists('mcrypt_module_open') && ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_ECB, ""))) {
874      $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
875      mcrypt_generic_init($td, $this->config->get_des_key(), $iv);
876      $cypher = mcrypt_generic($td, $pass);
877      mcrypt_generic_deinit($td);
878      mcrypt_module_close($td);
879    }
880    else if (function_exists('des')) {
881      $cypher = des($this->config->get_des_key(), $pass, 1, 0, NULL);
882    }
883    else {
884      $cypher = $pass;
885
886      raise_error(array(
887        'code' => 500,
888        'type' => 'php',
889        'file' => __FILE__,
890        'message' => "Could not convert encrypt password. Make sure Mcrypt is installed or lib/des.inc is available"
891        ), true, false);
892    }
893
894    return base64_encode($cypher);
895  }
896
897
898  /**
899   * Decrypt IMAP password using DES encryption
900   *
901   * @param string Encrypted password
902   * @return string Plain password
903   */
904  public function decrypt_passwd($cypher)
905  {
906    if (function_exists('mcrypt_module_open') && ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_ECB, ""))) {
907      $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
908      mcrypt_generic_init($td, $this->config->get_des_key(), $iv);
909      $pass = mdecrypt_generic($td, base64_decode($cypher));
910      mcrypt_generic_deinit($td);
911      mcrypt_module_close($td);
912    }
913    else if (function_exists('des')) {
914      $pass = des($this->config->get_des_key(), base64_decode($cypher), 0, 0, NULL);
915    }
916    else {
917      $pass = base64_decode($cypher);
918    }
919
920    return preg_replace('/\x00/', '', $pass);
921  }
922
[1562]923
924  /**
925   * Build a valid URL to this instance of RoundCube
926   *
927   * @param mixed Either a string with the action or url parameters as key-value pairs
928   * @return string Valid application URL
929   */
930  public function url($p)
931  {
932    if (!is_array($p))
[1564]933      $p = array('_action' => @func_get_arg(0));
[1771]934
935    if (!$p['task'] || !in_array($p['task'], rcmail::$main_tasks))
936      $p['task'] = $this->task;
937
[1781]938    $p['_task'] = $p['task'];
939    unset($p['task']);
940
[1771]941    $url = './';
942    $delm = '?';
943    foreach (array_reverse($p) as $par => $val)
944    {
945      if (!empty($val)) {
946        $url .= $delm.urlencode($par).'='.urlencode($val);
947        $delm = '&';
948      }
949    }
[1562]950    return $url;
951  }
[1890]952
953
954  /**
955   * Helper method to set a cookie with the current path and host settings
956   *
957   * @param string Cookie name
958   * @param string Cookie value
959   * @param string Expiration time
960   */
961  public static function setcookie($name, $value, $exp = 0)
962  {
963    $cookie = session_get_cookie_params();
964    setcookie($name, $value, $exp, $cookie['path'], $cookie['domain'],
965      ($_SERVER['HTTPS'] && ($_SERVER['HTTPS'] != 'off')));
966  }
[1344]967}
968
969
Note: See TracBrowser for help on using the repository browser.