4 +-----------------------------------------------------------------------+
5 | program/include/rcmail.php |
7 | This file is part of the Roundcube Webmail client |
8 | Copyright (C) 2008-2010, Roundcube Dev. - Switzerland |
9 | Licensed under the GNU GPL |
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 +-----------------------------------------------------------------------+
18 $Id: rcmail.php 4779 2011-05-17 15:35:14Z alec $
24 * Application class of Roundcube Webmail
25 * implemented as singleton
36 static public $main_tasks = array('mail','settings','addressbook','login','logout','utils','dummy');
39 * Singleton instace of rcmail
43 static private $instance;
46 * Stores instance of rcube_config.
53 * Stores rcube_user instance.
60 * Instace of database class.
67 * Instace of rcube_session class.
74 * Instance of rcube_smtp class.
81 * Instance of rcube_imap class.
88 * Instance of rcube_template class.
95 * Instance of rcube_plugin_api.
97 * @var rcube_plugin_api
114 public $comm_path = './';
117 private $books = array();
121 * This implements the 'singleton' design pattern
123 * @return rcmail The one and only instance
125 static function get_instance()
127 if (!self::$instance) {
128 self::$instance = new rcmail();
129 self::$instance->startup(); // init AFTER object was linked with self::$instance
132 return self::$instance;
137 * Private constructor
139 private function __construct()
141 // load configuration
142 $this->config = new rcube_config();
144 register_shutdown_function(array($this, 'shutdown'));
149 * Initial startup function
150 * to register session, create database and imap connections
152 * @todo Remove global vars $DB, $USER
154 private function startup()
157 if ($this->config->get('log_driver') == 'syslog') {
158 $syslog_id = $this->config->get('syslog_id', 'roundcube');
159 $syslog_facility = $this->config->get('syslog_facility', LOG_USER);
160 openlog($syslog_id, LOG_ODELAY, $syslog_facility);
163 // connect to database
164 $GLOBALS['DB'] = $this->get_dbh();
167 $this->session_init();
169 // create user object
170 $this->set_user(new rcube_user($_SESSION['user_id']));
172 // configure session (after user config merge!)
173 $this->session_configure();
175 // set task and action properties
176 $this->set_task(get_input_value('_task', RCUBE_INPUT_GPC));
177 $this->action = asciiwords(get_input_value('_action', RCUBE_INPUT_GPC));
179 // reset some session parameters when changing task
180 if ($this->task != 'utils') {
181 if ($this->session && $_SESSION['task'] != $this->task)
182 $this->session->remove('page');
183 // set current task to session
184 $_SESSION['task'] = $this->task;
188 if (!empty($_REQUEST['_remote']))
189 $GLOBALS['OUTPUT'] = $this->json_init();
191 $GLOBALS['OUTPUT'] = $this->load_gui(!empty($_REQUEST['_framed']));
193 // create plugin API and load plugins
194 $this->plugins = rcube_plugin_api::get_instance();
197 $this->plugins->init();
202 * Setter for application task
204 * @param string Task to set
206 public function set_task($task)
208 $task = asciiwords($task);
210 if ($this->user && $this->user->ID)
211 $task = !$task ? 'mail' : $task;
216 $this->comm_path = $this->url(array('task' => $this->task));
219 $this->output->set_env('task', $this->task);
224 * Setter for system user object
226 * @param rcube_user Current user instance
228 public function set_user($user)
230 if (is_object($user)) {
232 $GLOBALS['USER'] = $this->user;
234 // overwrite config with user preferences
235 $this->config->set_user_prefs((array)$this->user->get_prefs());
238 $_SESSION['language'] = $this->user->language = $this->language_prop($this->config->get('language', $_SESSION['language']));
241 setlocale(LC_ALL, $_SESSION['language'] . '.utf8', 'en_US.utf8');
243 // workaround for http://bugs.php.net/bug.php?id=18556
244 if (in_array($_SESSION['language'], array('tr_TR', 'ku', 'az_AZ')))
245 setlocale(LC_CTYPE, 'en_US' . '.utf8');
250 * Check the given string and return a valid language code
252 * @param string Language code
253 * @return string Valid language code
255 private function language_prop($lang)
257 static $rcube_languages, $rcube_language_aliases;
259 // user HTTP_ACCEPT_LANGUAGE if no language is specified
260 if (empty($lang) || $lang == 'auto') {
261 $accept_langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
262 $lang = str_replace('-', '_', $accept_langs[0]);
265 if (empty($rcube_languages)) {
266 @include(INSTALL_PATH . 'program/localization/index.inc');
269 // check if we have an alias for that language
270 if (!isset($rcube_languages[$lang]) && isset($rcube_language_aliases[$lang])) {
271 $lang = $rcube_language_aliases[$lang];
273 // try the first two chars
274 else if (!isset($rcube_languages[$lang])) {
275 $short = substr($lang, 0, 2);
277 // check if we have an alias for the short language code
278 if (!isset($rcube_languages[$short]) && isset($rcube_language_aliases[$short])) {
279 $lang = $rcube_language_aliases[$short];
281 // expand 'nn' to 'nn_NN'
282 else if (!isset($rcube_languages[$short])) {
283 $lang = $short.'_'.strtoupper($short);
287 if (!isset($rcube_languages[$lang]) || !is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
296 * Get the current database connection
298 * @return rcube_mdb2 Database connection object
300 public function get_dbh()
303 $config_all = $this->config->all();
305 $this->db = new rcube_mdb2($config_all['db_dsnw'], $config_all['db_dsnr'], $config_all['db_persistent']);
306 $this->db->sqlite_initials = INSTALL_PATH . 'SQL/sqlite.initial.sql';
307 $this->db->set_debug((bool)$config_all['sql_debug']);
315 * Return instance of the internal address book class
317 * @param string Address book identifier
318 * @param boolean True if the address book needs to be writeable
319 * @return rcube_contacts Address book object
321 public function get_address_book($id, $writeable = false)
324 $ldap_config = (array)$this->config->get('ldap_public');
325 $abook_type = strtolower($this->config->get('address_book_type'));
327 $plugin = $this->plugins->exec_hook('addressbook_get', array('id' => $id, 'writeable' => $writeable));
329 // plugin returned instance of a rcube_addressbook
330 if ($plugin['instance'] instanceof rcube_addressbook) {
331 $contacts = $plugin['instance'];
333 else if ($id && $ldap_config[$id]) {
334 $contacts = new rcube_ldap($ldap_config[$id], $this->config->get('ldap_debug'), $this->config->mail_domain($_SESSION['imap_host']));
336 else if ($id === '0') {
337 $contacts = new rcube_contacts($this->db, $this->user->ID);
339 else if ($abook_type == 'ldap') {
340 // Use the first writable LDAP address book.
341 foreach ($ldap_config as $id => $prop) {
342 if (!$writeable || $prop['writable']) {
343 $contacts = new rcube_ldap($prop, $this->config->get('ldap_debug'), $this->config->mail_domain($_SESSION['imap_host']));
348 else { // $id == 'sql'
349 $contacts = new rcube_contacts($this->db, $this->user->ID);
352 // add to the 'books' array for shutdown function
353 if (!in_array($contacts, $this->books))
354 $this->books[] = $contacts;
361 * Return address books list
363 * @param boolean True if the address book needs to be writeable
364 * @return array Address books array
366 public function get_address_sources($writeable = false)
368 $abook_type = strtolower($this->config->get('address_book_type'));
369 $ldap_config = $this->config->get('ldap_public');
370 $autocomplete = (array) $this->config->get('autocomplete_addressbooks');
373 // We are using the DB address book
374 if ($abook_type != 'ldap') {
375 $contacts = new rcube_contacts($this->db, null);
378 'name' => rcube_label('personaladrbook'),
379 'groups' => $contacts->groups,
381 'autocomplete' => in_array('sql', $autocomplete)
386 $ldap_config = (array) $ldap_config;
387 foreach ($ldap_config as $id => $prop)
390 'name' => $prop['name'],
392 'readonly' => !$prop['writable'],
393 'autocomplete' => in_array('sql', $autocomplete)
397 $plugin = $this->plugins->exec_hook('addressbooks_list', array('sources' => $list));
398 $list = $plugin['sources'];
400 if ($writeable && !empty($list)) {
401 foreach ($list as $idx => $item) {
402 if ($item['readonly']) {
413 * Init output object for GUI and add common scripts.
414 * This will instantiate a rcmail_template object and set
415 * environment vars according to the current session and configuration
417 * @param boolean True if this request is loaded in a (i)frame
418 * @return rcube_template Reference to HTML output object
420 public function load_gui($framed = false)
423 if (!($this->output instanceof rcube_template))
424 $this->output = new rcube_template($this->task, $framed);
426 // set keep-alive/check-recent interval
427 if ($this->session && ($keep_alive = $this->session->get_keep_alive())) {
428 $this->output->set_env('keep_alive', $keep_alive);
432 $this->comm_path .= '&_framed=1';
433 $this->output->set_env('framed', true);
436 $this->output->set_env('task', $this->task);
437 $this->output->set_env('action', $this->action);
438 $this->output->set_env('comm_path', $this->comm_path);
439 $this->output->set_charset(RCMAIL_CHARSET);
441 // add some basic label to client
442 $this->output->add_label('loading', 'servererror');
444 return $this->output;
449 * Create an output object for JSON responses
451 * @return rcube_json_output Reference to JSON output object
453 public function json_init()
455 if (!($this->output instanceof rcube_json_output))
456 $this->output = new rcube_json_output($this->task);
458 return $this->output;
463 * Create SMTP object and connect to server
465 * @param boolean True if connection should be established
467 public function smtp_init($connect = false)
469 $this->smtp = new rcube_smtp();
472 $this->smtp->connect();
477 * Create global IMAP object and connect to server
479 * @param boolean True if connection should be established
480 * @todo Remove global $IMAP
482 public function imap_init($connect = false)
484 // already initialized
485 if (is_object($this->imap))
488 $this->imap = new rcube_imap($this->db);
489 $this->imap->debug_level = $this->config->get('debug_level');
490 $this->imap->skip_deleted = $this->config->get('skip_deleted');
492 // enable caching of imap data
493 if ($this->config->get('enable_caching')) {
494 $this->imap->set_caching(true);
497 // set pagesize from config
498 $this->imap->set_pagesize($this->config->get('pagesize', 50));
500 // Setting root and delimiter before establishing the connection
501 // can save time detecting them using NAMESPACE and LIST
503 'auth_method' => $this->config->get('imap_auth_type', 'check'),
504 'auth_cid' => $this->config->get('imap_auth_cid'),
505 'auth_pw' => $this->config->get('imap_auth_pw'),
506 'debug' => (bool) $this->config->get('imap_debug', 0),
507 'force_caps' => (bool) $this->config->get('imap_force_caps'),
508 'timeout' => (int) $this->config->get('imap_timeout', 0),
511 $this->imap->set_options($options);
513 // set global object for backward compatibility
514 $GLOBALS['IMAP'] = $this->imap;
516 $hook = $this->plugins->exec_hook('imap_init', array('fetch_headers' => $this->imap->fetch_add_headers));
517 if ($hook['fetch_headers'])
518 $this->imap->fetch_add_headers = $hook['fetch_headers'];
520 // support this parameter for backward compatibility but log warning
522 $this->imap_connect();
524 'code' => 800, 'type' => 'imap',
525 'file' => __FILE__, 'line' => __LINE__,
526 'message' => "rcube::imap_init(true) is deprecated, use rcube::imap_connect() instead"),
533 * Connect to IMAP server with stored session data
535 * @return bool True on success, false on error
537 public function imap_connect()
542 if ($_SESSION['imap_host'] && !$this->imap->conn->connected()) {
543 if (!$this->imap->connect($_SESSION['imap_host'], $_SESSION['username'], $this->decrypt($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl'])) {
545 $this->output->show_message($this->imap->get_error_code() == -1 ? 'imaperror' : 'sessionerror', 'error');
548 $this->set_imap_prop();
549 return $this->imap->conn;
558 * Create session object and start the session.
560 public function session_init()
562 // session started (Installer?)
566 $lifetime = $this->config->get('session_lifetime', 0) * 60;
568 // set session domain
569 if ($domain = $this->config->get('session_domain')) {
570 ini_set('session.cookie_domain', $domain);
572 // set session garbage collecting time according to session_lifetime
574 ini_set('session.gc_maxlifetime', $lifetime * 2);
577 ini_set('session.cookie_secure', rcube_https_check());
578 ini_set('session.name', 'roundcube_sessid');
579 ini_set('session.use_cookies', 1);
580 ini_set('session.use_only_cookies', 1);
581 ini_set('session.serialize_handler', 'php');
583 // use database for storing session data
584 $this->session = new rcube_session($this->get_dbh(), $lifetime);
586 $this->session->register_gc_handler('rcmail_temp_gc');
587 if ($this->config->get('enable_caching'))
588 $this->session->register_gc_handler('rcmail_cache_gc');
590 // start PHP session (if not in CLI mode)
591 if ($_SERVER['REMOTE_ADDR'])
594 // set initial session vars
595 if (!isset($_SESSION['auth_time'])) {
596 $_SESSION['auth_time'] = time();
597 $_SESSION['temp'] = true;
603 * Configure session object internals
605 public function session_configure()
610 $lifetime = $this->config->get('session_lifetime', 0) * 60;
612 // set keep-alive/check-recent interval
613 if ($keep_alive = $this->config->get('keep_alive')) {
614 // be sure that it's less than session lifetime
616 $keep_alive = min($keep_alive, $lifetime - 30);
617 $keep_alive = max(60, $keep_alive);
618 $this->session->set_keep_alive($keep_alive);
624 * Perfom login to the IMAP server and to the webmail service.
625 * This will also create a new user entry if auto_create_user is configured.
627 * @param string IMAP user name
628 * @param string IMAP password
629 * @param string IMAP host
630 * @return boolean True on success, False on failure
632 function login($username, $pass, $host=NULL)
635 $config = $this->config->all();
638 $host = $config['default_host'];
640 // Validate that selected host is in the list of configured hosts
641 if (is_array($config['default_host'])) {
643 foreach ($config['default_host'] as $key => $host_allowed) {
644 if (!is_numeric($key))
645 $host_allowed = $key;
646 if ($host == $host_allowed) {
654 else if (!empty($config['default_host']) && $host != rcube_parse_host($config['default_host']))
658 $a_host = parse_url($host);
659 if ($a_host['host']) {
660 $host = $a_host['host'];
661 $imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? $a_host['scheme'] : null;
662 if (!empty($a_host['port']))
663 $imap_port = $a_host['port'];
664 else if ($imap_ssl && $imap_ssl != 'tls' && (!$config['default_port'] || $config['default_port'] == 143))
668 $imap_port = $imap_port ? $imap_port : $config['default_port'];
670 /* Modify username with domain if required
671 Inspired by Marco <P0L0_notspam_binware.org>
673 // Check if we need to add domain
674 if (!empty($config['username_domain']) && strpos($username, '@') === false) {
675 if (is_array($config['username_domain']) && isset($config['username_domain'][$host]))
676 $username .= '@'.rcube_parse_host($config['username_domain'][$host], $host);
677 else if (is_string($config['username_domain']))
678 $username .= '@'.rcube_parse_host($config['username_domain'], $host);
681 // Convert username to lowercase. If IMAP backend
682 // is case-insensitive we need to store always the same username (#1487113)
683 if ($config['login_lc']) {
684 $username = mb_strtolower($username);
687 // try to resolve email address from virtuser table
688 if (strpos($username, '@') && ($virtuser = rcube_user::email2user($username))) {
689 $username = $virtuser;
692 // Here we need IDNA ASCII
693 // Only rcube_contacts class is using domain names in Unicode
694 $host = rcube_idn_to_ascii($host);
695 if (strpos($username, '@')) {
696 // lowercase domain name
697 list($local, $domain) = explode('@', $username);
698 $username = $local . '@' . mb_strtolower($domain);
699 $username = rcube_idn_to_ascii($username);
702 // user already registered -> overwrite username
703 if ($user = rcube_user::query($username, $host))
704 $username = $user->data['username'];
710 if (!($imap_login = $this->imap->connect($host, $username, $pass, $imap_port, $imap_ssl))) {
711 // try with lowercase
712 $username_lc = mb_strtolower($username);
713 if ($username_lc != $username) {
714 // try to find user record again -> overwrite username
715 if (!$user && ($user = rcube_user::query($username_lc, $host)))
716 $username_lc = $user->data['username'];
718 if ($imap_login = $this->imap->connect($host, $username_lc, $pass, $imap_port, $imap_ssl))
719 $username = $username_lc;
723 // exit if IMAP login failed
727 $this->set_imap_prop();
729 // user already registered -> update user's record
730 if (is_object($user)) {
731 // create default folders on first login
732 if (!$user->data['last_login'] && $config['create_default_folders'])
733 $this->imap->create_default_folders();
736 // create new system user
737 else if ($config['auto_create_user']) {
738 if ($created = rcube_user::create($username, $host)) {
740 // create default folders on first login
741 if ($config['create_default_folders'])
742 $this->imap->create_default_folders();
746 'code' => 600, 'type' => 'php',
747 'file' => __FILE__, 'line' => __LINE__,
748 'message' => "Failed to create a user record. Maybe aborted by a plugin?"
754 'code' => 600, 'type' => 'php',
755 'file' => __FILE__, 'line' => __LINE__,
756 'message' => "Acces denied for new user $username. 'auto_create_user' is disabled"
761 if (is_object($user) && $user->ID) {
762 $this->set_user($user);
765 $_SESSION['user_id'] = $user->ID;
766 $_SESSION['username'] = $user->data['username'];
767 $_SESSION['imap_host'] = $host;
768 $_SESSION['imap_port'] = $imap_port;
769 $_SESSION['imap_ssl'] = $imap_ssl;
770 $_SESSION['password'] = $this->encrypt($pass);
771 $_SESSION['login_time'] = mktime();
773 if (isset($_REQUEST['_timezone']) && $_REQUEST['_timezone'] != '_default_')
774 $_SESSION['timezone'] = floatval($_REQUEST['_timezone']);
776 // force reloading complete list of subscribed mailboxes
777 $this->imap->clear_cache('mailboxes');
787 * Set root dir and last stored mailbox
788 * This must be done AFTER connecting to the server!
790 public function set_imap_prop()
792 $this->imap->set_charset($this->config->get('default_charset', RCMAIL_CHARSET));
794 if ($default_folders = $this->config->get('default_imap_folders')) {
795 $this->imap->set_default_mailboxes($default_folders);
797 if (isset($_SESSION['mbox'])) {
798 $this->imap->set_mailbox($_SESSION['mbox']);
800 if (isset($_SESSION['page'])) {
801 $this->imap->set_page($_SESSION['page']);
807 * Auto-select IMAP host based on the posted login information
809 * @return string Selected IMAP host
811 public function autoselect_host()
813 $default_host = $this->config->get('default_host');
816 if (is_array($default_host)) {
817 $post_host = get_input_value('_host', RCUBE_INPUT_POST);
819 // direct match in default_host array
820 if ($default_host[$post_host] || in_array($post_host, array_values($default_host))) {
824 // try to select host by mail domain
825 list($user, $domain) = explode('@', get_input_value('_user', RCUBE_INPUT_POST));
826 if (!empty($domain)) {
827 foreach ($default_host as $imap_host => $mail_domains) {
828 if (is_array($mail_domains) && in_array($domain, $mail_domains)) {
835 // take the first entry if $host is still an array
837 $host = array_shift($default_host);
840 else if (empty($default_host)) {
841 $host = get_input_value('_host', RCUBE_INPUT_POST);
844 $host = rcube_parse_host($default_host);
851 * Get localized text in the desired language
853 * @param mixed Named parameters array or label name
854 * @return string Localized text
856 public function gettext($attrib, $domain=null)
858 // load localization files if not done yet
859 if (empty($this->texts))
860 $this->load_language();
862 // extract attributes
863 if (is_string($attrib))
864 $attrib = array('name' => $attrib);
866 $nr = is_numeric($attrib['nr']) ? $attrib['nr'] : 1;
867 $name = $attrib['name'] ? $attrib['name'] : '';
869 // check for text with domain
870 if ($domain && ($text_item = $this->texts[$domain.'.'.$name]))
872 // text does not exist
873 else if (!($text_item = $this->texts[$name])) {
877 // make text item array
878 $a_text_item = is_array($text_item) ? $text_item : array('single' => $text_item);
880 // decide which text to use
882 $text = $a_text_item['single'];
885 $text = $a_text_item['multiple'];
888 if ($a_text_item['none'])
889 $text = $a_text_item['none'];
890 else if ($a_text_item['single'])
891 $text = $a_text_item['single'];
892 else if ($a_text_item['multiple'])
893 $text = $a_text_item['multiple'];
896 // default text is single
898 $text = $a_text_item['single'];
901 // replace vars in text
902 if (is_array($attrib['vars'])) {
903 foreach ($attrib['vars'] as $var_key => $var_value)
904 $text = str_replace($var_key[0]!='$' ? '$'.$var_key : $var_key, $var_value, $text);
908 if (($attrib['uppercase'] && strtolower($attrib['uppercase']=='first')) || $attrib['ucfirst'])
909 return ucfirst($text);
910 else if ($attrib['uppercase'])
911 return mb_strtoupper($text);
912 else if ($attrib['lowercase'])
913 return mb_strtolower($text);
920 * Load a localization package
922 * @param string Language ID
924 public function load_language($lang = null, $add = array())
926 $lang = $this->language_prop(($lang ? $lang : $_SESSION['language']));
928 // load localized texts
929 if (empty($this->texts) || $lang != $_SESSION['language']) {
930 $this->texts = array();
932 // handle empty lines after closing PHP tag in localization files
935 // get english labels (these should be complete)
936 @include(INSTALL_PATH . 'program/localization/en_US/labels.inc');
937 @include(INSTALL_PATH . 'program/localization/en_US/messages.inc');
939 if (is_array($labels))
940 $this->texts = $labels;
941 if (is_array($messages))
942 $this->texts = array_merge($this->texts, $messages);
944 // include user language files
945 if ($lang != 'en' && is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
946 include_once(INSTALL_PATH . 'program/localization/' . $lang . '/labels.inc');
947 include_once(INSTALL_PATH . 'program/localization/' . $lang . '/messages.inc');
949 if (is_array($labels))
950 $this->texts = array_merge($this->texts, $labels);
951 if (is_array($messages))
952 $this->texts = array_merge($this->texts, $messages);
957 $_SESSION['language'] = $lang;
960 // append additional texts (from plugin)
961 if (is_array($add) && !empty($add))
962 $this->texts += $add;
967 * Read directory program/localization and return a list of available languages
969 * @return array List of available localizations
971 public function list_languages()
973 static $sa_languages = array();
975 if (!sizeof($sa_languages)) {
976 @include(INSTALL_PATH . 'program/localization/index.inc');
978 if ($dh = @opendir(INSTALL_PATH . 'program/localization')) {
979 while (($name = readdir($dh)) !== false) {
980 if ($name[0] == '.' || !is_dir(INSTALL_PATH . 'program/localization/' . $name))
983 if ($label = $rcube_languages[$name])
984 $sa_languages[$name] = $label;
990 return $sa_languages;
995 * Check the auth hash sent by the client against the local session credentials
997 * @return boolean True if valid, False if not
999 function authenticate_session()
1001 // advanced session authentication
1002 if ($this->config->get('double_auth')) {
1004 $valid = ($_COOKIE['sessauth'] == $this->get_auth_hash(session_id(), $_SESSION['auth_time']) ||
1005 $_COOKIE['sessauth'] == $this->get_auth_hash(session_id(), $_SESSION['last_auth']));
1007 // renew auth cookie every 5 minutes (only for GET requests)
1008 if (!$valid || ($_SERVER['REQUEST_METHOD']!='POST' && $now - $_SESSION['auth_time'] > 300)) {
1009 $_SESSION['last_auth'] = $_SESSION['auth_time'];
1010 $_SESSION['auth_time'] = $now;
1011 rcmail::setcookie('sessauth', $this->get_auth_hash(session_id(), $now), 0);
1015 $valid = $this->config->get('ip_check') ? $_SERVER['REMOTE_ADDR'] == $this->session->get_ip() : true;
1018 // check session filetime
1019 $lifetime = $this->config->get('session_lifetime');
1020 $sess_ts = $this->session->get_ts();
1021 if (!empty($lifetime) && !empty($sess_ts) && $sess_ts + $lifetime*60 < time()) {
1030 * Destroy session data and remove cookie
1032 public function kill_session()
1034 $this->plugins->exec_hook('session_destroy');
1036 $this->session->remove();
1037 $_SESSION = array('language' => $this->user->language, 'auth_time' => time(), 'temp' => true);
1038 rcmail::setcookie('sessauth', '-del-', time() - 60);
1039 $this->user->reset();
1044 * Do server side actions on logout
1046 public function logout_actions()
1048 $config = $this->config->all();
1050 // on logout action we're not connected to imap server
1051 if (($config['logout_purge'] && !empty($config['trash_mbox'])) || $config['logout_expunge']) {
1052 if (!$this->authenticate_session())
1055 $this->imap_connect();
1058 if ($config['logout_purge'] && !empty($config['trash_mbox'])) {
1059 $this->imap->clear_mailbox($config['trash_mbox']);
1062 if ($config['logout_expunge']) {
1063 $this->imap->expunge('INBOX');
1069 * Function to be executed in script shutdown
1070 * Registered with register_shutdown_function()
1072 public function shutdown()
1074 if (is_object($this->smtp))
1075 $this->smtp->disconnect();
1077 foreach ($this->books as $book)
1078 if (is_object($book))
1081 if (is_object($this->imap))
1082 $this->imap->close();
1084 // before closing the database connection, write session data
1085 if ($_SERVER['REMOTE_ADDR'])
1086 session_write_close();
1088 // write performance stats to logs/console
1089 if ($this->config->get('devel_mode')) {
1090 if (function_exists('memory_get_usage'))
1091 $mem = show_bytes(memory_get_usage());
1092 if (function_exists('memory_get_peak_usage'))
1093 $mem .= '/'.show_bytes(memory_get_peak_usage());
1095 $log = $this->task . ($this->action ? '/'.$this->action : '') . ($mem ? " [$mem]" : '');
1096 if (defined('RCMAIL_START'))
1097 rcube_print_time(RCMAIL_START, $log);
1105 * Generate a unique token to be used in a form request
1107 * @return string The request token
1109 public function get_request_token()
1111 $sess_id = $_COOKIE[ini_get('session.name')];
1112 if (!$sess_id) $sess_id = session_id();
1113 return md5('RT' . $this->task . $this->config->get('des_key') . $sess_id);
1118 * Check if the current request contains a valid token
1120 * @param int Request method
1121 * @return boolean True if request token is valid false if not
1123 public function check_request($mode = RCUBE_INPUT_POST)
1125 $token = get_input_value('_token', $mode);
1126 $sess_id = $_COOKIE[ini_get('session.name')];
1127 return !empty($sess_id) && $token == $this->get_request_token();
1132 * Create unique authorization hash
1134 * @param string Session ID
1135 * @param int Timestamp
1136 * @return string The generated auth hash
1138 private function get_auth_hash($sess_id, $ts)
1140 $auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
1143 $this->config->get('ip_check') ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
1144 $_SERVER['HTTP_USER_AGENT']);
1146 if (function_exists('sha1'))
1147 return sha1($auth_string);
1149 return md5($auth_string);
1154 * Encrypt using 3DES
1156 * @param string $clear clear text input
1157 * @param string $key encryption key to retrieve from the configuration, defaults to 'des_key'
1158 * @param boolean $base64 whether or not to base64_encode() the result before returning
1160 * @return string encrypted text
1162 public function encrypt($clear, $key = 'des_key', $base64 = true)
1167 * Add a single canary byte to the end of the clear text, which
1168 * will help find out how much of padding will need to be removed
1169 * upon decryption; see http://php.net/mcrypt_generic#68082
1171 $clear = pack("a*H2", $clear, "80");
1173 if (function_exists('mcrypt_module_open') &&
1174 ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_CBC, "")))
1176 $iv = $this->create_iv(mcrypt_enc_get_iv_size($td));
1177 mcrypt_generic_init($td, $this->config->get_crypto_key($key), $iv);
1178 $cipher = $iv . mcrypt_generic($td, $clear);
1179 mcrypt_generic_deinit($td);
1180 mcrypt_module_close($td);
1183 @include_once('lib/des.inc');
1185 if (function_exists('des')) {
1187 $iv = $this->create_iv($des_iv_size);
1188 $cipher = $iv . des($this->config->get_crypto_key($key), $clear, 1, 1, $iv);
1192 'code' => 500, 'type' => 'php',
1193 'file' => __FILE__, 'line' => __LINE__,
1194 'message' => "Could not perform encryption; make sure Mcrypt is installed or lib/des.inc is available"
1199 return $base64 ? base64_encode($cipher) : $cipher;
1203 * Decrypt 3DES-encrypted string
1205 * @param string $cipher encrypted text
1206 * @param string $key encryption key to retrieve from the configuration, defaults to 'des_key'
1207 * @param boolean $base64 whether or not input is base64-encoded
1209 * @return string decrypted text
1211 public function decrypt($cipher, $key = 'des_key', $base64 = true)
1216 $cipher = $base64 ? base64_decode($cipher) : $cipher;
1218 if (function_exists('mcrypt_module_open') &&
1219 ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_CBC, "")))
1221 $iv_size = mcrypt_enc_get_iv_size($td);
1222 $iv = substr($cipher, 0, $iv_size);
1224 // session corruption? (#1485970)
1225 if (strlen($iv) < $iv_size)
1228 $cipher = substr($cipher, $iv_size);
1229 mcrypt_generic_init($td, $this->config->get_crypto_key($key), $iv);
1230 $clear = mdecrypt_generic($td, $cipher);
1231 mcrypt_generic_deinit($td);
1232 mcrypt_module_close($td);
1235 @include_once('lib/des.inc');
1237 if (function_exists('des')) {
1239 $iv = substr($cipher, 0, $des_iv_size);
1240 $cipher = substr($cipher, $des_iv_size);
1241 $clear = des($this->config->get_crypto_key($key), $cipher, 0, 1, $iv);
1245 'code' => 500, 'type' => 'php',
1246 'file' => __FILE__, 'line' => __LINE__,
1247 'message' => "Could not perform decryption; make sure Mcrypt is installed or lib/des.inc is available"
1253 * Trim PHP's padding and the canary byte; see note in
1254 * rcmail::encrypt() and http://php.net/mcrypt_generic#68082
1256 $clear = substr(rtrim($clear, "\0"), 0, -1);
1262 * Generates encryption initialization vector (IV)
1264 * @param int Vector size
1265 * @return string Vector string
1267 private function create_iv($size)
1269 // mcrypt_create_iv() can be slow when system lacks entrophy
1270 // we'll generate IV vector manually
1272 for ($i = 0; $i < $size; $i++)
1273 $iv .= chr(mt_rand(0, 255));
1278 * Build a valid URL to this instance of Roundcube
1280 * @param mixed Either a string with the action or url parameters as key-value pairs
1281 * @return string Valid application URL
1283 public function url($p)
1286 $p = array('_action' => @func_get_arg(0));
1288 $task = $p['_task'] ? $p['_task'] : ($p['task'] ? $p['task'] : $this->task);
1289 $p['_task'] = $task;
1294 foreach (array_reverse($p) as $key => $val)
1297 $par = $key[0] == '_' ? $key : '_'.$key;
1298 $url .= $delm.urlencode($par).'='.urlencode($val);
1307 * Helper method to set a cookie with the current path and host settings
1309 * @param string Cookie name
1310 * @param string Cookie value
1311 * @param string Expiration time
1313 public static function setcookie($name, $value, $exp = 0)
1318 $cookie = session_get_cookie_params();
1320 setcookie($name, $value, $exp, $cookie['path'], $cookie['domain'],
1321 rcube_https_check(), true);