4 +-----------------------------------------------------------------------+
5 | program/include/main.inc |
7 | This file is part of the RoundCube Webmail client |
8 | Copyright (C) 2005-2008, RoundCube Dev, - Switzerland |
9 | Licensed under the GNU GPL |
12 | Provide basic functions for the webmail package |
14 +-----------------------------------------------------------------------+
15 | Author: Thomas Bruederli <roundcube@gmail.com> |
16 +-----------------------------------------------------------------------+
18 $Id: main.inc 1255 2008-04-05 12:49:21Z thomasb $
23 * RoundCube Webmail common functions
26 * @author Thomas Bruederli <roundcube@gmail.com>
29 require_once('lib/utf7.inc');
30 require_once('include/rcube_user.inc');
31 require_once('include/rcube_shared.inc');
32 require_once('include/rcmail_template.inc');
34 // define constannts for input reading
35 define('RCUBE_INPUT_GET', 0x0101);
36 define('RCUBE_INPUT_POST', 0x0102);
37 define('RCUBE_INPUT_GPC', 0x0103);
41 * Initial startup function
42 * to register session, create database and imap connections
44 * @param string Current task
46 function rcmail_startup($task='mail')
48 global $sess_id, $sess_user_lang;
49 global $CONFIG, $INSTALL_PATH, $BROWSER, $OUTPUT, $_SESSION, $IMAP, $DB, $USER;
52 $BROWSER = rcube_browser();
55 $CONFIG = rcmail_load_config();
58 if (isset($CONFIG['session_domain']) && !empty($CONFIG['session_domain'])) {
59 ini_set('session.cookie_domain', $CONFIG['session_domain']);
62 // set session garbage collecting time according to session_lifetime
63 if (!empty($CONFIG['session_lifetime']))
64 ini_set('session.gc_maxlifetime', ($CONFIG['session_lifetime']) * 120);
66 // prepare DB connection
67 $dbwrapper = empty($CONFIG['db_backend']) ? 'db' : $CONFIG['db_backend'];
68 $dbclass = "rcube_" . $dbwrapper;
69 require_once("include/$dbclass.inc");
71 $DB = new $dbclass($CONFIG['db_dsnw'], $CONFIG['db_dsnr'], $CONFIG['db_persistent']);
72 $DB->sqlite_initials = $INSTALL_PATH.'SQL/sqlite.initial.sql';
73 $DB->set_debug((bool)$CONFIG['sql_debug']);
76 // use database for storing session data
77 include_once('include/session.inc');
81 $sess_id = session_id();
83 // create session and set session vars
84 if (!isset($_SESSION['auth_time']))
86 $_SESSION['user_lang'] = rcube_language_prop($CONFIG['locale_string']);
87 $_SESSION['auth_time'] = time();
88 $_SESSION['temp'] = true;
91 // set session vars global
92 $sess_user_lang = rcube_language_prop($_SESSION['user_lang']);
95 $USER = new rcube_user($_SESSION['user_id']);
97 // overwrite config with user preferences
98 $CONFIG = array_merge($CONFIG, (array)$USER->get_prefs());
101 // reset some session parameters when changing task
102 if ($_SESSION['task'] != $task)
103 unset($_SESSION['page']);
105 // set current task to session
106 $_SESSION['task'] = $task;
108 // create IMAP object
114 if ($CONFIG['locale_string'])
115 setlocale(LC_ALL, $CONFIG['locale_string']);
116 else if ($sess_user_lang)
117 setlocale(LC_ALL, $sess_user_lang);
120 register_shutdown_function('rcmail_shutdown');
125 * Load roundcube configuration array
127 * @return array Named configuration parameters
129 function rcmail_load_config()
131 global $INSTALL_PATH;
134 include_once('config/main.inc.php');
135 $conf = is_array($rcmail_config) ? $rcmail_config : array();
137 // load host-specific configuration
138 rcmail_load_host_config($conf);
140 $conf['skin_path'] = $conf['skin_path'] ? unslashify($conf['skin_path']) : 'skins/default';
143 include_once('config/db.inc.php');
144 $conf = array_merge($conf, $rcmail_config);
146 if (empty($conf['log_dir']))
147 $conf['log_dir'] = $INSTALL_PATH.'logs';
149 $conf['log_dir'] = unslashify($conf['log_dir']);
151 // set PHP error logging according to config
152 if ($conf['debug_level'] & 1)
154 ini_set('log_errors', 1);
155 ini_set('error_log', $conf['log_dir'].'/errors');
157 if ($conf['debug_level'] & 4)
158 ini_set('display_errors', 1);
160 ini_set('display_errors', 0);
167 * Load a host-specific config file if configured
168 * This will merge the host specific configuration with the given one
170 * @param array Global configuration parameters
172 function rcmail_load_host_config(&$config)
176 if (is_array($config['include_host_config']))
177 $fname = $config['include_host_config'][$_SERVER['HTTP_HOST']];
178 else if (!empty($config['include_host_config']))
179 $fname = preg_replace('/[^a-z0-9\.\-_]/i', '', $_SERVER['HTTP_HOST']) . '.inc.php';
181 if ($fname && is_file('config/'.$fname))
183 include('config/'.$fname);
184 $config = array_merge($config, $rcmail_config);
190 * Create unique authorization hash
192 * @param string Session ID
193 * @param int Timestamp
194 * @return string The generated auth hash
196 function rcmail_auth_hash($sess_id, $ts)
200 $auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
203 $CONFIG['ip_check'] ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
204 $_SERVER['HTTP_USER_AGENT']);
206 if (function_exists('sha1'))
207 return sha1($auth_string);
209 return md5($auth_string);
214 * Check the auth hash sent by the client against the local session credentials
216 * @return boolean True if valid, False if not
218 function rcmail_authenticate_session()
220 global $CONFIG, $SESS_CLIENT_IP, $SESS_CHANGED;
222 // advanced session authentication
223 if ($CONFIG['double_auth'])
226 $valid = ($_COOKIE['sessauth'] == rcmail_auth_hash(session_id(), $_SESSION['auth_time']) ||
227 $_COOKIE['sessauth'] == rcmail_auth_hash(session_id(), $_SESSION['last_auth']));
229 // renew auth cookie every 5 minutes (only for GET requests)
230 if (!$valid || ($_SERVER['REQUEST_METHOD']!='POST' && $now-$_SESSION['auth_time'] > 300))
232 $_SESSION['last_auth'] = $_SESSION['auth_time'];
233 $_SESSION['auth_time'] = $now;
234 setcookie('sessauth', rcmail_auth_hash(session_id(), $now));
238 $valid = $CONFIG['ip_check'] ? $_SERVER['REMOTE_ADDR'] == $SESS_CLIENT_IP : true;
240 // check session filetime
241 if (!empty($CONFIG['session_lifetime']) && isset($SESS_CHANGED)
242 && $SESS_CHANGED + $CONFIG['session_lifetime']*60 < time())
250 * Create global IMAP object and connect to server
252 * @param boolean True if connection should be established
254 function rcmail_imap_init($connect=FALSE)
256 global $CONFIG, $DB, $IMAP, $OUTPUT;
258 $IMAP = new rcube_imap($DB);
259 $IMAP->debug_level = $CONFIG['debug_level'];
260 $IMAP->skip_deleted = $CONFIG['skip_deleted'];
263 // connect with stored session data
266 if (!($conn = $IMAP->connect($_SESSION['imap_host'], $_SESSION['username'], decrypt_passwd($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl'])))
267 $OUTPUT->show_message('imaperror', 'error');
269 rcmail_set_imap_prop();
272 // enable caching of imap data
273 if ($CONFIG['enable_caching']===TRUE)
274 $IMAP->set_caching(TRUE);
276 // set pagesize from config
277 if (isset($CONFIG['pagesize']))
278 $IMAP->set_pagesize($CONFIG['pagesize']);
283 * Set root dir and last stored mailbox
284 * This must be done AFTER connecting to the server!
286 function rcmail_set_imap_prop()
288 global $CONFIG, $IMAP;
290 if (!empty($CONFIG['default_charset']))
291 $IMAP->set_charset($CONFIG['default_charset']);
293 // set root dir from config
294 if (!empty($CONFIG['imap_root']))
295 $IMAP->set_rootdir($CONFIG['imap_root']);
297 if (is_array($CONFIG['default_imap_folders']))
298 $IMAP->set_default_mailboxes($CONFIG['default_imap_folders']);
300 if (!empty($_SESSION['mbox']))
301 $IMAP->set_mailbox($_SESSION['mbox']);
302 if (isset($_SESSION['page']))
303 $IMAP->set_page($_SESSION['page']);
308 * Do these things on script shutdown
310 function rcmail_shutdown()
312 global $IMAP, $CONTACTS;
314 if (is_object($IMAP))
317 $IMAP->write_cache();
320 if (is_object($CONTACTS))
323 // before closing the database connection, write session data
324 session_write_close();
329 * Destroy session data and remove cookie
331 function rcmail_kill_session()
335 if ((isset($_SESSION['sort_col']) && $_SESSION['sort_col']!=$a_user_prefs['message_sort_col']) ||
336 (isset($_SESSION['sort_order']) && $_SESSION['sort_order']!=$a_user_prefs['message_sort_order']))
338 $a_user_prefs = array('message_sort_col' => $_SESSION['sort_col'], 'message_sort_order' => $_SESSION['sort_order']);
339 $USER->save_prefs($a_user_prefs);
342 $_SESSION = array('user_lang' => $GLOBALS['sess_user_lang'], 'auth_time' => time(), 'temp' => true);
343 setcookie('sessauth', '-del-', time()-60);
349 * Return correct name for a specific database table
351 * @param string Table name
352 * @return string Translated table name
354 function get_table_name($table)
358 // return table name if configured
359 $config_key = 'db_table_'.$table;
361 if (strlen($CONFIG[$config_key]))
362 return $CONFIG[$config_key];
369 * Return correct name for a specific database sequence
370 * (used for Postres only)
372 * @param string Secuence name
373 * @return string Translated sequence name
375 function get_sequence_name($sequence)
379 // return table name if configured
380 $config_key = 'db_sequence_'.$sequence;
382 if (strlen($CONFIG[$config_key]))
383 return $CONFIG[$config_key];
390 * Check the given string and returns language properties
392 * @param string Language code
393 * @param string Peropert name
394 * @return string Property value
396 function rcube_language_prop($lang, $prop='lang')
398 global $INSTALL_PATH;
399 static $rcube_languages, $rcube_language_aliases, $rcube_charsets;
401 if (empty($rcube_languages))
402 @include($INSTALL_PATH.'program/localization/index.inc');
404 // check if we have an alias for that language
405 if (!isset($rcube_languages[$lang]) && isset($rcube_language_aliases[$lang]))
406 $lang = $rcube_language_aliases[$lang];
408 // try the first two chars
409 if (!isset($rcube_languages[$lang]) && strlen($lang)>2)
411 $lang = substr($lang, 0, 2);
412 $lang = rcube_language_prop($lang);
415 if (!isset($rcube_languages[$lang]))
418 // language has special charset configured
419 if (isset($rcube_charsets[$lang]))
420 $charset = $rcube_charsets[$lang];
425 if ($prop=='charset')
433 * Init output object for GUI and add common scripts.
434 * This will instantiate a rcmail_template object and set
435 * environment vars according to the current session and configuration
437 function rcmail_load_gui()
439 global $CONFIG, $OUTPUT, $sess_user_lang;
442 $OUTPUT = new rcmail_template($CONFIG, $GLOBALS['_task']);
443 $OUTPUT->set_env('comm_path', $GLOBALS['COMM_PATH']);
445 if (is_array($CONFIG['javascript_config']))
447 foreach ($CONFIG['javascript_config'] as $js_config_var)
448 $OUTPUT->set_env($js_config_var, $CONFIG[$js_config_var]);
451 if (!empty($GLOBALS['_framed']))
452 $OUTPUT->set_env('framed', true);
454 // set locale setting
455 rcmail_set_locale($sess_user_lang);
457 // set user-selected charset
458 if (!empty($CONFIG['charset']))
459 $OUTPUT->set_charset($CONFIG['charset']);
461 // register common UI objects
462 $OUTPUT->add_handlers(array(
463 'loginform' => 'rcmail_login_form',
464 'username' => 'rcmail_current_username',
465 'message' => 'rcmail_message_container',
466 'charsetselector' => 'rcmail_charset_selector',
469 // add some basic label to client
470 if (!$OUTPUT->ajax_call)
471 rcube_add_label('loading', 'movingmessage');
476 * Set localization charset based on the given language.
477 * This also creates a global property for mbstring usage.
479 function rcmail_set_locale($lang)
481 global $OUTPUT, $MBSTRING;
482 static $s_mbstring_loaded = NULL;
484 // settings for mbstring module (by Tadashi Jokagi)
485 if (is_null($s_mbstring_loaded))
486 $MBSTRING = $s_mbstring_loaded = extension_loaded("mbstring");
488 $MBSTRING = $s_mbstring_loaded = FALSE;
491 mb_internal_encoding(RCMAIL_CHARSET);
493 $OUTPUT->set_charset(rcube_language_prop($lang, 'charset'));
498 * Auto-select IMAP host based on the posted login information
500 * @return string Selected IMAP host
502 function rcmail_autoselect_host()
506 $host = isset($_POST['_host']) ? get_input_value('_host', RCUBE_INPUT_POST) : $CONFIG['default_host'];
509 list($user, $domain) = explode('@', get_input_value('_user', RCUBE_INPUT_POST));
512 foreach ($host as $imap_host => $mail_domains)
513 if (is_array($mail_domains) && in_array($domain, $mail_domains))
520 // take the first entry if $host is still an array
522 $host = array_shift($host);
530 * Perfom login to the IMAP server and to the webmail service.
531 * This will also create a new user entry if auto_create_user is configured.
533 * @param string IMAP user name
534 * @param string IMAP password
535 * @param string IMAP host
536 * @return boolean True on success, False on failure
538 function rcmail_login($user, $pass, $host=NULL)
540 global $CONFIG, $IMAP, $DB, $USER, $sess_user_lang;
544 $host = $CONFIG['default_host'];
546 // Validate that selected host is in the list of configured hosts
547 if (is_array($CONFIG['default_host']))
550 foreach ($CONFIG['default_host'] as $key => $host_allowed)
552 if (!is_numeric($key))
553 $host_allowed = $key;
554 if ($host == $host_allowed)
563 else if (!empty($CONFIG['default_host']) && $host != $CONFIG['default_host'])
567 $a_host = parse_url($host);
570 $host = $a_host['host'];
571 $imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? $a_host['scheme'] : null;
572 $imap_port = isset($a_host['port']) ? $a_host['port'] : ($imap_ssl ? 993 : $CONFIG['default_port']);
575 $imap_port = $CONFIG['default_port'];
578 /* Modify username with domain if required
579 Inspired by Marco <P0L0_notspam_binware.org>
581 // Check if we need to add domain
582 if (!empty($CONFIG['username_domain']) && !strpos($user, '@'))
584 if (is_array($CONFIG['username_domain']) && isset($CONFIG['username_domain'][$host]))
585 $user .= '@'.$CONFIG['username_domain'][$host];
586 else if (is_string($CONFIG['username_domain']))
587 $user .= '@'.$CONFIG['username_domain'];
590 // try to resolve email address from virtuser table
591 if (!empty($CONFIG['virtuser_file']) && strpos($user, '@'))
592 $user = rcube_user::email2user($user);
594 // lowercase username if it's an e-mail address (#1484473)
595 if (strpos($user, '@'))
596 $user = strtolower($user);
598 // query if user already registered
599 if ($existing = rcube_user::query($user, $host))
602 // user already registered -> overwrite username
605 $user_id = $USER->ID;
606 $user = $USER->data['username'];
609 // exit if IMAP login failed
610 if (!($imap_login = $IMAP->connect($host, $user, $pass, $imap_port, $imap_ssl)))
613 // user already registered
617 $CONFIG = array_merge($CONFIG, (array)$USER->get_prefs());
619 // set user specific language
620 if (!empty($USER->data['language']))
621 $sess_user_lang = $_SESSION['user_lang'] = $USER->data['language'];
623 // update user's record
626 // create new system user
627 else if ($CONFIG['auto_create_user'])
629 if ($created = rcube_user::create($user, $host))
633 // get existing mailboxes
634 $a_mailboxes = $IMAP->list_mailboxes();
642 'file' => "config/main.inc.php",
643 'message' => "Acces denied for new user $user. 'auto_create_user' is disabled"
649 $_SESSION['user_id'] = $USER->ID;
650 $_SESSION['username'] = $USER->data['username'];
651 $_SESSION['imap_host'] = $host;
652 $_SESSION['imap_port'] = $imap_port;
653 $_SESSION['imap_ssl'] = $imap_ssl;
654 $_SESSION['user_lang'] = $sess_user_lang;
655 $_SESSION['password'] = encrypt_passwd($pass);
656 $_SESSION['login_time'] = mktime();
658 // force reloading complete list of subscribed mailboxes
659 rcmail_set_imap_prop();
660 $IMAP->clear_cache('mailboxes');
662 if ($CONFIG['create_default_folders'])
663 $IMAP->create_default_folders();
673 * Load virtuser table in array
675 * @return array Virtuser table entries
677 function rcmail_getvirtualfile()
680 if (empty($CONFIG['virtuser_file']) || !is_file($CONFIG['virtuser_file']))
684 $a_lines = file($CONFIG['virtuser_file']);
690 * Find matches of the given pattern in virtuser table
692 * @param string Regular expression to search for
693 * @return array Matching entries
695 function rcmail_findinvirtual($pattern)
698 $virtual = rcmail_getvirtualfile();
702 // check each line for matches
703 foreach ($virtual as $line)
706 if (empty($line) || $line{0}=='#')
709 if (eregi($pattern, $line))
718 * Overwrite action variable
720 * @param string New action value
722 function rcmail_overwrite_action($action)
725 $GLOBALS['_action'] = $action;
726 $OUTPUT->set_env('action', $action);
731 * Compose an URL for a specific action
733 * @param string Request action
734 * @param array More URL parameters
735 * @param string Request task (omit if the same)
736 * @return The application URL
738 function rcmail_url($action, $p=array(), $task=null)
740 global $MAIN_TASKS, $COMM_PATH;
744 if ($task && in_array($task, $MAIN_TASKS))
745 $base = ereg_replace('_task=[a-z]+', '_task='.$task, $COMM_PATH);
748 foreach ($p as $key => $val)
749 $qstring .= '&'.urlencode($key).'='.urlencode($val);
751 return $base . ($action ? '&_action='.$action : '') . $qstring;
756 function show_message($message, $type='notice', $vars=NULL)
759 $OUTPUT->show_message($message, $type, $vars);
764 * Encrypt IMAP password using DES encryption
766 * @param string Password to encrypt
767 * @return string Encryprted string
769 function encrypt_passwd($pass)
771 if (function_exists('mcrypt_module_open') && ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_ECB, ""))) {
772 $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
773 mcrypt_generic_init($td, get_des_key(), $iv);
774 $cypher = mcrypt_generic($td, $pass);
775 mcrypt_generic_deinit($td);
776 mcrypt_module_close($td);
778 else if (function_exists('des')) {
779 $cypher = des(get_des_key(), $pass, 1, 0, NULL);
788 'message' => "Could not convert encrypt password. Make sure Mcrypt is installed or lib/des.inc is available"
792 return base64_encode($cypher);
797 * Decrypt IMAP password using DES encryption
799 * @param string Encrypted password
800 * @return string Plain password
802 function decrypt_passwd($cypher)
804 if (function_exists('mcrypt_module_open') && ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_ECB, ""))) {
805 $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
806 mcrypt_generic_init($td, get_des_key(), $iv);
807 $pass = mdecrypt_generic($td, base64_decode($cypher));
808 mcrypt_generic_deinit($td);
809 mcrypt_module_close($td);
811 else if (function_exists('des')) {
812 $pass = des(get_des_key(), base64_decode($cypher), 0, 0, NULL);
815 $pass = base64_decode($cypher);
818 return preg_replace('/\x00/', '', $pass);
823 * Return a 24 byte key for the DES encryption
825 * @return string DES encryption key
827 function get_des_key()
829 $key = !empty($GLOBALS['CONFIG']['des_key']) ? $GLOBALS['CONFIG']['des_key'] : 'rcmail?24BitPwDkeyF**ECB';
832 // make sure the key is exactly 24 chars long
834 $key .= str_repeat('_', 24-$len);
843 * Read directory program/localization and return a list of available languages
845 * @return array List of available localizations
847 function rcube_list_languages()
849 global $CONFIG, $INSTALL_PATH;
850 static $sa_languages = array();
852 if (!sizeof($sa_languages))
854 @include($INSTALL_PATH.'program/localization/index.inc');
856 if ($dh = @opendir($INSTALL_PATH.'program/localization'))
858 while (($name = readdir($dh)) !== false)
860 if ($name{0}=='.' || !is_dir($INSTALL_PATH.'program/localization/'.$name))
863 if ($label = $rcube_languages[$name])
864 $sa_languages[$name] = $label ? $label : $name;
869 return $sa_languages;
874 * Add a localized label to the client environment
876 function rcube_add_label()
880 $arg_list = func_get_args();
881 foreach ($arg_list as $i => $name)
882 $OUTPUT->command('add_label', $name, rcube_label($name));
887 * Garbage collector function for temp files.
888 * Remove temp files older than two days
890 function rcmail_temp_gc()
892 $tmp = unslashify($CONFIG['temp_dir']);
893 $expire = mktime() - 172800; // expire in 48 hours
895 if ($dir = opendir($tmp))
897 while (($fname = readdir($dir)) !== false)
899 if ($fname{0} == '.')
902 if (filemtime($tmp.'/'.$fname) < $expire)
903 @unlink($tmp.'/'.$fname);
912 * Garbage collector for cache entries.
913 * Remove all expired message cache records
915 function rcmail_message_cache_gc()
919 // no cache lifetime configured
920 if (empty($CONFIG['message_cache_lifetime']))
923 // get target timestamp
924 $ts = get_offset_time($CONFIG['message_cache_lifetime'], -1);
926 $DB->query("DELETE FROM ".get_table_name('messages')."
927 WHERE created < ".$DB->fromunixtime($ts));
932 * Convert a string from one charset to another.
933 * Uses mbstring and iconv functions if possible
935 * @param string Input string
936 * @param string Suspected charset of the input string
937 * @param string Target charset to convert to; defaults to RCMAIL_CHARSET
938 * @return Converted string
940 function rcube_charset_convert($str, $from, $to=NULL)
943 static $convert_warning = false;
945 $from = strtoupper($from);
946 $to = $to==NULL ? strtoupper(RCMAIL_CHARSET) : strtoupper($to);
947 $error = false; $conv = null;
949 if ($from==$to || $str=='' || empty($from))
953 'UNKNOWN-8BIT' => 'ISO-8859-15',
954 'X-UNKNOWN' => 'ISO-8859-15',
955 'X-USER-DEFINED' => 'ISO-8859-15',
956 'ISO-8859-8-I' => 'ISO-8859-8',
957 'KS_C_5601-1987' => 'EUC-KR',
960 // convert charset using iconv module
961 if (function_exists('iconv') && $from != 'UTF-7' && $to != 'UTF-7')
963 $aliases['GB2312'] = 'GB18030';
964 return iconv(($aliases[$from] ? $aliases[$from] : $from), ($aliases[$to] ? $aliases[$to] : $to) . "//IGNORE", $str);
967 // convert charset using mbstring module
970 $aliases['UTF-7'] = 'UTF7-IMAP';
971 $aliases['WINDOWS-1257'] = 'ISO-8859-13';
973 // return if convert succeeded
974 if (($out = mb_convert_encoding($str, ($aliases[$to] ? $aliases[$to] : $to), ($aliases[$from] ? $aliases[$from] : $from))) != '')
979 if (class_exists('utf8'))
982 // convert string to UTF-8
983 if ($from == 'UTF-7')
984 $str = utf7_to_utf8($str);
985 else if (($from == 'ISO-8859-1') && function_exists('utf8_encode'))
986 $str = utf8_encode($str);
987 else if ($from != 'UTF-8' && $conv)
989 $conv->loadCharset($from);
990 $str = $conv->strToUtf8($str);
992 else if ($from != 'UTF-8')
995 // encode string for output
997 return utf8_to_utf7($str);
998 else if ($to == 'ISO-8859-1' && function_exists('utf8_decode'))
999 return utf8_decode($str);
1000 else if ($to != 'UTF-8' && $conv)
1002 $conv->loadCharset($to);
1003 return $conv->utf8ToStr($str);
1005 else if ($to != 'UTF-8')
1009 if ($error && !$convert_warning)
1015 'message' => "Could not convert string charset. Make sure iconv is installed or lib/utf8.class is available"
1018 $convert_warning = true;
1021 // return UTF-8 string
1027 * Replacing specials characters to a specific encoding type
1029 * @param string Input string
1030 * @param string Encoding type: text|html|xml|js|url
1031 * @param string Replace mode for tags: show|replace|remove
1032 * @param boolean Convert newlines
1033 * @return The quoted string
1035 function rep_specialchars_output($str, $enctype='', $mode='', $newlines=TRUE)
1037 global $OUTPUT_TYPE, $OUTPUT;
1038 static $html_encode_arr, $js_rep_table, $xml_rep_table;
1041 $enctype = $GLOBALS['OUTPUT_TYPE'];
1043 // encode for plaintext
1044 if ($enctype=='text')
1045 return str_replace("\r\n", "\n", $mode=='remove' ? strip_tags($str) : $str);
1047 // encode for HTML output
1048 if ($enctype=='html')
1050 if (!$html_encode_arr)
1052 $html_encode_arr = get_html_translation_table(HTML_SPECIALCHARS);
1053 unset($html_encode_arr['?']);
1056 $ltpos = strpos($str, '<');
1057 $encode_arr = $html_encode_arr;
1059 // don't replace quotes and html tags
1060 if (($mode=='show' || $mode=='') && $ltpos!==false && strpos($str, '>', $ltpos)!==false)
1062 unset($encode_arr['"']);
1063 unset($encode_arr['<']);
1064 unset($encode_arr['>']);
1065 unset($encode_arr['&']);
1067 else if ($mode=='remove')
1068 $str = strip_tags($str);
1070 // avoid douple quotation of &
1071 $out = preg_replace('/&([a-z]{2,5}|#[0-9]{2,4});/', '&\\1;', strtr($str, $encode_arr));
1073 return $newlines ? nl2br($out) : $out;
1076 if ($enctype=='url')
1077 return rawurlencode($str);
1079 // if the replace tables for XML and JS are not yet defined
1082 $js_rep_table = $xml_rep_table = array();
1083 $xml_rep_table['&'] = '&';
1085 for ($c=160; $c<256; $c++) // can be increased to support more charsets
1087 $xml_rep_table[Chr($c)] = "&#$c;";
1089 if ($OUTPUT->get_charset()=='ISO-8859-1')
1090 $js_rep_table[Chr($c)] = sprintf("\\u%04x", $c);
1093 $xml_rep_table['"'] = '"';
1097 if ($enctype=='xml')
1098 return strtr($str, $xml_rep_table);
1100 // encode for javascript use
1103 if ($OUTPUT->get_charset()!='UTF-8')
1104 $str = rcube_charset_convert($str, RCMAIL_CHARSET, $OUTPUT->get_charset());
1106 return preg_replace(array("/\r?\n/", "/\r/"), array('\n', '\n'), addslashes(strtr($str, $js_rep_table)));
1109 // no encoding given -> return original string
1114 * Quote a given string.
1115 * Shortcut function for rep_specialchars_output
1117 * @return string HTML-quoted string
1118 * @see rep_specialchars_output()
1120 function Q($str, $mode='strict', $newlines=TRUE)
1122 return rep_specialchars_output($str, 'html', $mode, $newlines);
1126 * Quote a given string for javascript output.
1127 * Shortcut function for rep_specialchars_output
1129 * @return string JS-quoted string
1130 * @see rep_specialchars_output()
1134 return rep_specialchars_output($str, 'js');
1139 * Read input value and convert it for internal use
1140 * Performs stripslashes() and charset conversion if necessary
1142 * @param string Field name to read
1143 * @param int Source to get value from (GPC)
1144 * @param boolean Allow HTML tags in field value
1145 * @param string Charset to convert into
1146 * @return string Field value or NULL if not available
1148 function get_input_value($fname, $source, $allow_html=FALSE, $charset=NULL)
1153 if ($source==RCUBE_INPUT_GET && isset($_GET[$fname]))
1154 $value = $_GET[$fname];
1155 else if ($source==RCUBE_INPUT_POST && isset($_POST[$fname]))
1156 $value = $_POST[$fname];
1157 else if ($source==RCUBE_INPUT_GPC)
1159 if (isset($_POST[$fname]))
1160 $value = $_POST[$fname];
1161 else if (isset($_GET[$fname]))
1162 $value = $_GET[$fname];
1163 else if (isset($_COOKIE[$fname]))
1164 $value = $_COOKIE[$fname];
1167 // strip slashes if magic_quotes enabled
1168 if ((bool)get_magic_quotes_gpc())
1169 $value = stripslashes($value);
1171 // remove HTML tags if not allowed
1173 $value = strip_tags($value);
1175 // convert to internal charset
1176 if (is_object($OUTPUT))
1177 return rcube_charset_convert($value, $OUTPUT->get_charset(), $charset);
1183 * Remove all non-ascii and non-word chars
1186 function asciiwords($str)
1188 return preg_replace('/[^a-z0-9.-_]/i', '', $str);
1192 * Remove single and double quotes from given string
1194 * @param string Input value
1195 * @return string Dequoted string
1197 function strip_quotes($str)
1199 return preg_replace('/[\'"]/', '', $str);
1204 * Remove new lines characters from given string
1206 * @param string Input value
1207 * @return string Stripped string
1209 function strip_newlines($str)
1211 return preg_replace('/[\r\n]/', '', $str);
1216 * Check if a specific template exists
1218 * @param string Template name
1219 * @return boolean True if template exists
1221 function template_exists($name)
1224 $skin_path = $CONFIG['skin_path'];
1226 // check template file
1227 return is_file("$skin_path/templates/$name.html");
1232 * Wrapper for rcmail_template::parse()
1235 function parse_template($name='main', $exit=true)
1237 $GLOBALS['OUTPUT']->parse($name, $exit);
1242 * Create a HTML table based on the given data
1244 * @param array Named table attributes
1245 * @param mixed Table row data. Either a two-dimensional array or a valid SQL result set
1246 * @param array List of cols to show
1247 * @param string Name of the identifier col
1248 * @return string HTML table code
1250 function rcube_table_output($attrib, $table_data, $a_show_cols, $id_col)
1254 // allow the following attributes to be added to the <table> tag
1255 $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
1257 $table = '<table' . $attrib_str . ">\n";
1260 $table .= "<thead><tr>\n";
1262 foreach ($a_show_cols as $col)
1263 $table .= '<td class="'.$col.'">' . Q(rcube_label($col)) . "</td>\n";
1265 $table .= "</tr></thead>\n<tbody>\n";
1268 if (!is_array($table_data))
1270 while ($table_data && ($sql_arr = $DB->fetch_assoc($table_data)))
1272 $zebra_class = $c%2 ? 'even' : 'odd';
1274 $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $sql_arr[$id_col]);
1277 foreach ($a_show_cols as $col)
1279 $cont = Q($sql_arr[$col]);
1280 $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1283 $table .= "</tr>\n";
1289 foreach ($table_data as $row_data)
1291 $zebra_class = $c%2 ? 'even' : 'odd';
1293 $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $row_data[$id_col]);
1296 foreach ($a_show_cols as $col)
1298 $cont = Q($row_data[$col]);
1299 $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1302 $table .= "</tr>\n";
1307 // complete message table
1308 $table .= "</tbody></table>\n";
1315 * Create an edit field for inclusion on a form
1317 * @param string col field name
1318 * @param string value field value
1319 * @param array attrib HTML element attributes for field
1320 * @param string type HTML element type (default 'text')
1321 * @return string HTML field definition
1323 function rcmail_get_edit_field($col, $value, $attrib, $type='text')
1326 $attrib['name'] = $fname;
1328 if ($type=='checkbox')
1330 $attrib['value'] = '1';
1331 $input = new checkbox($attrib);
1333 else if ($type=='textarea')
1335 $attrib['cols'] = $attrib['size'];
1336 $input = new textarea($attrib);
1339 $input = new textfield($attrib);
1341 // use value from post
1342 if (!empty($_POST[$fname]))
1343 $value = get_input_value($fname, RCUBE_INPUT_POST);
1345 $out = $input->show($value);
1352 * Return the mail domain configured for the given host
1354 * @param string IMAP host
1355 * @return string Resolved SMTP host
1357 function rcmail_mail_domain($host)
1362 if (is_array($CONFIG['mail_domain']))
1364 if (isset($CONFIG['mail_domain'][$host]))
1365 $domain = $CONFIG['mail_domain'][$host];
1367 else if (!empty($CONFIG['mail_domain']))
1368 $domain = $CONFIG['mail_domain'];
1375 * Replace all css definitions with #container [def]
1376 * and remove css-inlined scripting
1378 * @param string CSS source code
1379 * @param string Container ID to use as prefix
1380 * @return string Modified CSS source
1382 function rcmail_mod_css_styles($source, $container_id, $base_url = '')
1384 $a_css_values = array();
1387 // ignore the whole block if evil styles are detected
1388 if (stristr($source, 'expression') || stristr($source, 'behavior'))
1391 // cut out all contents between { and }
1392 while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos)))
1394 $key = sizeof($a_css_values);
1395 $a_css_values[$key] = substr($source, $pos+1, $pos2-($pos+1));
1396 $source = substr($source, 0, $pos+1) . "<<str_replacement[$key]>>" . substr($source, $pos2, strlen($source)-$pos2);
1400 // remove html comments and add #container to each tag selector.
1401 // also replace body definition because we also stripped off the <body> tag
1402 $styles = preg_replace(
1404 '/(^\s*<!--)|(-->\s*$)/',
1405 '/(^\s*|,\s*|\}\s*)([a-z0-9\._#][a-z0-9\.\-_]*)/im',
1406 '/@import\s+(url\()?[\'"]?([^\)\'"]+)[\'"]?(\))?/ime',
1407 '/<<str_replacement\[([0-9]+)\]>>/e',
1408 "/$container_id\s+body/i"
1412 "\\1#$container_id \\2",
1413 "sprintf(\"@import url('./bin/modcss.php?u=%s&c=%s')\", urlencode(make_absolute_url('\\2','$base_url')), urlencode($container_id))",
1414 "\$a_css_values[\\1]",
1415 "$container_id div.rcmBody"
1423 * Try to autodetect operating system and find the correct line endings
1425 * @return string The appropriate mail header delimiter
1427 function rcmail_header_delm()
1431 // use the configured delimiter for headers
1432 if (!empty($CONFIG['mail_header_delimiter']))
1433 return $CONFIG['mail_header_delimiter'];
1434 else if (strtolower(substr(PHP_OS, 0, 3)=='win'))
1436 else if (strtolower(substr(PHP_OS, 0, 3)=='mac'))
1444 * Compose a valid attribute string for HTML tags
1446 * @param array Named tag attributes
1447 * @param array List of allowed attributes
1448 * @return string HTML formatted attribute string
1450 function create_attrib_string($attrib, $allowed_attribs=array('id', 'class', 'style'))
1452 // allow the following attributes to be added to the <iframe> tag
1454 foreach ($allowed_attribs as $a)
1455 if (isset($attrib[$a]))
1456 $attrib_str .= sprintf(' %s="%s"', $a, str_replace('"', '"', $attrib[$a]));
1463 * Convert a HTML attribute string attributes to an associative array (name => value)
1465 * @param string Input string
1466 * @return array Key-value pairs of parsed attributes
1468 function parse_attrib_string($str)
1471 preg_match_all('/\s*([-_a-z]+)=(["\'])([^"]+)\2/Ui', stripslashes($str), $regs, PREG_SET_ORDER);
1473 // convert attributes to an associative array (name => value)
1475 foreach ($regs as $attr)
1476 $attrib[strtolower($attr[1])] = $attr[3];
1483 * Convert the given date to a human readable form
1484 * This uses the date formatting properties from config
1486 * @param mixed Date representation (string or timestamp)
1487 * @param string Date format to use
1488 * @return string Formatted date string
1490 function format_date($date, $format=NULL)
1492 global $CONFIG, $sess_user_lang;
1496 if (is_numeric($date))
1498 else if (!empty($date))
1499 $ts = @strtotime($date);
1504 // get user's timezone
1505 $tz = $CONFIG['timezone'];
1506 if ($CONFIG['dst_active'])
1509 // convert time to user's timezone
1510 $timestamp = $ts - date('Z', $ts) + ($tz * 3600);
1512 // get current timestamp in user's timezone
1513 $now = time(); // local time
1514 $now -= (int)date('Z'); // make GMT time
1515 $now += ($tz * 3600); // user's time
1516 $now_date = getdate($now);
1518 $today_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday'], $now_date['year']);
1519 $week_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday']-6, $now_date['year']);
1521 // define date format depending on current time
1522 if ($CONFIG['prettydate'] && !$format && $timestamp > $today_limit && $timestamp < $now)
1523 return sprintf('%s %s', rcube_label('today'), date($CONFIG['date_today'] ? $CONFIG['date_today'] : 'H:i', $timestamp));
1524 else if ($CONFIG['prettydate'] && !$format && $timestamp > $week_limit && $timestamp < $now)
1525 $format = $CONFIG['date_short'] ? $CONFIG['date_short'] : 'D H:i';
1527 $format = $CONFIG['date_long'] ? $CONFIG['date_long'] : 'd.m.Y H:i';
1530 // parse format string manually in order to provide localized weekday and month names
1531 // an alternative would be to convert the date() format string to fit with strftime()
1533 for($i=0; $i<strlen($format); $i++)
1535 if ($format{$i}=='\\') // skip escape chars
1538 // write char "as-is"
1539 if ($format{$i}==' ' || $format{$i-1}=='\\')
1540 $out .= $format{$i};
1542 else if ($format{$i}=='D')
1543 $out .= rcube_label(strtolower(date('D', $timestamp)));
1545 else if ($format{$i}=='l')
1546 $out .= rcube_label(strtolower(date('l', $timestamp)));
1547 // month name (short)
1548 else if ($format{$i}=='M')
1549 $out .= rcube_label(strtolower(date('M', $timestamp)));
1550 // month name (long)
1551 else if ($format{$i}=='F')
1552 $out .= rcube_label(strtolower(date('F', $timestamp)));
1554 $out .= date($format{$i}, $timestamp);
1562 * Compose a valid representaion of name and e-mail address
1564 * @param string E-mail address
1565 * @param string Person name
1566 * @return string Formatted string
1568 function format_email_recipient($email, $name='')
1570 if ($name && $name != $email)
1572 // Special chars as defined by RFC 822 need to in quoted string (or escaped).
1573 return sprintf('%s <%s>', preg_match('/[\(\)\<\>\\\.\[\]@,;:"]/', $name) ? '"'.addcslashes($name, '"').'"' : $name, $email);
1581 /****** debugging functions ********/
1585 * Print or write debug messages
1587 * @param mixed Debug message or data
1589 function console($msg)
1591 if (!is_string($msg))
1592 $msg = var_export($msg, true);
1594 if (!($GLOBALS['CONFIG']['debug_level'] & 4))
1595 write_log('console', $msg);
1596 else if ($GLOBALS['REMOTE_REQUEST'])
1597 print "/*\n $msg \n*/\n";
1600 print '<div style="background:#eee; border:1px solid #ccc; margin-bottom:3px; padding:6px"><pre>';
1602 print "</pre></div>\n";
1608 * Append a line to a logfile in the logs directory.
1609 * Date will be added automatically to the line.
1611 * @param $name Name of logfile
1612 * @param $line Line to append
1614 function write_log($name, $line)
1616 global $CONFIG, $INSTALL_PATH;
1618 if (!is_string($line))
1619 $line = var_export($line, true);
1621 $log_entry = sprintf("[%s]: %s\n",
1622 date("d-M-Y H:i:s O", mktime()),
1625 if (empty($CONFIG['log_dir']))
1626 $CONFIG['log_dir'] = $INSTALL_PATH.'logs';
1628 // try to open specific log file for writing
1629 if ($fp = @fopen($CONFIG['log_dir'].'/'.$name, 'a'))
1631 fwrite($fp, $log_entry);
1640 function rcube_timer()
1642 list($usec, $sec) = explode(" ", microtime());
1643 return ((float)$usec + (float)$sec);
1650 function rcube_print_time($timer, $label='Timer')
1652 static $print_count = 0;
1655 $now = rcube_timer();
1656 $diff = $now-$timer;
1659 $label = 'Timer '.$print_count;
1661 console(sprintf("%s: %0.4f sec", $label, $diff));
1666 * Return the mailboxlist in HTML
1668 * @param array Named parameters
1669 * @return string HTML code for the gui object
1671 function rcmail_mailbox_list($attrib)
1673 global $IMAP, $CONFIG, $OUTPUT, $COMM_PATH;
1674 static $s_added_script = FALSE;
1675 static $a_mailboxes;
1677 // add some labels to client
1678 rcube_add_label('purgefolderconfirm');
1679 rcube_add_label('deletemessagesconfirm');
1681 // $mboxlist_start = rcube_timer();
1683 $type = $attrib['type'] ? $attrib['type'] : 'ul';
1684 $add_attrib = $type=='select' ? array('style', 'class', 'id', 'name', 'onchange') :
1685 array('style', 'class', 'id');
1687 if ($type=='ul' && !$attrib['id'])
1688 $attrib['id'] = 'rcmboxlist';
1690 // allow the following attributes to be added to the <ul> tag
1691 $attrib_str = create_attrib_string($attrib, $add_attrib);
1693 $out = '<' . $type . $attrib_str . ">\n";
1695 // add no-selection option
1696 if ($type=='select' && $attrib['noselection'])
1697 $out .= sprintf('<option value="0">%s</option>'."\n",
1698 rcube_label($attrib['noselection']));
1701 $mbox_name = $IMAP->get_mailbox_name();
1703 // build the folders tree
1704 if (empty($a_mailboxes))
1707 $a_folders = $IMAP->list_mailboxes();
1708 $delimiter = $IMAP->get_hierarchy_delimiter();
1709 $a_mailboxes = array();
1711 // rcube_print_time($mboxlist_start, 'list_mailboxes()');
1713 foreach ($a_folders as $folder)
1714 rcmail_build_folder_tree($a_mailboxes, $folder, $delimiter);
1717 // var_dump($a_mailboxes);
1719 if ($type=='select')
1720 $out .= rcmail_render_folder_tree_select($a_mailboxes, $mbox_name, $attrib['maxlength']);
1722 $out .= rcmail_render_folder_tree_html($a_mailboxes, $mbox_name, $attrib['maxlength']);
1724 // rcube_print_time($mboxlist_start, 'render_folder_tree()');
1728 $OUTPUT->add_gui_object('mailboxlist', $attrib['id']);
1730 return $out . "</$type>";
1737 * Create a hierarchical array of the mailbox list
1740 function rcmail_build_folder_tree(&$arrFolders, $folder, $delm='/', $path='')
1742 $pos = strpos($folder, $delm);
1745 $subFolders = substr($folder, $pos+1);
1746 $currentFolder = substr($folder, 0, $pos);
1750 $subFolders = false;
1751 $currentFolder = $folder;
1754 $path .= $currentFolder;
1756 if (!isset($arrFolders[$currentFolder]))
1758 $arrFolders[$currentFolder] = array('id' => $path,
1759 'name' => rcube_charset_convert($currentFolder, 'UTF-7'),
1760 'folders' => array());
1763 if (!empty($subFolders))
1764 rcmail_build_folder_tree($arrFolders[$currentFolder]['folders'], $subFolders, $delm, $path.$delm);
1769 * Return html for a structured list <ul> for the mailbox tree
1772 function rcmail_render_folder_tree_html(&$arrFolders, &$mbox_name, $maxlength, $nestLevel=0)
1774 global $COMM_PATH, $IMAP, $CONFIG, $OUTPUT;
1778 foreach ($arrFolders as $key => $folder)
1780 $zebra_class = ($nestLevel*$idx)%2 ? 'even' : 'odd';
1783 if ($folder_class = rcmail_folder_classname($folder['id']))
1784 $foldername = rcube_label($folder_class);
1787 $foldername = $folder['name'];
1789 // shorten the folder name to a given length
1790 if ($maxlength && $maxlength>1)
1792 $fname = abbreviate_string($foldername, $maxlength);
1793 if ($fname != $foldername)
1794 $title = ' title="'.Q($foldername).'"';
1795 $foldername = $fname;
1799 // make folder name safe for ids and class names
1800 $folder_id = preg_replace('/[^A-Za-z0-9\-_]/', '', $folder['id']);
1801 $class_name = preg_replace('/[^a-z0-9\-_]/', '', $folder_class ? $folder_class : strtolower($folder['id']));
1803 // set special class for Sent, Drafts, Trash and Junk
1804 if ($folder['id']==$CONFIG['sent_mbox'])
1805 $class_name = 'sent';
1806 else if ($folder['id']==$CONFIG['drafts_mbox'])
1807 $class_name = 'drafts';
1808 else if ($folder['id']==$CONFIG['trash_mbox'])
1809 $class_name = 'trash';
1810 else if ($folder['id']==$CONFIG['junk_mbox'])
1811 $class_name = 'junk';
1813 $js_name = htmlspecialchars(JQ($folder['id']));
1814 $out .= sprintf('<li id="rcmli%s" class="mailbox %s %s%s%s"><a href="%s"'.
1815 ' onclick="return %s.command(\'list\',\'%s\',this)"'.
1816 ' onmouseover="return %s.focus_folder(\'%s\')"' .
1817 ' onmouseout="return %s.unfocus_folder(\'%s\')"' .
1818 ' onmouseup="return %s.folder_mouse_up(\'%s\')"%s>%s</a>',
1822 $unread_count ? ' unread' : '',
1823 $folder['id']==$mbox_name ? ' selected' : '',
1824 Q(rcmail_url('', array('_mbox' => $folder['id']))),
1836 if (!empty($folder['folders']))
1837 $out .= "\n<ul>\n" . rcmail_render_folder_tree_html($folder['folders'], $mbox_name, $maxlength, $nestLevel+1) . "</ul>\n";
1848 * Return html for a flat list <select> for the mailbox tree
1851 function rcmail_render_folder_tree_select(&$arrFolders, &$mbox_name, $maxlength, $nestLevel=0)
1853 global $IMAP, $OUTPUT;
1857 foreach ($arrFolders as $key=>$folder)
1859 if ($folder_class = rcmail_folder_classname($folder['id']))
1860 $foldername = rcube_label($folder_class);
1863 $foldername = $folder['name'];
1865 // shorten the folder name to a given length
1866 if ($maxlength && $maxlength>1)
1867 $foldername = abbreviate_string($foldername, $maxlength);
1870 $out .= sprintf('<option value="%s">%s%s</option>'."\n",
1871 htmlspecialchars($folder['id']),
1872 str_repeat(' ', $nestLevel*4),
1875 if (!empty($folder['folders']))
1876 $out .= rcmail_render_folder_tree_select($folder['folders'], $mbox_name, $maxlength, $nestLevel+1);
1886 * Return internal name for the given folder if it matches the configured special folders
1889 function rcmail_folder_classname($folder_id)
1894 $folder_lc = strtolower($folder_id);
1896 // for these mailboxes we have localized labels and css classes
1897 foreach (array('inbox', 'sent', 'drafts', 'trash', 'junk') as $smbx)
1899 if ($folder_lc == $smbx || $folder_id == $CONFIG[$smbx.'_mbox'])
1908 * Try to localize the given IMAP folder name.
1909 * UTF-7 decode it in case no localized text was found
1911 * @param string Folder name
1912 * @return string Localized folder name in UTF-8 encoding
1914 function rcmail_localize_foldername($name)
1916 if ($folder_class = rcmail_folder_classname($name))
1917 return rcube_label($folder_class);
1919 return rcube_charset_convert($name, 'UTF-7');