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