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 1145 2008-02-27 13:39:22Z 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';
75 // use database for storing session data
76 include_once('include/session.inc');
80 $sess_id = session_id();
82 // create session and set session vars
83 if (!isset($_SESSION['auth_time']))
85 $_SESSION['user_lang'] = rcube_language_prop($CONFIG['locale_string']);
86 $_SESSION['auth_time'] = time();
87 $_SESSION['temp'] = true;
90 // set session vars global
91 $sess_user_lang = rcube_language_prop($_SESSION['user_lang']);
94 $USER = new rcube_user($_SESSION['user_id']);
96 // overwrite config with user preferences
97 $CONFIG = array_merge($CONFIG, (array)$USER->get_prefs());
100 // reset some session parameters when changing task
101 if ($_SESSION['task'] != $task)
102 unset($_SESSION['page']);
104 // set current task to session
105 $_SESSION['task'] = $task;
107 // create IMAP object
113 if ($CONFIG['locale_string'])
114 setlocale(LC_ALL, $CONFIG['locale_string']);
115 else if ($sess_user_lang)
116 setlocale(LC_ALL, $sess_user_lang);
119 register_shutdown_function('rcmail_shutdown');
124 * Load roundcube configuration array
126 * @return array Named configuration parameters
128 function rcmail_load_config()
130 global $INSTALL_PATH;
133 include_once('config/main.inc.php');
134 $conf = is_array($rcmail_config) ? $rcmail_config : array();
136 // load host-specific configuration
137 rcmail_load_host_config($conf);
139 $conf['skin_path'] = $conf['skin_path'] ? unslashify($conf['skin_path']) : 'skins/default';
142 include_once('config/db.inc.php');
143 $conf = array_merge($conf, $rcmail_config);
145 if (empty($conf['log_dir']))
146 $conf['log_dir'] = $INSTALL_PATH.'logs';
148 $conf['log_dir'] = unslashify($conf['log_dir']);
150 // set PHP error logging according to config
151 if ($conf['debug_level'] & 1)
153 ini_set('log_errors', 1);
154 ini_set('error_log', $conf['log_dir'].'/errors');
156 if ($conf['debug_level'] & 4)
157 ini_set('display_errors', 1);
159 ini_set('display_errors', 0);
166 * Load a host-specific config file if configured
167 * This will merge the host specific configuration with the given one
169 * @param array Global configuration parameters
171 function rcmail_load_host_config(&$config)
175 if (is_array($config['include_host_config']))
176 $fname = $config['include_host_config'][$_SERVER['HTTP_HOST']];
177 else if (!empty($config['include_host_config']))
178 $fname = preg_replace('/[^a-z0-9\.\-_]/i', '', $_SERVER['HTTP_HOST']) . '.inc.php';
180 if ($fname && is_file('config/'.$fname))
182 include('config/'.$fname);
183 $config = array_merge($config, $rcmail_config);
189 * Create unique authorization hash
191 * @param string Session ID
192 * @param int Timestamp
193 * @return string The generated auth hash
195 function rcmail_auth_hash($sess_id, $ts)
199 $auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
202 $CONFIG['ip_check'] ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
203 $_SERVER['HTTP_USER_AGENT']);
205 if (function_exists('sha1'))
206 return sha1($auth_string);
208 return md5($auth_string);
213 * Check the auth hash sent by the client against the local session credentials
215 * @return boolean True if valid, False if not
217 function rcmail_authenticate_session()
219 global $CONFIG, $SESS_CLIENT_IP, $SESS_CHANGED;
221 // advanced session authentication
222 if ($CONFIG['double_auth'])
225 $valid = ($_COOKIE['sessauth'] == rcmail_auth_hash(session_id(), $_SESSION['auth_time']) ||
226 $_COOKIE['sessauth'] == rcmail_auth_hash(session_id(), $_SESSION['last_auth']));
228 // renew auth cookie every 5 minutes (only for GET requests)
229 if (!$valid || ($_SERVER['REQUEST_METHOD']!='POST' && $now-$_SESSION['auth_time'] > 300))
231 $_SESSION['last_auth'] = $_SESSION['auth_time'];
232 $_SESSION['auth_time'] = $now;
233 setcookie('sessauth', rcmail_auth_hash(session_id(), $now));
237 $valid = $CONFIG['ip_check'] ? $_SERVER['REMOTE_ADDR'] == $SESS_CLIENT_IP : true;
239 // check session filetime
240 if (!empty($CONFIG['session_lifetime']) && isset($SESS_CHANGED)
241 && $SESS_CHANGED + $CONFIG['session_lifetime']*60 < time())
249 * Create global IMAP object and connect to server
251 * @param boolean True if connection should be established
253 function rcmail_imap_init($connect=FALSE)
255 global $CONFIG, $DB, $IMAP, $OUTPUT;
257 $IMAP = new rcube_imap($DB);
258 $IMAP->debug_level = $CONFIG['debug_level'];
259 $IMAP->skip_deleted = $CONFIG['skip_deleted'];
262 // connect with stored session data
265 if (!($conn = $IMAP->connect($_SESSION['imap_host'], $_SESSION['username'], decrypt_passwd($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl'])))
266 $OUTPUT->show_message('imaperror', 'error');
268 rcmail_set_imap_prop();
271 // enable caching of imap data
272 if ($CONFIG['enable_caching']===TRUE)
273 $IMAP->set_caching(TRUE);
275 // set pagesize from config
276 if (isset($CONFIG['pagesize']))
277 $IMAP->set_pagesize($CONFIG['pagesize']);
282 * Set root dir and last stored mailbox
283 * This must be done AFTER connecting to the server!
285 function rcmail_set_imap_prop()
287 global $CONFIG, $IMAP;
289 // set root dir from config
290 if (!empty($CONFIG['imap_root']))
291 $IMAP->set_rootdir($CONFIG['imap_root']);
293 if (is_array($CONFIG['default_imap_folders']))
294 $IMAP->set_default_mailboxes($CONFIG['default_imap_folders']);
296 if (!empty($_SESSION['mbox']))
297 $IMAP->set_mailbox($_SESSION['mbox']);
298 if (isset($_SESSION['page']))
299 $IMAP->set_page($_SESSION['page']);
304 * Do these things on script shutdown
306 function rcmail_shutdown()
308 global $IMAP, $CONTACTS;
310 if (is_object($IMAP))
313 $IMAP->write_cache();
316 if (is_object($CONTACTS))
319 // before closing the database connection, write session data
320 session_write_close();
325 * Destroy session data and remove cookie
327 function rcmail_kill_session()
331 if ((isset($_SESSION['sort_col']) && $_SESSION['sort_col']!=$a_user_prefs['message_sort_col']) ||
332 (isset($_SESSION['sort_order']) && $_SESSION['sort_order']!=$a_user_prefs['message_sort_order']))
334 $a_user_prefs = array('message_sort_col' => $_SESSION['sort_col'], 'message_sort_order' => $_SESSION['sort_order']);
335 $USER->save_prefs($a_user_prefs);
338 $_SESSION = array('user_lang' => $GLOBALS['sess_user_lang'], 'auth_time' => time(), 'temp' => true);
339 setcookie('sessauth', '-del-', time()-60);
345 * Return correct name for a specific database table
347 * @param string Table name
348 * @return string Translated table name
350 function get_table_name($table)
354 // return table name if configured
355 $config_key = 'db_table_'.$table;
357 if (strlen($CONFIG[$config_key]))
358 return $CONFIG[$config_key];
365 * Return correct name for a specific database sequence
366 * (used for Postres only)
368 * @param string Secuence name
369 * @return string Translated sequence name
371 function get_sequence_name($sequence)
375 // return table name if configured
376 $config_key = 'db_sequence_'.$sequence;
378 if (strlen($CONFIG[$config_key]))
379 return $CONFIG[$config_key];
386 * Check the given string and returns language properties
388 * @param string Language code
389 * @param string Peropert name
390 * @return string Property value
392 function rcube_language_prop($lang, $prop='lang')
394 global $INSTALL_PATH;
395 static $rcube_languages, $rcube_language_aliases, $rcube_charsets;
397 if (empty($rcube_languages))
398 @include($INSTALL_PATH.'program/localization/index.inc');
400 // check if we have an alias for that language
401 if (!isset($rcube_languages[$lang]) && isset($rcube_language_aliases[$lang]))
402 $lang = $rcube_language_aliases[$lang];
404 // try the first two chars
405 if (!isset($rcube_languages[$lang]) && strlen($lang)>2)
407 $lang = substr($lang, 0, 2);
408 $lang = rcube_language_prop($lang);
411 if (!isset($rcube_languages[$lang]))
414 // language has special charset configured
415 if (isset($rcube_charsets[$lang]))
416 $charset = $rcube_charsets[$lang];
421 if ($prop=='charset')
429 * Init output object for GUI and add common scripts.
430 * This will instantiate a rcmail_template object and set
431 * environment vars according to the current session and configuration
433 function rcmail_load_gui()
435 global $CONFIG, $OUTPUT, $sess_user_lang;
438 $OUTPUT = new rcmail_template($CONFIG, $GLOBALS['_task']);
439 $OUTPUT->set_env('comm_path', $GLOBALS['COMM_PATH']);
441 if (is_array($CONFIG['javascript_config']))
443 foreach ($CONFIG['javascript_config'] as $js_config_var)
444 $OUTPUT->set_env($js_config_var, $CONFIG[$js_config_var]);
447 if (!empty($GLOBALS['_framed']))
448 $OUTPUT->set_env('framed', true);
450 // set locale setting
451 rcmail_set_locale($sess_user_lang);
453 // set user-selected charset
454 if (!empty($CONFIG['charset']))
455 $OUTPUT->set_charset($CONFIG['charset']);
457 // register common UI objects
458 $OUTPUT->add_handlers(array(
459 'loginform' => 'rcmail_login_form',
460 'username' => 'rcmail_current_username',
461 'message' => 'rcmail_message_container',
462 'charsetselector' => 'rcmail_charset_selector',
465 // add some basic label to client
466 if (!$OUTPUT->ajax_call)
467 rcube_add_label('loading', 'movingmessage');
472 * Set localization charset based on the given language.
473 * This also creates a global property for mbstring usage.
475 function rcmail_set_locale($lang)
477 global $OUTPUT, $MBSTRING;
478 static $s_mbstring_loaded = NULL;
480 // settings for mbstring module (by Tadashi Jokagi)
481 if (is_null($s_mbstring_loaded))
482 $MBSTRING = $s_mbstring_loaded = extension_loaded("mbstring");
484 $MBSTRING = $s_mbstring_loaded = FALSE;
487 mb_internal_encoding(RCMAIL_CHARSET);
489 $OUTPUT->set_charset(rcube_language_prop($lang, 'charset'));
494 * Auto-select IMAP host based on the posted login information
496 * @return string Selected IMAP host
498 function rcmail_autoselect_host()
502 $host = isset($_POST['_host']) ? get_input_value('_host', RCUBE_INPUT_POST) : $CONFIG['default_host'];
505 list($user, $domain) = explode('@', get_input_value('_user', RCUBE_INPUT_POST));
508 foreach ($host as $imap_host => $mail_domains)
509 if (is_array($mail_domains) && in_array($domain, $mail_domains))
516 // take the first entry if $host is still an array
518 $host = array_shift($host);
526 * Perfom login to the IMAP server and to the webmail service.
527 * This will also create a new user entry if auto_create_user is configured.
529 * @param string IMAP user name
530 * @param string IMAP password
531 * @param string IMAP host
532 * @return boolean True on success, False on failure
534 function rcmail_login($user, $pass, $host=NULL)
536 global $CONFIG, $IMAP, $DB, $USER, $sess_user_lang;
540 $host = $CONFIG['default_host'];
542 // Validate that selected host is in the list of configured hosts
543 if (is_array($CONFIG['default_host']))
546 foreach ($CONFIG['default_host'] as $key => $host_allowed)
548 if (!is_numeric($key))
549 $host_allowed = $key;
550 if ($host == $host_allowed)
559 else if (!empty($CONFIG['default_host']) && $host != $CONFIG['default_host'])
563 $a_host = parse_url($host);
566 $host = $a_host['host'];
567 $imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? $a_host['scheme'] : null;
568 $imap_port = isset($a_host['port']) ? $a_host['port'] : ($imap_ssl ? 993 : $CONFIG['default_port']);
571 $imap_port = $CONFIG['default_port'];
574 /* Modify username with domain if required
575 Inspired by Marco <P0L0_notspam_binware.org>
577 // Check if we need to add domain
578 if (!empty($CONFIG['username_domain']) && !strpos($user, '@'))
580 if (is_array($CONFIG['username_domain']) && isset($CONFIG['username_domain'][$host]))
581 $user .= '@'.$CONFIG['username_domain'][$host];
582 else if (is_string($CONFIG['username_domain']))
583 $user .= '@'.$CONFIG['username_domain'];
586 // try to resolve email address from virtuser table
587 if (!empty($CONFIG['virtuser_file']) && strpos($user, '@'))
588 $user = rcube_user::email2user($user);
590 // lowercase username if it's an e-mail address (#1484473)
591 if (strpos($user, '@'))
592 $user = strtolower($user);
594 // query if user already registered
595 if ($existing = rcube_user::query($user, $host))
598 // user already registered -> overwrite username
601 $user_id = $USER->ID;
602 $user = $USER->data['username'];
605 // exit if IMAP login failed
606 if (!($imap_login = $IMAP->connect($host, $user, $pass, $imap_port, $imap_ssl)))
609 // user already registered
613 $CONFIG = array_merge($CONFIG, (array)$USER->get_prefs());
615 // set user specific language
616 if (!empty($USER->data['language']))
617 $sess_user_lang = $_SESSION['user_lang'] = $USER->data['language'];
619 // update user's record
622 // create new system user
623 else if ($CONFIG['auto_create_user'])
625 if ($created = rcube_user::create($user, $host))
629 // get existing mailboxes
630 $a_mailboxes = $IMAP->list_mailboxes();
638 'file' => "config/main.inc.php",
639 'message' => "Acces denied for new user $user. 'auto_create_user' is disabled"
645 $_SESSION['user_id'] = $USER->ID;
646 $_SESSION['username'] = $USER->data['username'];
647 $_SESSION['imap_host'] = $host;
648 $_SESSION['imap_port'] = $imap_port;
649 $_SESSION['imap_ssl'] = $imap_ssl;
650 $_SESSION['user_lang'] = $sess_user_lang;
651 $_SESSION['password'] = encrypt_passwd($pass);
652 $_SESSION['login_time'] = mktime();
654 // force reloading complete list of subscribed mailboxes
655 rcmail_set_imap_prop();
656 $IMAP->clear_cache('mailboxes');
658 if ($CONFIG['create_default_folders'])
659 $IMAP->create_default_folders();
669 * Load virtuser table in array
671 * @return array Virtuser table entries
673 function rcmail_getvirtualfile()
676 if (empty($CONFIG['virtuser_file']) || !is_file($CONFIG['virtuser_file']))
680 $a_lines = file($CONFIG['virtuser_file']);
686 * Find matches of the given pattern in virtuser table
688 * @param string Regular expression to search for
689 * @return array Matching entries
691 function rcmail_findinvirtual($pattern)
694 $virtual = rcmail_getvirtualfile();
698 // check each line for matches
699 foreach ($virtual as $line)
702 if (empty($line) || $line{0}=='#')
705 if (eregi($pattern, $line))
714 * Overwrite action variable
716 * @param string New action value
718 function rcmail_overwrite_action($action)
721 $GLOBALS['_action'] = $action;
722 $OUTPUT->set_env('action', $action);
727 * Compose an URL for a specific action
729 * @param string Request action
730 * @param array More URL parameters
731 * @param string Request task (omit if the same)
732 * @return The application URL
734 function rcmail_url($action, $p=array(), $task=null)
736 global $MAIN_TASKS, $COMM_PATH;
740 if ($task && in_array($task, $MAIN_TASKS))
741 $base = ereg_replace('_task=[a-z]+', '_task='.$task, $COMM_PATH);
744 foreach ($p as $key => $val)
745 $qstring .= '&'.urlencode($key).'='.urlencode($val);
747 return $base . ($action ? '&_action='.$action : '') . $qstring;
752 function show_message($message, $type='notice', $vars=NULL)
755 $OUTPUT->show_message($message, $type, $vars);
760 * Encrypt IMAP password using DES encryption
762 * @param string Password to encrypt
763 * @return string Encryprted string
765 function encrypt_passwd($pass)
767 if (function_exists('mcrypt_module_open') && ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_ECB, ""))) {
768 $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
769 mcrypt_generic_init($td, get_des_key(), $iv);
770 $cypher = mcrypt_generic($td, $pass);
771 mcrypt_generic_deinit($td);
772 mcrypt_module_close($td);
774 else if (function_exists('des')) {
775 $cypher = des(get_des_key(), $pass, 1, 0, NULL);
784 'message' => "Could not convert encrypt password. Make sure Mcrypt is installed or lib/des.inc is available"
788 return base64_encode($cypher);
793 * Decrypt IMAP password using DES encryption
795 * @param string Encrypted password
796 * @return string Plain password
798 function decrypt_passwd($cypher)
800 if (function_exists('mcrypt_module_open') && ($td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_ECB, ""))) {
801 $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
802 mcrypt_generic_init($td, get_des_key(), $iv);
803 $pass = mdecrypt_generic($td, base64_decode($cypher));
804 mcrypt_generic_deinit($td);
805 mcrypt_module_close($td);
807 else if (function_exists('des')) {
808 $pass = des(get_des_key(), base64_decode($cypher), 0, 0, NULL);
811 $pass = base64_decode($cypher);
814 return preg_replace('/\x00/', '', $pass);
819 * Return a 24 byte key for the DES encryption
821 * @return string DES encryption key
823 function get_des_key()
825 $key = !empty($GLOBALS['CONFIG']['des_key']) ? $GLOBALS['CONFIG']['des_key'] : 'rcmail?24BitPwDkeyF**ECB';
828 // make sure the key is exactly 24 chars long
830 $key .= str_repeat('_', 24-$len);
839 * Read directory program/localization and return a list of available languages
841 * @return array List of available localizations
843 function rcube_list_languages()
845 global $CONFIG, $INSTALL_PATH;
846 static $sa_languages = array();
848 if (!sizeof($sa_languages))
850 @include($INSTALL_PATH.'program/localization/index.inc');
852 if ($dh = @opendir($INSTALL_PATH.'program/localization'))
854 while (($name = readdir($dh)) !== false)
856 if ($name{0}=='.' || !is_dir($INSTALL_PATH.'program/localization/'.$name))
859 if ($label = $rcube_languages[$name])
860 $sa_languages[$name] = $label ? $label : $name;
865 return $sa_languages;
870 * Add a localized label to the client environment
872 function rcube_add_label()
876 $arg_list = func_get_args();
877 foreach ($arg_list as $i => $name)
878 $OUTPUT->command('add_label', $name, rcube_label($name));
883 * Garbage collector function for temp files.
884 * Remove temp files older than two days
886 function rcmail_temp_gc()
888 $tmp = unslashify($CONFIG['temp_dir']);
889 $expire = mktime() - 172800; // expire in 48 hours
891 if ($dir = opendir($tmp))
893 while (($fname = readdir($dir)) !== false)
895 if ($fname{0} == '.')
898 if (filemtime($tmp.'/'.$fname) < $expire)
899 @unlink($tmp.'/'.$fname);
908 * Garbage collector for cache entries.
909 * Remove all expired message cache records
911 function rcmail_message_cache_gc()
915 // no cache lifetime configured
916 if (empty($CONFIG['message_cache_lifetime']))
919 // get target timestamp
920 $ts = get_offset_time($CONFIG['message_cache_lifetime'], -1);
922 $DB->query("DELETE FROM ".get_table_name('messages')."
923 WHERE created < ".$DB->fromunixtime($ts));
928 * Convert a string from one charset to another.
929 * Uses mbstring and iconv functions if possible
931 * @param string Input string
932 * @param string Suspected charset of the input string
933 * @param string Target charset to convert to; defaults to RCMAIL_CHARSET
934 * @return Converted string
936 function rcube_charset_convert($str, $from, $to=NULL)
939 static $convert_warning = false;
941 $from = strtoupper($from);
942 $to = $to==NULL ? strtoupper(RCMAIL_CHARSET) : strtoupper($to);
943 $error = false; $conv = null;
945 if ($from==$to || $str=='' || empty($from))
949 'UNKNOWN-8BIT' => 'ISO-8859-15',
950 'X-UNKNOWN' => 'ISO-8859-15',
951 'X-USER-DEFINED' => 'ISO-8859-15',
952 'ISO-8859-8-I' => 'ISO-8859-8',
953 'KS_C_5601-1987' => 'EUC-KR',
954 'GB2312' => 'GB18030'
957 // convert charset using iconv module
958 if (function_exists('iconv') && $from != 'UTF-7' && $to != 'UTF-7')
960 return iconv(($aliases[$from] ? $aliases[$from] : $from), ($aliases[$to] ? $aliases[$to] : $to) . "//IGNORE", $str);
963 // convert charset using mbstring module
966 $mb_map = $aliases + array('UTF-7' => 'UTF7-IMAP');
968 // return if convert succeeded
969 if (($out = mb_convert_encoding($str, ($mb_map[$to] ? $mb_map[$to] : $to), ($mb_map[$from] ? $mb_map[$from] : $from))) != '')
974 if (class_exists('utf8'))
977 // convert string to UTF-8
978 if ($from == 'UTF-7')
979 $str = utf7_to_utf8($str);
980 else if (($from == 'ISO-8859-1') && function_exists('utf8_encode'))
981 $str = utf8_encode($str);
982 else if ($from != 'UTF-8' && $conv)
984 $conv->loadCharset($from);
985 $str = $conv->strToUtf8($str);
987 else if ($from != 'UTF-8')
990 // encode string for output
992 return utf8_to_utf7($str);
993 else if ($to == 'ISO-8859-1' && function_exists('utf8_decode'))
994 return utf8_decode($str);
995 else if ($to != 'UTF-8' && $conv)
997 $conv->loadCharset($to);
998 return $conv->utf8ToStr($str);
1000 else if ($to != 'UTF-8')
1004 if ($error && !$convert_warning)
1010 'message' => "Could not convert string charset. Make sure iconv is installed or lib/utf8.class is available"
1013 $convert_warning = true;
1016 // return UTF-8 string
1022 * Replacing specials characters to a specific encoding type
1024 * @param string Input string
1025 * @param string Encoding type: text|html|xml|js|url
1026 * @param string Replace mode for tags: show|replace|remove
1027 * @param boolean Convert newlines
1028 * @return The quoted string
1030 function rep_specialchars_output($str, $enctype='', $mode='', $newlines=TRUE)
1032 global $OUTPUT_TYPE, $OUTPUT;
1033 static $html_encode_arr, $js_rep_table, $xml_rep_table;
1036 $enctype = $GLOBALS['OUTPUT_TYPE'];
1038 // encode for plaintext
1039 if ($enctype=='text')
1040 return str_replace("\r\n", "\n", $mode=='remove' ? strip_tags($str) : $str);
1042 // encode for HTML output
1043 if ($enctype=='html')
1045 if (!$html_encode_arr)
1047 $html_encode_arr = get_html_translation_table(HTML_SPECIALCHARS);
1048 unset($html_encode_arr['?']);
1051 $ltpos = strpos($str, '<');
1052 $encode_arr = $html_encode_arr;
1054 // don't replace quotes and html tags
1055 if (($mode=='show' || $mode=='') && $ltpos!==false && strpos($str, '>', $ltpos)!==false)
1057 unset($encode_arr['"']);
1058 unset($encode_arr['<']);
1059 unset($encode_arr['>']);
1060 unset($encode_arr['&']);
1062 else if ($mode=='remove')
1063 $str = strip_tags($str);
1065 // avoid douple quotation of &
1066 $out = preg_replace('/&([a-z]{2,5}|#[0-9]{2,4});/', '&\\1;', strtr($str, $encode_arr));
1068 return $newlines ? nl2br($out) : $out;
1071 if ($enctype=='url')
1072 return rawurlencode($str);
1074 // if the replace tables for XML and JS are not yet defined
1077 $js_rep_table = $xml_rep_table = array();
1078 $xml_rep_table['&'] = '&';
1080 for ($c=160; $c<256; $c++) // can be increased to support more charsets
1082 $xml_rep_table[Chr($c)] = "&#$c;";
1084 if ($OUTPUT->get_charset()=='ISO-8859-1')
1085 $js_rep_table[Chr($c)] = sprintf("\\u%04x", $c);
1088 $xml_rep_table['"'] = '"';
1092 if ($enctype=='xml')
1093 return strtr($str, $xml_rep_table);
1095 // encode for javascript use
1098 if ($OUTPUT->get_charset()!='UTF-8')
1099 $str = rcube_charset_convert($str, RCMAIL_CHARSET, $OUTPUT->get_charset());
1101 return preg_replace(array("/\r?\n/", "/\r/"), array('\n', '\n'), addslashes(strtr($str, $js_rep_table)));
1104 // no encoding given -> return original string
1109 * Quote a given string.
1110 * Shortcut function for rep_specialchars_output
1112 * @return string HTML-quoted string
1113 * @see rep_specialchars_output()
1115 function Q($str, $mode='strict', $newlines=TRUE)
1117 return rep_specialchars_output($str, 'html', $mode, $newlines);
1121 * Quote a given string for javascript output.
1122 * Shortcut function for rep_specialchars_output
1124 * @return string JS-quoted string
1125 * @see rep_specialchars_output()
1129 return rep_specialchars_output($str, 'js');
1134 * Read input value and convert it for internal use
1135 * Performs stripslashes() and charset conversion if necessary
1137 * @param string Field name to read
1138 * @param int Source to get value from (GPC)
1139 * @param boolean Allow HTML tags in field value
1140 * @param string Charset to convert into
1141 * @return string Field value or NULL if not available
1143 function get_input_value($fname, $source, $allow_html=FALSE, $charset=NULL)
1148 if ($source==RCUBE_INPUT_GET && isset($_GET[$fname]))
1149 $value = $_GET[$fname];
1150 else if ($source==RCUBE_INPUT_POST && isset($_POST[$fname]))
1151 $value = $_POST[$fname];
1152 else if ($source==RCUBE_INPUT_GPC)
1154 if (isset($_POST[$fname]))
1155 $value = $_POST[$fname];
1156 else if (isset($_GET[$fname]))
1157 $value = $_GET[$fname];
1158 else if (isset($_COOKIE[$fname]))
1159 $value = $_COOKIE[$fname];
1162 // strip slashes if magic_quotes enabled
1163 if ((bool)get_magic_quotes_gpc())
1164 $value = stripslashes($value);
1166 // remove HTML tags if not allowed
1168 $value = strip_tags($value);
1170 // convert to internal charset
1171 if (is_object($OUTPUT))
1172 return rcube_charset_convert($value, $OUTPUT->get_charset(), $charset);
1178 * Remove all non-ascii and non-word chars
1181 function asciiwords($str)
1183 return preg_replace('/[^a-z0-9.-_]/i', '', $str);
1187 * Remove single and double quotes from given string
1189 * @param string Input value
1190 * @return string Dequoted string
1192 function strip_quotes($str)
1194 return preg_replace('/[\'"]/', '', $str);
1199 * Remove new lines characters from given string
1201 * @param string Input value
1202 * @return string Stripped string
1204 function strip_newlines($str)
1206 return preg_replace('/[\r\n]/', '', $str);
1211 * Check if a specific template exists
1213 * @param string Template name
1214 * @return boolean True if template exists
1216 function template_exists($name)
1219 $skin_path = $CONFIG['skin_path'];
1221 // check template file
1222 return is_file("$skin_path/templates/$name.html");
1227 * Wrapper for rcmail_template::parse()
1230 function parse_template($name='main', $exit=true)
1232 $GLOBALS['OUTPUT']->parse($name, $exit);
1237 * Create a HTML table based on the given data
1239 * @param array Named table attributes
1240 * @param mixed Table row data. Either a two-dimensional array or a valid SQL result set
1241 * @param array List of cols to show
1242 * @param string Name of the identifier col
1243 * @return string HTML table code
1245 function rcube_table_output($attrib, $table_data, $a_show_cols, $id_col)
1249 // allow the following attributes to be added to the <table> tag
1250 $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
1252 $table = '<table' . $attrib_str . ">\n";
1255 $table .= "<thead><tr>\n";
1257 foreach ($a_show_cols as $col)
1258 $table .= '<td class="'.$col.'">' . Q(rcube_label($col)) . "</td>\n";
1260 $table .= "</tr></thead>\n<tbody>\n";
1263 if (!is_array($table_data))
1265 while ($table_data && ($sql_arr = $DB->fetch_assoc($table_data)))
1267 $zebra_class = $c%2 ? 'even' : 'odd';
1269 $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $sql_arr[$id_col]);
1272 foreach ($a_show_cols as $col)
1274 $cont = Q($sql_arr[$col]);
1275 $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1278 $table .= "</tr>\n";
1284 foreach ($table_data as $row_data)
1286 $zebra_class = $c%2 ? 'even' : 'odd';
1288 $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $row_data[$id_col]);
1291 foreach ($a_show_cols as $col)
1293 $cont = Q($row_data[$col]);
1294 $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1297 $table .= "</tr>\n";
1302 // complete message table
1303 $table .= "</tbody></table>\n";
1310 * Create an edit field for inclusion on a form
1312 * @param string col field name
1313 * @param string value field value
1314 * @param array attrib HTML element attributes for field
1315 * @param string type HTML element type (default 'text')
1316 * @return string HTML field definition
1318 function rcmail_get_edit_field($col, $value, $attrib, $type='text')
1321 $attrib['name'] = $fname;
1323 if ($type=='checkbox')
1325 $attrib['value'] = '1';
1326 $input = new checkbox($attrib);
1328 else if ($type=='textarea')
1330 $attrib['cols'] = $attrib['size'];
1331 $input = new textarea($attrib);
1334 $input = new textfield($attrib);
1336 // use value from post
1337 if (!empty($_POST[$fname]))
1338 $value = get_input_value($fname, RCUBE_INPUT_POST);
1340 $out = $input->show($value);
1347 * Return the mail domain configured for the given host
1349 * @param string IMAP host
1350 * @return string Resolved SMTP host
1352 function rcmail_mail_domain($host)
1357 if (is_array($CONFIG['mail_domain']))
1359 if (isset($CONFIG['mail_domain'][$host]))
1360 $domain = $CONFIG['mail_domain'][$host];
1362 else if (!empty($CONFIG['mail_domain']))
1363 $domain = $CONFIG['mail_domain'];
1370 * Replace all css definitions with #container [def]
1372 * @param string CSS source code
1373 * @param string Container ID to use as prefix
1374 * @return string Modified CSS source
1376 function rcmail_mod_css_styles($source, $container_id, $base_url = '')
1378 $a_css_values = array();
1381 // cut out all contents between { and }
1382 while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos)))
1384 $key = sizeof($a_css_values);
1385 $a_css_values[$key] = substr($source, $pos+1, $pos2-($pos+1));
1386 $source = substr($source, 0, $pos+1) . "<<str_replacement[$key]>>" . substr($source, $pos2, strlen($source)-$pos2);
1390 // remove html commends and add #container to each tag selector.
1391 // also replace body definition because we also stripped off the <body> tag
1392 $styles = preg_replace(
1394 '/(^\s*<!--)|(-->\s*$)/',
1395 '/(^\s*|,\s*|\}\s*)([a-z0-9\._#][a-z0-9\.\-_]*)/im',
1396 '/@import\s+(url\()?[\'"]?([^\)\'"]+)[\'"]?(\))?/ime',
1397 '/<<str_replacement\[([0-9]+)\]>>/e',
1398 "/$container_id\s+body/i"
1402 "\\1#$container_id \\2",
1403 "sprintf(\"@import url('./bin/modcss.php?u=%s&c=%s')\", urlencode(make_absolute_url('\\2','$base_url')), urlencode($container_id))",
1404 "\$a_css_values[\\1]",
1405 "$container_id div.rcmBody"
1413 * Try to autodetect operating system and find the correct line endings
1415 * @return string The appropriate mail header delimiter
1417 function rcmail_header_delm()
1421 // use the configured delimiter for headers
1422 if (!empty($CONFIG['mail_header_delimiter']))
1423 return $CONFIG['mail_header_delimiter'];
1424 else if (strtolower(substr(PHP_OS, 0, 3)=='win'))
1426 else if (strtolower(substr(PHP_OS, 0, 3)=='mac'))
1434 * Compose a valid attribute string for HTML tags
1436 * @param array Named tag attributes
1437 * @param array List of allowed attributes
1438 * @return string HTML formatted attribute string
1440 function create_attrib_string($attrib, $allowed_attribs=array('id', 'class', 'style'))
1442 // allow the following attributes to be added to the <iframe> tag
1444 foreach ($allowed_attribs as $a)
1445 if (isset($attrib[$a]))
1446 $attrib_str .= sprintf(' %s="%s"', $a, str_replace('"', '"', $attrib[$a]));
1453 * Convert a HTML attribute string attributes to an associative array (name => value)
1455 * @param string Input string
1456 * @return array Key-value pairs of parsed attributes
1458 function parse_attrib_string($str)
1461 preg_match_all('/\s*([-_a-z]+)=(["\'])([^"]+)\2/Ui', stripslashes($str), $regs, PREG_SET_ORDER);
1463 // convert attributes to an associative array (name => value)
1465 foreach ($regs as $attr)
1466 $attrib[strtolower($attr[1])] = $attr[3];
1473 * Convert the given date to a human readable form
1474 * This uses the date formatting properties from config
1476 * @param mixed Date representation (string or timestamp)
1477 * @param string Date format to use
1478 * @return string Formatted date string
1480 function format_date($date, $format=NULL)
1482 global $CONFIG, $sess_user_lang;
1486 if (is_numeric($date))
1488 else if (!empty($date))
1489 $ts = @strtotime($date);
1494 // get user's timezone
1495 $tz = $CONFIG['timezone'];
1496 if ($CONFIG['dst_active'])
1499 // convert time to user's timezone
1500 $timestamp = $ts - date('Z', $ts) + ($tz * 3600);
1502 // get current timestamp in user's timezone
1503 $now = time(); // local time
1504 $now -= (int)date('Z'); // make GMT time
1505 $now += ($tz * 3600); // user's time
1506 $now_date = getdate($now);
1508 $today_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday'], $now_date['year']);
1509 $week_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday']-6, $now_date['year']);
1511 // define date format depending on current time
1512 if ($CONFIG['prettydate'] && !$format && $timestamp > $today_limit && $timestamp < $now)
1513 return sprintf('%s %s', rcube_label('today'), date($CONFIG['date_today'] ? $CONFIG['date_today'] : 'H:i', $timestamp));
1514 else if ($CONFIG['prettydate'] && !$format && $timestamp > $week_limit && $timestamp < $now)
1515 $format = $CONFIG['date_short'] ? $CONFIG['date_short'] : 'D H:i';
1517 $format = $CONFIG['date_long'] ? $CONFIG['date_long'] : 'd.m.Y H:i';
1520 // parse format string manually in order to provide localized weekday and month names
1521 // an alternative would be to convert the date() format string to fit with strftime()
1523 for($i=0; $i<strlen($format); $i++)
1525 if ($format{$i}=='\\') // skip escape chars
1528 // write char "as-is"
1529 if ($format{$i}==' ' || $format{$i-1}=='\\')
1530 $out .= $format{$i};
1532 else if ($format{$i}=='D')
1533 $out .= rcube_label(strtolower(date('D', $timestamp)));
1535 else if ($format{$i}=='l')
1536 $out .= rcube_label(strtolower(date('l', $timestamp)));
1537 // month name (short)
1538 else if ($format{$i}=='M')
1539 $out .= rcube_label(strtolower(date('M', $timestamp)));
1540 // month name (long)
1541 else if ($format{$i}=='F')
1542 $out .= rcube_label(strtolower(date('F', $timestamp)));
1544 $out .= date($format{$i}, $timestamp);
1552 * Compose a valid representaion of name and e-mail address
1554 * @param string E-mail address
1555 * @param string Person name
1556 * @return string Formatted string
1558 function format_email_recipient($email, $name='')
1560 if ($name && $name != $email)
1561 return sprintf('%s <%s>', strpos($name, ",") ? '"'.$name.'"' : $name, $email);
1568 /****** debugging functions ********/
1572 * Print or write debug messages
1574 * @param mixed Debug message or data
1576 function console($msg)
1578 if (!is_string($msg))
1579 $msg = var_export($msg, true);
1581 if (!($GLOBALS['CONFIG']['debug_level'] & 4))
1582 write_log('console', $msg);
1583 else if ($GLOBALS['REMOTE_REQUEST'])
1584 print "/*\n $msg \n*/\n";
1587 print '<div style="background:#eee; border:1px solid #ccc; margin-bottom:3px; padding:6px"><pre>';
1589 print "</pre></div>\n";
1595 * Append a line to a logfile in the logs directory.
1596 * Date will be added automatically to the line.
1598 * @param $name Name of logfile
1599 * @param $line Line to append
1601 function write_log($name, $line)
1603 global $CONFIG, $INSTALL_PATH;
1605 if (!is_string($line))
1606 $line = var_export($line, true);
1608 $log_entry = sprintf("[%s]: %s\n",
1609 date("d-M-Y H:i:s O", mktime()),
1612 if (empty($CONFIG['log_dir']))
1613 $CONFIG['log_dir'] = $INSTALL_PATH.'logs';
1615 // try to open specific log file for writing
1616 if ($fp = @fopen($CONFIG['log_dir'].'/'.$name, 'a'))
1618 fwrite($fp, $log_entry);
1627 function rcube_timer()
1629 list($usec, $sec) = explode(" ", microtime());
1630 return ((float)$usec + (float)$sec);
1637 function rcube_print_time($timer, $label='Timer')
1639 static $print_count = 0;
1642 $now = rcube_timer();
1643 $diff = $now-$timer;
1646 $label = 'Timer '.$print_count;
1648 console(sprintf("%s: %0.4f sec", $label, $diff));
1653 * Return the mailboxlist in HTML
1655 * @param array Named parameters
1656 * @return string HTML code for the gui object
1658 function rcmail_mailbox_list($attrib)
1660 global $IMAP, $CONFIG, $OUTPUT, $COMM_PATH;
1661 static $s_added_script = FALSE;
1662 static $a_mailboxes;
1664 // add some labels to client
1665 rcube_add_label('purgefolderconfirm');
1666 rcube_add_label('deletemessagesconfirm');
1668 // $mboxlist_start = rcube_timer();
1670 $type = $attrib['type'] ? $attrib['type'] : 'ul';
1671 $add_attrib = $type=='select' ? array('style', 'class', 'id', 'name', 'onchange') :
1672 array('style', 'class', 'id');
1674 if ($type=='ul' && !$attrib['id'])
1675 $attrib['id'] = 'rcmboxlist';
1677 // allow the following attributes to be added to the <ul> tag
1678 $attrib_str = create_attrib_string($attrib, $add_attrib);
1680 $out = '<' . $type . $attrib_str . ">\n";
1682 // add no-selection option
1683 if ($type=='select' && $attrib['noselection'])
1684 $out .= sprintf('<option value="0">%s</option>'."\n",
1685 rcube_label($attrib['noselection']));
1688 $mbox_name = $IMAP->get_mailbox_name();
1690 // build the folders tree
1691 if (empty($a_mailboxes))
1694 $a_folders = $IMAP->list_mailboxes();
1695 $delimiter = $IMAP->get_hierarchy_delimiter();
1696 $a_mailboxes = array();
1698 // rcube_print_time($mboxlist_start, 'list_mailboxes()');
1700 foreach ($a_folders as $folder)
1701 rcmail_build_folder_tree($a_mailboxes, $folder, $delimiter);
1704 // var_dump($a_mailboxes);
1706 if ($type=='select')
1707 $out .= rcmail_render_folder_tree_select($a_mailboxes, $mbox_name, $attrib['maxlength']);
1709 $out .= rcmail_render_folder_tree_html($a_mailboxes, $mbox_name, $attrib['maxlength']);
1711 // rcube_print_time($mboxlist_start, 'render_folder_tree()');
1715 $OUTPUT->add_gui_object('mailboxlist', $attrib['id']);
1717 return $out . "</$type>";
1724 * Create a hierarchical array of the mailbox list
1727 function rcmail_build_folder_tree(&$arrFolders, $folder, $delm='/', $path='')
1729 $pos = strpos($folder, $delm);
1732 $subFolders = substr($folder, $pos+1);
1733 $currentFolder = substr($folder, 0, $pos);
1737 $subFolders = false;
1738 $currentFolder = $folder;
1741 $path .= $currentFolder;
1743 if (!isset($arrFolders[$currentFolder]))
1745 $arrFolders[$currentFolder] = array('id' => $path,
1746 'name' => rcube_charset_convert($currentFolder, 'UTF-7'),
1747 'folders' => array());
1750 if (!empty($subFolders))
1751 rcmail_build_folder_tree($arrFolders[$currentFolder]['folders'], $subFolders, $delm, $path.$delm);
1756 * Return html for a structured list <ul> for the mailbox tree
1759 function rcmail_render_folder_tree_html(&$arrFolders, &$mbox_name, $maxlength, $nestLevel=0)
1761 global $COMM_PATH, $IMAP, $CONFIG, $OUTPUT;
1765 foreach ($arrFolders as $key => $folder)
1767 $zebra_class = ($nestLevel*$idx)%2 ? 'even' : 'odd';
1770 if ($folder_class = rcmail_folder_classname($folder['id']))
1771 $foldername = rcube_label($folder_class);
1774 $foldername = $folder['name'];
1776 // shorten the folder name to a given length
1777 if ($maxlength && $maxlength>1)
1779 $fname = abbreviate_string($foldername, $maxlength);
1780 if ($fname != $foldername)
1781 $title = ' title="'.Q($foldername).'"';
1782 $foldername = $fname;
1786 // add unread message count display
1787 if ($unread_count = $IMAP->messagecount($folder['id'], 'RECENT', ($folder['id']==$mbox_name)))
1788 $foldername .= sprintf(' (%d)', $unread_count);
1790 // make folder name safe for ids and class names
1791 $folder_id = preg_replace('/[^A-Za-z0-9\-_]/', '', $folder['id']);
1792 $class_name = preg_replace('/[^a-z0-9\-_]/', '', $folder_class ? $folder_class : strtolower($folder['id']));
1794 // set special class for Sent, Drafts, Trash and Junk
1795 if ($folder['id']==$CONFIG['sent_mbox'])
1796 $class_name = 'sent';
1797 else if ($folder['id']==$CONFIG['drafts_mbox'])
1798 $class_name = 'drafts';
1799 else if ($folder['id']==$CONFIG['trash_mbox'])
1800 $class_name = 'trash';
1801 else if ($folder['id']==$CONFIG['junk_mbox'])
1802 $class_name = 'junk';
1804 $js_name = htmlspecialchars(JQ($folder['id']));
1805 $out .= sprintf('<li id="rcmli%s" class="mailbox %s %s%s%s"><a href="%s"'.
1806 ' onclick="return %s.command(\'list\',\'%s\',this)"'.
1807 ' onmouseover="return %s.focus_folder(\'%s\')"' .
1808 ' onmouseout="return %s.unfocus_folder(\'%s\')"' .
1809 ' onmouseup="return %s.folder_mouse_up(\'%s\')"%s>%s</a>',
1813 $unread_count ? ' unread' : '',
1814 $folder['id']==$mbox_name ? ' selected' : '',
1815 Q(rcmail_url('', array('_mbox' => $folder['id']))),
1827 if (!empty($folder['folders']))
1828 $out .= "\n<ul>\n" . rcmail_render_folder_tree_html($folder['folders'], $mbox_name, $maxlength, $nestLevel+1) . "</ul>\n";
1839 * Return html for a flat list <select> for the mailbox tree
1842 function rcmail_render_folder_tree_select(&$arrFolders, &$mbox_name, $maxlength, $nestLevel=0)
1844 global $IMAP, $OUTPUT;
1848 foreach ($arrFolders as $key=>$folder)
1850 if ($folder_class = rcmail_folder_classname($folder['id']))
1851 $foldername = rcube_label($folder_class);
1854 $foldername = $folder['name'];
1856 // shorten the folder name to a given length
1857 if ($maxlength && $maxlength>1)
1858 $foldername = abbreviate_string($foldername, $maxlength);
1861 $out .= sprintf('<option value="%s">%s%s</option>'."\n",
1862 htmlspecialchars($folder['id']),
1863 str_repeat(' ', $nestLevel*4),
1866 if (!empty($folder['folders']))
1867 $out .= rcmail_render_folder_tree_select($folder['folders'], $mbox_name, $maxlength, $nestLevel+1);
1877 * Return internal name for the given folder if it matches the configured special folders
1880 function rcmail_folder_classname($folder_id)
1885 $folder_lc = strtolower($folder_id);
1887 // for these mailboxes we have localized labels and css classes
1888 foreach (array('inbox', 'sent', 'drafts', 'trash', 'junk') as $smbx)
1890 if ($folder_lc == $smbx || $folder_id == $CONFIG[$smbx.'_mbox'])
1899 * Try to localize the given IMAP folder name.
1900 * UTF-7 decode it in case no localized text was found
1902 * @param string Folder name
1903 * @return string Localized folder name in UTF-8 encoding
1905 function rcmail_localize_foldername($name)
1907 if ($folder_class = rcmail_folder_classname($name))
1908 return rcube_label($folder_class);
1910 return rcube_charset_convert($name, 'UTF-7');