4 +-----------------------------------------------------------------------+
5 | program/include/rcmail.php |
7 | This file is part of the RoundCube Webmail client |
8 | Copyright (C) 2008-2009, 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 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 rcmail 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();
86 if ($this->config->get('log_driver') == 'syslog') {
87 $syslog_id = $this->config->get('syslog_id', 'roundcube');
88 $syslog_facility = $this->config->get('syslog_facility', LOG_USER);
89 openlog($syslog_id, LOG_ODELAY, $syslog_facility);
92 // set task and action properties
93 $this->set_task(strip_quotes(get_input_value('_task', RCUBE_INPUT_GPC)));
94 $this->action = asciiwords(get_input_value('_action', RCUBE_INPUT_GPC));
96 // connect to database
97 $GLOBALS['DB'] = $this->get_dbh();
99 // use database for storing session data
100 include_once('include/session.inc');
102 // set session domain
103 if (!empty($config_all['session_domain'])) {
104 ini_set('session.cookie_domain', $config_all['session_domain']);
106 // set session garbage collecting time according to session_lifetime
107 if (!empty($config_all['session_lifetime'])) {
108 ini_set('session.gc_maxlifetime', ($config_all['session_lifetime']) * 120);
111 // start PHP session (if not in CLI mode)
112 if ($_SERVER['REMOTE_ADDR'])
115 // set initial session vars
116 if (!isset($_SESSION['auth_time'])) {
117 $_SESSION['auth_time'] = time();
118 $_SESSION['temp'] = true;
121 // create user object
122 $this->set_user(new rcube_user($_SESSION['user_id']));
124 // reset some session parameters when changing task
125 if ($_SESSION['task'] != $this->task)
126 unset($_SESSION['page']);
128 // set current task to session
129 $_SESSION['task'] = $this->task;
131 // create IMAP object
132 if ($this->task == 'mail')
138 * Setter for application task
140 * @param string Task to set
142 public function set_task($task)
144 if (!in_array($task, self::$main_tasks))
148 $this->comm_path = $this->url(array('task' => $task));
151 $this->output->set_env('task', $task);
156 * Setter for system user object
158 * @param object rcube_user Current user instance
160 public function set_user($user)
162 if (is_object($user)) {
164 $GLOBALS['USER'] = $this->user;
166 // overwrite config with user preferences
167 $this->config->merge((array)$this->user->get_prefs());
170 $_SESSION['language'] = $this->user->language = $this->language_prop($this->config->get('language', $_SESSION['language']));
173 setlocale(LC_ALL, $_SESSION['language'] . '.utf8', 'en_US.utf8');
175 // workaround for http://bugs.php.net/bug.php?id=18556
176 if (in_array($_SESSION['language'], array('tr_TR', 'ku', 'az_AZ')))
177 setlocale(LC_CTYPE, 'en_US' . '.utf8');
182 * Check the given string and return a valid language code
184 * @param string Language code
185 * @return string Valid language code
187 private function language_prop($lang)
189 static $rcube_languages, $rcube_language_aliases;
191 // user HTTP_ACCEPT_LANGUAGE if no language is specified
192 if (empty($lang) || $lang == 'auto') {
193 $accept_langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
194 $lang = str_replace('-', '_', $accept_langs[0]);
197 if (empty($rcube_languages)) {
198 @include(INSTALL_PATH . 'program/localization/index.inc');
201 // check if we have an alias for that language
202 if (!isset($rcube_languages[$lang]) && isset($rcube_language_aliases[$lang])) {
203 $lang = $rcube_language_aliases[$lang];
205 // try the first two chars
206 else if (!isset($rcube_languages[$lang])) {
207 $short = substr($lang, 0, 2);
209 // check if we have an alias for the short language code
210 if (!isset($rcube_languages[$short]) && isset($rcube_language_aliases[$short])) {
211 $lang = $rcube_language_aliases[$short];
213 // expand 'nn' to 'nn_NN'
214 else if (!isset($rcube_languages[$short])) {
215 $lang = $short.'_'.strtoupper($short);
219 if (!isset($rcube_languages[$lang]) || !is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
228 * Get the current database connection
230 * @return object rcube_mdb2 Database connection object
232 public function get_dbh()
235 $config_all = $this->config->all();
237 $this->db = new rcube_mdb2($config_all['db_dsnw'], $config_all['db_dsnr'], $config_all['db_persistent']);
238 $this->db->sqlite_initials = INSTALL_PATH . 'SQL/sqlite.initial.sql';
239 $this->db->set_debug((bool)$config_all['sql_debug']);
240 $this->db->db_connect('w');
248 * Return instance of the internal address book class
250 * @param boolean True if the address book needs to be writeable
251 * @return object rcube_contacts Address book object
253 public function get_address_book($id, $writeable = false)
256 $ldap_config = (array)$this->config->get('ldap_public');
257 $abook_type = strtolower($this->config->get('address_book_type'));
259 if ($id && $ldap_config[$id]) {
260 $contacts = new rcube_ldap($ldap_config[$id]);
262 else if ($abook_type == 'ldap') {
263 // Use the first writable LDAP address book.
264 foreach ($ldap_config as $id => $prop) {
265 if (!$writeable || $prop['writable']) {
266 $contacts = new rcube_ldap($prop);
272 $contacts = new rcube_contacts($this->db, $this->user->ID);
280 * Init output object for GUI and add common scripts.
281 * This will instantiate a rcmail_template object and set
282 * environment vars according to the current session and configuration
284 * @param boolean True if this request is loaded in a (i)frame
285 * @return object rcube_template Reference to HTML output object
287 public function load_gui($framed = false)
290 if (!($this->output instanceof rcube_template))
291 $this->output = new rcube_template($this->task, $framed);
293 foreach (array('flag_for_deletion','read_when_deleted') as $js_config_var) {
294 $this->output->set_env($js_config_var, $this->config->get($js_config_var));
297 // set keep-alive/check-recent interval
298 if ($keep_alive = $this->config->get('keep_alive')) {
299 // be sure that it's less than session lifetime
300 if ($session_lifetime = $this->config->get('session_lifetime'))
301 $keep_alive = min($keep_alive, $session_lifetime * 60 - 30);
302 $this->output->set_env('keep_alive', max(60, $keep_alive));
306 $this->comm_path .= '&_framed=1';
307 $this->output->set_env('framed', true);
310 $this->output->set_env('task', $this->task);
311 $this->output->set_env('action', $this->action);
312 $this->output->set_env('comm_path', $this->comm_path);
313 $this->output->set_charset($this->config->get('charset', RCMAIL_CHARSET));
315 // add some basic label to client
316 $this->output->add_label('loading');
318 return $this->output;
323 * Create an output object for JSON responses
325 * @return object rcube_json_output Reference to JSON output object
327 public function init_json()
329 if (!($this->output instanceof rcube_json_output))
330 $this->output = new rcube_json_output($this->task);
332 return $this->output;
337 * Create global IMAP object and connect to server
339 * @param boolean True if connection should be established
340 * @todo Remove global $IMAP
342 public function imap_init($connect = false)
344 $this->imap = new rcube_imap($this->db);
345 $this->imap->debug_level = $this->config->get('debug_level');
346 $this->imap->skip_deleted = $this->config->get('skip_deleted');
348 // enable caching of imap data
349 if ($this->config->get('enable_caching')) {
350 $this->imap->set_caching(true);
353 // set pagesize from config
354 $this->imap->set_pagesize($this->config->get('pagesize', 50));
356 // Setting root and delimiter before iil_Connect can save time detecting them
357 // using NAMESPACE and LIST
359 'imap' => $this->config->get('imap_auth_type', 'check'),
360 'delimiter' => isset($_SESSION['imap_delimiter']) ? $_SESSION['imap_delimiter'] : $this->config->get('imap_delimiter'),
363 if (isset($_SESSION['imap_root']))
364 $options['rootdir'] = $_SESSION['imap_root'];
365 else if ($imap_root = $this->config->get('imap_root'))
366 $options['rootdir'] = $imap_root;
368 $this->imap->set_options($options);
370 // set global object for backward compatibility
371 $GLOBALS['IMAP'] = $this->imap;
374 $this->imap_connect();
379 * Connect to IMAP server with stored session data
381 * @return bool True on success, false on error
383 public function imap_connect()
387 if ($_SESSION['imap_host'] && !$this->imap->conn) {
388 if (!($conn = $this->imap->connect($_SESSION['imap_host'], $_SESSION['username'], $this->decrypt_passwd($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl']))) {
390 $this->output->show_message($this->imap->error_code == -1 ? 'imaperror' : 'sessionerror', 'error');
393 $this->set_imap_prop();
401 * Perfom login to the IMAP server and to the webmail service.
402 * This will also create a new user entry if auto_create_user is configured.
404 * @param string IMAP user name
405 * @param string IMAP password
406 * @param string IMAP host
407 * @return boolean True on success, False on failure
409 function login($username, $pass, $host=NULL)
412 $config = $this->config->all();
415 $host = $config['default_host'];
417 // Validate that selected host is in the list of configured hosts
418 if (is_array($config['default_host'])) {
420 foreach ($config['default_host'] as $key => $host_allowed) {
421 if (!is_numeric($key))
422 $host_allowed = $key;
423 if ($host == $host_allowed) {
431 else if (!empty($config['default_host']) && $host != $config['default_host'])
435 $a_host = parse_url($host);
436 if ($a_host['host']) {
437 $host = $a_host['host'];
438 $imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? $a_host['scheme'] : null;
439 $imap_port = isset($a_host['port']) ? $a_host['port'] : ($imap_ssl ? 993 : $config['default_port']);
442 $imap_port = $config['default_port'];
445 /* Modify username with domain if required
446 Inspired by Marco <P0L0_notspam_binware.org>
448 // Check if we need to add domain
449 if (!empty($config['username_domain']) && !strpos($username, '@')) {
450 if (is_array($config['username_domain']) && isset($config['username_domain'][$host]))
451 $username .= '@'.$config['username_domain'][$host];
452 else if (is_string($config['username_domain']))
453 $username .= '@'.$config['username_domain'];
456 // try to resolve email address from virtuser table
457 if (!empty($config['virtuser_file']) && strpos($username, '@'))
458 $username = rcube_user::email2user($username);
460 // lowercase username if it's an e-mail address (#1484473)
461 if (strpos($username, '@'))
462 $username = rc_strtolower($username);
464 // user already registered -> overwrite username
465 if ($user = rcube_user::query($username, $host))
466 $username = $user->data['username'];
468 // exit if IMAP login failed
469 if (!($imap_login = $this->imap->connect($host, $username, $pass, $imap_port, $imap_ssl)))
472 // user already registered -> update user's record
473 if (is_object($user)) {
476 // create new system user
477 else if ($config['auto_create_user']) {
478 if ($created = rcube_user::create($username, $host)) {
481 // get existing mailboxes (but why?)
482 // $a_mailboxes = $this->imap->list_mailboxes();
489 'file' => RCMAIL_CONFIG_DIR."/main.inc.php",
490 'message' => "Acces denied for new user $username. 'auto_create_user' is disabled"
495 if (is_object($user) && $user->ID) {
496 $this->set_user($user);
499 $_SESSION['user_id'] = $user->ID;
500 $_SESSION['username'] = $user->data['username'];
501 $_SESSION['imap_host'] = $host;
502 $_SESSION['imap_port'] = $imap_port;
503 $_SESSION['imap_ssl'] = $imap_ssl;
504 $_SESSION['password'] = $this->encrypt_passwd($pass);
505 $_SESSION['login_time'] = mktime();
507 if ($_REQUEST['_timezone'] != '_default_')
508 $_SESSION['timezone'] = floatval($_REQUEST['_timezone']);
510 // force reloading complete list of subscribed mailboxes
511 $this->set_imap_prop();
512 $this->imap->clear_cache('mailboxes');
514 if ($config['create_default_folders'])
515 $this->imap->create_default_folders();
525 * Set root dir and last stored mailbox
526 * This must be done AFTER connecting to the server!
528 public function set_imap_prop()
530 $this->imap->set_charset($this->config->get('default_charset', RCMAIL_CHARSET));
532 if ($default_folders = $this->config->get('default_imap_folders')) {
533 $this->imap->set_default_mailboxes($default_folders);
535 if (!empty($_SESSION['mbox'])) {
536 $this->imap->set_mailbox($_SESSION['mbox']);
538 if (isset($_SESSION['page'])) {
539 $this->imap->set_page($_SESSION['page']);
542 // cache IMAP root and delimiter in session for performance reasons
543 $_SESSION['imap_root'] = $this->imap->root_dir;
544 $_SESSION['imap_delimiter'] = $this->imap->delimiter;
549 * Auto-select IMAP host based on the posted login information
551 * @return string Selected IMAP host
553 public function autoselect_host()
555 $default_host = $this->config->get('default_host');
558 if (is_array($default_host)) {
559 $post_host = get_input_value('_host', RCUBE_INPUT_POST);
561 // direct match in default_host array
562 if ($default_host[$post_host] || in_array($post_host, array_values($default_host))) {
566 // try to select host by mail domain
567 list($user, $domain) = explode('@', get_input_value('_user', RCUBE_INPUT_POST));
568 if (!empty($domain)) {
569 foreach ($default_host as $imap_host => $mail_domains) {
570 if (is_array($mail_domains) && in_array($domain, $mail_domains)) {
577 // take the first entry if $host is still an array
579 $host = array_shift($default_host);
582 else if (empty($default_host)) {
583 $host = get_input_value('_host', RCUBE_INPUT_POST);
586 $host = $default_host;
593 * Get localized text in the desired language
595 * @param mixed Named parameters array or label name
596 * @return string Localized text
598 public function gettext($attrib)
600 // load localization files if not done yet
601 if (empty($this->texts))
602 $this->load_language();
604 // extract attributes
605 if (is_string($attrib))
606 $attrib = array('name' => $attrib);
608 $nr = is_numeric($attrib['nr']) ? $attrib['nr'] : 1;
609 $vars = isset($attrib['vars']) ? $attrib['vars'] : '';
611 $command_name = !empty($attrib['command']) ? $attrib['command'] : NULL;
612 $alias = $attrib['name'] ? $attrib['name'] : ($command_name && $command_label_map[$command_name] ? $command_label_map[$command_name] : '');
614 // text does not exist
615 if (!($text_item = $this->texts[$alias])) {
622 'message' => "Missing localized text for '$alias' in '$sess_user_lang'"), TRUE, FALSE);
627 // make text item array
628 $a_text_item = is_array($text_item) ? $text_item : array('single' => $text_item);
630 // decide which text to use
632 $text = $a_text_item['single'];
635 $text = $a_text_item['multiple'];
638 if ($a_text_item['none'])
639 $text = $a_text_item['none'];
640 else if ($a_text_item['single'])
641 $text = $a_text_item['single'];
642 else if ($a_text_item['multiple'])
643 $text = $a_text_item['multiple'];
646 // default text is single
648 $text = $a_text_item['single'];
651 // replace vars in text
652 if (is_array($attrib['vars'])) {
653 foreach ($attrib['vars'] as $var_key => $var_value)
654 $a_replace_vars[$var_key{0}=='$' ? substr($var_key, 1) : $var_key] = $var_value;
658 $text = preg_replace('/\$\{?([_a-z]{1}[_a-z0-9]*)\}?/ei', '$a_replace_vars["\1"]', $text);
661 if (($attrib['uppercase'] && strtolower($attrib['uppercase']=='first')) || $attrib['ucfirst'])
662 return ucfirst($text);
663 else if ($attrib['uppercase'])
664 return strtoupper($text);
665 else if ($attrib['lowercase'])
666 return strtolower($text);
673 * Load a localization package
675 * @param string Language ID
677 public function load_language($lang = null)
679 $lang = $this->language_prop(($lang ? $lang : $_SESSION['language']));
681 // load localized texts
682 if (empty($this->texts) || $lang != $_SESSION['language']) {
683 $this->texts = array();
685 // get english labels (these should be complete)
686 @include(INSTALL_PATH . 'program/localization/en_US/labels.inc');
687 @include(INSTALL_PATH . 'program/localization/en_US/messages.inc');
689 if (is_array($labels))
690 $this->texts = $labels;
691 if (is_array($messages))
692 $this->texts = array_merge($this->texts, $messages);
694 // include user language files
695 if ($lang != 'en' && is_dir(INSTALL_PATH . 'program/localization/' . $lang)) {
696 include_once(INSTALL_PATH . 'program/localization/' . $lang . '/labels.inc');
697 include_once(INSTALL_PATH . 'program/localization/' . $lang . '/messages.inc');
699 if (is_array($labels))
700 $this->texts = array_merge($this->texts, $labels);
701 if (is_array($messages))
702 $this->texts = array_merge($this->texts, $messages);
705 $_SESSION['language'] = $lang;
711 * Read directory program/localization and return a list of available languages
713 * @return array List of available localizations
715 public function list_languages()
717 static $sa_languages = array();
719 if (!sizeof($sa_languages)) {
720 @include(INSTALL_PATH . 'program/localization/index.inc');
722 if ($dh = @opendir(INSTALL_PATH . 'program/localization')) {
723 while (($name = readdir($dh)) !== false) {
724 if ($name{0}=='.' || !is_dir(INSTALL_PATH . 'program/localization/' . $name))
727 if ($label = $rcube_languages[$name])
728 $sa_languages[$name] = $label ? $label : $name;
734 return $sa_languages;
739 * Check the auth hash sent by the client against the local session credentials
741 * @return boolean True if valid, False if not
743 function authenticate_session()
745 global $SESS_CLIENT_IP, $SESS_CHANGED;
747 // advanced session authentication
748 if ($this->config->get('double_auth')) {
750 $valid = ($_COOKIE['sessauth'] == $this->get_auth_hash(session_id(), $_SESSION['auth_time']) ||
751 $_COOKIE['sessauth'] == $this->get_auth_hash(session_id(), $_SESSION['last_auth']));
753 // renew auth cookie every 5 minutes (only for GET requests)
754 if (!$valid || ($_SERVER['REQUEST_METHOD']!='POST' && $now - $_SESSION['auth_time'] > 300)) {
755 $_SESSION['last_auth'] = $_SESSION['auth_time'];
756 $_SESSION['auth_time'] = $now;
757 rcmail::setcookie('sessauth', $this->get_auth_hash(session_id(), $now), 0);
761 $valid = $this->config->get('ip_check') ? $_SERVER['REMOTE_ADDR'] == $SESS_CLIENT_IP : true;
764 // check session filetime
765 $lifetime = $this->config->get('session_lifetime');
766 if (!empty($lifetime) && isset($SESS_CHANGED) && $SESS_CHANGED + $lifetime*60 < time()) {
775 * Destroy session data and remove cookie
777 public function kill_session()
779 $_SESSION = array('language' => $this->user->language, 'auth_time' => time(), 'temp' => true);
780 rcmail::setcookie('sessauth', '-del-', time() - 60);
781 $this->user->reset();
786 * Do server side actions on logout
788 public function logout_actions()
790 $config = $this->config->all();
792 // on logout action we're not connected to imap server
793 if (($config['logout_purge'] && !empty($config['trash_mbox'])) || $config['logout_expunge']) {
794 if (!$this->authenticate_session())
797 $this->imap_init(true);
800 if ($config['logout_purge'] && !empty($config['trash_mbox'])) {
801 $this->imap->clear_mailbox($config['trash_mbox']);
804 if ($config['logout_expunge']) {
805 $this->imap->expunge('INBOX');
811 * Function to be executed in script shutdown
812 * Registered with register_shutdown_function()
814 public function shutdown()
816 if (is_object($this->imap)) {
817 $this->imap->close();
818 $this->imap->write_cache();
821 if (is_object($this->contacts))
822 $this->contacts->close();
824 // before closing the database connection, write session data
825 if ($_SERVER['REMOTE_ADDR'])
826 session_write_close();
831 * Create unique authorization hash
833 * @param string Session ID
834 * @param int Timestamp
835 * @return string The generated auth hash
837 private function get_auth_hash($sess_id, $ts)
839 $auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
842 $this->config->get('ip_check') ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
843 $_SERVER['HTTP_USER_AGENT']);
845 if (function_exists('sha1'))
846 return sha1($auth_string);
848 return md5($auth_string);
852 * Encrypt IMAP password using DES encryption
854 * @param string Password to encrypt
855 * @return string Encryprted string
857 public function encrypt_passwd($pass)
859 if (function_exists('mcrypt_module_open') && ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_ECB, ""))) {
860 $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
861 mcrypt_generic_init($td, $this->config->get_des_key(), $iv);
862 $cypher = mcrypt_generic($td, $pass);
863 mcrypt_generic_deinit($td);
864 mcrypt_module_close($td);
866 else if (function_exists('des')) {
867 $cypher = des($this->config->get_des_key(), $pass, 1, 0, NULL);
876 'message' => "Could not convert encrypt password. Make sure Mcrypt is installed or lib/des.inc is available"
880 return base64_encode($cypher);
885 * Decrypt IMAP password using DES encryption
887 * @param string Encrypted password
888 * @return string Plain password
890 public function decrypt_passwd($cypher)
892 if (function_exists('mcrypt_module_open') && ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_ECB, ""))) {
893 $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
894 mcrypt_generic_init($td, $this->config->get_des_key(), $iv);
895 $pass = mdecrypt_generic($td, base64_decode($cypher));
896 mcrypt_generic_deinit($td);
897 mcrypt_module_close($td);
899 else if (function_exists('des')) {
900 $pass = des($this->config->get_des_key(), base64_decode($cypher), 0, 0, NULL);
903 $pass = base64_decode($cypher);
906 return preg_replace('/\x00/', '', $pass);
911 * Build a valid URL to this instance of RoundCube
913 * @param mixed Either a string with the action or url parameters as key-value pairs
914 * @return string Valid application URL
916 public function url($p)
919 $p = array('_action' => @func_get_arg(0));
921 if (!$p['task'] || !in_array($p['task'], rcmail::$main_tasks))
922 $p['task'] = $this->task;
924 $p['_task'] = $p['task'];
929 foreach (array_reverse($p) as $par => $val)
932 $url .= $delm.urlencode($par).'='.urlencode($val);
941 * Helper method to set a cookie with the current path and host settings
943 * @param string Cookie name
944 * @param string Cookie value
945 * @param string Expiration time
947 public static function setcookie($name, $value, $exp = 0)
949 $cookie = session_get_cookie_params();
950 setcookie($name, $value, $exp, $cookie['path'], $cookie['domain'],
951 ($_SERVER['HTTPS'] && ($_SERVER['HTTPS'] != 'off')));