4 +-----------------------------------------------------------------------+
5 | program/include/main.inc |
7 | This file is part of the RoundCube Webmail client |
8 | Copyright (C) 2005-2007, 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 567 2007-05-17 18:41:24Z thomasb $
22 require_once('lib/des.inc');
23 require_once('lib/utf7.inc');
24 require_once('lib/utf8.class.php');
25 require_once('include/rcmail_template.inc');
28 // define constannts for input reading
29 define('RCUBE_INPUT_GET', 0x0101);
30 define('RCUBE_INPUT_POST', 0x0102);
31 define('RCUBE_INPUT_GPC', 0x0103);
34 // register session and connect to server
35 function rcmail_startup($task='mail')
37 global $sess_id, $sess_user_lang;
38 global $CONFIG, $INSTALL_PATH, $BROWSER, $OUTPUT, $_SESSION, $IMAP, $DB;
41 $BROWSER = rcube_browser();
44 $CONFIG = rcmail_load_config();
46 // set session garbage collecting time according to session_lifetime
47 if (!empty($CONFIG['session_lifetime']))
48 ini_set('session.gc_maxlifetime', ($CONFIG['session_lifetime']) * 120);
50 // prepare DB connection
51 require_once('include/rcube_'.(empty($CONFIG['db_backend']) ? 'db' : $CONFIG['db_backend']).'.inc');
53 $DB = new rcube_db($CONFIG['db_dsnw'], $CONFIG['db_dsnr'], $CONFIG['db_persistent']);
54 $DB->sqlite_initials = $INSTALL_PATH.'SQL/sqlite.initial.sql';
57 // use database for storing session data
58 include_once('include/session.inc');
62 $sess_id = session_id();
64 // create session and set session vars
65 if (!isset($_SESSION['auth_time']))
67 $_SESSION['user_lang'] = rcube_language_prop($CONFIG['locale_string']);
68 $_SESSION['auth_time'] = time();
69 $_SESSION['temp'] = true;
72 // set session vars global
73 $sess_user_lang = rcube_language_prop($_SESSION['user_lang']);
76 // overwrite config with user preferences
77 if (is_array($_SESSION['user_prefs']))
78 $CONFIG = array_merge($CONFIG, $_SESSION['user_prefs']);
81 // reset some session parameters when changing task
82 if ($_SESSION['task'] != $task)
83 unset($_SESSION['page']);
85 // set current task to session
86 $_SESSION['task'] = $task;
94 if ($CONFIG['locale_string'])
95 setlocale(LC_ALL, $CONFIG['locale_string']);
96 else if ($sess_user_lang)
97 setlocale(LC_ALL, $sess_user_lang);
100 register_shutdown_function('rcmail_shutdown');
104 // load roundcube configuration into global var
105 function rcmail_load_config()
107 global $INSTALL_PATH;
110 include_once('config/main.inc.php');
111 $conf = is_array($rcmail_config) ? $rcmail_config : array();
113 // load host-specific configuration
114 rcmail_load_host_config($conf);
116 $conf['skin_path'] = $conf['skin_path'] ? unslashify($conf['skin_path']) : 'skins/default';
119 include_once('config/db.inc.php');
120 $conf = array_merge($conf, $rcmail_config);
122 if (empty($conf['log_dir']))
123 $conf['log_dir'] = $INSTALL_PATH.'logs';
125 $conf['log_dir'] = unslashify($conf['log_dir']);
127 // set PHP error logging according to config
128 if ($conf['debug_level'] & 1)
130 ini_set('log_errors', 1);
131 ini_set('error_log', $conf['log_dir'].'/errors');
133 if ($conf['debug_level'] & 4)
134 ini_set('display_errors', 1);
136 ini_set('display_errors', 0);
142 // load a host-specific config file if configured
143 function rcmail_load_host_config(&$config)
147 if (is_array($config['include_host_config']))
148 $fname = $config['include_host_config'][$_SERVER['HTTP_HOST']];
149 else if (!empty($config['include_host_config']))
150 $fname = preg_replace('/[^a-z0-9\.\-_]/i', '', $_SERVER['HTTP_HOST']) . '.inc.php';
152 if ($fname && is_file('config/'.$fname))
154 include('config/'.$fname);
155 $config = array_merge($config, $rcmail_config);
160 // create authorization hash
161 function rcmail_auth_hash($sess_id, $ts)
165 $auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
168 $CONFIG['ip_check'] ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
169 $_SERVER['HTTP_USER_AGENT']);
171 if (function_exists('sha1'))
172 return sha1($auth_string);
174 return md5($auth_string);
178 // compare the auth hash sent by the client with the local session credentials
179 function rcmail_authenticate_session()
181 global $CONFIG, $SESS_CLIENT_IP, $SESS_CHANGED;
183 // advanced session authentication
184 if ($CONFIG['double_auth'])
187 $valid = ($_COOKIE['sessauth'] == rcmail_auth_hash(session_id(), $_SESSION['auth_time']) ||
188 $_COOKIE['sessauth'] == rcmail_auth_hash(session_id(), $_SESSION['last_auth']));
190 // renew auth cookie every 5 minutes (only for GET requests)
191 if (!$valid || ($_SERVER['REQUEST_METHOD']!='POST' && $now-$_SESSION['auth_time'] > 300))
193 $_SESSION['last_auth'] = $_SESSION['auth_time'];
194 $_SESSION['auth_time'] = $now;
195 setcookie('sessauth', rcmail_auth_hash(session_id(), $now));
199 $valid = $CONFIG['ip_check'] ? $_SERVER['REMOTE_ADDR'] == $SESS_CLIENT_IP : true;
201 // check session filetime
202 if (!empty($CONFIG['session_lifetime']) && isset($SESS_CHANGED) && $SESS_CHANGED + $CONFIG['session_lifetime']*60 < time())
209 // create IMAP object and connect to server
210 function rcmail_imap_init($connect=FALSE)
212 global $CONFIG, $DB, $IMAP, $OUTPUT;
214 $IMAP = new rcube_imap($DB);
215 $IMAP->debug_level = $CONFIG['debug_level'];
216 $IMAP->skip_deleted = $CONFIG['skip_deleted'];
219 // connect with stored session data
222 if (!($conn = $IMAP->connect($_SESSION['imap_host'], $_SESSION['username'], decrypt_passwd($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl'])))
223 $OUTPUT->show_message('imaperror', 'error');
225 rcmail_set_imap_prop();
228 // enable caching of imap data
229 if ($CONFIG['enable_caching']===TRUE)
230 $IMAP->set_caching(TRUE);
232 // set pagesize from config
233 if (isset($CONFIG['pagesize']))
234 $IMAP->set_pagesize($CONFIG['pagesize']);
238 // set root dir and last stored mailbox
239 // this must be done AFTER connecting to the server
240 function rcmail_set_imap_prop()
242 global $CONFIG, $IMAP;
244 // set root dir from config
245 if (!empty($CONFIG['imap_root']))
246 $IMAP->set_rootdir($CONFIG['imap_root']);
248 if (is_array($CONFIG['default_imap_folders']))
249 $IMAP->set_default_mailboxes($CONFIG['default_imap_folders']);
251 if (!empty($_SESSION['mbox']))
252 $IMAP->set_mailbox($_SESSION['mbox']);
253 if (isset($_SESSION['page']))
254 $IMAP->set_page($_SESSION['page']);
258 // do these things on script shutdown
259 function rcmail_shutdown()
263 if (is_object($IMAP))
266 $IMAP->write_cache();
269 // before closing the database connection, write session data
270 session_write_close();
274 // destroy session data and remove cookie
275 function rcmail_kill_session()
277 // save user preferences
278 $a_user_prefs = $_SESSION['user_prefs'];
279 if (!is_array($a_user_prefs))
280 $a_user_prefs = array();
282 if ((isset($_SESSION['sort_col']) && $_SESSION['sort_col']!=$a_user_prefs['message_sort_col']) ||
283 (isset($_SESSION['sort_order']) && $_SESSION['sort_order']!=$a_user_prefs['message_sort_order']))
285 $a_user_prefs['message_sort_col'] = $_SESSION['sort_col'];
286 $a_user_prefs['message_sort_order'] = $_SESSION['sort_order'];
287 rcmail_save_user_prefs($a_user_prefs);
290 $_SESSION = array('user_lang' => $GLOBALS['sess_user_lang'], 'auth_time' => time(), 'temp' => true);
291 setcookie('sessauth', '-del-', time()-60);
295 // return correct name for a specific database table
296 function get_table_name($table)
300 // return table name if configured
301 $config_key = 'db_table_'.$table;
303 if (strlen($CONFIG[$config_key]))
304 return $CONFIG[$config_key];
310 // return correct name for a specific database sequence
311 // (used for Postres only)
312 function get_sequence_name($sequence)
316 // return table name if configured
317 $config_key = 'db_sequence_'.$sequence;
319 if (strlen($CONFIG[$config_key]))
320 return $CONFIG[$config_key];
326 // check the given string and returns language properties
327 function rcube_language_prop($lang, $prop='lang')
329 global $INSTALL_PATH;
330 static $rcube_languages, $rcube_language_aliases, $rcube_charsets;
332 if (empty($rcube_languages))
333 @include($INSTALL_PATH.'program/localization/index.inc');
335 // check if we have an alias for that language
336 if (!isset($rcube_languages[$lang]) && isset($rcube_language_aliases[$lang]))
337 $lang = $rcube_language_aliases[$lang];
339 // try the first two chars
340 if (!isset($rcube_languages[$lang]) && strlen($lang)>2)
342 $lang = substr($lang, 0, 2);
343 $lang = rcube_language_prop($lang);
346 if (!isset($rcube_languages[$lang]))
349 // language has special charset configured
350 if (isset($rcube_charsets[$lang]))
351 $charset = $rcube_charsets[$lang];
356 if ($prop=='charset')
363 // init output object for GUI and add common scripts
364 function rcmail_load_gui()
366 global $CONFIG, $OUTPUT, $sess_user_lang;
369 $OUTPUT = new rcmail_template($CONFIG, $GLOBALS['_task']);
370 $OUTPUT->set_env('comm_path', $GLOBALS['COMM_PATH']);
372 if (is_array($CONFIG['javascript_config']))
374 foreach ($CONFIG['javascript_config'] as $js_config_var)
375 $OUTPUT->set_env($js_config_var, $CONFIG[$js_config_var]);
378 if (!empty($GLOBALS['_framed']))
379 $OUTPUT->set_env('framed', true);
381 // set locale setting
382 rcmail_set_locale($sess_user_lang);
384 // set user-selected charset
385 if (!empty($CONFIG['charset']))
386 $OUTPUT->set_charset($CONFIG['charset']);
388 // register common UI objects
389 $OUTPUT->add_handlers(array(
390 'loginform' => 'rcmail_login_form',
391 'username' => 'rcmail_current_username',
392 'message' => 'rcmail_message_container',
393 'charsetselector' => 'rcmail_charset_selector',
396 // add some basic label to client
397 if (!$OUTPUT->ajax_call)
398 rcube_add_label('loading');
402 // set localization charset based on the given language
403 function rcmail_set_locale($lang)
405 global $OUTPUT, $MBSTRING;
406 static $s_mbstring_loaded = NULL;
408 // settings for mbstring module (by Tadashi Jokagi)
409 if (is_null($s_mbstring_loaded))
410 $MBSTRING = $s_mbstring_loaded = extension_loaded("mbstring");
412 $MBSTRING = $s_mbstring_loaded = FALSE;
415 mb_internal_encoding(RCMAIL_CHARSET);
417 $OUTPUT->set_charset(rcube_language_prop($lang, 'charset'));
421 // auto-select IMAP host based on the posted login information
422 function rcmail_autoselect_host()
426 $host = isset($_POST['_host']) ? get_input_value('_host', RCUBE_INPUT_POST) : $CONFIG['default_host'];
429 list($user, $domain) = explode('@', get_input_value('_user', RCUBE_INPUT_POST));
432 foreach ($host as $imap_host => $mail_domains)
433 if (is_array($mail_domains) && in_array($domain, $mail_domains))
440 // take the first entry if $host is still an array
442 $host = array_shift($host);
449 // perfom login to the IMAP server and to the webmail service
450 function rcmail_login($user, $pass, $host=NULL)
452 global $CONFIG, $IMAP, $DB, $sess_user_lang;
456 $host = $CONFIG['default_host'];
458 // Validate that selected host is in the list of configured hosts
459 if (is_array($CONFIG['default_host']))
462 foreach ($CONFIG['default_host'] as $key => $host_allowed)
464 if (!is_numeric($key))
465 $host_allowed = $key;
466 if ($host == $host_allowed)
475 else if (!empty($CONFIG['default_host']) && $host != $CONFIG['default_host'])
479 $a_host = parse_url($host);
482 $host = $a_host['host'];
483 $imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? TRUE : FALSE;
484 $imap_port = isset($a_host['port']) ? $a_host['port'] : ($imap_ssl ? 993 : $CONFIG['default_port']);
487 $imap_port = $CONFIG['default_port'];
490 /* Modify username with domain if required
491 Inspired by Marco <P0L0_notspam_binware.org>
493 // Check if we need to add domain
494 if (!empty($CONFIG['username_domain']) && !strstr($user, '@'))
496 if (is_array($CONFIG['username_domain']) && isset($CONFIG['username_domain'][$host]))
497 $user .= '@'.$CONFIG['username_domain'][$host];
498 else if (is_string($CONFIG['username_domain']))
499 $user .= '@'.$CONFIG['username_domain'];
503 // query if user already registered
504 $sql_result = $DB->query("SELECT user_id, username, language, preferences
505 FROM ".get_table_name('users')."
506 WHERE mail_host=? AND (username=? OR alias=?)",
511 // user already registered -> overwrite username
512 if ($sql_arr = $DB->fetch_assoc($sql_result))
514 $user_id = $sql_arr['user_id'];
515 $user = $sql_arr['username'];
518 // try to resolve email address from virtuser table
519 if (!empty($CONFIG['virtuser_file']) && strstr($user, '@'))
520 $user = rcmail_email2user($user);
523 // exit if IMAP login failed
524 if (!($imap_login = $IMAP->connect($host, $user, $pass, $imap_port, $imap_ssl)))
527 // user already registered
528 if ($user_id && !empty($sql_arr))
531 if (strlen($sql_arr['preferences']))
533 $user_prefs = unserialize($sql_arr['preferences']);
534 $_SESSION['user_prefs'] = $user_prefs;
535 array_merge($CONFIG, $user_prefs);
539 // set user specific language
540 if (strlen($sql_arr['language']))
541 $sess_user_lang = $_SESSION['user_lang'] = $sql_arr['language'];
543 // update user's record
544 $DB->query("UPDATE ".get_table_name('users')."
545 SET last_login=".$DB->now()."
549 // create new system user
550 else if ($CONFIG['auto_create_user'])
552 $user_id = rcmail_create_user($user, $host);
557 $_SESSION['user_id'] = $user_id;
558 $_SESSION['imap_host'] = $host;
559 $_SESSION['imap_port'] = $imap_port;
560 $_SESSION['imap_ssl'] = $imap_ssl;
561 $_SESSION['username'] = $user;
562 $_SESSION['user_lang'] = $sess_user_lang;
563 $_SESSION['password'] = encrypt_passwd($pass);
564 $_SESSION['login_time'] = mktime();
566 // force reloading complete list of subscribed mailboxes
567 rcmail_set_imap_prop();
568 $IMAP->clear_cache('mailboxes');
569 $IMAP->create_default_folders();
578 // create new entry in users and identities table
579 function rcmail_create_user($user, $host)
581 global $DB, $CONFIG, $IMAP;
585 // try to resolve user in virtusertable
586 if (!empty($CONFIG['virtuser_file']) && strstr($user, '@')==FALSE)
587 $user_email = rcmail_user2email($user);
589 $DB->query("INSERT INTO ".get_table_name('users')."
590 (created, last_login, username, mail_host, alias, language)
591 VALUES (".$DB->now().", ".$DB->now().", ?, ?, ?, ?)",
592 strip_newlines($user),
593 strip_newlines($host),
594 strip_newlines($user_email),
595 $_SESSION['user_lang']);
597 if ($user_id = $DB->insert_id(get_sequence_name('users')))
599 $mail_domain = rcmail_mail_domain($host);
602 $user_email = strstr($user, '@') ? $user : sprintf('%s@%s', $user, $mail_domain);
604 $user_name = $user!=$user_email ? $user : '';
606 // try to resolve the e-mail address from the virtuser table
607 if (!empty($CONFIG['virtuser_query']) &&
608 ($sql_result = $DB->query(preg_replace('/%u/', $user, $CONFIG['virtuser_query']))) &&
610 while ($sql_arr = $DB->fetch_array($sql_result))
612 $DB->query("INSERT INTO ".get_table_name('identities')."
613 (user_id, del, standard, name, email)
614 VALUES (?, 0, 1, ?, ?)",
616 strip_newlines($user_name),
617 preg_replace('/^@/', $user . '@', $sql_arr[0]));
621 // also create new identity records
622 $DB->query("INSERT INTO ".get_table_name('identities')."
623 (user_id, del, standard, name, email)
624 VALUES (?, 0, 1, ?, ?)",
626 strip_newlines($user_name),
627 strip_newlines($user_email));
630 // get existing mailboxes
631 $a_mailboxes = $IMAP->list_mailboxes();
635 raise_error(array('code' => 500,
639 'message' => "Failed to create new user"), TRUE, FALSE);
646 // load virtuser table in array
647 function rcmail_getvirtualfile()
650 if (empty($CONFIG['virtuser_file']) || !is_file($CONFIG['virtuser_file']))
654 $a_lines = file($CONFIG['virtuser_file']);
659 // find matches of the given pattern in virtuser table
660 function rcmail_findinvirtual($pattern)
663 $virtual = rcmail_getvirtualfile();
667 // check each line for matches
668 foreach ($virtual as $line)
671 if (empty($line) || $line{0}=='#')
674 if (eregi($pattern, $line))
682 // resolve username with virtuser table
683 function rcmail_email2user($email)
686 $r = rcmail_findinvirtual("^$email");
688 for ($i=0; $i<count($r); $i++)
691 $arr = preg_split('/\s+/', $data);
694 $user = trim($arr[count($arr)-1]);
703 // resolve e-mail address with virtuser table
704 function rcmail_user2email($user)
707 $r = rcmail_findinvirtual("$user$");
709 for ($i=0; $i<count($r); $i++)
712 $arr = preg_split('/\s+/', $data);
715 $email = trim($arr[0]);
724 function rcmail_save_user_prefs($a_user_prefs)
726 global $DB, $CONFIG, $sess_user_lang;
728 $DB->query("UPDATE ".get_table_name('users')."
732 serialize($a_user_prefs),
734 $_SESSION['user_id']);
736 if ($DB->affected_rows())
738 $_SESSION['user_prefs'] = $a_user_prefs;
739 $CONFIG = array_merge($CONFIG, $a_user_prefs);
747 // overwrite action variable
748 function rcmail_overwrite_action($action)
751 $GLOBALS['_action'] = $action;
752 $OUTPUT->set_env('action', $action);
757 * Compose an URL for a specific action
759 * @param string Request action
760 * @param array More URL parameters
761 * @param string Request task (omit if the same)
762 * @return The application URL
764 function rcmail_url($action, $p=array(), $task=null)
766 global $MAIN_TASKS, $COMM_PATH;
770 if ($task && in_array($task, $MAIN_TASKS))
771 $base = ereg_replace('_task=[a-z]+', '_task='.$task, $COMM_PATH);
774 foreach ($p as $key => $val)
775 $qstring .= '&'.urlencode($key).'='.urlencode($val);
777 return $base . ($action ? '&_action='.$action : '') . $qstring;
782 function show_message($message, $type='notice', $vars=NULL)
785 $OUTPUT->show_message($message, $type, $vars);
789 // encrypt IMAP password using DES encryption
790 function encrypt_passwd($pass)
792 $cypher = des(get_des_key(), $pass, 1, 0, NULL);
793 return base64_encode($cypher);
797 // decrypt IMAP password using DES encryption
798 function decrypt_passwd($cypher)
800 $pass = des(get_des_key(), base64_decode($cypher), 0, 0, NULL);
801 return preg_replace('/\x00/', '', $pass);
805 // return a 24 byte key for the DES encryption
806 function get_des_key()
808 $key = !empty($GLOBALS['CONFIG']['des_key']) ? $GLOBALS['CONFIG']['des_key'] : 'rcmail?24BitPwDkeyF**ECB';
811 // make sure the key is exactly 24 chars long
813 $key .= str_repeat('_', 24-$len);
821 // read directory program/localization/ and return a list of available languages
822 function rcube_list_languages()
824 global $CONFIG, $INSTALL_PATH;
825 static $sa_languages = array();
827 if (!sizeof($sa_languages))
829 @include($INSTALL_PATH.'program/localization/index.inc');
831 if ($dh = @opendir($INSTALL_PATH.'program/localization'))
833 while (($name = readdir($dh)) !== false)
835 if ($name{0}=='.' || !is_dir($INSTALL_PATH.'program/localization/'.$name))
838 if ($label = $rcube_languages[$name])
839 $sa_languages[$name] = $label ? $label : $name;
844 return $sa_languages;
848 // add a localized label to the client environment
849 function rcube_add_label()
853 $arg_list = func_get_args();
854 foreach ($arg_list as $i => $name)
855 $OUTPUT->command('add_label', $name, rcube_label($name));
859 // remove temp files older than two day
860 function rcmail_temp_gc()
862 $tmp = unslashify($CONFIG['temp_dir']);
863 $expire = mktime() - 172800; // expire in 48 hours
865 if ($dir = opendir($tmp))
867 while (($fname = readdir($dir)) !== false)
869 if ($fname{0} == '.')
872 if (filemtime($tmp.'/'.$fname) < $expire)
873 @unlink($tmp.'/'.$fname);
881 // remove all expired message cache records
882 function rcmail_message_cache_gc()
886 // no cache lifetime configured
887 if (empty($CONFIG['message_cache_lifetime']))
890 // get target timestamp
891 $ts = get_offset_time($CONFIG['message_cache_lifetime'], -1);
893 $DB->query("DELETE FROM ".get_table_name('messages')."
894 WHERE created < ".$DB->fromunixtime($ts));
899 * Convert a string from one charset to another.
900 * Uses mbstring and iconv functions if possible
902 * @param string Input string
903 * @param string Suspected charset of the input string
904 * @param string Target charset to convert to; defaults to RCMAIL_CHARSET
905 * @return Converted string
907 function rcube_charset_convert($str, $from, $to=NULL)
911 $from = strtoupper($from);
912 $to = $to==NULL ? strtoupper(RCMAIL_CHARSET) : strtoupper($to);
914 if ($from==$to || $str=='' || empty($from))
917 // convert charset using mbstring module
920 $to = $to=="UTF-7" ? "UTF7-IMAP" : $to;
921 $from = $from=="UTF-7" ? "UTF7-IMAP": $from;
923 // return if convert succeeded
924 if (($out = mb_convert_encoding($str, $to, $from)) != '')
928 // convert charset using iconv module
929 if (function_exists('iconv') && $from!='UTF-7' && $to!='UTF-7')
930 return iconv($from, $to, $str);
934 // convert string to UTF-8
936 $str = utf7_to_utf8($str);
937 else if (($from=='ISO-8859-1') && function_exists('utf8_encode'))
938 $str = utf8_encode($str);
939 else if ($from!='UTF-8')
941 $conv->loadCharset($from);
942 $str = $conv->strToUtf8($str);
945 // encode string for output
947 return utf8_to_utf7($str);
948 else if ($to=='ISO-8859-1' && function_exists('utf8_decode'))
949 return utf8_decode($str);
950 else if ($to!='UTF-8')
952 $conv->loadCharset($to);
953 return $conv->utf8ToStr($str);
956 // return UTF-8 string
962 * Replacing specials characters to a specific encoding type
964 * @param string Input string
965 * @param string Encoding type: text|html|xml|js|url
966 * @param string Replace mode for tags: show|replace|remove
967 * @param boolean Convert newlines
968 * @return The quoted string
970 function rep_specialchars_output($str, $enctype='', $mode='', $newlines=TRUE)
972 global $OUTPUT_TYPE, $OUTPUT;
973 static $html_encode_arr, $js_rep_table, $xml_rep_table;
976 $enctype = $GLOBALS['OUTPUT_TYPE'];
978 // convert nbsps back to normal spaces if not html
979 if ($enctype!='html')
980 $str = str_replace(chr(160), ' ', $str);
982 // encode for plaintext
983 if ($enctype=='text')
984 return str_replace("\r\n", "\n", $mode=='remove' ? strip_tags($str) : $str);
986 // encode for HTML output
987 if ($enctype=='html')
989 if (!$html_encode_arr)
991 $html_encode_arr = get_html_translation_table(HTML_SPECIALCHARS);
992 unset($html_encode_arr['?']);
995 $ltpos = strpos($str, '<');
996 $encode_arr = $html_encode_arr;
998 // don't replace quotes and html tags
999 if (($mode=='show' || $mode=='') && $ltpos!==false && strpos($str, '>', $ltpos)!==false)
1001 unset($encode_arr['"']);
1002 unset($encode_arr['<']);
1003 unset($encode_arr['>']);
1004 unset($encode_arr['&']);
1006 else if ($mode=='remove')
1007 $str = strip_tags($str);
1009 // avoid douple quotation of &
1010 $out = preg_replace('/&([a-z]{2,5}|#[0-9]{2,4});/', '&\\1;', strtr($str, $encode_arr));
1012 return $newlines ? nl2br($out) : $out;
1015 if ($enctype=='url')
1016 return rawurlencode($str);
1018 // if the replace tables for XML and JS are not yet defined
1021 $js_rep_table = $xml_rep_table = array();
1022 $xml_rep_table['&'] = '&';
1024 for ($c=160; $c<256; $c++) // can be increased to support more charsets
1027 $xml_rep_table[Chr($c)] = "&#$c;";
1029 if ($OUTPUT->get_charset()=='ISO-8859-1')
1030 $js_rep_table[Chr($c)] = sprintf("\u%s%s", str_repeat('0', 4-strlen($hex)), $hex);
1033 $xml_rep_table['"'] = '"';
1037 if ($enctype=='xml')
1038 return strtr($str, $xml_rep_table);
1040 // encode for javascript use
1043 if ($OUTPUT->get_charset()!='UTF-8')
1044 $str = rcube_charset_convert($str, RCMAIL_CHARSET, $OUTPUT->get_charset());
1046 return preg_replace(array("/\r?\n/", "/\r/"), array('\n', '\n'), addslashes(strtr($str, $js_rep_table)));
1049 // no encoding given -> return original string
1054 * Quote a given string. Alias function for rep_specialchars_output
1055 * @see rep_specialchars_output
1057 function Q($str, $mode='strict', $newlines=TRUE)
1059 return rep_specialchars_output($str, 'html', $mode, $newlines);
1063 * Quote a given string. Alias function for rep_specialchars_output
1064 * @see rep_specialchars_output
1068 return rep_specialchars_output($str, 'js');
1073 * Read input value and convert it for internal use
1074 * Performs stripslashes() and charset conversion if necessary
1076 * @param string Field name to read
1077 * @param int Source to get value from (GPC)
1078 * @param boolean Allow HTML tags in field value
1079 * @param string Charset to convert into
1080 * @return string Field value or NULL if not available
1082 function get_input_value($fname, $source, $allow_html=FALSE, $charset=NULL)
1087 if ($source==RCUBE_INPUT_GET && isset($_GET[$fname]))
1088 $value = $_GET[$fname];
1089 else if ($source==RCUBE_INPUT_POST && isset($_POST[$fname]))
1090 $value = $_POST[$fname];
1091 else if ($source==RCUBE_INPUT_GPC)
1093 if (isset($_POST[$fname]))
1094 $value = $_POST[$fname];
1095 else if (isset($_GET[$fname]))
1096 $value = $_GET[$fname];
1097 else if (isset($_COOKIE[$fname]))
1098 $value = $_COOKIE[$fname];
1101 // strip slashes if magic_quotes enabled
1102 if ((bool)get_magic_quotes_gpc())
1103 $value = stripslashes($value);
1105 // remove HTML tags if not allowed
1107 $value = strip_tags($value);
1109 // convert to internal charset
1110 if (is_object($OUTPUT))
1111 return rcube_charset_convert($value, $OUTPUT->get_charset(), $charset);
1117 * Remove single and double quotes from given string
1119 function strip_quotes($str)
1121 return preg_replace('/[\'"]/', '', $str);
1125 * Remove new lines characters from given string
1127 function strip_newlines($str)
1129 return preg_replace('/[\r\n]/', '', $str);
1133 // return boolean if a specific template exists
1134 function template_exists($name)
1137 $skin_path = $CONFIG['skin_path'];
1139 // check template file
1140 return is_file("$skin_path/templates/$name.html");
1144 // Wrapper for rcmail_template::parse()
1146 function parse_template($name='main', $exit=true)
1148 $GLOBALS['OUTPUT']->parse($name, $exit);
1153 function rcube_table_output($attrib, $table_data, $a_show_cols, $id_col)
1157 // allow the following attributes to be added to the <table> tag
1158 $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
1160 $table = '<table' . $attrib_str . ">\n";
1163 $table .= "<thead><tr>\n";
1165 foreach ($a_show_cols as $col)
1166 $table .= '<td class="'.$col.'">' . Q(rcube_label($col)) . "</td>\n";
1168 $table .= "</tr></thead>\n<tbody>\n";
1171 if (!is_array($table_data))
1173 while ($table_data && ($sql_arr = $DB->fetch_assoc($table_data)))
1175 $zebra_class = $c%2 ? 'even' : 'odd';
1177 $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $sql_arr[$id_col]);
1180 foreach ($a_show_cols as $col)
1182 $cont = Q($sql_arr[$col]);
1183 $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1186 $table .= "</tr>\n";
1192 foreach ($table_data as $row_data)
1194 $zebra_class = $c%2 ? 'even' : 'odd';
1196 $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $row_data[$id_col]);
1199 foreach ($a_show_cols as $col)
1201 $cont = Q($row_data[$col]);
1202 $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1205 $table .= "</tr>\n";
1210 // complete message table
1211 $table .= "</tbody></table>\n";
1218 * Create an edit field for inclusion on a form
1220 * @param string col field name
1221 * @param string value field value
1222 * @param array attrib HTML element attributes for field
1223 * @param string type HTML element type (default 'text')
1224 * @return string HTML field definition
1226 function rcmail_get_edit_field($col, $value, $attrib, $type='text')
1229 $attrib['name'] = $fname;
1231 if ($type=='checkbox')
1233 $attrib['value'] = '1';
1234 $input = new checkbox($attrib);
1236 else if ($type=='textarea')
1238 $attrib['cols'] = $attrib['size'];
1239 $input = new textarea($attrib);
1242 $input = new textfield($attrib);
1244 // use value from post
1245 if (!empty($_POST[$fname]))
1246 $value = $_POST[$fname];
1248 $out = $input->show($value);
1254 // return the mail domain configured for the given host
1255 function rcmail_mail_domain($host)
1260 if (is_array($CONFIG['mail_domain']))
1262 if (isset($CONFIG['mail_domain'][$host]))
1263 $domain = $CONFIG['mail_domain'][$host];
1265 else if (!empty($CONFIG['mail_domain']))
1266 $domain = $CONFIG['mail_domain'];
1272 // compose a valid attribute string for HTML tags
1273 function create_attrib_string($attrib, $allowed_attribs=array('id', 'class', 'style'))
1275 // allow the following attributes to be added to the <iframe> tag
1277 foreach ($allowed_attribs as $a)
1278 if (isset($attrib[$a]))
1279 $attrib_str .= sprintf(' %s="%s"', $a, str_replace('"', '"', $attrib[$a]));
1285 // convert a HTML attribute string attributes to an associative array (name => value)
1286 function parse_attrib_string($str)
1289 preg_match_all('/\s*([-_a-z]+)=(["\'])([^"]+)\2/Ui', stripslashes($str), $regs, PREG_SET_ORDER);
1291 // convert attributes to an associative array (name => value)
1293 foreach ($regs as $attr)
1294 $attrib[strtolower($attr[1])] = $attr[3];
1300 function format_date($date, $format=NULL)
1302 global $CONFIG, $sess_user_lang;
1306 if (is_numeric($date))
1308 else if (!empty($date))
1309 $ts = @strtotime($date);
1314 // get user's timezone
1315 $tz = $CONFIG['timezone'];
1316 if ($CONFIG['dst_active'])
1319 // convert time to user's timezone
1320 $timestamp = $ts - date('Z', $ts) + ($tz * 3600);
1322 // get current timestamp in user's timezone
1323 $now = time(); // local time
1324 $now -= (int)date('Z'); // make GMT time
1325 $now += ($tz * 3600); // user's time
1326 $now_date = getdate($now);
1328 $today_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday'], $now_date['year']);
1329 $week_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday']-6, $now_date['year']);
1331 // define date format depending on current time
1332 if ($CONFIG['prettydate'] && !$format && $timestamp > $today_limit && $timestamp < $now)
1333 return sprintf('%s %s', rcube_label('today'), date($CONFIG['date_today'] ? $CONFIG['date_today'] : 'H:i', $timestamp));
1334 else if ($CONFIG['prettydate'] && !$format && $timestamp > $week_limit && $timestamp < $now)
1335 $format = $CONFIG['date_short'] ? $CONFIG['date_short'] : 'D H:i';
1337 $format = $CONFIG['date_long'] ? $CONFIG['date_long'] : 'd.m.Y H:i';
1340 // parse format string manually in order to provide localized weekday and month names
1341 // an alternative would be to convert the date() format string to fit with strftime()
1343 for($i=0; $i<strlen($format); $i++)
1345 if ($format{$i}=='\\') // skip escape chars
1348 // write char "as-is"
1349 if ($format{$i}==' ' || $format{$i-1}=='\\')
1350 $out .= $format{$i};
1352 else if ($format{$i}=='D')
1353 $out .= rcube_label(strtolower(date('D', $timestamp)));
1355 else if ($format{$i}=='l')
1356 $out .= rcube_label(strtolower(date('l', $timestamp)));
1357 // month name (short)
1358 else if ($format{$i}=='M')
1359 $out .= rcube_label(strtolower(date('M', $timestamp)));
1360 // month name (long)
1361 else if ($format{$i}=='F')
1362 $out .= rcube_label(strtolower(date('F', $timestamp)));
1364 $out .= date($format{$i}, $timestamp);
1371 function format_email_recipient($email, $name='')
1373 if ($name && $name != $email)
1374 return sprintf('%s <%s>', strpos($name, ",") ? '"'.$name.'"' : $name, $email);
1381 // ************** functions delivering gui objects **************
1385 function rcmail_message_container($attrib)
1390 $attrib['id'] = 'rcmMessageContainer';
1392 // allow the following attributes to be added to the <table> tag
1393 $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
1394 $out = '<div' . $attrib_str . "></div>";
1396 $OUTPUT->add_gui_object('message', $attrib['id']);
1402 // return the IMAP username of the current session
1403 function rcmail_current_username($attrib)
1409 if (!empty($s_username))
1412 // get e-mail address form default identity
1413 $sql_result = $DB->query("SELECT email AS mailto
1414 FROM ".get_table_name('identities')."
1418 $_SESSION['user_id']);
1420 if ($DB->num_rows($sql_result))
1422 $sql_arr = $DB->fetch_assoc($sql_result);
1423 $s_username = $sql_arr['mailto'];
1425 else if (strstr($_SESSION['username'], '@'))
1426 $s_username = $_SESSION['username'];
1428 $s_username = $_SESSION['username'].'@'.$_SESSION['imap_host'];
1434 // return code for the webmail login form
1435 function rcmail_login_form($attrib)
1437 global $CONFIG, $OUTPUT, $SESS_HIDDEN_FIELD;
1440 $labels['user'] = rcube_label('username');
1441 $labels['pass'] = rcube_label('password');
1442 $labels['host'] = rcube_label('server');
1444 $input_user = new textfield(array('name' => '_user', 'id' => 'rcmloginuser', 'size' => 30, 'autocomplete' => 'off'));
1445 $input_pass = new passwordfield(array('name' => '_pass', 'id' => 'rcmloginpwd', 'size' => 30));
1446 $input_action = new hiddenfield(array('name' => '_action', 'value' => 'login'));
1449 $fields['user'] = $input_user->show(get_input_value('_user', RCUBE_INPUT_POST));
1450 $fields['pass'] = $input_pass->show();
1451 $fields['action'] = $input_action->show();
1453 if (is_array($CONFIG['default_host']))
1455 $select_host = new select(array('name' => '_host', 'id' => 'rcmloginhost'));
1457 foreach ($CONFIG['default_host'] as $key => $value)
1459 if (!is_array($value))
1460 $select_host->add($value, (is_numeric($key) ? $value : $key));
1463 unset($select_host);
1468 $fields['host'] = isset($select_host) ? $select_host->show($_POST['_host']) : null;
1470 else if (!strlen($CONFIG['default_host']))
1472 $input_host = new textfield(array('name' => '_host', 'id' => 'rcmloginhost', 'size' => 30));
1473 $fields['host'] = $input_host->show($_POST['_host']);
1476 $form_name = strlen($attrib['form']) ? $attrib['form'] : 'form';
1477 $form_start = !strlen($attrib['form']) ? '<form name="form" action="./" method="post">' : '';
1478 $form_end = !strlen($attrib['form']) ? '</form>' : '';
1480 if ($fields['host'])
1485 <td class="title"><label for="rcmloginhost">$labels[host]</label></td>
1486 <td>$fields[host]</td>
1490 $OUTPUT->add_gui_object('loginform', $form_name);
1498 <td class="title"><label for="rcmloginuser">$labels[user]</label></td>
1499 <td>$fields[user]</td>
1503 <td class="title"><label for="rcmloginpwd">$labels[pass]</label></td>
1504 <td>$fields[pass]</td>
1514 function rcmail_charset_selector($attrib)
1518 // pass the following attributes to the form class
1519 $field_attrib = array('name' => '_charset');
1520 foreach ($attrib as $attr => $value)
1521 if (in_array($attr, array('id', 'class', 'style', 'size', 'tabindex')))
1522 $field_attrib[$attr] = $value;
1525 'US-ASCII' => 'ASCII (English)',
1526 'EUC-JP' => 'EUC-JP (Japanese)',
1527 'EUC-KR' => 'EUC-KR (Korean)',
1528 'BIG5' => 'BIG5 (Chinese)',
1529 'GB2312' => 'GB2312 (Chinese)',
1530 'ISO-2022-JP' => 'ISO-2022-JP (Japanese)',
1531 'ISO-8859-1' => 'ISO-8859-1 (Latin-1)',
1532 'ISO-8859-2' => 'ISO-8895-2 (Central European)',
1533 'ISO-8859-7' => 'ISO-8859-7 (Greek)',
1534 'ISO-8859-9' => 'ISO-8859-9 (Turkish)',
1535 'Windows-1251' => 'Windows-1251 (Cyrillic)',
1536 'Windows-1252' => 'Windows-1252 (Western)',
1537 'Windows-1255' => 'Windows-1255 (Hebrew)',
1538 'Windows-1256' => 'Windows-1256 (Arabic)',
1539 'Windows-1257' => 'Windows-1257 (Baltic)',
1543 $select = new select($field_attrib);
1544 $select->add(array_values($charsets), array_keys($charsets));
1546 $set = $_POST['_charset'] ? $_POST['_charset'] : $OUTPUT->get_charset();
1547 return $select->show($set);
1551 // return code for search function
1552 function rcmail_search_form($attrib)
1556 // add some labels to client
1557 rcube_add_label('searching');
1559 $attrib['name'] = '_q';
1561 if (empty($attrib['id']))
1562 $attrib['id'] = 'rcmqsearchbox';
1564 $input_q = new textfield($attrib);
1565 $out = $input_q->show();
1567 $OUTPUT->add_gui_object('qsearchbox', $attrib['id']);
1569 // add form tag around text field
1570 if (empty($attrib['form']))
1572 '<form name="rcmqsearchform" action="./" '.
1573 'onsubmit="%s.command(\'search\');return false" style="display:inline;">%s</form>',
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)
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);
1637 function rcube_timer()
1639 list($usec, $sec) = explode(" ", microtime());
1640 return ((float)$usec + (float)$sec);
1644 function rcube_print_time($timer, $label='Timer')
1646 static $print_count = 0;
1649 $now = rcube_timer();
1650 $diff = $now-$timer;
1653 $label = 'Timer '.$print_count;
1655 console(sprintf("%s: %0.4f sec", $label, $diff));