]> git.donarmstrong.com Git - roundcube.git/blob - program/include/rcmail.php
Imported Upstream version 0.3
[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]);
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);
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
370     // enable caching of imap data
371     if ($this->config->get('enable_caching')) {
372       $this->imap->set_caching(true);
373     }
374
375     // set pagesize from config
376     $this->imap->set_pagesize($this->config->get('pagesize', 50));
377     
378     // Setting root and delimiter before iil_Connect can save time detecting them
379     // using NAMESPACE and LIST 
380     $options = array(
381       'imap' => $this->config->get('imap_auth_type', 'check'),
382       'delimiter' => isset($_SESSION['imap_delimiter']) ? $_SESSION['imap_delimiter'] : $this->config->get('imap_delimiter'),
383       'rootdir' => isset($_SESSION['imap_root']) ? $_SESSION['imap_root'] : $this->config->get('imap_root'),
384       'debug_mode' => (bool) $this->config->get('imap_debug', 0),
385     );
386
387     $this->imap->set_options($options);
388   
389     // set global object for backward compatibility
390     $GLOBALS['IMAP'] = $this->imap;
391     
392     if ($connect)
393       $this->imap_connect();
394   }
395
396
397   /**
398    * Connect to IMAP server with stored session data
399    *
400    * @return bool True on success, false on error
401    */
402   public function imap_connect()
403   {
404     $conn = false;
405     
406     if ($_SESSION['imap_host'] && !$this->imap->conn) {
407       if (!($conn = $this->imap->connect($_SESSION['imap_host'], $_SESSION['username'], $this->decrypt($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl']))) {
408         if ($this->output)
409           $this->output->show_message($this->imap->error_code == -1 ? 'imaperror' : 'sessionerror', 'error');
410       }
411
412       $this->set_imap_prop();
413     }
414
415     return $conn;
416   }
417
418
419   /**
420    * Perfom login to the IMAP server and to the webmail service.
421    * This will also create a new user entry if auto_create_user is configured.
422    *
423    * @param string IMAP user name
424    * @param string IMAP password
425    * @param string IMAP host
426    * @return boolean True on success, False on failure
427    */
428   function login($username, $pass, $host=NULL)
429   {
430     $user = NULL;
431     $config = $this->config->all();
432
433     if (!$host)
434       $host = $config['default_host'];
435
436     // Validate that selected host is in the list of configured hosts
437     if (is_array($config['default_host'])) {
438       $allowed = false;
439       foreach ($config['default_host'] as $key => $host_allowed) {
440         if (!is_numeric($key))
441           $host_allowed = $key;
442         if ($host == $host_allowed) {
443           $allowed = true;
444           break;
445         }
446       }
447       if (!$allowed)
448         return false;
449       }
450     else if (!empty($config['default_host']) && $host != $config['default_host'])
451       return false;
452
453     // parse $host URL
454     $a_host = parse_url($host);
455     if ($a_host['host']) {
456       $host = $a_host['host'];
457       $imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? $a_host['scheme'] : null;
458       if(!empty($a_host['port']))
459         $imap_port = $a_host['port'];
460       else if ($imap_ssl && $imap_ssl != 'tls')
461         $imap_port = 993;
462     }
463     
464     $imap_port = $imap_port ? $imap_port : $config['default_port'];
465
466     /* Modify username with domain if required  
467        Inspired by Marco <P0L0_notspam_binware.org>
468     */
469     // Check if we need to add domain
470     if (!empty($config['username_domain']) && !strpos($username, '@')) {
471       if (is_array($config['username_domain']) && isset($config['username_domain'][$host]))
472         $username .= '@'.$config['username_domain'][$host];
473       else if (is_string($config['username_domain']))
474         $username .= '@'.$config['username_domain'];
475     }
476
477     // try to resolve email address from virtuser table
478     if (strpos($username, '@'))
479       if ($virtuser = rcube_user::email2user($username))
480         $username = $virtuser;
481
482     // lowercase username if it's an e-mail address (#1484473)
483     if (strpos($username, '@'))
484       $username = mb_strtolower($username);
485
486     // user already registered -> overwrite username
487     if ($user = rcube_user::query($username, $host))
488       $username = $user->data['username'];
489
490     // exit if IMAP login failed
491     if (!($imap_login  = $this->imap->connect($host, $username, $pass, $imap_port, $imap_ssl)))
492       return false;
493
494     // user already registered -> update user's record
495     if (is_object($user)) {
496       $user->touch();
497     }
498     // create new system user
499     else if ($config['auto_create_user']) {
500       if ($created = rcube_user::create($username, $host)) {
501         $user = $created;
502
503         // get existing mailboxes (but why?)
504         // $a_mailboxes = $this->imap->list_mailboxes();
505       }
506       else {
507         raise_error(array(
508           'code' => 600,
509           'type' => 'php',
510           'message' => "Failed to create a user record. Maybe aborted by a plugin?"
511           ), true, false);        
512       }
513     }
514     else {
515       raise_error(array(
516         'code' => 600,
517         'type' => 'php',
518         'file' => RCMAIL_CONFIG_DIR."/main.inc.php",
519         'message' => "Acces denied for new user $username. 'auto_create_user' is disabled"
520         ), true, false);
521     }
522
523     // login succeeded
524     if (is_object($user) && $user->ID) {
525       $this->set_user($user);
526
527       // set session vars
528       $_SESSION['user_id']   = $user->ID;
529       $_SESSION['username']  = $user->data['username'];
530       $_SESSION['imap_host'] = $host;
531       $_SESSION['imap_port'] = $imap_port;
532       $_SESSION['imap_ssl']  = $imap_ssl;
533       $_SESSION['password']  = $this->encrypt($pass);
534       $_SESSION['login_time'] = mktime();
535       
536       if ($_REQUEST['_timezone'] != '_default_')
537         $_SESSION['timezone'] = floatval($_REQUEST['_timezone']);
538
539       // force reloading complete list of subscribed mailboxes
540       $this->set_imap_prop();
541       $this->imap->clear_cache('mailboxes');
542
543       if ($config['create_default_folders'])
544           $this->imap->create_default_folders();
545
546       return true;
547     }
548
549     return false;
550   }
551
552
553   /**
554    * Set root dir and last stored mailbox
555    * This must be done AFTER connecting to the server!
556    */
557   public function set_imap_prop()
558   {
559     $this->imap->set_charset($this->config->get('default_charset', RCMAIL_CHARSET));
560
561     if ($default_folders = $this->config->get('default_imap_folders')) {
562       $this->imap->set_default_mailboxes($default_folders);
563     }
564     if (!empty($_SESSION['mbox'])) {
565       $this->imap->set_mailbox($_SESSION['mbox']);
566     }
567     if (isset($_SESSION['page'])) {
568       $this->imap->set_page($_SESSION['page']);
569     }
570     
571     // cache IMAP root and delimiter in session for performance reasons
572     $_SESSION['imap_root'] = $this->imap->root_dir;
573     $_SESSION['imap_delimiter'] = $this->imap->delimiter;
574   }
575
576
577   /**
578    * Auto-select IMAP host based on the posted login information
579    *
580    * @return string Selected IMAP host
581    */
582   public function autoselect_host()
583   {
584     $default_host = $this->config->get('default_host');
585     $host = null;
586     
587     if (is_array($default_host)) {
588       $post_host = get_input_value('_host', RCUBE_INPUT_POST);
589       
590       // direct match in default_host array
591       if ($default_host[$post_host] || in_array($post_host, array_values($default_host))) {
592         $host = $post_host;
593       }
594       
595       // try to select host by mail domain
596       list($user, $domain) = explode('@', get_input_value('_user', RCUBE_INPUT_POST));
597       if (!empty($domain)) {
598         foreach ($default_host as $imap_host => $mail_domains) {
599           if (is_array($mail_domains) && in_array($domain, $mail_domains)) {
600             $host = $imap_host;
601             break;
602           }
603         }
604       }
605
606       // take the first entry if $host is still an array
607       if (empty($host)) {
608         $host = array_shift($default_host);
609       }
610     }
611     else if (empty($default_host)) {
612       $host = get_input_value('_host', RCUBE_INPUT_POST);
613     }
614     else
615       $host = $default_host;
616
617     return $host;
618   }
619
620
621   /**
622    * Get localized text in the desired language
623    *
624    * @param mixed Named parameters array or label name
625    * @return string Localized text
626    */
627   public function gettext($attrib, $domain=null)
628   {
629     // load localization files if not done yet
630     if (empty($this->texts))
631       $this->load_language();
632     
633     // extract attributes
634     if (is_string($attrib))
635       $attrib = array('name' => $attrib);
636
637     $nr = is_numeric($attrib['nr']) ? $attrib['nr'] : 1;
638     $vars = isset($attrib['vars']) ? $attrib['vars'] : '';
639
640     $command_name = !empty($attrib['command']) ? $attrib['command'] : NULL;
641     $alias = $attrib['name'] ? $attrib['name'] : ($command_name && $command_label_map[$command_name] ? $command_label_map[$command_name] : '');
642     
643     // check for text with domain
644     if ($domain && ($text_item = $this->texts[$domain.'.'.$alias]))
645       ;
646     // text does not exist
647     else if (!($text_item = $this->texts[$alias])) {
648       /*
649       raise_error(array(
650         'code' => 500,
651         'type' => 'php',
652         'line' => __LINE__,
653         'file' => __FILE__,
654         'message' => "Missing localized text for '$alias' in '$sess_user_lang'"), TRUE, FALSE);
655       */
656       return "[$alias]";
657     }
658
659     // make text item array 
660     $a_text_item = is_array($text_item) ? $text_item : array('single' => $text_item);
661
662     // decide which text to use
663     if ($nr == 1) {
664       $text = $a_text_item['single'];
665     }
666     else if ($nr > 0) {
667       $text = $a_text_item['multiple'];
668     }
669     else if ($nr == 0) {
670       if ($a_text_item['none'])
671         $text = $a_text_item['none'];
672       else if ($a_text_item['single'])
673         $text = $a_text_item['single'];
674       else if ($a_text_item['multiple'])
675         $text = $a_text_item['multiple'];
676     }
677
678     // default text is single
679     if ($text == '') {
680       $text = $a_text_item['single'];
681     }
682
683     // replace vars in text
684     if (is_array($attrib['vars'])) {
685       foreach ($attrib['vars'] as $var_key => $var_value)
686         $a_replace_vars[$var_key{0}=='$' ? substr($var_key, 1) : $var_key] = $var_value;
687     }
688
689     if ($a_replace_vars)
690       $text = preg_replace('/\$\{?([_a-z]{1}[_a-z0-9]*)\}?/ei', '$a_replace_vars["\1"]', $text);
691
692     // format output
693     if (($attrib['uppercase'] && strtolower($attrib['uppercase']=='first')) || $attrib['ucfirst'])
694       return ucfirst($text);
695     else if ($attrib['uppercase'])
696       return strtoupper($text);
697     else if ($attrib['lowercase'])
698       return strtolower($text);
699
700     return $text;
701   }
702
703
704   /**
705    * Load a localization package
706    *
707    * @param string Language ID
708    */
709   public function load_language($lang = null, $add = array())
710   {
711     $lang = $this->language_prop(($lang ? $lang : $_SESSION['language']));
712     
713     // load localized texts
714     if (empty($this->texts) || $lang != $_SESSION['language']) {
715       $this->texts = array();
716
717       // get english labels (these should be complete)
718       @include(INSTALL_PATH . 'program/localization/en_US/labels.inc');
719       @include(INSTALL_PATH . 'program/localization/en_US/messages.inc');
720
721       if (is_array($labels))
722         $this->texts = $labels;
723       if (is_array($messages))
724         $this->texts = array_merge($this->texts, $messages);
725
726       // include user language files
727       if ($lang != 'en' && is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
728         include_once(INSTALL_PATH . 'program/localization/' . $lang . '/labels.inc');
729         include_once(INSTALL_PATH . 'program/localization/' . $lang . '/messages.inc');
730
731         if (is_array($labels))
732           $this->texts = array_merge($this->texts, $labels);
733         if (is_array($messages))
734           $this->texts = array_merge($this->texts, $messages);
735       }
736       
737       $_SESSION['language'] = $lang;
738     }
739
740     // append additional texts (from plugin)
741     if (is_array($add) && !empty($add))
742       $this->texts += $add;
743   }
744
745
746   /**
747    * Read directory program/localization and return a list of available languages
748    *
749    * @return array List of available localizations
750    */
751   public function list_languages()
752   {
753     static $sa_languages = array();
754
755     if (!sizeof($sa_languages)) {
756       @include(INSTALL_PATH . 'program/localization/index.inc');
757
758       if ($dh = @opendir(INSTALL_PATH . 'program/localization')) {
759         while (($name = readdir($dh)) !== false) {
760           if ($name{0}=='.' || !is_dir(INSTALL_PATH . 'program/localization/' . $name))
761             continue;
762
763           if ($label = $rcube_languages[$name])
764             $sa_languages[$name] = $label ? $label : $name;
765         }
766         closedir($dh);
767       }
768     }
769
770     return $sa_languages;
771   }
772
773
774   /**
775    * Check the auth hash sent by the client against the local session credentials
776    *
777    * @return boolean True if valid, False if not
778    */
779   function authenticate_session()
780   {
781     global $SESS_CLIENT_IP, $SESS_CHANGED;
782
783     // advanced session authentication
784     if ($this->config->get('double_auth')) {
785       $now = time();
786       $valid = ($_COOKIE['sessauth'] == $this->get_auth_hash(session_id(), $_SESSION['auth_time']) ||
787                 $_COOKIE['sessauth'] == $this->get_auth_hash(session_id(), $_SESSION['last_auth']));
788
789       // renew auth cookie every 5 minutes (only for GET requests)
790       if (!$valid || ($_SERVER['REQUEST_METHOD']!='POST' && $now - $_SESSION['auth_time'] > 300)) {
791         $_SESSION['last_auth'] = $_SESSION['auth_time'];
792         $_SESSION['auth_time'] = $now;
793         rcmail::setcookie('sessauth', $this->get_auth_hash(session_id(), $now), 0);
794       }
795     }
796     else {
797       $valid = $this->config->get('ip_check') ? $_SERVER['REMOTE_ADDR'] == $SESS_CLIENT_IP : true;
798     }
799
800     // check session filetime
801     $lifetime = $this->config->get('session_lifetime');
802     if (!empty($lifetime) && isset($SESS_CHANGED) && $SESS_CHANGED + $lifetime*60 < time()) {
803       $valid = false;
804     }
805
806     return $valid;
807   }
808
809
810   /**
811    * Destroy session data and remove cookie
812    */
813   public function kill_session()
814   {
815     $this->plugins->exec_hook('kill_session');
816     
817     rcube_sess_unset();
818     $_SESSION = array('language' => $this->user->language, 'auth_time' => time(), 'temp' => true);
819     rcmail::setcookie('sessauth', '-del-', time() - 60);
820     $this->user->reset();
821   }
822
823
824   /**
825    * Do server side actions on logout
826    */
827   public function logout_actions()
828   {
829     $config = $this->config->all();
830     
831     // on logout action we're not connected to imap server  
832     if (($config['logout_purge'] && !empty($config['trash_mbox'])) || $config['logout_expunge']) {
833       if (!$this->authenticate_session())
834         return;
835
836       $this->imap_init(true);
837     }
838
839     if ($config['logout_purge'] && !empty($config['trash_mbox'])) {
840       $this->imap->clear_mailbox($config['trash_mbox']);
841     }
842
843     if ($config['logout_expunge']) {
844       $this->imap->expunge('INBOX');
845     }
846   }
847
848
849   /**
850    * Function to be executed in script shutdown
851    * Registered with register_shutdown_function()
852    */
853   public function shutdown()
854   {
855     if (is_object($this->imap)) {
856       $this->imap->close();
857       $this->imap->write_cache();
858     }
859
860     if (is_object($this->smtp))
861       $this->smtp->disconnect();
862
863     if (is_object($this->contacts))
864       $this->contacts->close();
865
866     // before closing the database connection, write session data
867     if ($_SERVER['REMOTE_ADDR'])
868       session_write_close();
869   }
870   
871   
872   /**
873    * Generate a unique token to be used in a form request
874    *
875    * @return string The request token
876    */
877   public function get_request_token()
878   {
879     $key = $this->task;
880     
881     if (!$_SESSION['request_tokens'][$key])
882       $_SESSION['request_tokens'][$key] = md5(uniqid($key . rand(), true));
883     
884     return $_SESSION['request_tokens'][$key];
885   }
886   
887   
888   /**
889    * Check if the current request contains a valid token
890    *
891    * @param int Request method
892    * @return boolean True if request token is valid false if not
893    */
894   public function check_request($mode = RCUBE_INPUT_POST)
895   {
896     $token = get_input_value('_token', $mode);
897     return !empty($token) && $_SESSION['request_tokens'][$this->task] == $token;
898   }
899   
900   
901   /**
902    * Create unique authorization hash
903    *
904    * @param string Session ID
905    * @param int Timestamp
906    * @return string The generated auth hash
907    */
908   private function get_auth_hash($sess_id, $ts)
909   {
910     $auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
911       $sess_id,
912       $ts,
913       $this->config->get('ip_check') ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
914       $_SERVER['HTTP_USER_AGENT']);
915
916     if (function_exists('sha1'))
917       return sha1($auth_string);
918     else
919       return md5($auth_string);
920   }
921
922
923   /**
924    * Encrypt using 3DES
925    *
926    * @param string $clear clear text input
927    * @param string $key encryption key to retrieve from the configuration, defaults to 'des_key'
928    * @param boolean $base64 whether or not to base64_encode() the result before returning
929    *
930    * @return string encrypted text
931    */
932   public function encrypt($clear, $key = 'des_key', $base64 = true)
933   {
934     if (!$clear)
935       return '';
936     /*-
937      * Add a single canary byte to the end of the clear text, which
938      * will help find out how much of padding will need to be removed
939      * upon decryption; see http://php.net/mcrypt_generic#68082
940      */
941     $clear = pack("a*H2", $clear, "80");
942   
943     if (function_exists('mcrypt_module_open') &&
944         ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_CBC, "")))
945     {
946       $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
947       mcrypt_generic_init($td, $this->config->get_crypto_key($key), $iv);
948       $cipher = $iv . mcrypt_generic($td, $clear);
949       mcrypt_generic_deinit($td);
950       mcrypt_module_close($td);
951     }
952     else if (function_exists('des'))
953     {
954       define('DES_IV_SIZE', 8);
955       $iv = '';
956       for ($i = 0; $i < constant('DES_IV_SIZE'); $i++)
957         $iv .= sprintf("%c", mt_rand(0, 255));
958       $cipher = $iv . des($this->config->get_crypto_key($key), $clear, 1, 1, $iv);
959     }
960     else
961     {
962       raise_error(array(
963         'code' => 500,
964         'type' => 'php',
965         'file' => __FILE__,
966         'message' => "Could not perform encryption; make sure Mcrypt is installed or lib/des.inc is available"
967       ), true, true);
968     }
969   
970     return $base64 ? base64_encode($cipher) : $cipher;
971   }
972
973   /**
974    * Decrypt 3DES-encrypted string
975    *
976    * @param string $cipher encrypted text
977    * @param string $key encryption key to retrieve from the configuration, defaults to 'des_key'
978    * @param boolean $base64 whether or not input is base64-encoded
979    *
980    * @return string decrypted text
981    */
982   public function decrypt($cipher, $key = 'des_key', $base64 = true)
983   {
984     if (!$cipher)
985       return '';
986   
987     $cipher = $base64 ? base64_decode($cipher) : $cipher;
988
989     if (function_exists('mcrypt_module_open') &&
990         ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_CBC, "")))
991     {
992       $iv = substr($cipher, 0, mcrypt_enc_get_iv_size($td));
993       $cipher = substr($cipher, mcrypt_enc_get_iv_size($td));
994       mcrypt_generic_init($td, $this->config->get_crypto_key($key), $iv);
995       $clear = mdecrypt_generic($td, $cipher);
996       mcrypt_generic_deinit($td);
997       mcrypt_module_close($td);
998     }
999     else if (function_exists('des'))
1000     {
1001       define('DES_IV_SIZE', 8);
1002       $iv = substr($cipher, 0, constant('DES_IV_SIZE'));
1003       $cipher = substr($cipher, constant('DES_IV_SIZE'));
1004       $clear = des($this->config->get_crypto_key($key), $cipher, 0, 1, $iv);
1005     }
1006     else
1007     {
1008       raise_error(array(
1009         'code' => 500,
1010         'type' => 'php',
1011         'file' => __FILE__,
1012         'message' => "Could not perform decryption; make sure Mcrypt is installed or lib/des.inc is available"
1013       ), true, true);
1014     }
1015   
1016     /*-
1017      * Trim PHP's padding and the canary byte; see note in
1018      * rcmail::encrypt() and http://php.net/mcrypt_generic#68082
1019      */
1020     $clear = substr(rtrim($clear, "\0"), 0, -1);
1021   
1022     return $clear;
1023   }
1024
1025   /**
1026    * Build a valid URL to this instance of RoundCube
1027    *
1028    * @param mixed Either a string with the action or url parameters as key-value pairs
1029    * @return string Valid application URL
1030    */
1031   public function url($p)
1032   {
1033     if (!is_array($p))
1034       $p = array('_action' => @func_get_arg(0));
1035     
1036     $task = $p['_task'] ? $p['_task'] : ($p['task'] ? $p['task'] : $this->task);
1037     $p['_task'] = $task;
1038     unset($p['task']);
1039
1040     $url = './';
1041     $delm = '?';
1042     foreach (array_reverse($p) as $key => $val)
1043     {
1044       if (!empty($val)) {
1045         $par = $key[0] == '_' ? $key : '_'.$key;
1046         $url .= $delm.urlencode($par).'='.urlencode($val);
1047         $delm = '&';
1048       }
1049     }
1050     return $url;
1051   }
1052
1053
1054   /**
1055    * Helper method to set a cookie with the current path and host settings
1056    *
1057    * @param string Cookie name
1058    * @param string Cookie value
1059    * @param string Expiration time
1060    */
1061   public static function setcookie($name, $value, $exp = 0)
1062   {
1063     $cookie = session_get_cookie_params();
1064     setcookie($name, $value, $exp, $cookie['path'], $cookie['domain'],
1065       ($_SERVER['HTTPS'] && ($_SERVER['HTTPS'] != 'off')));
1066   }
1067 }
1068
1069