4 +-----------------------------------------------------------------------+
5 | program/include/main.inc |
7 | This file is part of the RoundCube Webmail client |
8 | Copyright (C) 2005, 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 429 2006-12-22 22:26:24Z thomasb $
22 require_once('lib/des.inc');
23 require_once('lib/utf7.inc');
24 require_once('lib/utf8.class.php');
27 // define constannts for input reading
28 define('RCUBE_INPUT_GET', 0x0101);
29 define('RCUBE_INPUT_POST', 0x0102);
30 define('RCUBE_INPUT_GPC', 0x0103);
33 // register session and connect to server
34 function rcmail_startup($task='mail')
36 global $sess_id, $sess_auth, $sess_user_lang;
37 global $CONFIG, $INSTALL_PATH, $BROWSER, $OUTPUT, $_SESSION, $IMAP, $DB, $JS_OBJECT_NAME;
40 $BROWSER = rcube_browser();
43 include_once('config/main.inc.php');
44 $CONFIG = is_array($rcmail_config) ? $rcmail_config : array();
46 // load host-specific configuration
47 rcmail_load_host_config($CONFIG);
49 $CONFIG['skin_path'] = $CONFIG['skin_path'] ? unslashify($CONFIG['skin_path']) : 'skins/default';
52 include_once('config/db.inc.php');
53 $CONFIG = array_merge($CONFIG, $rcmail_config);
55 if (empty($CONFIG['log_dir']))
56 $CONFIG['log_dir'] = $INSTALL_PATH.'logs';
58 $CONFIG['log_dir'] = unslashify($CONFIG['log_dir']);
60 // set PHP error logging according to config
61 if ($CONFIG['debug_level'] & 1)
63 ini_set('log_errors', 1);
64 ini_set('error_log', $CONFIG['log_dir'].'/errors');
66 if ($CONFIG['debug_level'] & 4)
67 ini_set('display_errors', 1);
69 ini_set('display_errors', 0);
72 // set session garbage collecting time according to session_lifetime
73 if (!empty($CONFIG['session_lifetime']))
74 ini_set('session.gc_maxlifetime', ($CONFIG['session_lifetime']+2)*60);
77 // prepare DB connection
78 require_once('include/rcube_'.(empty($CONFIG['db_backend']) ? 'db' : $CONFIG['db_backend']).'.inc');
80 $DB = new rcube_db($CONFIG['db_dsnw'], $CONFIG['db_dsnr'], $CONFIG['db_persistent']);
81 $DB->sqlite_initials = $INSTALL_PATH.'SQL/sqlite.initial.sql';
84 // we can use the database for storing session data
86 include_once('include/session.inc');
90 $sess_id = session_id();
92 // create session and set session vars
93 if (!isset($_SESSION['auth_time']))
95 $_SESSION['user_lang'] = rcube_language_prop($CONFIG['locale_string']);
96 $_SESSION['auth_time'] = mktime();
97 setcookie('sessauth', rcmail_auth_hash($sess_id, $_SESSION['auth_time']));
100 // set session vars global
101 $sess_user_lang = rcube_language_prop($_SESSION['user_lang']);
104 // overwrite config with user preferences
105 if (is_array($_SESSION['user_prefs']))
106 $CONFIG = array_merge($CONFIG, $_SESSION['user_prefs']);
109 // reset some session parameters when changing task
110 if ($_SESSION['task'] != $task)
111 unset($_SESSION['page']);
113 // set current task to session
114 $_SESSION['task'] = $task;
116 // create IMAP object
122 if ($CONFIG['locale_string'])
123 setlocale(LC_ALL, $CONFIG['locale_string']);
124 else if ($sess_user_lang)
125 setlocale(LC_ALL, $sess_user_lang);
128 register_shutdown_function('rcmail_shutdown');
132 // load a host-specific config file if configured
133 function rcmail_load_host_config(&$config)
137 if (is_array($config['include_host_config']))
138 $fname = $config['include_host_config'][$_SERVER['HTTP_HOST']];
139 else if (!empty($config['include_host_config']))
140 $fname = preg_replace('/[^a-z0-9\.\-_]/i', '', $_SERVER['HTTP_HOST']) . '.inc.php';
142 if ($fname && is_file('config/'.$fname))
144 include('config/'.$fname);
145 $config = array_merge($config, $rcmail_config);
150 // create authorization hash
151 function rcmail_auth_hash($sess_id, $ts)
155 $auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
158 $CONFIG['ip_check'] ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
159 $_SERVER['HTTP_USER_AGENT']);
161 if (function_exists('sha1'))
162 return sha1($auth_string);
164 return md5($auth_string);
168 // compare the auth hash sent by the client with the local session credentials
169 function rcmail_authenticate_session()
172 $valid = ($_COOKIE['sessauth'] == rcmail_auth_hash(session_id(), $_SESSION['auth_time']));
174 // renew auth cookie every 5 minutes (only for GET requests)
175 if (!$valid || ($_SERVER['REQUEST_METHOD']!='POST' && $now-$_SESSION['auth_time'] > 300))
177 $_SESSION['auth_time'] = $now;
178 setcookie('sessauth', rcmail_auth_hash(session_id(), $now));
185 // create IMAP object and connect to server
186 function rcmail_imap_init($connect=FALSE)
188 global $CONFIG, $DB, $IMAP;
190 $IMAP = new rcube_imap($DB);
191 $IMAP->debug_level = $CONFIG['debug_level'];
192 $IMAP->skip_deleted = $CONFIG['skip_deleted'];
195 // connect with stored session data
198 if (!($conn = $IMAP->connect($_SESSION['imap_host'], $_SESSION['username'], decrypt_passwd($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl'])))
199 show_message('imaperror', 'error');
201 rcmail_set_imap_prop();
204 // enable caching of imap data
205 if ($CONFIG['enable_caching']===TRUE)
206 $IMAP->set_caching(TRUE);
208 // set pagesize from config
209 if (isset($CONFIG['pagesize']))
210 $IMAP->set_pagesize($CONFIG['pagesize']);
214 // set root dir and last stored mailbox
215 // this must be done AFTER connecting to the server
216 function rcmail_set_imap_prop()
218 global $CONFIG, $IMAP;
220 // set root dir from config
221 if (!empty($CONFIG['imap_root']))
222 $IMAP->set_rootdir($CONFIG['imap_root']);
224 if (is_array($CONFIG['default_imap_folders']))
225 $IMAP->set_default_mailboxes($CONFIG['default_imap_folders']);
227 if (!empty($_SESSION['mbox']))
228 $IMAP->set_mailbox($_SESSION['mbox']);
229 if (isset($_SESSION['page']))
230 $IMAP->set_page($_SESSION['page']);
234 // do these things on script shutdown
235 function rcmail_shutdown()
239 if (is_object($IMAP))
242 $IMAP->write_cache();
245 // before closing the database connection, write session data
246 session_write_close();
250 // destroy session data and remove cookie
251 function rcmail_kill_session()
253 // save user preferences
254 $a_user_prefs = $_SESSION['user_prefs'];
255 if (!is_array($a_user_prefs))
256 $a_user_prefs = array();
258 if ((isset($_SESSION['sort_col']) && $_SESSION['sort_col']!=$a_user_prefs['message_sort_col']) ||
259 (isset($_SESSION['sort_order']) && $_SESSION['sort_order']!=$a_user_prefs['message_sort_order']))
261 $a_user_prefs['message_sort_col'] = $_SESSION['sort_col'];
262 $a_user_prefs['message_sort_order'] = $_SESSION['sort_order'];
263 rcmail_save_user_prefs($a_user_prefs);
271 // return correct name for a specific database table
272 function get_table_name($table)
276 // return table name if configured
277 $config_key = 'db_table_'.$table;
279 if (strlen($CONFIG[$config_key]))
280 return $CONFIG[$config_key];
286 // return correct name for a specific database sequence
287 // (used for Postres only)
288 function get_sequence_name($sequence)
292 // return table name if configured
293 $config_key = 'db_sequence_'.$sequence;
295 if (strlen($CONFIG[$config_key]))
296 return $CONFIG[$config_key];
302 // check the given string and returns language properties
303 function rcube_language_prop($lang, $prop='lang')
305 global $INSTALL_PATH;
306 static $rcube_languages, $rcube_language_aliases, $rcube_charsets;
308 if (empty($rcube_languages))
309 @include($INSTALL_PATH.'program/localization/index.inc');
311 // check if we have an alias for that language
312 if (!isset($rcube_languages[$lang]) && isset($rcube_language_aliases[$lang]))
313 $lang = $rcube_language_aliases[$lang];
315 // try the first two chars
316 if (!isset($rcube_languages[$lang]) && strlen($lang)>2)
318 $lang = substr($lang, 0, 2);
319 $lang = rcube_language_prop($lang);
322 if (!isset($rcube_languages[$lang]))
325 // language has special charset configured
326 if (isset($rcube_charsets[$lang]))
327 $charset = $rcube_charsets[$lang];
332 if ($prop=='charset')
339 // init output object for GUI and add common scripts
342 global $CONFIG, $OUTPUT, $COMM_PATH, $JS_OBJECT_NAME, $sess_user_lang;
345 $OUTPUT = new rcube_html_page();
347 // add common javascripts
348 $javascript = "var $JS_OBJECT_NAME = new rcube_webmail();\n";
349 $javascript .= "$JS_OBJECT_NAME.set_env('comm_path', '$COMM_PATH');\n";
351 if (isset($CONFIG['javascript_config'] )){
352 foreach ($CONFIG['javascript_config'] as $js_config_var){
353 $javascript .= "$JS_OBJECT_NAME.set_env('$js_config_var', '" . $CONFIG[$js_config_var] . "');\n";
357 if (!empty($GLOBALS['_framed']))
358 $javascript .= "$JS_OBJECT_NAME.set_env('framed', true);\n";
360 $OUTPUT->add_script($javascript);
361 $OUTPUT->include_script('common.js');
362 $OUTPUT->include_script('app.js');
363 $OUTPUT->scripts_path = 'program/js/';
365 // set locale setting
366 rcmail_set_locale($sess_user_lang);
368 // set user-selected charset
369 if (!empty($CONFIG['charset']))
370 $OUTPUT->set_charset($CONFIG['charset']);
372 // add some basic label to client
373 rcube_add_label('loading','checkingmail');
377 // set localization charset based on the given language
378 function rcmail_set_locale($lang)
380 global $OUTPUT, $MBSTRING, $MBSTRING_ENCODING;
381 static $s_mbstring_loaded = NULL;
383 // settings for mbstring module (by Tadashi Jokagi)
384 if ($s_mbstring_loaded===NULL)
386 if ($s_mbstring_loaded = extension_loaded("mbstring"))
389 if (function_exists("mb_mbstring_encodings"))
390 $MBSTRING_ENCODING = mb_mbstring_encodings();
392 $MBSTRING_ENCODING = array("ISO-8859-1", "UTF-7", "UTF7-IMAP", "UTF-8",
393 "ISO-2022-JP", "EUC-JP", "EUCJP-WIN",
396 $MBSTRING_ENCODING = array_map("strtoupper", $MBSTRING_ENCODING);
397 if (in_array("SJIS", $MBSTRING_ENCODING))
398 $MBSTRING_ENCODING[] = "SHIFT_JIS";
403 $MBSTRING_ENCODING = array();
407 if ($MBSTRING && function_exists("mb_language"))
409 if (!@mb_language(strtok($lang, "_")))
410 $MBSTRING = FALSE; // unsupport language
413 $OUTPUT->set_charset(rcube_language_prop($lang, 'charset'));
417 // perfom login to the IMAP server and to the webmail service
418 function rcmail_login($user, $pass, $host=NULL)
420 global $CONFIG, $IMAP, $DB, $sess_user_lang;
424 $host = $CONFIG['default_host'];
426 // Validate that selected host is in the list of configured hosts
427 if (is_array($CONFIG['default_host']))
430 foreach ($CONFIG['default_host'] as $key => $host_allowed)
432 if (!is_numeric($key))
433 $host_allowed = $key;
434 if ($host == $host_allowed)
443 else if (!empty($CONFIG['default_host']) && $host != $CONFIG['default_host'])
447 $a_host = parse_url($host);
450 $host = $a_host['host'];
451 $imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? TRUE : FALSE;
452 $imap_port = isset($a_host['port']) ? $a_host['port'] : ($imap_ssl ? 993 : $CONFIG['default_port']);
455 $imap_port = $CONFIG['default_port'];
458 /* Modify username with domain if required
459 Inspired by Marco <P0L0_notspam_binware.org>
461 // Check if we need to add domain
462 if ($CONFIG['username_domain'] && !strstr($user, '@'))
464 if (is_array($CONFIG['username_domain']) && isset($CONFIG['username_domain'][$host]))
465 $user .= '@'.$CONFIG['username_domain'][$host];
466 else if (!empty($CONFIG['username_domain']))
467 $user .= '@'.$CONFIG['username_domain'];
471 // query if user already registered
472 $sql_result = $DB->query("SELECT user_id, username, language, preferences
473 FROM ".get_table_name('users')."
474 WHERE mail_host=? AND (username=? OR alias=?)",
479 // user already registered -> overwrite username
480 if ($sql_arr = $DB->fetch_assoc($sql_result))
482 $user_id = $sql_arr['user_id'];
483 $user = $sql_arr['username'];
486 // try to resolve email address from virtuser table
487 if (!empty($CONFIG['virtuser_file']) && strstr($user, '@'))
488 $user = rcmail_email2user($user);
491 // exit if IMAP login failed
492 if (!($imap_login = $IMAP->connect($host, $user, $pass, $imap_port, $imap_ssl)))
495 // user already registered
496 if ($user_id && !empty($sql_arr))
499 if (strlen($sql_arr['preferences']))
501 $user_prefs = unserialize($sql_arr['preferences']);
502 $_SESSION['user_prefs'] = $user_prefs;
503 array_merge($CONFIG, $user_prefs);
507 // set user specific language
508 if (strlen($sql_arr['language']))
509 $sess_user_lang = $_SESSION['user_lang'] = $sql_arr['language'];
511 // update user's record
512 $DB->query("UPDATE ".get_table_name('users')."
517 // create new system user
518 else if ($CONFIG['auto_create_user'])
520 $user_id = rcmail_create_user($user, $host);
525 $_SESSION['user_id'] = $user_id;
526 $_SESSION['imap_host'] = $host;
527 $_SESSION['imap_port'] = $imap_port;
528 $_SESSION['imap_ssl'] = $imap_ssl;
529 $_SESSION['username'] = $user;
530 $_SESSION['user_lang'] = $sess_user_lang;
531 $_SESSION['password'] = encrypt_passwd($pass);
533 // force reloading complete list of subscribed mailboxes
534 rcmail_set_imap_prop();
535 $IMAP->clear_cache('mailboxes');
536 $IMAP->create_default_folders();
545 // create new entry in users and identities table
546 function rcmail_create_user($user, $host)
548 global $DB, $CONFIG, $IMAP;
552 // try to resolve user in virtusertable
553 if (!empty($CONFIG['virtuser_file']) && strstr($user, '@')==FALSE)
554 $user_email = rcmail_user2email($user);
556 $DB->query("INSERT INTO ".get_table_name('users')."
557 (created, last_login, username, mail_host, alias, language)
558 VALUES (now(), now(), ?, ?, ?, ?)",
562 $_SESSION['user_lang']);
564 if ($user_id = $DB->insert_id(get_sequence_name('users')))
566 $mail_domain = $host;
567 if (is_array($CONFIG['mail_domain']))
569 if (isset($CONFIG['mail_domain'][$host]))
570 $mail_domain = $CONFIG['mail_domain'][$host];
572 else if (!empty($CONFIG['mail_domain']))
573 $mail_domain = $CONFIG['mail_domain'];
576 $user_email = strstr($user, '@') ? $user : sprintf('%s@%s', $user, $mail_domain);
578 $user_name = $user!=$user_email ? $user : '';
580 // try to resolve the e-mail address from the virtuser table
581 if (!empty($CONFIG['virtuser_query']))
583 $sql_result = $DB->query(preg_replace('/%u/', $user, $CONFIG['virtuser_query']));
584 if ($sql_arr = $DB->fetch_array($sql_result))
585 $user_email = $sql_arr[0];
588 // also create new identity records
589 $DB->query("INSERT INTO ".get_table_name('identities')."
590 (user_id, del, standard, name, email)
591 VALUES (?, 0, 1, ?, ?)",
597 // get existing mailboxes
598 $a_mailboxes = $IMAP->list_mailboxes();
602 raise_error(array('code' => 500,
606 'message' => "Failed to create new user"), TRUE, FALSE);
613 // load virtuser table in array
614 function rcmail_getvirtualfile()
617 if (empty($CONFIG['virtuser_file']) || !is_file($CONFIG['virtuser_file']))
621 $a_lines = file($CONFIG['virtuser_file']);
626 // find matches of the given pattern in virtuser table
627 function rcmail_findinvirtual($pattern)
630 $virtual = rcmail_getvirtualfile();
634 // check each line for matches
635 foreach ($virtual as $line)
638 if (empty($line) || $line{0}=='#')
641 if (eregi($pattern, $line))
649 // resolve username with virtuser table
650 function rcmail_email2user($email)
653 $r = rcmail_findinvirtual("^$email");
655 for ($i=0; $i<count($r); $i++)
658 $arr = preg_split('/\s+/', $data);
661 $user = trim($arr[count($arr)-1]);
670 // resolve e-mail address with virtuser table
671 function rcmail_user2email($user)
674 $r = rcmail_findinvirtual("$user$");
676 for ($i=0; $i<count($r); $i++)
679 $arr = preg_split('/\s+/', $data);
682 $email = trim($arr[0]);
691 function rcmail_save_user_prefs($a_user_prefs)
693 global $DB, $CONFIG, $sess_user_lang;
695 $DB->query("UPDATE ".get_table_name('users')."
699 serialize($a_user_prefs),
701 $_SESSION['user_id']);
703 if ($DB->affected_rows())
705 $_SESSION['user_prefs'] = $a_user_prefs;
706 $CONFIG = array_merge($CONFIG, $a_user_prefs);
714 // overwrite action variable
715 function rcmail_overwrite_action($action)
717 global $OUTPUT, $JS_OBJECT_NAME;
718 $GLOBALS['_action'] = $action;
720 $OUTPUT->add_script(sprintf("\n%s.set_env('action', '%s');", $JS_OBJECT_NAME, $action));
724 function show_message($message, $type='notice', $vars=NULL)
726 global $OUTPUT, $JS_OBJECT_NAME, $REMOTE_REQUEST;
728 $framed = $GLOBALS['_framed'];
729 $command = sprintf("display_message('%s', '%s');",
730 addslashes(rep_specialchars_output(rcube_label(array('name' => $message, 'vars' => $vars)))),
734 return 'this.'.$command;
737 $OUTPUT->add_script(sprintf("%s%s.%s\n",
738 $framed ? sprintf('if(parent.%s)parent.', $JS_OBJECT_NAME) : '',
742 // console(rcube_label($message));
746 function console($msg, $type=1)
748 if ($GLOBALS['REMOTE_REQUEST'])
758 // encrypt IMAP password using DES encryption
759 function encrypt_passwd($pass)
761 $cypher = des(get_des_key(), $pass, 1, 0, NULL);
762 return base64_encode($cypher);
766 // decrypt IMAP password using DES encryption
767 function decrypt_passwd($cypher)
769 $pass = des(get_des_key(), base64_decode($cypher), 0, 0, NULL);
770 return preg_replace('/\x00/', '', $pass);
774 // return a 24 byte key for the DES encryption
775 function get_des_key()
777 $key = !empty($GLOBALS['CONFIG']['des_key']) ? $GLOBALS['CONFIG']['des_key'] : 'rcmail?24BitPwDkeyF**ECB';
780 // make sure the key is exactly 24 chars long
782 $key .= str_repeat('_', 24-$len);
790 // send correct response on a remote request
791 function rcube_remote_response($js_code, $flush=FALSE)
793 global $OUTPUT, $CHARSET;
794 static $s_header_sent = FALSE;
798 $s_header_sent = TRUE;
799 send_nocacheing_headers();
800 header('Content-Type: application/x-javascript; charset='.$CHARSET);
801 print '/** remote response ['.date('d/M/Y h:i:s O')."] **/\n";
804 // send response code
805 print rcube_charset_convert($js_code, $CHARSET, $OUTPUT->get_charset());
807 if ($flush) // flush the output buffer
809 else // terminate script
814 // send correctly formatted response for a request posted to an iframe
815 function rcube_iframe_response($js_code='')
817 global $OUTPUT, $JS_OBJECT_NAME;
819 if (!empty($js_code))
820 $OUTPUT->add_script("if(parent.$JS_OBJECT_NAME){\n" . $js_code . "\n}");
827 // read directory program/localization/ and return a list of available languages
828 function rcube_list_languages()
830 global $CONFIG, $INSTALL_PATH;
831 static $sa_languages = array();
833 if (!sizeof($sa_languages))
835 @include($INSTALL_PATH.'program/localization/index.inc');
837 if ($dh = @opendir($INSTALL_PATH.'program/localization'))
839 while (($name = readdir($dh)) !== false)
841 if ($name{0}=='.' || !is_dir($INSTALL_PATH.'program/localization/'.$name))
844 if ($label = $rcube_languages[$name])
845 $sa_languages[$name] = $label ? $label : $name;
850 return $sa_languages;
854 // add a localized label to the client environment
855 function rcube_add_label()
857 global $OUTPUT, $JS_OBJECT_NAME;
859 $arg_list = func_get_args();
860 foreach ($arg_list as $i => $name)
861 $OUTPUT->add_script(sprintf("%s.add_label('%s', '%s');",
864 rep_specialchars_output(rcube_label($name), 'js')));
868 // remove temp files of a session
869 function rcmail_clear_session_temp($sess_id)
873 $temp_dir = slashify($CONFIG['temp_dir']);
874 $cache_dir = $temp_dir.$sess_id;
876 if (is_dir($cache_dir))
878 clear_directory($cache_dir);
884 // remove all expired message cache records
885 function rcmail_message_cache_gc()
889 // no cache lifetime configured
890 if (empty($CONFIG['message_cache_lifetime']))
893 // get target timestamp
894 $ts = get_offset_time($CONFIG['message_cache_lifetime'], -1);
896 $DB->query("DELETE FROM ".get_table_name('messages')."
897 WHERE created < ".$DB->fromunixtime($ts));
901 // convert a string from one charset to another
902 // this function is not complete and not tested well
903 function rcube_charset_convert($str, $from, $to=NULL)
905 global $MBSTRING, $MBSTRING_ENCODING;
907 $from = strtoupper($from);
908 $to = $to==NULL ? strtoupper($GLOBALS['CHARSET']) : strtoupper($to);
913 // convert charset using mbstring module
916 $to = $to=="UTF-7" ? "UTF7-IMAP" : $to;
917 $from = $from=="UTF-7" ? "UTF7-IMAP": $from;
919 if (in_array($to, $MBSTRING_ENCODING) && in_array($from, $MBSTRING_ENCODING))
920 return mb_convert_encoding($str, $to, $from);
923 // convert charset using iconv module
924 if (function_exists('iconv') && $from!='UTF-7' && $to!='UTF-7')
925 return iconv($from, $to, $str);
929 // convert string to UTF-8
931 $str = rcube_charset_convert(UTF7DecodeString($str), 'ISO-8859-1');
932 else if ($from=='ISO-8859-1' && function_exists('utf8_encode'))
933 $str = utf8_encode($str);
934 else if ($from!='UTF-8')
936 $conv->loadCharset($from);
937 $str = $conv->strToUtf8($str);
940 // encode string for output
942 return UTF7EncodeString($str);
943 else if ($to=='ISO-8859-1' && function_exists('utf8_decode'))
944 return utf8_decode($str);
945 else if ($to!='UTF-8')
947 $conv->loadCharset($to);
948 return $conv->utf8ToStr($str);
951 // return UTF-8 string
957 // replace specials characters to a specific encoding type
958 function rep_specialchars_output($str, $enctype='', $mode='', $newlines=TRUE)
960 global $OUTPUT_TYPE, $OUTPUT;
961 static $html_encode_arr, $js_rep_table, $rtf_rep_table, $xml_rep_table;
964 $enctype = $GLOBALS['OUTPUT_TYPE'];
966 // convert nbsps back to normal spaces if not html
967 if ($enctype!='html')
968 $str = str_replace(chr(160), ' ', $str);
970 // encode for plaintext
971 if ($enctype=='text')
972 return str_replace("\r\n", "\n", $mode=='remove' ? strip_tags($str) : $str);
974 // encode for HTML output
975 if ($enctype=='html')
977 if (!$html_encode_arr)
979 $html_encode_arr = get_html_translation_table(HTML_SPECIALCHARS);
980 unset($html_encode_arr['?']);
981 unset($html_encode_arr['&']);
984 $ltpos = strpos($str, '<');
985 $encode_arr = $html_encode_arr;
987 // don't replace quotes and html tags
988 if (($mode=='show' || $mode=='') && $ltpos!==false && strpos($str, '>', $ltpos)!==false)
990 unset($encode_arr['"']);
991 unset($encode_arr['<']);
992 unset($encode_arr['>']);
994 else if ($mode=='remove')
995 $str = strip_tags($str);
997 $out = strtr($str, $encode_arr);
999 return $newlines ? nl2br($out) : $out;
1003 if ($enctype=='url')
1004 return rawurlencode($str);
1007 // if the replace tables for RTF, XML and JS are not yet defined
1010 $js_rep_table = $rtf_rep_table = $xml_rep_table = array();
1011 $xml_rep_table['&'] = '&';
1013 for ($c=160; $c<256; $c++) // can be increased to support more charsets
1016 $rtf_rep_table[Chr($c)] = "\\'$hex";
1017 $xml_rep_table[Chr($c)] = "&#$c;";
1019 if ($OUTPUT->get_charset()=='ISO-8859-1')
1020 $js_rep_table[Chr($c)] = sprintf("\u%s%s", str_repeat('0', 4-strlen($hex)), $hex);
1023 $js_rep_table['"'] = sprintf("\u%s%s", str_repeat('0', 4-strlen(dechex(34))), dechex(34));
1024 $xml_rep_table['"'] = '"';
1028 if ($enctype=='xml')
1029 return strtr($str, $xml_rep_table);
1031 // encode for javascript use
1034 if ($OUTPUT->get_charset()!='UTF-8')
1035 $str = rcube_charset_convert($str, $GLOBALS['CHARSET'], $OUTPUT->get_charset());
1037 return preg_replace(array("/\r\n/", '/"/', "/([^\\\])'/"), array('\n', '\"', "$1\'"), strtr($str, $js_rep_table));
1041 if ($enctype=='rtf')
1042 return preg_replace("/\r\n/", "\par ", strtr($str, $rtf_rep_table));
1044 // no encoding given -> return original string
1050 * Read input value and convert it for internal use
1051 * Performs stripslashes() and charset conversion if necessary
1053 * @param string Field name to read
1054 * @param int Source to get value from (GPC)
1055 * @param boolean Allow HTML tags in field value
1056 * @param string Charset to convert into
1057 * @return string Field value or NULL if not available
1059 function get_input_value($fname, $source, $allow_html=FALSE, $charset=NULL)
1064 if ($source==RCUBE_INPUT_GET && isset($_GET[$fname]))
1065 $value = $_GET[$fname];
1066 else if ($source==RCUBE_INPUT_POST && isset($_POST[$fname]))
1067 $value = $_POST[$fname];
1068 else if ($source==RCUBE_INPUT_GPC)
1070 if (isset($_POST[$fname]))
1071 $value = $_POST[$fname];
1072 else if (isset($_GET[$fname]))
1073 $value = $_GET[$fname];
1074 else if (isset($_COOKIE[$fname]))
1075 $value = $_COOKIE[$fname];
1078 // strip slashes if magic_quotes enabled
1079 if ((bool)get_magic_quotes_gpc())
1080 $value = stripslashes($value);
1082 // remove HTML tags if not allowed
1084 $value = strip_tags($value);
1086 // convert to internal charset
1087 if (is_object($OUTPUT))
1088 return rcube_charset_convert($value, $OUTPUT->get_charset(), $charset);
1094 * Remove single and double quotes from given string
1096 function strip_quotes($str)
1098 return preg_replace('/[\'"]/', '', $str);
1102 // ************** template parsing and gui functions **************
1105 // return boolean if a specific template exists
1106 function template_exists($name)
1108 global $CONFIG, $OUTPUT;
1109 $skin_path = $CONFIG['skin_path'];
1111 // check template file
1112 return is_file("$skin_path/templates/$name.html");
1116 // get page template an replace variable
1117 // similar function as used in nexImage
1118 function parse_template($name='main', $exit=TRUE)
1120 global $CONFIG, $OUTPUT;
1121 $skin_path = $CONFIG['skin_path'];
1123 // read template file
1125 $path = "$skin_path/templates/$name.html";
1127 if($fp = @fopen($path, 'r'))
1129 $templ = fread($fp, filesize($path));
1134 raise_error(array('code' => 500,
1138 'message' => "Error loading template for '$name'"), TRUE, TRUE);
1143 // parse for specialtags
1144 $output = parse_rcube_xml($templ);
1146 $OUTPUT->write(trim(parse_with_globals($output)), $skin_path);
1154 // replace all strings ($varname) with the content of the according global variable
1155 function parse_with_globals($input)
1157 $GLOBALS['__comm_path'] = $GLOBALS['COMM_PATH'];
1158 $output = preg_replace('/\$(__[a-z0-9_\-]+)/e', '$GLOBALS["\\1"]', $input);
1164 function parse_rcube_xml($input)
1166 $output = preg_replace('/<roundcube:([-_a-z]+)\s+([^>]+)>/Uie', "rcube_xml_command('\\1', '\\2')", $input);
1171 function rcube_xml_command($command, $str_attrib, $add_attrib=array())
1173 global $IMAP, $CONFIG, $OUTPUT;
1175 $command = strtolower($command);
1176 $attrib = parse_attrib_string($str_attrib) + $add_attrib;
1183 if ($attrib['command'])
1184 return rcube_button($attrib);
1189 if ($attrib['name'] || $attrib['command'])
1190 return rep_specialchars_output(rcube_label($attrib));
1193 // create a menu item
1195 if ($attrib['command'] && $attrib['group'])
1196 rcube_menu($attrib);
1201 $path = realpath($CONFIG['skin_path'].$attrib['file']);
1203 if($fp = @fopen($path, 'r'))
1205 $incl = fread($fp, filesize($path));
1207 return parse_rcube_xml($incl);
1211 // return code for a specific application object
1213 $object = strtolower($attrib['name']);
1215 $object_handlers = array(
1217 'loginform' => 'rcmail_login_form',
1218 'username' => 'rcmail_current_username',
1221 'mailboxlist' => 'rcmail_mailbox_list',
1222 'message' => 'rcmail_message_container',
1223 'messages' => 'rcmail_message_list',
1224 'messagecountdisplay' => 'rcmail_messagecount_display',
1225 'quotadisplay' => 'rcmail_quota_display',
1226 'messageheaders' => 'rcmail_message_headers',
1227 'messagebody' => 'rcmail_message_body',
1228 'messageattachments' => 'rcmail_message_attachments',
1229 'blockedobjects' => 'rcmail_remote_objects_msg',
1230 'messagecontentframe' => 'rcmail_messagecontent_frame',
1231 'messagepartframe' => 'rcmail_message_part_frame',
1232 'messagepartcontrols' => 'rcmail_message_part_controls',
1233 'composeheaders' => 'rcmail_compose_headers',
1234 'composesubject' => 'rcmail_compose_subject',
1235 'composebody' => 'rcmail_compose_body',
1236 'composeattachmentlist' => 'rcmail_compose_attachment_list',
1237 'composeattachmentform' => 'rcmail_compose_attachment_form',
1238 'composeattachment' => 'rcmail_compose_attachment_field',
1239 'priorityselector' => 'rcmail_priority_selector',
1240 'charsetselector' => 'rcmail_charset_selector',
1241 'searchform' => 'rcmail_search_form',
1242 'receiptcheckbox' => 'rcmail_receipt_checkbox',
1245 'addresslist' => 'rcmail_contacts_list',
1246 'addressframe' => 'rcmail_contact_frame',
1247 'recordscountdisplay' => 'rcmail_rowcount_display',
1248 'contactdetails' => 'rcmail_contact_details',
1249 'contacteditform' => 'rcmail_contact_editform',
1250 'ldappublicsearch' => 'rcmail_ldap_public_search_form',
1251 'ldappublicaddresslist' => 'rcmail_ldap_public_list',
1254 'userprefs' => 'rcmail_user_prefs_form',
1255 'itentitieslist' => 'rcmail_identities_list',
1256 'identityframe' => 'rcmail_identity_frame',
1257 'identityform' => 'rcube_identity_form',
1258 'foldersubscription' => 'rcube_subscription_form',
1259 'createfolder' => 'rcube_create_folder_form',
1260 'renamefolder' => 'rcube_rename_folder_form',
1261 'composebody' => 'rcmail_compose_body'
1265 // execute object handler function
1266 if ($object_handlers[$object] && function_exists($object_handlers[$object]))
1267 return call_user_func($object_handlers[$object], $attrib);
1269 else if ($object=='productname')
1271 $name = !empty($CONFIG['product_name']) ? $CONFIG['product_name'] : 'RoundCube Webmail';
1272 return rep_specialchars_output($name, 'html', 'all');
1274 else if ($object=='version')
1276 return (string)RCMAIL_VERSION;
1278 else if ($object=='pagetitle')
1280 $task = $GLOBALS['_task'];
1281 $title = !empty($CONFIG['product_name']) ? $CONFIG['product_name'].' :: ' : '';
1284 $title = rcube_label(array('name' => 'welcome', 'vars' => array('product' => $CONFIG['product_name'])));
1285 else if ($task=='mail' && isset($GLOBALS['MESSAGE']['subject']))
1286 $title .= $GLOBALS['MESSAGE']['subject'];
1287 else if (isset($GLOBALS['PAGE_TITLE']))
1288 $title .= $GLOBALS['PAGE_TITLE'];
1289 else if ($task=='mail' && ($mbox_name = $IMAP->get_mailbox_name()))
1290 $title .= rcube_charset_convert($mbox_name, 'UTF-7', 'UTF-8');
1292 $title .= ucfirst($task);
1294 return rep_specialchars_output($title, 'html', 'all');
1304 // create and register a button
1305 function rcube_button($attrib)
1307 global $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $BROWSER, $COMM_PATH, $MAIN_TASKS;
1308 static $sa_buttons = array();
1309 static $s_button_count = 100;
1311 // these commands can be called directly via url
1312 $a_static_commands = array('compose', 'list');
1314 $skin_path = $CONFIG['skin_path'];
1316 if (!($attrib['command'] || $attrib['name']))
1319 // try to find out the button type
1320 if ($attrib['type'])
1321 $attrib['type'] = strtolower($attrib['type']);
1323 $attrib['type'] = ($attrib['image'] || $attrib['imagepas'] || $arg['imageact']) ? 'image' : 'link';
1326 $command = $attrib['command'];
1328 // take the button from the stack
1329 if($attrib['name'] && $sa_buttons[$attrib['name']])
1330 $attrib = $sa_buttons[$attrib['name']];
1332 // add button to button stack
1333 else if($attrib['image'] || $arg['imageact'] || $attrib['imagepas'] || $attrib['class'])
1335 if(!$attrib['name'])
1336 $attrib['name'] = $command;
1338 if (!$attrib['image'])
1339 $attrib['image'] = $attrib['imagepas'] ? $attrib['imagepas'] : $attrib['imageact'];
1341 $sa_buttons[$attrib['name']] = $attrib;
1344 // get saved button for this command/name
1345 else if ($command && $sa_buttons[$command])
1346 $attrib = $sa_buttons[$command];
1352 // set border to 0 because of the link arround the button
1353 if ($attrib['type']=='image' && !isset($attrib['border']))
1354 $attrib['border'] = 0;
1357 $attrib['id'] = sprintf('rcmbtn%d', $s_button_count++);
1359 // get localized text for labels and titles
1360 if ($attrib['title'])
1361 $attrib['title'] = rep_specialchars_output(rcube_label($attrib['title']));
1362 if ($attrib['label'])
1363 $attrib['label'] = rep_specialchars_output(rcube_label($attrib['label']));
1366 $attrib['alt'] = rep_specialchars_output(rcube_label($attrib['alt']));
1368 // set title to alt attribute for IE browsers
1369 if ($BROWSER['ie'] && $attrib['title'] && !$attrib['alt'])
1371 $attrib['alt'] = $attrib['title'];
1372 unset($attrib['title']);
1375 // add empty alt attribute for XHTML compatibility
1376 if (!isset($attrib['alt']))
1377 $attrib['alt'] = '';
1380 // register button in the system
1381 if ($attrib['command'])
1383 $OUTPUT->add_script(sprintf("%s.register_button('%s', '%s', '%s', '%s', '%s', '%s');",
1388 $attrib['imageact'] ? $skin_path.$attrib['imageact'] : $attrib['classact'],
1389 $attrib['imagesel'] ? $skin_path.$attrib['imagesel'] : $attrib['classsel'],
1390 $attrib['imageover'] ? $skin_path.$attrib['imageover'] : ''));
1392 // make valid href to specific buttons
1393 if (in_array($attrib['command'], $MAIN_TASKS))
1394 $attrib['href'] = htmlentities(ereg_replace('_task=[a-z]+', '_task='.$attrib['command'], $COMM_PATH));
1395 else if (in_array($attrib['command'], $a_static_commands))
1396 $attrib['href'] = htmlentities($COMM_PATH.'&_action='.$attrib['command']);
1399 // overwrite attributes
1400 if (!$attrib['href'])
1401 $attrib['href'] = '#';
1404 $attrib['onclick'] = sprintf("return %s.command('%s','%s',this)", $JS_OBJECT_NAME, $command, $attrib['prop']);
1406 if ($command && $attrib['imageover'])
1408 $attrib['onmouseover'] = sprintf("return %s.button_over('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
1409 $attrib['onmouseout'] = sprintf("return %s.button_out('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
1412 if ($command && $attrib['imagesel'])
1414 $attrib['onmousedown'] = sprintf("return %s.button_sel('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
1415 $attrib['onmouseup'] = sprintf("return %s.button_out('%s','%s')", $JS_OBJECT_NAME, $command, $attrib['id']);
1420 // generate image tag
1421 if ($attrib['type']=='image')
1423 $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'width', 'height', 'border', 'hspace', 'vspace', 'align', 'alt'));
1424 $img_tag = sprintf('<img src="%%s"%s />', $attrib_str);
1425 $btn_content = sprintf($img_tag, $skin_path.$attrib['image']);
1426 if ($attrib['label'])
1427 $btn_content .= ' '.$attrib['label'];
1429 $link_attrib = array('href', 'onclick', 'onmouseover', 'onmouseout', 'onmousedown', 'onmouseup', 'title');
1431 else if ($attrib['type']=='link')
1433 $btn_content = $attrib['label'] ? $attrib['label'] : $attrib['command'];
1434 $link_attrib = array('href', 'onclick', 'title', 'id', 'class', 'style');
1436 else if ($attrib['type']=='input')
1438 $attrib['type'] = 'button';
1440 if ($attrib['label'])
1441 $attrib['value'] = $attrib['label'];
1443 $attrib_str = create_attrib_string($attrib, array('type', 'value', 'onclick', 'id', 'class', 'style'));
1444 $out = sprintf('<input%s disabled />', $attrib_str);
1447 // generate html code for button
1450 $attrib_str = create_attrib_string($attrib, $link_attrib);
1451 $out = sprintf('<a%s>%s</a>', $attrib_str, $btn_content);
1458 function rcube_menu($attrib)
1466 function rcube_table_output($attrib, $table_data, $a_show_cols, $id_col)
1470 // allow the following attributes to be added to the <table> tag
1471 $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
1473 $table = '<table' . $attrib_str . ">\n";
1476 $table .= "<thead><tr>\n";
1478 foreach ($a_show_cols as $col)
1479 $table .= '<td class="'.$col.'">' . rep_specialchars_output(rcube_label($col)) . "</td>\n";
1481 $table .= "</tr></thead>\n<tbody>\n";
1485 if (!is_array($table_data))
1487 while ($table_data && ($sql_arr = $DB->fetch_assoc($table_data)))
1489 $zebra_class = $c%2 ? 'even' : 'odd';
1491 $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $sql_arr[$id_col]);
1494 foreach ($a_show_cols as $col)
1496 $cont = rep_specialchars_output($sql_arr[$col]);
1497 $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1500 $table .= "</tr>\n";
1506 foreach ($table_data as $row_data)
1508 $zebra_class = $c%2 ? 'even' : 'odd';
1510 $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $row_data[$id_col]);
1513 foreach ($a_show_cols as $col)
1515 $cont = rep_specialchars_output($row_data[$col]);
1516 $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1519 $table .= "</tr>\n";
1524 // complete message table
1525 $table .= "</tbody></table>\n";
1532 function rcmail_get_edit_field($col, $value, $attrib, $type='text')
1535 $attrib['name'] = $fname;
1537 if ($type=='checkbox')
1539 $attrib['value'] = '1';
1540 $input = new checkbox($attrib);
1542 else if ($type=='textarea')
1544 $attrib['cols'] = $attrib['size'];
1545 $input = new textarea($attrib);
1548 $input = new textfield($attrib);
1550 // use value from post
1551 if (!empty($_POST[$fname]))
1552 $value = $_POST[$fname];
1554 $out = $input->show($value);
1560 // compose a valid attribute string for HTML tags
1561 function create_attrib_string($attrib, $allowed_attribs=array('id', 'class', 'style'))
1563 // allow the following attributes to be added to the <iframe> tag
1565 foreach ($allowed_attribs as $a)
1566 if (isset($attrib[$a]))
1567 $attrib_str .= sprintf(' %s="%s"', $a, str_replace('"', '"', $attrib[$a]));
1573 // convert a HTML attribute string attributes to an associative array (name => value)
1574 function parse_attrib_string($str)
1577 preg_match_all('/\s*([-_a-z]+)=["]([^"]+)["]?/i', stripslashes($str), $regs, PREG_SET_ORDER);
1579 // convert attributes to an associative array (name => value)
1581 foreach ($regs as $attr)
1582 $attrib[strtolower($attr[1])] = $attr[2];
1588 function format_date($date, $format=NULL)
1590 global $CONFIG, $sess_user_lang;
1594 if (is_numeric($date))
1596 else if (!empty($date))
1597 $ts = @strtotime($date);
1602 // get user's timezone
1603 $tz = $CONFIG['timezone'];
1604 if ($CONFIG['dst_active'])
1607 // convert time to user's timezone
1608 $timestamp = $ts - date('Z', $ts) + ($tz * 3600);
1610 // get current timestamp in user's timezone
1611 $now = time(); // local time
1612 $now -= (int)date('Z'); // make GMT time
1613 $now += ($tz * 3600); // user's time
1614 $now_date = getdate();
1616 $today_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday'], $now_date['year']);
1617 $week_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday']-6, $now_date['year']);
1619 // define date format depending on current time
1620 if ($CONFIG['prettydate'] && !$format && $timestamp > $today_limit)
1621 return sprintf('%s %s', rcube_label('today'), date('H:i', $timestamp));
1622 else if ($CONFIG['prettydate'] && !$format && $timestamp > $week_limit)
1623 $format = $CONFIG['date_short'] ? $CONFIG['date_short'] : 'D H:i';
1625 $format = $CONFIG['date_long'] ? $CONFIG['date_long'] : 'd.m.Y H:i';
1628 // parse format string manually in order to provide localized weekday and month names
1629 // an alternative would be to convert the date() format string to fit with strftime()
1631 for($i=0; $i<strlen($format); $i++)
1633 if ($format{$i}=='\\') // skip escape chars
1636 // write char "as-is"
1637 if ($format{$i}==' ' || $format{$i-1}=='\\')
1638 $out .= $format{$i};
1640 else if ($format{$i}=='D')
1641 $out .= rcube_label(strtolower(date('D', $timestamp)));
1643 else if ($format{$i}=='l')
1644 $out .= rcube_label(strtolower(date('l', $timestamp)));
1645 // month name (short)
1646 else if ($format{$i}=='M')
1647 $out .= rcube_label(strtolower(date('M', $timestamp)));
1648 // month name (long)
1649 else if ($format{$i}=='F')
1650 $out .= rcube_label(strtolower(date('F', $timestamp)));
1652 $out .= date($format{$i}, $timestamp);
1659 // ************** functions delivering gui objects **************
1663 function rcmail_message_container($attrib)
1665 global $OUTPUT, $JS_OBJECT_NAME;
1668 $attrib['id'] = 'rcmMessageContainer';
1670 // allow the following attributes to be added to the <table> tag
1671 $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
1672 $out = '<div' . $attrib_str . "></div>";
1674 $OUTPUT->add_script("$JS_OBJECT_NAME.gui_object('message', '$attrib[id]');");
1680 // return the IMAP username of the current session
1681 function rcmail_current_username($attrib)
1687 if (!empty($s_username))
1690 // get e-mail address form default identity
1691 $sql_result = $DB->query("SELECT email AS mailto
1692 FROM ".get_table_name('identities')."
1696 $_SESSION['user_id']);
1698 if ($DB->num_rows($sql_result))
1700 $sql_arr = $DB->fetch_assoc($sql_result);
1701 $s_username = $sql_arr['mailto'];
1703 else if (strstr($_SESSION['username'], '@'))
1704 $s_username = $_SESSION['username'];
1706 $s_username = $_SESSION['username'].'@'.$_SESSION['imap_host'];
1712 // return code for the webmail login form
1713 function rcmail_login_form($attrib)
1715 global $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $SESS_HIDDEN_FIELD;
1718 $labels['user'] = rcube_label('username');
1719 $labels['pass'] = rcube_label('password');
1720 $labels['host'] = rcube_label('server');
1722 $input_user = new textfield(array('name' => '_user', 'id' => 'rcmloginuser', 'size' => 30));
1723 $input_pass = new passwordfield(array('name' => '_pass', 'id' => 'rcmloginpwd', 'size' => 30));
1724 $input_action = new hiddenfield(array('name' => '_action', 'value' => 'login'));
1727 $fields['user'] = $input_user->show(get_input_value('_user', RCUBE_INPUT_POST));
1728 $fields['pass'] = $input_pass->show();
1729 $fields['action'] = $input_action->show();
1731 if (is_array($CONFIG['default_host']))
1733 $select_host = new select(array('name' => '_host', 'id' => 'rcmloginhost'));
1735 foreach ($CONFIG['default_host'] as $key => $value)
1736 $select_host->add($value, (is_numeric($key) ? $value : $key));
1738 $fields['host'] = $select_host->show($_POST['_host']);
1740 else if (!strlen($CONFIG['default_host']))
1742 $input_host = new textfield(array('name' => '_host', 'id' => 'rcmloginhost', 'size' => 30));
1743 $fields['host'] = $input_host->show($_POST['_host']);
1746 $form_name = strlen($attrib['form']) ? $attrib['form'] : 'form';
1747 $form_start = !strlen($attrib['form']) ? '<form name="form" action="./" method="post">' : '';
1748 $form_end = !strlen($attrib['form']) ? '</form>' : '';
1750 if ($fields['host'])
1755 <td class="title"><label for="rcmloginhost">$labels[host]</label></td>
1756 <td>$fields[host]</td>
1760 $OUTPUT->add_script("$JS_OBJECT_NAME.gui_object('loginform', '$form_name');");
1768 <td class="title"><label for="rcmloginuser">$labels[user]</label></td>
1769 <td>$fields[user]</td>
1773 <td class="title"><label for="rcmloginpwd">$labels[pass]</label></td>
1774 <td>$fields[pass]</td>
1784 function rcmail_charset_selector($attrib)
1788 // pass the following attributes to the form class
1789 $field_attrib = array('name' => '_charset');
1790 foreach ($attrib as $attr => $value)
1791 if (in_array($attr, array('id', 'class', 'style', 'size', 'tabindex')))
1792 $field_attrib[$attr] = $value;
1795 'US-ASCII' => 'ASCII (English)',
1796 'EUC-JP' => 'EUC-JP (Japanese)',
1797 'EUC-KR' => 'EUC-KR (Korean)',
1798 'BIG5' => 'BIG5 (Chinese)',
1799 'GB2312' => 'GB2312 (Chinese)',
1800 'ISO-2022-JP' => 'ISO-2022-JP (Japanese)',
1801 'ISO-8859-1' => 'ISO-8859-1 (Latin-1)',
1802 'ISO-8859-2' => 'ISO-8895-2 (Central European)',
1803 'ISO-8859-7' => 'ISO-8859-7 (Greek)',
1804 'ISO-8859-9' => 'ISO-8859-9 (Turkish)',
1805 'Windows-1251' => 'Windows-1251 (Cyrillic)',
1806 'Windows-1252' => 'Windows-1252 (Western)',
1807 'Windows-1255' => 'Windows-1255 (Hebrew)',
1808 'Windows-1256' => 'Windows-1256 (Arabic)',
1809 'Windows-1257' => 'Windows-1257 (Baltic)',
1813 $select = new select($field_attrib);
1814 $select->add(array_values($charsets), array_keys($charsets));
1816 $set = $_POST['_charset'] ? $_POST['_charset'] : $OUTPUT->get_charset();
1817 return $select->show($set);
1821 /****** debugging function ********/
1823 function rcube_timer()
1825 list($usec, $sec) = explode(" ", microtime());
1826 return ((float)$usec + (float)$sec);
1830 function rcube_print_time($timer, $label='Timer')
1832 static $print_count = 0;
1835 $now = rcube_timer();
1836 $diff = $now-$timer;
1839 $label = 'Timer '.$print_count;
1841 console(sprintf("%s: %0.4f sec", $label, $diff));