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