4 +-----------------------------------------------------------------------+
5 | program/include/rcmail.php |
7 | This file is part of the RoundCube Webmail client |
8 | Copyright (C) 2008, 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: rcube_browser.php 328 2006-08-30 17:41:21Z thomasb $
24 * Application class of RoundCube Webmail
25 * implemented as singleton
31 static public $main_tasks = array('mail','settings','addressbook','login','logout');
33 static private $instance;
40 public $task = 'mail';
42 public $comm_path = './';
48 * This implements the 'singleton' design pattern
50 * @return object qvert The one and only instance
52 static function get_instance()
54 if (!self::$instance) {
55 self::$instance = new rcmail();
56 self::$instance->startup(); // init AFTER object was linked with self::$instance
59 return self::$instance;
66 private function __construct()
69 $this->config = new rcube_config();
71 register_shutdown_function(array($this, 'shutdown'));
76 * Initial startup function
77 * to register session, create database and imap connections
79 * @todo Remove global vars $DB, $USER
81 private function startup()
83 $config_all = $this->config->all();
85 // set task and action properties
86 $this->set_task(strip_quotes(get_input_value('_task', RCUBE_INPUT_GPC)));
87 $this->action = strip_quotes(get_input_value('_action', RCUBE_INPUT_GPC));
89 // connect to database
90 $GLOBALS['DB'] = $this->get_dbh();
92 // use database for storing session data
93 include_once('include/session.inc');
96 if (!empty($config_all['session_domain'])) {
97 ini_set('session.cookie_domain', $config_all['session_domain']);
99 // set session garbage collecting time according to session_lifetime
100 if (!empty($config_all['session_lifetime'])) {
101 ini_set('session.gc_maxlifetime', ($config_all['session_lifetime']) * 120);
104 // start PHP session (if not in CLI mode)
105 if ($_SERVER['REMOTE_ADDR'])
108 // set initial session vars
109 if (!isset($_SESSION['auth_time'])) {
110 $_SESSION['auth_time'] = time();
111 $_SESSION['temp'] = true;
115 // create user object
116 $this->set_user(new rcube_user($_SESSION['user_id']));
118 // reset some session parameters when changing task
119 if ($_SESSION['task'] != $this->task)
120 unset($_SESSION['page']);
122 // set current task to session
123 $_SESSION['task'] = $this->task;
125 // create IMAP object
126 if ($this->task == 'mail')
132 * Setter for application task
134 * @param string Task to set
136 public function set_task($task)
138 if (!in_array($task, self::$main_tasks))
142 $this->comm_path = './?_task=' . $task;
145 $this->output->set_env('task', $task);
150 * Setter for system user object
152 * @param object rcube_user Current user instance
154 public function set_user($user)
156 if (is_object($user)) {
158 $GLOBALS['USER'] = $this->user;
160 // overwrite config with user preferences
161 $this->config->merge((array)$this->user->get_prefs());
164 $_SESSION['language'] = $this->user->language = $this->language_prop($this->config->get('language'));
167 setlocale(LC_ALL, $_SESSION['language'] . '.utf8');
172 * Check the given string and return a valid language code
174 * @param string Language code
175 * @return string Valid language code
177 private function language_prop($lang)
179 static $rcube_languages, $rcube_language_aliases;
181 if (empty($rcube_languages)) {
182 @include(INSTALL_PATH . 'program/localization/index.inc');
185 // check if we have an alias for that language
186 if (!isset($rcube_languages[$lang]) && isset($rcube_language_aliases[$lang])) {
187 $lang = $rcube_language_aliases[$lang];
189 // try the first two chars
190 else if (!isset($rcube_languages[$lang])) {
191 $short = substr($lang, 0, 2);
193 // check if we have an alias for the short language code
194 if (!isset($rcube_languages[$short]) && isset($rcube_language_aliases[$short])) {
195 $lang = $rcube_language_aliases[$short];
197 // expand 'nn' to 'nn_NN'
198 else if (!isset($rcube_languages[$short])) {
199 $lang = $short.'_'.strtoupper($short);
203 if (!isset($rcube_languages[$lang]) || !is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
212 * Get the current database connection
214 * @return object rcube_db Database connection object
216 public function get_dbh()
219 $dbclass = "rcube_" . $this->config->get('db_backend', 'mdb2');
220 $config_all = $this->config->all();
222 $this->db = new $dbclass($config_all['db_dsnw'], $config_all['db_dsnr'], $config_all['db_persistent']);
223 $this->db->sqlite_initials = INSTALL_PATH . 'SQL/sqlite.initial.sql';
224 $this->db->set_debug((bool)$config_all['sql_debug']);
225 $this->db->db_connect('w');
233 * Init output object for GUI and add common scripts.
234 * This will instantiate a rcmail_template object and set
235 * environment vars according to the current session and configuration
237 public function load_gui($framed = false)
240 $this->output = new rcube_template($this->task, $framed);
242 foreach (array('flag_for_deletion') as $js_config_var) {
243 $this->output->set_env($js_config_var, $this->config->get($js_config_var));
247 $this->comm_path .= '&_framed=1';
248 $this->output->set_env('framed', true);
251 $this->output->set_env('task', $this->task);
252 $this->output->set_env('action', $this->action);
253 $this->output->set_env('comm_path', $this->comm_path);
254 $this->output->set_charset($this->config->get('charset', RCMAIL_CHARSET));
256 // add some basic label to client
257 $this->output->add_label('loading');
259 return $this->output;
264 * Create an output object for JSON responses
266 public function init_json()
268 $this->output = new rcube_json_output($this->task);
270 return $this->output;
275 * Create global IMAP object and connect to server
277 * @param boolean True if connection should be established
278 * @todo Remove global $IMAP
280 public function imap_init($connect = false)
282 $this->imap = new rcube_imap($this->db);
283 $this->imap->debug_level = $this->config->get('debug_level');
284 $this->imap->skip_deleted = $this->config->get('skip_deleted');
286 // enable caching of imap data
287 if ($this->config->get('enable_caching')) {
288 $this->imap->set_caching(true);
291 // set pagesize from config
292 $this->imap->set_pagesize($this->config->get('pagesize', 50));
294 // set global object for backward compatibility
295 $GLOBALS['IMAP'] = $this->imap;
298 $this->imap_connect();
303 * Connect to IMAP server with stored session data
305 * @return bool True on success, false on error
307 public function imap_connect()
311 if ($_SESSION['imap_host']) {
312 if (!($conn = $this->imap->connect($_SESSION['imap_host'], $_SESSION['username'], $this->decrypt_passwd($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl'], rcmail::get_instance()->config->get('imap_auth_type', 'check')))) {
314 $this->output->show_message($this->imap->error_code == -1 ? 'imaperror' : 'sessionerror', 'error');
317 $this->set_imap_prop();
325 * Perfom login to the IMAP server and to the webmail service.
326 * This will also create a new user entry if auto_create_user is configured.
328 * @param string IMAP user name
329 * @param string IMAP password
330 * @param string IMAP host
331 * @return boolean True on success, False on failure
333 function login($username, $pass, $host=NULL)
336 $config = $this->config->all();
339 $host = $config['default_host'];
341 // Validate that selected host is in the list of configured hosts
342 if (is_array($config['default_host'])) {
344 foreach ($config['default_host'] as $key => $host_allowed) {
345 if (!is_numeric($key))
346 $host_allowed = $key;
347 if ($host == $host_allowed) {
355 else if (!empty($config['default_host']) && $host != $config['default_host'])
359 $a_host = parse_url($host);
360 if ($a_host['host']) {
361 $host = $a_host['host'];
362 $imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? $a_host['scheme'] : null;
363 $imap_port = isset($a_host['port']) ? $a_host['port'] : ($imap_ssl ? 993 : $config['default_port']);
366 $imap_port = $config['default_port'];
369 /* Modify username with domain if required
370 Inspired by Marco <P0L0_notspam_binware.org>
372 // Check if we need to add domain
373 if (!empty($config['username_domain']) && !strpos($username, '@')) {
374 if (is_array($config['username_domain']) && isset($config['username_domain'][$host]))
375 $username .= '@'.$config['username_domain'][$host];
376 else if (is_string($config['username_domain']))
377 $username .= '@'.$config['username_domain'];
380 // try to resolve email address from virtuser table
381 if (!empty($config['virtuser_file']) && strpos($username, '@'))
382 $username = rcube_user::email2user($username);
384 // lowercase username if it's an e-mail address (#1484473)
385 if (strpos($username, '@'))
386 $username = strtolower($username);
388 // user already registered -> overwrite username
389 if ($user = rcube_user::query($username, $host))
390 $username = $user->data['username'];
392 // exit if IMAP login failed
393 if (!($imap_login = $this->imap->connect($host, $username, $pass, $imap_port, $imap_ssl, $config['imap_auth_type'])))
396 // user already registered -> update user's record
397 if (is_object($user)) {
400 // create new system user
401 else if ($config['auto_create_user']) {
402 if ($created = rcube_user::create($username, $host)) {
405 // get existing mailboxes (but why?)
406 // $a_mailboxes = $this->imap->list_mailboxes();
413 'file' => "config/main.inc.php",
414 'message' => "Acces denied for new user $username. 'auto_create_user' is disabled"
419 if (is_object($user) && $user->ID) {
420 $this->set_user($user);
423 $_SESSION['user_id'] = $user->ID;
424 $_SESSION['username'] = $user->data['username'];
425 $_SESSION['imap_host'] = $host;
426 $_SESSION['imap_port'] = $imap_port;
427 $_SESSION['imap_ssl'] = $imap_ssl;
428 $_SESSION['password'] = $this->encrypt_passwd($pass);
429 $_SESSION['login_time'] = mktime();
431 // force reloading complete list of subscribed mailboxes
432 $this->set_imap_prop();
433 $this->imap->clear_cache('mailboxes');
435 if ($config['create_default_folders'])
436 $this->imap->create_default_folders();
446 * Set root dir and last stored mailbox
447 * This must be done AFTER connecting to the server!
449 public function set_imap_prop()
451 $this->imap->set_charset($this->config->get('default_charset', RCMAIL_CHARSET));
453 // set root dir from config
454 if ($imap_root = $this->config->get('imap_root')) {
455 $this->imap->set_rootdir($imap_root);
457 if ($default_folders = $this->config->get('default_imap_folders')) {
458 $this->imap->set_default_mailboxes($default_folders);
460 if (!empty($_SESSION['mbox'])) {
461 $this->imap->set_mailbox($_SESSION['mbox']);
463 if (isset($_SESSION['page'])) {
464 $this->imap->set_page($_SESSION['page']);
470 * Auto-select IMAP host based on the posted login information
472 * @return string Selected IMAP host
474 public function autoselect_host()
476 $default_host = $this->config->get('default_host');
477 $host = !empty($default_host) ? get_input_value('_host', RCUBE_INPUT_POST) : $default_host;
479 if (is_array($host)) {
480 list($user, $domain) = explode('@', get_input_value('_user', RCUBE_INPUT_POST));
481 if (!empty($domain)) {
482 foreach ($host as $imap_host => $mail_domains) {
483 if (is_array($mail_domains) && in_array($domain, $mail_domains)) {
490 // take the first entry if $host is still an array
492 $host = array_shift($host);
500 * Get localized text in the desired language
502 * @param mixed Named parameters array or label name
503 * @return string Localized text
505 public function gettext($attrib)
507 // load localization files if not done yet
508 if (empty($this->texts))
509 $this->load_language();
511 // extract attributes
512 if (is_string($attrib))
513 $attrib = array('name' => $attrib);
515 $nr = is_numeric($attrib['nr']) ? $attrib['nr'] : 1;
516 $vars = isset($attrib['vars']) ? $attrib['vars'] : '';
518 $command_name = !empty($attrib['command']) ? $attrib['command'] : NULL;
519 $alias = $attrib['name'] ? $attrib['name'] : ($command_name && $command_label_map[$command_name] ? $command_label_map[$command_name] : '');
521 // text does not exist
522 if (!($text_item = $this->texts[$alias])) {
529 'message' => "Missing localized text for '$alias' in '$sess_user_lang'"), TRUE, FALSE);
534 // make text item array
535 $a_text_item = is_array($text_item) ? $text_item : array('single' => $text_item);
537 // decide which text to use
539 $text = $a_text_item['single'];
542 $text = $a_text_item['multiple'];
545 if ($a_text_item['none'])
546 $text = $a_text_item['none'];
547 else if ($a_text_item['single'])
548 $text = $a_text_item['single'];
549 else if ($a_text_item['multiple'])
550 $text = $a_text_item['multiple'];
553 // default text is single
555 $text = $a_text_item['single'];
558 // replace vars in text
559 if (is_array($attrib['vars'])) {
560 foreach ($attrib['vars'] as $var_key => $var_value)
561 $a_replace_vars[$var_key{0}=='$' ? substr($var_key, 1) : $var_key] = $var_value;
565 $text = preg_replace('/\$\{?([_a-z]{1}[_a-z0-9]*)\}?/ei', '$a_replace_vars["\1"]', $text);
568 if (($attrib['uppercase'] && strtolower($attrib['uppercase']=='first')) || $attrib['ucfirst'])
569 return ucfirst($text);
570 else if ($attrib['uppercase'])
571 return strtoupper($text);
572 else if ($attrib['lowercase'])
573 return strtolower($text);
580 * Load a localization package
582 * @param string Language ID
584 public function load_language($lang = null)
586 $lang = $lang ? $this->language_prop($lang) : $_SESSION['language'];
588 // load localized texts
589 if (empty($this->texts) || $lang != $_SESSION['language']) {
590 $this->texts = array();
592 // get english labels (these should be complete)
593 @include(INSTALL_PATH . 'program/localization/en_US/labels.inc');
594 @include(INSTALL_PATH . 'program/localization/en_US/messages.inc');
596 if (is_array($labels))
597 $this->texts = $labels;
598 if (is_array($messages))
599 $this->texts = array_merge($this->texts, $messages);
601 // include user language files
602 if ($lang != 'en' && is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
603 include_once(INSTALL_PATH . 'program/localization/' . $lang . '/labels.inc');
604 include_once(INSTALL_PATH . 'program/localization/' . $lang . '/messages.inc');
606 if (is_array($labels))
607 $this->texts = array_merge($this->texts, $labels);
608 if (is_array($messages))
609 $this->texts = array_merge($this->texts, $messages);
612 $_SESSION['language'] = $lang;
618 * Read directory program/localization and return a list of available languages
620 * @return array List of available localizations
622 public function list_languages()
624 static $sa_languages = array();
626 if (!sizeof($sa_languages)) {
627 @include(INSTALL_PATH . 'program/localization/index.inc');
629 if ($dh = @opendir(INSTALL_PATH . 'program/localization')) {
630 while (($name = readdir($dh)) !== false) {
631 if ($name{0}=='.' || !is_dir(INSTALL_PATH . 'program/localization/' . $name))
634 if ($label = $rcube_languages[$name])
635 $sa_languages[$name] = $label ? $label : $name;
641 return $sa_languages;
646 * Check the auth hash sent by the client against the local session credentials
648 * @return boolean True if valid, False if not
650 function authenticate_session()
652 global $SESS_CLIENT_IP, $SESS_CHANGED;
654 // advanced session authentication
655 if ($this->config->get('double_auth')) {
657 $valid = ($_COOKIE['sessauth'] == $this->get_auth_hash(session_id(), $_SESSION['auth_time']) ||
658 $_COOKIE['sessauth'] == $this->get_auth_hash(session_id(), $_SESSION['last_auth']));
660 // renew auth cookie every 5 minutes (only for GET requests)
661 if (!$valid || ($_SERVER['REQUEST_METHOD']!='POST' && $now - $_SESSION['auth_time'] > 300)) {
662 $_SESSION['last_auth'] = $_SESSION['auth_time'];
663 $_SESSION['auth_time'] = $now;
664 setcookie('sessauth', $this->get_auth_hash(session_id(), $now));
668 $valid = $this->config->get('ip_check') ? $_SERVER['REMOTE_ADDR'] == $SESS_CLIENT_IP : true;
671 // check session filetime
672 $lifetime = $this->config->get('session_lifetime');
673 if (!empty($lifetime) && isset($SESS_CHANGED) && $SESS_CHANGED + $lifetime*60 < time()) {
682 * Destroy session data and remove cookie
684 public function kill_session()
686 $user_prefs = $this->user->get_prefs();
688 if ((isset($_SESSION['sort_col']) && $_SESSION['sort_col'] != $user_prefs['message_sort_col']) ||
689 (isset($_SESSION['sort_order']) && $_SESSION['sort_order'] != $user_prefs['message_sort_order'])) {
690 $this->user->save_prefs(array('message_sort_col' => $_SESSION['sort_col'], 'message_sort_order' => $_SESSION['sort_order']));
693 $_SESSION = array('language' => $USER->language, 'auth_time' => time(), 'temp' => true);
694 setcookie('sessauth', '-del-', time() - 60);
695 $this->user->reset();
700 * Do server side actions on logout
702 public function logout_actions()
704 $config = $this->config->all();
706 // on logout action we're not connected to imap server
707 if (($config['logout_purge'] && !empty($config['trash_mbox'])) || $config['logout_expunge']) {
708 if (!$this->authenticate_session())
711 $this->imap_init(true);
714 if ($config['logout_purge'] && !empty($config['trash_mbox'])) {
715 $this->imap->clear_mailbox($config['trash_mbox']);
718 if ($config['logout_expunge']) {
719 $this->imap->expunge('INBOX');
725 * Function to be executed in script shutdown
726 * Registered with register_shutdown_function()
728 public function shutdown()
730 if (is_object($this->imap)) {
731 $this->imap->close();
732 $this->imap->write_cache();
735 if (is_object($this->contacts))
736 $this->contacts->close();
738 // before closing the database connection, write session data
739 if ($_SERVER['REMOTE_ADDR'])
740 session_write_close();
745 * Create unique authorization hash
747 * @param string Session ID
748 * @param int Timestamp
749 * @return string The generated auth hash
751 private function get_auth_hash($sess_id, $ts)
753 $auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
756 $this->config->get('ip_check') ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
757 $_SERVER['HTTP_USER_AGENT']);
759 if (function_exists('sha1'))
760 return sha1($auth_string);
762 return md5($auth_string);
766 * Encrypt IMAP password using DES encryption
768 * @param string Password to encrypt
769 * @return string Encryprted string
771 public function encrypt_passwd($pass)
773 if (function_exists('mcrypt_module_open') && ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_ECB, ""))) {
774 $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
775 mcrypt_generic_init($td, $this->config->get_des_key(), $iv);
776 $cypher = mcrypt_generic($td, $pass);
777 mcrypt_generic_deinit($td);
778 mcrypt_module_close($td);
780 else if (function_exists('des')) {
781 $cypher = des($this->config->get_des_key(), $pass, 1, 0, NULL);
790 'message' => "Could not convert encrypt password. Make sure Mcrypt is installed or lib/des.inc is available"
794 return base64_encode($cypher);
799 * Decrypt IMAP password using DES encryption
801 * @param string Encrypted password
802 * @return string Plain password
804 public function decrypt_passwd($cypher)
806 if (function_exists('mcrypt_module_open') && ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_ECB, ""))) {
807 $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
808 mcrypt_generic_init($td, $this->config->get_des_key(), $iv);
809 $pass = mdecrypt_generic($td, base64_decode($cypher));
810 mcrypt_generic_deinit($td);
811 mcrypt_module_close($td);
813 else if (function_exists('des')) {
814 $pass = des($this->config->get_des_key(), base64_decode($cypher), 0, 0, NULL);
817 $pass = base64_decode($cypher);
820 return preg_replace('/\x00/', '', $pass);