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

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

Allow plugins to add client scripts and handle HTTP requests

File size: 27.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, 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: rcmail.php 328 2006-08-30 17:41:21Z thomasb $
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');
32 
33  static private $instance;
34 
35  public $config;
36  public $user;
37  public $db;
38  public $imap;
39  public $output;
40  public $plugins;
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   *
51   * @return object rcmail The one and only instance
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
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    // set task and action properties
94    $this->set_task(strip_quotes(get_input_value('_task', RCUBE_INPUT_GPC)));
95    $this->action = asciiwords(get_input_value('_action', RCUBE_INPUT_GPC));
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
112    // start PHP session (if not in CLI mode)
113    if ($_SERVER['REMOTE_ADDR'])
114      session_start();
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();
135     
136    // create plugin API and load plugins
137    $this->plugins = rcube_plugin_api::get_instance();
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;
152    $this->comm_path = $this->url(array('task' => $task));
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   
174    $_SESSION['language'] = $this->user->language = $this->language_prop($this->config->get('language', $_SESSION['language']));
175
176    // set localization
177    setlocale(LC_ALL, $_SESSION['language'] . '.utf8', 'en_US.utf8');
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'); 
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;
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     
201    if (empty($rcube_languages)) {
202      @include(INSTALL_PATH . 'program/localization/index.inc');
203    }
204   
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
210    else if (!isset($rcube_languages[$lang])) {
211      $short = substr($lang, 0, 2);
212     
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      }
217      // expand 'nn' to 'nn_NN'
218      else if (!isset($rcube_languages[$short])) {
219        $lang = $short.'_'.strtoupper($short);
220      }
221    }
222
223    if (!isset($rcube_languages[$lang]) || !is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
224      $lang = 'en_US';
225    }
226
227    return $lang;
228  }
229 
230 
231  /**
232   * Get the current database connection
233   *
234   * @return object rcube_mdb2  Database connection object
235   */
236  public function get_dbh()
237  {
238    if (!$this->db) {
239      $config_all = $this->config->all();
240
241      $this->db = new rcube_mdb2($config_all['db_dsnw'], $config_all['db_dsnr'], $config_all['db_persistent']);
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  /**
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  /**
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
287   *
288   * @param boolean True if this request is loaded in a (i)frame
289   * @return object rcube_template Reference to HTML output object
290   */
291  public function load_gui($framed = false)
292  {
293    // init output page
294    if (!($this->output instanceof rcube_template))
295      $this->output = new rcube_template($this->task, $framed);
296
297    foreach (array('flag_for_deletion','read_when_deleted') as $js_config_var) {
298      $this->output->set_env($js_config_var, $this->config->get($js_config_var));
299    }
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    }
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   
322    // load plugins stuff
323    $this->plugins->init_gui($this->output);
324   
325    return $this->output;
326  }
327 
328 
329  /**
330   * Create an output object for JSON responses
331   *
332   * @return object rcube_json_output Reference to JSON output object
333   */
334  public function init_json()
335  {
336    if (!($this->output instanceof rcube_json_output))
337      $this->output = new rcube_json_output($this->task);
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   */
349  public function imap_init($connect = false)
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));
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);
376 
377    // set global object for backward compatibility
378    $GLOBALS['IMAP'] = $this->imap;
379   
380    if ($connect)
381      $this->imap_connect();
382  }
383
384
385  /**
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   
394    if ($_SESSION['imap_host'] && !$this->imap->conn) {
395      if (!($conn = $this->imap->connect($_SESSION['imap_host'], $_SESSION['username'], $this->decrypt_passwd($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl']))) {
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
403    return $conn;
404  }
405
406
407  /**
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, '@'))
469      $username = rc_strtolower($username);
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
476    if (!($imap_login  = $this->imap->connect($host, $username, $pass, $imap_port, $imap_ssl)))
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',
496        'file' => RCMAIL_CONFIG_DIR."/main.inc.php",
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;
511      $_SESSION['password']  = $this->encrypt_passwd($pass);
512      $_SESSION['login_time'] = mktime();
513     
514      if ($_REQUEST['_timezone'] != '_default_')
515        $_SESSION['timezone'] = floatval($_REQUEST['_timezone']);
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    }
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;
552  }
553
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');
563    $host = null;
564   
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
574      list($user, $domain) = explode('@', get_input_value('_user', RCUBE_INPUT_POST));
575      if (!empty($domain)) {
576        foreach ($default_host as $imap_host => $mail_domains) {
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
585      if (empty($host)) {
586        $host = array_shift($default_host);
587      }
588    }
589    else if (empty($default_host)) {
590      $host = get_input_value('_host', RCUBE_INPUT_POST);
591    }
592    else
593      $host = $default_host;
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   */
605  public function gettext($attrib)
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] : '');
620
621    // text does not exist
622    if (!($text_item = $this->texts[$alias])) {
623      /*
624      raise_error(array(
625        'code' => 500,
626        'type' => 'php',
627        'line' => __LINE__,
628        'file' => __FILE__,
629        'message' => "Missing localized text for '$alias' in '$sess_user_lang'"), TRUE, FALSE);
630      */
631      return "[$alias]";
632    }
633
634    // make text item array
635    $a_text_item = is_array($text_item) ? $text_item : array('single' => $text_item);
636
637    // decide which text to use
638    if ($nr == 1) {
639      $text = $a_text_item['single'];
640    }
641    else if ($nr > 0) {
642      $text = $a_text_item['multiple'];
643    }
644    else if ($nr == 0) {
645      if ($a_text_item['none'])
646        $text = $a_text_item['none'];
647      else if ($a_text_item['single'])
648        $text = $a_text_item['single'];
649      else if ($a_text_item['multiple'])
650        $text = $a_text_item['multiple'];
651    }
652
653    // default text is single
654    if ($text == '') {
655      $text = $a_text_item['single'];
656    }
657
658    // replace vars in text
659    if (is_array($attrib['vars'])) {
660      foreach ($attrib['vars'] as $var_key => $var_value)
661        $a_replace_vars[$var_key{0}=='$' ? substr($var_key, 1) : $var_key] = $var_value;
662    }
663
664    if ($a_replace_vars)
665      $text = preg_replace('/\$\{?([_a-z]{1}[_a-z0-9]*)\}?/ei', '$a_replace_vars["\1"]', $text);
666
667    // format output
668    if (($attrib['uppercase'] && strtolower($attrib['uppercase']=='first')) || $attrib['ucfirst'])
669      return ucfirst($text);
670    else if ($attrib['uppercase'])
671      return strtoupper($text);
672    else if ($attrib['lowercase'])
673      return strtolower($text);
674
675    return $text;
676  }
677
678
679  /**
680   * Load a localization package
681   *
682   * @param string Language ID
683   */
684  public function load_language($lang = null)
685  {
686    $lang = $this->language_prop(($lang ? $lang : $_SESSION['language']));
687   
688    // load localized texts
689    if (empty($this->texts) || $lang != $_SESSION['language']) {
690      $this->texts = array();
691
692      // get english labels (these should be complete)
693      @include(INSTALL_PATH . 'program/localization/en_US/labels.inc');
694      @include(INSTALL_PATH . 'program/localization/en_US/messages.inc');
695
696      if (is_array($labels))
697        $this->texts = $labels;
698      if (is_array($messages))
699        $this->texts = array_merge($this->texts, $messages);
700
701      // include user language files
702      if ($lang != 'en' && is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
703        include_once(INSTALL_PATH . 'program/localization/' . $lang . '/labels.inc');
704        include_once(INSTALL_PATH . 'program/localization/' . $lang . '/messages.inc');
705
706        if (is_array($labels))
707          $this->texts = array_merge($this->texts, $labels);
708        if (is_array($messages))
709          $this->texts = array_merge($this->texts, $messages);
710      }
711     
712      $_SESSION['language'] = $lang;
713    }
714  }
715
716
717  /**
718   * Read directory program/localization and return a list of available languages
719   *
720   * @return array List of available localizations
721   */
722  public function list_languages()
723  {
724    static $sa_languages = array();
725
726    if (!sizeof($sa_languages)) {
727      @include(INSTALL_PATH . 'program/localization/index.inc');
728
729      if ($dh = @opendir(INSTALL_PATH . 'program/localization')) {
730        while (($name = readdir($dh)) !== false) {
731          if ($name{0}=='.' || !is_dir(INSTALL_PATH . 'program/localization/' . $name))
732            continue;
733
734          if ($label = $rcube_languages[$name])
735            $sa_languages[$name] = $label ? $label : $name;
736        }
737        closedir($dh);
738      }
739    }
740
741    return $sa_languages;
742  }
743
744
745  /**
746   * Check the auth hash sent by the client against the local session credentials
747   *
748   * @return boolean True if valid, False if not
749   */
750  function authenticate_session()
751  {
752    global $SESS_CLIENT_IP, $SESS_CHANGED;
753
754    // advanced session authentication
755    if ($this->config->get('double_auth')) {
756      $now = time();
757      $valid = ($_COOKIE['sessauth'] == $this->get_auth_hash(session_id(), $_SESSION['auth_time']) ||
758                $_COOKIE['sessauth'] == $this->get_auth_hash(session_id(), $_SESSION['last_auth']));
759
760      // renew auth cookie every 5 minutes (only for GET requests)
761      if (!$valid || ($_SERVER['REQUEST_METHOD']!='POST' && $now - $_SESSION['auth_time'] > 300)) {
762        $_SESSION['last_auth'] = $_SESSION['auth_time'];
763        $_SESSION['auth_time'] = $now;
764        rcmail::setcookie('sessauth', $this->get_auth_hash(session_id(), $now), 0);
765      }
766    }
767    else {
768      $valid = $this->config->get('ip_check') ? $_SERVER['REMOTE_ADDR'] == $SESS_CLIENT_IP : true;
769    }
770
771    // check session filetime
772    $lifetime = $this->config->get('session_lifetime');
773    if (!empty($lifetime) && isset($SESS_CHANGED) && $SESS_CHANGED + $lifetime*60 < time()) {
774      $valid = false;
775    }
776
777    return $valid;
778  }
779
780
781  /**
782   * Destroy session data and remove cookie
783   */
784  public function kill_session()
785  {
786    $_SESSION = array('language' => $this->user->language, 'auth_time' => time(), 'temp' => true);
787    rcmail::setcookie('sessauth', '-del-', time() - 60);
788    $this->user->reset();
789  }
790
791
792  /**
793   * Do server side actions on logout
794   */
795  public function logout_actions()
796  {
797    $config = $this->config->all();
798   
799    // on logout action we're not connected to imap server 
800    if (($config['logout_purge'] && !empty($config['trash_mbox'])) || $config['logout_expunge']) {
801      if (!$this->authenticate_session())
802        return;
803
804      $this->imap_init(true);
805    }
806
807    if ($config['logout_purge'] && !empty($config['trash_mbox'])) {
808      $this->imap->clear_mailbox($config['trash_mbox']);
809    }
810
811    if ($config['logout_expunge']) {
812      $this->imap->expunge('INBOX');
813    }
814  }
815
816
817  /**
818   * Function to be executed in script shutdown
819   * Registered with register_shutdown_function()
820   */
821  public function shutdown()
822  {
823    if (is_object($this->imap)) {
824      $this->imap->close();
825      $this->imap->write_cache();
826    }
827
828    if (is_object($this->contacts))
829      $this->contacts->close();
830
831    // before closing the database connection, write session data
832    if ($_SERVER['REMOTE_ADDR'])
833      session_write_close();
834  }
835 
836 
837  /**
838   * Create unique authorization hash
839   *
840   * @param string Session ID
841   * @param int Timestamp
842   * @return string The generated auth hash
843   */
844  private function get_auth_hash($sess_id, $ts)
845  {
846    $auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
847      $sess_id,
848      $ts,
849      $this->config->get('ip_check') ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
850      $_SERVER['HTTP_USER_AGENT']);
851
852    if (function_exists('sha1'))
853      return sha1($auth_string);
854    else
855      return md5($auth_string);
856  }
857
858  /**
859   * Encrypt IMAP password using DES encryption
860   *
861   * @param string Password to encrypt
862   * @return string Encryprted string
863   */
864  public function encrypt_passwd($pass)
865  {
866    if (function_exists('mcrypt_module_open') && ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_ECB, ""))) {
867      $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
868      mcrypt_generic_init($td, $this->config->get_des_key(), $iv);
869      $cypher = mcrypt_generic($td, $pass);
870      mcrypt_generic_deinit($td);
871      mcrypt_module_close($td);
872    }
873    else if (function_exists('des')) {
874      $cypher = des($this->config->get_des_key(), $pass, 1, 0, NULL);
875    }
876    else {
877      $cypher = $pass;
878
879      raise_error(array(
880        'code' => 500,
881        'type' => 'php',
882        'file' => __FILE__,
883        'message' => "Could not convert encrypt password. Make sure Mcrypt is installed or lib/des.inc is available"
884        ), true, false);
885    }
886
887    return base64_encode($cypher);
888  }
889
890
891  /**
892   * Decrypt IMAP password using DES encryption
893   *
894   * @param string Encrypted password
895   * @return string Plain password
896   */
897  public function decrypt_passwd($cypher)
898  {
899    if (function_exists('mcrypt_module_open') && ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_ECB, ""))) {
900      $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
901      mcrypt_generic_init($td, $this->config->get_des_key(), $iv);
902      $pass = mdecrypt_generic($td, base64_decode($cypher));
903      mcrypt_generic_deinit($td);
904      mcrypt_module_close($td);
905    }
906    else if (function_exists('des')) {
907      $pass = des($this->config->get_des_key(), base64_decode($cypher), 0, 0, NULL);
908    }
909    else {
910      $pass = base64_decode($cypher);
911    }
912
913    return preg_replace('/\x00/', '', $pass);
914  }
915
916
917  /**
918   * Build a valid URL to this instance of RoundCube
919   *
920   * @param mixed Either a string with the action or url parameters as key-value pairs
921   * @return string Valid application URL
922   */
923  public function url($p)
924  {
925    if (!is_array($p))
926      $p = array('_action' => @func_get_arg(0));
927
928    if (!$p['task'] || !in_array($p['task'], rcmail::$main_tasks))
929      $p['task'] = $this->task;
930
931    $p['_task'] = $p['task'];
932    unset($p['task']);
933
934    $url = './';
935    $delm = '?';
936    foreach (array_reverse($p) as $par => $val)
937    {
938      if (!empty($val)) {
939        $url .= $delm.urlencode($par).'='.urlencode($val);
940        $delm = '&';
941      }
942    }
943    return $url;
944  }
945
946
947  /**
948   * Helper method to set a cookie with the current path and host settings
949   *
950   * @param string Cookie name
951   * @param string Cookie value
952   * @param string Expiration time
953   */
954  public static function setcookie($name, $value, $exp = 0)
955  {
956    $cookie = session_get_cookie_params();
957    setcookie($name, $value, $exp, $cookie['path'], $cookie['domain'],
958      ($_SERVER['HTTPS'] && ($_SERVER['HTTPS'] != 'off')));
959  }
960}
961
962
Note: See TracBrowser for help on using the repository browser.