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 903 2007-10-22 06:52:13Z thomasb $
23 * RoundCube Webmail common functions
26 * @author Thomas Bruederli <roundcube@gmail.com>
29 require_once('lib/utf7.inc');
30 require_once('include/rcube_shared.inc');
31 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;
52 $BROWSER = rcube_browser();
55 $CONFIG = rcmail_load_config();
57 // set session garbage collecting time according to session_lifetime
58 if (!empty($CONFIG['session_lifetime']))
59 ini_set('session.gc_maxlifetime', ($CONFIG['session_lifetime']) * 120);
61 // prepare DB connection
62 $dbwrapper = empty($CONFIG['db_backend']) ? 'db' : $CONFIG['db_backend'];
63 $dbclass = "rcube_" . $dbwrapper;
64 require_once("include/$dbclass.inc");
66 $DB = new $dbclass($CONFIG['db_dsnw'], $CONFIG['db_dsnr'], $CONFIG['db_persistent']);
67 $DB->sqlite_initials = $INSTALL_PATH.'SQL/sqlite.initial.sql';
70 // use database for storing session data
71 include_once('include/session.inc');
75 $sess_id = session_id();
77 // create session and set session vars
78 if (!isset($_SESSION['auth_time']))
80 $_SESSION['user_lang'] = rcube_language_prop($CONFIG['locale_string']);
81 $_SESSION['auth_time'] = time();
82 $_SESSION['temp'] = true;
85 // set session vars global
86 $sess_user_lang = rcube_language_prop($_SESSION['user_lang']);
89 // overwrite config with user preferences
90 if (is_array($_SESSION['user_prefs']))
91 $CONFIG = array_merge($CONFIG, $_SESSION['user_prefs']);
94 // reset some session parameters when changing task
95 if ($_SESSION['task'] != $task)
96 unset($_SESSION['page']);
98 // set current task to session
99 $_SESSION['task'] = $task;
101 // create IMAP object
107 if ($CONFIG['locale_string'])
108 setlocale(LC_ALL, $CONFIG['locale_string']);
109 else if ($sess_user_lang)
110 setlocale(LC_ALL, $sess_user_lang);
113 register_shutdown_function('rcmail_shutdown');
118 * Load roundcube configuration array
120 * @return array Named configuration parameters
122 function rcmail_load_config()
124 global $INSTALL_PATH;
127 include_once('config/main.inc.php');
128 $conf = is_array($rcmail_config) ? $rcmail_config : array();
130 // load host-specific configuration
131 rcmail_load_host_config($conf);
133 $conf['skin_path'] = $conf['skin_path'] ? unslashify($conf['skin_path']) : 'skins/default';
136 include_once('config/db.inc.php');
137 $conf = array_merge($conf, $rcmail_config);
139 if (empty($conf['log_dir']))
140 $conf['log_dir'] = $INSTALL_PATH.'logs';
142 $conf['log_dir'] = unslashify($conf['log_dir']);
144 // set PHP error logging according to config
145 if ($conf['debug_level'] & 1)
147 ini_set('log_errors', 1);
148 ini_set('error_log', $conf['log_dir'].'/errors');
150 if ($conf['debug_level'] & 4)
151 ini_set('display_errors', 1);
153 ini_set('display_errors', 0);
160 * Load a host-specific config file if configured
161 * This will merge the host specific configuration with the given one
163 * @param array Global configuration parameters
165 function rcmail_load_host_config(&$config)
169 if (is_array($config['include_host_config']))
170 $fname = $config['include_host_config'][$_SERVER['HTTP_HOST']];
171 else if (!empty($config['include_host_config']))
172 $fname = preg_replace('/[^a-z0-9\.\-_]/i', '', $_SERVER['HTTP_HOST']) . '.inc.php';
174 if ($fname && is_file('config/'.$fname))
176 include('config/'.$fname);
177 $config = array_merge($config, $rcmail_config);
183 * Create unique authorization hash
185 * @param string Session ID
186 * @param int Timestamp
187 * @return string The generated auth hash
189 function rcmail_auth_hash($sess_id, $ts)
193 $auth_string = sprintf('rcmail*sess%sR%s*Chk:%s;%s',
196 $CONFIG['ip_check'] ? $_SERVER['REMOTE_ADDR'] : '***.***.***.***',
197 $_SERVER['HTTP_USER_AGENT']);
199 if (function_exists('sha1'))
200 return sha1($auth_string);
202 return md5($auth_string);
207 * Check the auth hash sent by the client against the local session credentials
209 * @return boolean True if valid, False if not
211 function rcmail_authenticate_session()
213 global $CONFIG, $SESS_CLIENT_IP, $SESS_CHANGED;
215 // advanced session authentication
216 if ($CONFIG['double_auth'])
219 $valid = ($_COOKIE['sessauth'] == rcmail_auth_hash(session_id(), $_SESSION['auth_time']) ||
220 $_COOKIE['sessauth'] == rcmail_auth_hash(session_id(), $_SESSION['last_auth']));
222 // renew auth cookie every 5 minutes (only for GET requests)
223 if (!$valid || ($_SERVER['REQUEST_METHOD']!='POST' && $now-$_SESSION['auth_time'] > 300))
225 $_SESSION['last_auth'] = $_SESSION['auth_time'];
226 $_SESSION['auth_time'] = $now;
227 setcookie('sessauth', rcmail_auth_hash(session_id(), $now));
231 $valid = $CONFIG['ip_check'] ? $_SERVER['REMOTE_ADDR'] == $SESS_CLIENT_IP : true;
233 // check session filetime
234 if (!empty($CONFIG['session_lifetime']) && isset($SESS_CHANGED) && $SESS_CHANGED + $CONFIG['session_lifetime']*60 < time())
242 * Create global IMAP object and connect to server
244 * @param boolean True if connection should be established
246 function rcmail_imap_init($connect=FALSE)
248 global $CONFIG, $DB, $IMAP, $OUTPUT;
250 $IMAP = new rcube_imap($DB);
251 $IMAP->debug_level = $CONFIG['debug_level'];
252 $IMAP->skip_deleted = $CONFIG['skip_deleted'];
255 // connect with stored session data
258 if (!($conn = $IMAP->connect($_SESSION['imap_host'], $_SESSION['username'], decrypt_passwd($_SESSION['password']), $_SESSION['imap_port'], $_SESSION['imap_ssl'])))
259 $OUTPUT->show_message('imaperror', 'error');
261 rcmail_set_imap_prop();
264 // enable caching of imap data
265 if ($CONFIG['enable_caching']===TRUE)
266 $IMAP->set_caching(TRUE);
268 // set pagesize from config
269 if (isset($CONFIG['pagesize']))
270 $IMAP->set_pagesize($CONFIG['pagesize']);
275 * Set root dir and last stored mailbox
276 * This must be done AFTER connecting to the server!
278 function rcmail_set_imap_prop()
280 global $CONFIG, $IMAP;
282 // set root dir from config
283 if (!empty($CONFIG['imap_root']))
284 $IMAP->set_rootdir($CONFIG['imap_root']);
286 if (is_array($CONFIG['default_imap_folders']))
287 $IMAP->set_default_mailboxes($CONFIG['default_imap_folders']);
289 if (!empty($_SESSION['mbox']))
290 $IMAP->set_mailbox($_SESSION['mbox']);
291 if (isset($_SESSION['page']))
292 $IMAP->set_page($_SESSION['page']);
297 * Do these things on script shutdown
299 function rcmail_shutdown()
301 global $IMAP, $CONTACTS;
303 if (is_object($IMAP))
306 $IMAP->write_cache();
309 if (is_object($CONTACTS))
312 // before closing the database connection, write session data
313 session_write_close();
318 * Destroy session data and remove cookie
320 function rcmail_kill_session()
322 // save user preferences
323 $a_user_prefs = $_SESSION['user_prefs'];
324 if (!is_array($a_user_prefs))
325 $a_user_prefs = array();
327 if ((isset($_SESSION['sort_col']) && $_SESSION['sort_col']!=$a_user_prefs['message_sort_col']) ||
328 (isset($_SESSION['sort_order']) && $_SESSION['sort_order']!=$a_user_prefs['message_sort_order']))
330 $a_user_prefs['message_sort_col'] = $_SESSION['sort_col'];
331 $a_user_prefs['message_sort_order'] = $_SESSION['sort_order'];
332 rcmail_save_user_prefs($a_user_prefs);
335 $_SESSION = array('user_lang' => $GLOBALS['sess_user_lang'], 'auth_time' => time(), 'temp' => true);
336 setcookie('sessauth', '-del-', time()-60);
341 * Return correct name for a specific database table
343 * @param string Table name
344 * @return string Translated table name
346 function get_table_name($table)
350 // return table name if configured
351 $config_key = 'db_table_'.$table;
353 if (strlen($CONFIG[$config_key]))
354 return $CONFIG[$config_key];
361 * Return correct name for a specific database sequence
362 * (used for Postres only)
364 * @param string Secuence name
365 * @return string Translated sequence name
367 function get_sequence_name($sequence)
371 // return table name if configured
372 $config_key = 'db_sequence_'.$sequence;
374 if (strlen($CONFIG[$config_key]))
375 return $CONFIG[$config_key];
382 * Check the given string and returns language properties
384 * @param string Language code
385 * @param string Peropert name
386 * @return string Property value
388 function rcube_language_prop($lang, $prop='lang')
390 global $INSTALL_PATH;
391 static $rcube_languages, $rcube_language_aliases, $rcube_charsets;
393 if (empty($rcube_languages))
394 @include($INSTALL_PATH.'program/localization/index.inc');
396 // check if we have an alias for that language
397 if (!isset($rcube_languages[$lang]) && isset($rcube_language_aliases[$lang]))
398 $lang = $rcube_language_aliases[$lang];
400 // try the first two chars
401 if (!isset($rcube_languages[$lang]) && strlen($lang)>2)
403 $lang = substr($lang, 0, 2);
404 $lang = rcube_language_prop($lang);
407 if (!isset($rcube_languages[$lang]))
410 // language has special charset configured
411 if (isset($rcube_charsets[$lang]))
412 $charset = $rcube_charsets[$lang];
417 if ($prop=='charset')
425 * Init output object for GUI and add common scripts.
426 * This will instantiate a rcmail_template object and set
427 * environment vars according to the current session and configuration
429 function rcmail_load_gui()
431 global $CONFIG, $OUTPUT, $sess_user_lang;
434 $OUTPUT = new rcmail_template($CONFIG, $GLOBALS['_task']);
435 $OUTPUT->set_env('comm_path', $GLOBALS['COMM_PATH']);
437 if (is_array($CONFIG['javascript_config']))
439 foreach ($CONFIG['javascript_config'] as $js_config_var)
440 $OUTPUT->set_env($js_config_var, $CONFIG[$js_config_var]);
443 if (!empty($GLOBALS['_framed']))
444 $OUTPUT->set_env('framed', true);
446 // set locale setting
447 rcmail_set_locale($sess_user_lang);
449 // set user-selected charset
450 if (!empty($CONFIG['charset']))
451 $OUTPUT->set_charset($CONFIG['charset']);
453 // register common UI objects
454 $OUTPUT->add_handlers(array(
455 'loginform' => 'rcmail_login_form',
456 'username' => 'rcmail_current_username',
457 'message' => 'rcmail_message_container',
458 'charsetselector' => 'rcmail_charset_selector',
461 // add some basic label to client
462 if (!$OUTPUT->ajax_call)
463 rcube_add_label('loading', 'movingmessage');
468 * Set localization charset based on the given language.
469 * This also creates a global property for mbstring usage.
471 function rcmail_set_locale($lang)
473 global $OUTPUT, $MBSTRING;
474 static $s_mbstring_loaded = NULL;
476 // settings for mbstring module (by Tadashi Jokagi)
477 if (is_null($s_mbstring_loaded))
478 $MBSTRING = $s_mbstring_loaded = extension_loaded("mbstring");
480 $MBSTRING = $s_mbstring_loaded = FALSE;
483 mb_internal_encoding(RCMAIL_CHARSET);
485 $OUTPUT->set_charset(rcube_language_prop($lang, 'charset'));
490 * Auto-select IMAP host based on the posted login information
492 * @return string Selected IMAP host
494 function rcmail_autoselect_host()
498 $host = isset($_POST['_host']) ? get_input_value('_host', RCUBE_INPUT_POST) : $CONFIG['default_host'];
501 list($user, $domain) = explode('@', get_input_value('_user', RCUBE_INPUT_POST));
504 foreach ($host as $imap_host => $mail_domains)
505 if (is_array($mail_domains) && in_array($domain, $mail_domains))
512 // take the first entry if $host is still an array
514 $host = array_shift($host);
522 * Perfom login to the IMAP server and to the webmail service.
523 * This will also create a new user entry if auto_create_user is configured.
525 * @param string IMAP user name
526 * @param string IMAP password
527 * @param string IMAP host
528 * @return boolean True on success, False on failure
530 function rcmail_login($user, $pass, $host=NULL)
532 global $CONFIG, $IMAP, $DB, $sess_user_lang;
536 $host = $CONFIG['default_host'];
538 // Validate that selected host is in the list of configured hosts
539 if (is_array($CONFIG['default_host']))
542 foreach ($CONFIG['default_host'] as $key => $host_allowed)
544 if (!is_numeric($key))
545 $host_allowed = $key;
546 if ($host == $host_allowed)
555 else if (!empty($CONFIG['default_host']) && $host != $CONFIG['default_host'])
559 $a_host = parse_url($host);
562 $host = $a_host['host'];
563 $imap_ssl = (isset($a_host['scheme']) && in_array($a_host['scheme'], array('ssl','imaps','tls'))) ? TRUE : FALSE;
564 $imap_port = isset($a_host['port']) ? $a_host['port'] : ($imap_ssl ? 993 : $CONFIG['default_port']);
567 $imap_port = $CONFIG['default_port'];
570 /* Modify username with domain if required
571 Inspired by Marco <P0L0_notspam_binware.org>
573 // Check if we need to add domain
574 if (!empty($CONFIG['username_domain']) && !strpos($user, '@'))
576 if (is_array($CONFIG['username_domain']) && isset($CONFIG['username_domain'][$host]))
577 $user .= '@'.$CONFIG['username_domain'][$host];
578 else if (is_string($CONFIG['username_domain']))
579 $user .= '@'.$CONFIG['username_domain'];
582 // try to resolve email address from virtuser table
583 if (!empty($CONFIG['virtuser_file']) && strpos($user, '@'))
584 $user = rcmail_email2user($user);
586 // lowercase username if it's an e-mail address (#1484473)
587 if (strpos($user, '@'))
588 $user = strtolower($user);
590 // query if user already registered
591 $sql_result = $DB->query(
592 "SELECT user_id, username, language, preferences
593 FROM ".get_table_name('users')."
594 WHERE mail_host=? AND (username=? OR alias=?)",
599 // user already registered -> overwrite username
600 if ($sql_arr = $DB->fetch_assoc($sql_result))
602 $user_id = $sql_arr['user_id'];
603 $user = $sql_arr['username'];
606 // exit if IMAP login failed
607 if (!($imap_login = $IMAP->connect($host, $user, $pass, $imap_port, $imap_ssl)))
610 // user already registered
611 if ($user_id && !empty($sql_arr))
614 if (strlen($sql_arr['preferences']))
616 $user_prefs = unserialize($sql_arr['preferences']);
617 $_SESSION['user_prefs'] = $user_prefs;
618 array_merge($CONFIG, $user_prefs);
622 // set user specific language
623 if (strlen($sql_arr['language']))
624 $sess_user_lang = $_SESSION['user_lang'] = $sql_arr['language'];
626 // update user's record
627 $DB->query("UPDATE ".get_table_name('users')."
628 SET last_login=".$DB->now()."
632 // create new system user
633 else if ($CONFIG['auto_create_user'])
635 $user_id = rcmail_create_user($user, $host);
642 'file' => "config/main.inc.php",
643 'message' => "Acces denied for new user $user. 'auto_create_user' is disabled"
649 $_SESSION['user_id'] = $user_id;
650 $_SESSION['imap_host'] = $host;
651 $_SESSION['imap_port'] = $imap_port;
652 $_SESSION['imap_ssl'] = $imap_ssl;
653 $_SESSION['username'] = $user;
654 $_SESSION['user_lang'] = $sess_user_lang;
655 $_SESSION['password'] = encrypt_passwd($pass);
656 $_SESSION['login_time'] = mktime();
658 // force reloading complete list of subscribed mailboxes
659 rcmail_set_imap_prop();
660 $IMAP->clear_cache('mailboxes');
661 $IMAP->create_default_folders();
671 * Create new entry in users and identities table
673 * @param string User name
674 * @param string IMAP host
675 * @return mixed New user ID or False on failure
677 function rcmail_create_user($user, $host)
679 global $DB, $CONFIG, $IMAP;
683 // try to resolve user in virtusertable
684 if (!empty($CONFIG['virtuser_file']) && !strpos($user, '@'))
685 $user_email = rcmail_user2email($user);
687 $DB->query("INSERT INTO ".get_table_name('users')."
688 (created, last_login, username, mail_host, alias, language)
689 VALUES (".$DB->now().", ".$DB->now().", ?, ?, ?, ?)",
690 strip_newlines($user),
691 strip_newlines($host),
692 strip_newlines($user_email),
693 $_SESSION['user_lang']);
695 if ($user_id = $DB->insert_id(get_sequence_name('users')))
697 $mail_domain = rcmail_mail_domain($host);
700 $user_email = strpos($user, '@') ? $user : sprintf('%s@%s', $user, $mail_domain);
702 $user_name = $user!=$user_email ? $user : '';
704 // try to resolve the e-mail address from the virtuser table
705 if (!empty($CONFIG['virtuser_query']) &&
706 ($sql_result = $DB->query(preg_replace('/%u/', $DB->quote($user), $CONFIG['virtuser_query']))) &&
709 while ($sql_arr = $DB->fetch_array($sql_result))
711 $DB->query("INSERT INTO ".get_table_name('identities')."
712 (user_id, del, standard, name, email)
713 VALUES (?, 0, 1, ?, ?)",
715 strip_newlines($user_name),
716 preg_replace('/^@/', $user . '@', $sql_arr[0]));
721 // also create new identity records
722 $DB->query("INSERT INTO ".get_table_name('identities')."
723 (user_id, del, standard, name, email)
724 VALUES (?, 0, 1, ?, ?)",
726 strip_newlines($user_name),
727 strip_newlines($user_email));
730 // get existing mailboxes
731 $a_mailboxes = $IMAP->list_mailboxes();
740 'message' => "Failed to create new user"), TRUE, FALSE);
748 * Load virtuser table in array
750 * @return array Virtuser table entries
752 function rcmail_getvirtualfile()
755 if (empty($CONFIG['virtuser_file']) || !is_file($CONFIG['virtuser_file']))
759 $a_lines = file($CONFIG['virtuser_file']);
765 * Find matches of the given pattern in virtuser table
767 * @param string Regular expression to search for
768 * @return array Matching entries
770 function rcmail_findinvirtual($pattern)
773 $virtual = rcmail_getvirtualfile();
777 // check each line for matches
778 foreach ($virtual as $line)
781 if (empty($line) || $line{0}=='#')
784 if (eregi($pattern, $line))
793 * Resolve username using a virtuser table
795 * @param string E-mail address to resolve
796 * @return string Resolved IMAP username
798 function rcmail_email2user($email)
801 $r = rcmail_findinvirtual("^$email");
803 for ($i=0; $i<count($r); $i++)
806 $arr = preg_split('/\s+/', $data);
809 $user = trim($arr[count($arr)-1]);
819 * Resolve e-mail address from virtuser table
821 * @param string User name
822 * @return string Resolved e-mail address
824 function rcmail_user2email($user)
827 $r = rcmail_findinvirtual("$user$");
829 for ($i=0; $i<count($r); $i++)
832 $arr = preg_split('/\s+/', $data);
835 $email = trim($arr[0]);
845 * Write the given user prefs to the user's record
847 * @param mixed User prefs to save
848 * @return boolean True on success, False on failure
850 function rcmail_save_user_prefs($a_user_prefs)
852 global $DB, $CONFIG, $sess_user_lang;
854 // merge (partial) prefs array with existing settings
855 $a_user_prefs += (array)$_SESSION['user_prefs'];
857 $DB->query("UPDATE ".get_table_name('users')."
861 serialize($a_user_prefs),
863 $_SESSION['user_id']);
865 if ($DB->affected_rows())
867 $_SESSION['user_prefs'] = $a_user_prefs;
868 $CONFIG = array_merge($CONFIG, $a_user_prefs);
877 * Overwrite action variable
879 * @param string New action value
881 function rcmail_overwrite_action($action)
884 $GLOBALS['_action'] = $action;
885 $OUTPUT->set_env('action', $action);
890 * Compose an URL for a specific action
892 * @param string Request action
893 * @param array More URL parameters
894 * @param string Request task (omit if the same)
895 * @return The application URL
897 function rcmail_url($action, $p=array(), $task=null)
899 global $MAIN_TASKS, $COMM_PATH;
903 if ($task && in_array($task, $MAIN_TASKS))
904 $base = ereg_replace('_task=[a-z]+', '_task='.$task, $COMM_PATH);
907 foreach ($p as $key => $val)
908 $qstring .= '&'.urlencode($key).'='.urlencode($val);
910 return $base . ($action ? '&_action='.$action : '') . $qstring;
915 function show_message($message, $type='notice', $vars=NULL)
918 $OUTPUT->show_message($message, $type, $vars);
923 * Encrypt IMAP password using DES encryption
925 * @param string Password to encrypt
926 * @return string Encryprted string
928 function encrypt_passwd($pass)
930 $td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_ECB, "");
931 $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
932 mcrypt_generic_init($td, get_des_key(), $iv);
933 $cypher = mcrypt_generic($td, $pass);
934 mcrypt_generic_deinit($td);
935 mcrypt_module_close($td);
936 return base64_encode($cypher);
941 * Decrypt IMAP password using DES encryption
943 * @param string Encrypted password
944 * @return string Plain password
946 function decrypt_passwd($cypher)
948 $td = mcrypt_module_open(MCRYPT_TripleDES, "", MCRYPT_MODE_ECB, "");
949 $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
950 mcrypt_generic_init($td, get_des_key(), $iv);
951 $pass = mdecrypt_generic($td, base64_decode($cypher));
952 mcrypt_generic_deinit($td);
953 mcrypt_module_close($td);
954 return preg_replace('/\x00/', '', $pass);
959 * Return a 24 byte key for the DES encryption
961 * @return string DES encryption key
963 function get_des_key()
965 $key = !empty($GLOBALS['CONFIG']['des_key']) ? $GLOBALS['CONFIG']['des_key'] : 'rcmail?24BitPwDkeyF**ECB';
968 // make sure the key is exactly 24 chars long
970 $key .= str_repeat('_', 24-$len);
979 * Read directory program/localization and return a list of available languages
981 * @return array List of available localizations
983 function rcube_list_languages()
985 global $CONFIG, $INSTALL_PATH;
986 static $sa_languages = array();
988 if (!sizeof($sa_languages))
990 @include($INSTALL_PATH.'program/localization/index.inc');
992 if ($dh = @opendir($INSTALL_PATH.'program/localization'))
994 while (($name = readdir($dh)) !== false)
996 if ($name{0}=='.' || !is_dir($INSTALL_PATH.'program/localization/'.$name))
999 if ($label = $rcube_languages[$name])
1000 $sa_languages[$name] = $label ? $label : $name;
1005 return $sa_languages;
1010 * Add a localized label to the client environment
1012 function rcube_add_label()
1016 $arg_list = func_get_args();
1017 foreach ($arg_list as $i => $name)
1018 $OUTPUT->command('add_label', $name, rcube_label($name));
1023 * Garbage collector function for temp files.
1024 * Remove temp files older than two days
1026 function rcmail_temp_gc()
1028 $tmp = unslashify($CONFIG['temp_dir']);
1029 $expire = mktime() - 172800; // expire in 48 hours
1031 if ($dir = opendir($tmp))
1033 while (($fname = readdir($dir)) !== false)
1035 if ($fname{0} == '.')
1038 if (filemtime($tmp.'/'.$fname) < $expire)
1039 @unlink($tmp.'/'.$fname);
1048 * Garbage collector for cache entries.
1049 * Remove all expired message cache records
1051 function rcmail_message_cache_gc()
1053 global $DB, $CONFIG;
1055 // no cache lifetime configured
1056 if (empty($CONFIG['message_cache_lifetime']))
1059 // get target timestamp
1060 $ts = get_offset_time($CONFIG['message_cache_lifetime'], -1);
1062 $DB->query("DELETE FROM ".get_table_name('messages')."
1063 WHERE created < ".$DB->fromunixtime($ts));
1068 * Convert a string from one charset to another.
1069 * Uses mbstring and iconv functions if possible
1071 * @param string Input string
1072 * @param string Suspected charset of the input string
1073 * @param string Target charset to convert to; defaults to RCMAIL_CHARSET
1074 * @return Converted string
1076 function rcube_charset_convert($str, $from, $to=NULL)
1080 $from = strtoupper($from);
1081 $to = $to==NULL ? strtoupper(RCMAIL_CHARSET) : strtoupper($to);
1083 if ($from==$to || $str=='' || empty($from))
1086 // convert charset using iconv module
1087 if (function_exists('iconv') && $from != 'UTF-7' && $to != 'UTF-7')
1089 $iconv_map = array('KS_C_5601-1987' => 'EUC-KR');
1090 return iconv(($iconv_map[$from] ? $iconv_map[$from] : $from), ($iconv_map[$to] ? $iconv_map[$to] : $to) . "//IGNORE", $str);
1093 // convert charset using mbstring module
1096 $mb_map = array('UTF-7' => 'UTF7-IMAP', 'KS_C_5601-1987' => 'EUC-KR');
1098 // return if convert succeeded
1099 if (($out = mb_convert_encoding($str, ($mb_map[$to] ? $mb_map[$to] : $to), ($mb_map[$from] ? $mb_map[$from] : $from))) != '')
1103 // convert string to UTF-8
1105 $str = utf7_to_utf8($str);
1106 else if (($from=='ISO-8859-1') && function_exists('utf8_encode'))
1107 $str = utf8_encode($str);
1109 // encode string for output
1111 return utf8_to_utf7($str);
1112 else if ($to=='ISO-8859-1' && function_exists('utf8_decode'))
1113 return utf8_decode($str);
1115 // return UTF-8 string
1121 * Replacing specials characters to a specific encoding type
1123 * @param string Input string
1124 * @param string Encoding type: text|html|xml|js|url
1125 * @param string Replace mode for tags: show|replace|remove
1126 * @param boolean Convert newlines
1127 * @return The quoted string
1129 function rep_specialchars_output($str, $enctype='', $mode='', $newlines=TRUE)
1131 global $OUTPUT_TYPE, $OUTPUT;
1132 static $html_encode_arr, $js_rep_table, $xml_rep_table;
1135 $enctype = $GLOBALS['OUTPUT_TYPE'];
1137 // encode for plaintext
1138 if ($enctype=='text')
1139 return str_replace("\r\n", "\n", $mode=='remove' ? strip_tags($str) : $str);
1141 // encode for HTML output
1142 if ($enctype=='html')
1144 if (!$html_encode_arr)
1146 $html_encode_arr = get_html_translation_table(HTML_SPECIALCHARS);
1147 unset($html_encode_arr['?']);
1150 $ltpos = strpos($str, '<');
1151 $encode_arr = $html_encode_arr;
1153 // don't replace quotes and html tags
1154 if (($mode=='show' || $mode=='') && $ltpos!==false && strpos($str, '>', $ltpos)!==false)
1156 unset($encode_arr['"']);
1157 unset($encode_arr['<']);
1158 unset($encode_arr['>']);
1159 unset($encode_arr['&']);
1161 else if ($mode=='remove')
1162 $str = strip_tags($str);
1164 // avoid douple quotation of &
1165 $out = preg_replace('/&([a-z]{2,5}|#[0-9]{2,4});/', '&\\1;', strtr($str, $encode_arr));
1167 return $newlines ? nl2br($out) : $out;
1170 if ($enctype=='url')
1171 return rawurlencode($str);
1173 // if the replace tables for XML and JS are not yet defined
1176 $js_rep_table = $xml_rep_table = array();
1177 $xml_rep_table['&'] = '&';
1179 for ($c=160; $c<256; $c++) // can be increased to support more charsets
1181 $xml_rep_table[Chr($c)] = "&#$c;";
1183 if ($OUTPUT->get_charset()=='ISO-8859-1')
1184 $js_rep_table[Chr($c)] = sprintf("\\u%04x", $c);
1187 $xml_rep_table['"'] = '"';
1191 if ($enctype=='xml')
1192 return strtr($str, $xml_rep_table);
1194 // encode for javascript use
1197 if ($OUTPUT->get_charset()!='UTF-8')
1198 $str = rcube_charset_convert($str, RCMAIL_CHARSET, $OUTPUT->get_charset());
1200 return preg_replace(array("/\r?\n/", "/\r/"), array('\n', '\n'), addslashes(strtr($str, $js_rep_table)));
1203 // no encoding given -> return original string
1208 * Quote a given string.
1209 * Shortcut function for rep_specialchars_output
1211 * @return string HTML-quoted string
1212 * @see rep_specialchars_output()
1214 function Q($str, $mode='strict', $newlines=TRUE)
1216 return rep_specialchars_output($str, 'html', $mode, $newlines);
1220 * Quote a given string for javascript output.
1221 * Shortcut function for rep_specialchars_output
1223 * @return string JS-quoted string
1224 * @see rep_specialchars_output()
1228 return rep_specialchars_output($str, 'js');
1233 * Read input value and convert it for internal use
1234 * Performs stripslashes() and charset conversion if necessary
1236 * @param string Field name to read
1237 * @param int Source to get value from (GPC)
1238 * @param boolean Allow HTML tags in field value
1239 * @param string Charset to convert into
1240 * @return string Field value or NULL if not available
1242 function get_input_value($fname, $source, $allow_html=FALSE, $charset=NULL)
1247 if ($source==RCUBE_INPUT_GET && isset($_GET[$fname]))
1248 $value = $_GET[$fname];
1249 else if ($source==RCUBE_INPUT_POST && isset($_POST[$fname]))
1250 $value = $_POST[$fname];
1251 else if ($source==RCUBE_INPUT_GPC)
1253 if (isset($_POST[$fname]))
1254 $value = $_POST[$fname];
1255 else if (isset($_GET[$fname]))
1256 $value = $_GET[$fname];
1257 else if (isset($_COOKIE[$fname]))
1258 $value = $_COOKIE[$fname];
1261 // strip slashes if magic_quotes enabled
1262 if ((bool)get_magic_quotes_gpc())
1263 $value = stripslashes($value);
1265 // remove HTML tags if not allowed
1267 $value = strip_tags($value);
1269 // convert to internal charset
1270 if (is_object($OUTPUT))
1271 return rcube_charset_convert($value, $OUTPUT->get_charset(), $charset);
1278 * Remove single and double quotes from given string
1280 * @param string Input value
1281 * @return string Dequoted string
1283 function strip_quotes($str)
1285 return preg_replace('/[\'"]/', '', $str);
1290 * Remove new lines characters from given string
1292 * @param string Input value
1293 * @return string Stripped string
1295 function strip_newlines($str)
1297 return preg_replace('/[\r\n]/', '', $str);
1302 * Check if a specific template exists
1304 * @param string Template name
1305 * @return boolean True if template exists
1307 function template_exists($name)
1310 $skin_path = $CONFIG['skin_path'];
1312 // check template file
1313 return is_file("$skin_path/templates/$name.html");
1318 * Wrapper for rcmail_template::parse()
1321 function parse_template($name='main', $exit=true)
1323 $GLOBALS['OUTPUT']->parse($name, $exit);
1328 * Create a HTML table based on the given data
1330 * @param array Named table attributes
1331 * @param mixed Table row data. Either a two-dimensional array or a valid SQL result set
1332 * @param array List of cols to show
1333 * @param string Name of the identifier col
1334 * @return string HTML table code
1336 function rcube_table_output($attrib, $table_data, $a_show_cols, $id_col)
1340 // allow the following attributes to be added to the <table> tag
1341 $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
1343 $table = '<table' . $attrib_str . ">\n";
1346 $table .= "<thead><tr>\n";
1348 foreach ($a_show_cols as $col)
1349 $table .= '<td class="'.$col.'">' . Q(rcube_label($col)) . "</td>\n";
1351 $table .= "</tr></thead>\n<tbody>\n";
1354 if (!is_array($table_data))
1356 while ($table_data && ($sql_arr = $DB->fetch_assoc($table_data)))
1358 $zebra_class = $c%2 ? 'even' : 'odd';
1360 $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $sql_arr[$id_col]);
1363 foreach ($a_show_cols as $col)
1365 $cont = Q($sql_arr[$col]);
1366 $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1369 $table .= "</tr>\n";
1375 foreach ($table_data as $row_data)
1377 $zebra_class = $c%2 ? 'even' : 'odd';
1379 $table .= sprintf('<tr id="rcmrow%d" class="contact '.$zebra_class.'">'."\n", $row_data[$id_col]);
1382 foreach ($a_show_cols as $col)
1384 $cont = Q($row_data[$col]);
1385 $table .= '<td class="'.$col.'">' . $cont . "</td>\n";
1388 $table .= "</tr>\n";
1393 // complete message table
1394 $table .= "</tbody></table>\n";
1401 * Create an edit field for inclusion on a form
1403 * @param string col field name
1404 * @param string value field value
1405 * @param array attrib HTML element attributes for field
1406 * @param string type HTML element type (default 'text')
1407 * @return string HTML field definition
1409 function rcmail_get_edit_field($col, $value, $attrib, $type='text')
1412 $attrib['name'] = $fname;
1414 if ($type=='checkbox')
1416 $attrib['value'] = '1';
1417 $input = new checkbox($attrib);
1419 else if ($type=='textarea')
1421 $attrib['cols'] = $attrib['size'];
1422 $input = new textarea($attrib);
1425 $input = new textfield($attrib);
1427 // use value from post
1428 if (!empty($_POST[$fname]))
1429 $value = $_POST[$fname];
1431 $out = $input->show($value);
1438 * Return the mail domain configured for the given host
1440 * @param string IMAP host
1441 * @return string Resolved SMTP host
1443 function rcmail_mail_domain($host)
1448 if (is_array($CONFIG['mail_domain']))
1450 if (isset($CONFIG['mail_domain'][$host]))
1451 $domain = $CONFIG['mail_domain'][$host];
1453 else if (!empty($CONFIG['mail_domain']))
1454 $domain = $CONFIG['mail_domain'];
1461 * Replace all css definitions with #container [def]
1463 * @param string CSS source code
1464 * @param string Container ID to use as prefix
1465 * @return string Modified CSS source
1467 function rcmail_mod_css_styles($source, $container_id, $base_url = '')
1469 $a_css_values = array();
1472 // cut out all contents between { and }
1473 while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos)))
1475 $key = sizeof($a_css_values);
1476 $a_css_values[$key] = substr($source, $pos+1, $pos2-($pos+1));
1477 $source = substr($source, 0, $pos+1) . "<<str_replacement[$key]>>" . substr($source, $pos2, strlen($source)-$pos2);
1481 // remove html commends and add #container to each tag selector.
1482 // also replace body definition because we also stripped off the <body> tag
1483 $styles = preg_replace(
1485 '/(^\s*<!--)|(-->\s*$)/',
1486 '/(^\s*|,\s*|\}\s*)([a-z0-9\._#][a-z0-9\.\-_]*)/im',
1487 '/@import\s+(url\()?[\'"]?([^\)\'"]+)[\'"]?(\))?/ime',
1488 '/<<str_replacement\[([0-9]+)\]>>/e',
1489 "/$container_id\s+body/i"
1493 "\\1#$container_id \\2",
1494 "sprintf(\"@import url('./bin/modcss.php?u=%s&c=%s')\", urlencode(make_absolute_url('\\2','$base_url')), urlencode($container_id))",
1495 "\$a_css_values[\\1]",
1496 "$container_id div.rcmBody"
1505 * Compose a valid attribute string for HTML tags
1507 * @param array Named tag attributes
1508 * @param array List of allowed attributes
1509 * @return string HTML formatted attribute string
1511 function create_attrib_string($attrib, $allowed_attribs=array('id', 'class', 'style'))
1513 // allow the following attributes to be added to the <iframe> tag
1515 foreach ($allowed_attribs as $a)
1516 if (isset($attrib[$a]))
1517 $attrib_str .= sprintf(' %s="%s"', $a, str_replace('"', '"', $attrib[$a]));
1524 * Convert a HTML attribute string attributes to an associative array (name => value)
1526 * @param string Input string
1527 * @return array Key-value pairs of parsed attributes
1529 function parse_attrib_string($str)
1532 preg_match_all('/\s*([-_a-z]+)=(["\'])([^"]+)\2/Ui', stripslashes($str), $regs, PREG_SET_ORDER);
1534 // convert attributes to an associative array (name => value)
1536 foreach ($regs as $attr)
1537 $attrib[strtolower($attr[1])] = $attr[3];
1544 * Convert the given date to a human readable form
1545 * This uses the date formatting properties from config
1547 * @param mixed Date representation (string or timestamp)
1548 * @param string Date format to use
1549 * @return string Formatted date string
1551 function format_date($date, $format=NULL)
1553 global $CONFIG, $sess_user_lang;
1557 if (is_numeric($date))
1559 else if (!empty($date))
1560 $ts = @strtotime($date);
1565 // get user's timezone
1566 $tz = $CONFIG['timezone'];
1567 if ($CONFIG['dst_active'])
1570 // convert time to user's timezone
1571 $timestamp = $ts - date('Z', $ts) + ($tz * 3600);
1573 // get current timestamp in user's timezone
1574 $now = time(); // local time
1575 $now -= (int)date('Z'); // make GMT time
1576 $now += ($tz * 3600); // user's time
1577 $now_date = getdate($now);
1579 $today_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday'], $now_date['year']);
1580 $week_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday']-6, $now_date['year']);
1582 // define date format depending on current time
1583 if ($CONFIG['prettydate'] && !$format && $timestamp > $today_limit && $timestamp < $now)
1584 return sprintf('%s %s', rcube_label('today'), date($CONFIG['date_today'] ? $CONFIG['date_today'] : 'H:i', $timestamp));
1585 else if ($CONFIG['prettydate'] && !$format && $timestamp > $week_limit && $timestamp < $now)
1586 $format = $CONFIG['date_short'] ? $CONFIG['date_short'] : 'D H:i';
1588 $format = $CONFIG['date_long'] ? $CONFIG['date_long'] : 'd.m.Y H:i';
1591 // parse format string manually in order to provide localized weekday and month names
1592 // an alternative would be to convert the date() format string to fit with strftime()
1594 for($i=0; $i<strlen($format); $i++)
1596 if ($format{$i}=='\\') // skip escape chars
1599 // write char "as-is"
1600 if ($format{$i}==' ' || $format{$i-1}=='\\')
1601 $out .= $format{$i};
1603 else if ($format{$i}=='D')
1604 $out .= rcube_label(strtolower(date('D', $timestamp)));
1606 else if ($format{$i}=='l')
1607 $out .= rcube_label(strtolower(date('l', $timestamp)));
1608 // month name (short)
1609 else if ($format{$i}=='M')
1610 $out .= rcube_label(strtolower(date('M', $timestamp)));
1611 // month name (long)
1612 else if ($format{$i}=='F')
1613 $out .= rcube_label(strtolower(date('F', $timestamp)));
1615 $out .= date($format{$i}, $timestamp);
1623 * Compose a valid representaion of name and e-mail address
1625 * @param string E-mail address
1626 * @param string Person name
1627 * @return string Formatted string
1629 function format_email_recipient($email, $name='')
1631 if ($name && $name != $email)
1632 return sprintf('%s <%s>', strpos($name, ",") ? '"'.$name.'"' : $name, $email);
1639 /****** debugging functions ********/
1643 * Print or write debug messages
1645 * @param mixed Debug message or data
1647 function console($msg)
1649 if (!is_string($msg))
1650 $msg = var_export($msg, true);
1652 if (!($GLOBALS['CONFIG']['debug_level'] & 4))
1653 write_log('console', $msg);
1654 else if ($GLOBALS['REMOTE_REQUEST'])
1655 print "/*\n $msg \n*/\n";
1658 print '<div style="background:#eee; border:1px solid #ccc; margin-bottom:3px; padding:6px"><pre>';
1660 print "</pre></div>\n";
1666 * Append a line to a logfile in the logs directory.
1667 * Date will be added automatically to the line.
1669 * @param $name Name of logfile
1670 * @param $line Line to append
1672 function write_log($name, $line)
1674 global $CONFIG, $INSTALL_PATH;
1676 if (!is_string($line))
1677 $line = var_export($line, true);
1679 $log_entry = sprintf("[%s]: %s\n",
1680 date("d-M-Y H:i:s O", mktime()),
1683 if (empty($CONFIG['log_dir']))
1684 $CONFIG['log_dir'] = $INSTALL_PATH.'logs';
1686 // try to open specific log file for writing
1687 if ($fp = @fopen($CONFIG['log_dir'].'/'.$name, 'a'))
1689 fwrite($fp, $log_entry);
1698 function rcube_timer()
1700 list($usec, $sec) = explode(" ", microtime());
1701 return ((float)$usec + (float)$sec);
1708 function rcube_print_time($timer, $label='Timer')
1710 static $print_count = 0;
1713 $now = rcube_timer();
1714 $diff = $now-$timer;
1717 $label = 'Timer '.$print_count;
1719 console(sprintf("%s: %0.4f sec", $label, $diff));
1724 * Return the mailboxlist in HTML
1726 * @param array Named parameters
1727 * @return string HTML code for the gui object
1729 function rcmail_mailbox_list($attrib)
1731 global $IMAP, $CONFIG, $OUTPUT, $COMM_PATH;
1732 static $s_added_script = FALSE;
1733 static $a_mailboxes;
1735 // add some labels to client
1736 rcube_add_label('purgefolderconfirm');
1737 rcube_add_label('deletemessagesconfirm');
1739 // $mboxlist_start = rcube_timer();
1741 $type = $attrib['type'] ? $attrib['type'] : 'ul';
1742 $add_attrib = $type=='select' ? array('style', 'class', 'id', 'name', 'onchange') :
1743 array('style', 'class', 'id');
1745 if ($type=='ul' && !$attrib['id'])
1746 $attrib['id'] = 'rcmboxlist';
1748 // allow the following attributes to be added to the <ul> tag
1749 $attrib_str = create_attrib_string($attrib, $add_attrib);
1751 $out = '<' . $type . $attrib_str . ">\n";
1753 // add no-selection option
1754 if ($type=='select' && $attrib['noselection'])
1755 $out .= sprintf('<option value="0">%s</option>'."\n",
1756 rcube_label($attrib['noselection']));
1759 $mbox_name = $IMAP->get_mailbox_name();
1761 // for these mailboxes we have localized labels
1762 $special_mailboxes = array('inbox', 'sent', 'drafts', 'trash', 'junk');
1765 // build the folders tree
1766 if (empty($a_mailboxes))
1769 $a_folders = $IMAP->list_mailboxes();
1770 $delimiter = $IMAP->get_hierarchy_delimiter();
1771 $a_mailboxes = array();
1773 // rcube_print_time($mboxlist_start, 'list_mailboxes()');
1775 foreach ($a_folders as $folder)
1776 rcmail_build_folder_tree($a_mailboxes, $folder, $delimiter);
1779 // var_dump($a_mailboxes);
1781 if ($type=='select')
1782 $out .= rcmail_render_folder_tree_select($a_mailboxes, $special_mailboxes, $mbox_name, $attrib['maxlength']);
1784 $out .= rcmail_render_folder_tree_html($a_mailboxes, $special_mailboxes, $mbox_name, $attrib['maxlength']);
1786 // rcube_print_time($mboxlist_start, 'render_folder_tree()');
1790 $OUTPUT->add_gui_object('mailboxlist', $attrib['id']);
1792 return $out . "</$type>";
1799 * Create a hierarchical array of the mailbox list
1802 function rcmail_build_folder_tree(&$arrFolders, $folder, $delm='/', $path='')
1804 $pos = strpos($folder, $delm);
1807 $subFolders = substr($folder, $pos+1);
1808 $currentFolder = substr($folder, 0, $pos);
1812 $subFolders = false;
1813 $currentFolder = $folder;
1816 $path .= $currentFolder;
1818 if (!isset($arrFolders[$currentFolder]))
1820 $arrFolders[$currentFolder] = array('id' => $path,
1821 'name' => rcube_charset_convert($currentFolder, 'UTF-7'),
1822 'folders' => array());
1825 if (!empty($subFolders))
1826 rcmail_build_folder_tree($arrFolders[$currentFolder]['folders'], $subFolders, $delm, $path.$delm);
1831 * Return html for a structured list <ul> for the mailbox tree
1834 function rcmail_render_folder_tree_html(&$arrFolders, &$special, &$mbox_name, $maxlength, $nestLevel=0)
1836 global $COMM_PATH, $IMAP, $CONFIG, $OUTPUT;
1840 foreach ($arrFolders as $key => $folder)
1842 $zebra_class = ($nestLevel*$idx)%2 ? 'even' : 'odd';
1845 $folder_lc = strtolower($folder['id']);
1846 if (in_array($folder_lc, $special))
1847 $foldername = rcube_label($folder_lc);
1850 $foldername = $folder['name'];
1852 // shorten the folder name to a given length
1853 if ($maxlength && $maxlength>1)
1855 $fname = abbrevate_string($foldername, $maxlength);
1856 if ($fname != $foldername)
1857 $title = ' title="'.Q($foldername).'"';
1858 $foldername = $fname;
1862 // add unread message count display
1863 if ($unread_count = $IMAP->messagecount($folder['id'], 'RECENT', ($folder['id']==$mbox_name)))
1864 $foldername .= sprintf(' (%d)', $unread_count);
1866 // make folder name safe for ids and class names
1867 $folder_id = preg_replace('/[^A-Za-z0-9\-_]/', '', $folder['id']);
1868 $class_name = preg_replace('/[^a-z0-9\-_]/', '', $folder_lc);
1870 // set special class for Sent, Drafts, Trash and Junk
1871 if ($folder['id']==$CONFIG['sent_mbox'])
1872 $class_name = 'sent';
1873 else if ($folder['id']==$CONFIG['drafts_mbox'])
1874 $class_name = 'drafts';
1875 else if ($folder['id']==$CONFIG['trash_mbox'])
1876 $class_name = 'trash';
1877 else if ($folder['id']==$CONFIG['junk_mbox'])
1878 $class_name = 'junk';
1880 $js_name = htmlspecialchars(JQ($folder['id']));
1881 $out .= sprintf('<li id="rcmli%s" class="mailbox %s %s%s%s"><a href="%s"'.
1882 ' onclick="return %s.command(\'list\',\'%s\',this)"'.
1883 ' onmouseover="return %s.focus_folder(\'%s\')"' .
1884 ' onmouseout="return %s.unfocus_folder(\'%s\')"' .
1885 ' onmouseup="return %s.folder_mouse_up(\'%s\')"%s>%s</a>',
1889 $unread_count ? ' unread' : '',
1890 $folder['id']==$mbox_name ? ' selected' : '',
1891 Q(rcmail_url('', array('_mbox' => $folder['id']))),
1903 if (!empty($folder['folders']))
1904 $out .= "\n<ul>\n" . rcmail_render_folder_tree_html($folder['folders'], $special, $mbox_name, $maxlength, $nestLevel+1) . "</ul>\n";
1915 * Return html for a flat list <select> for the mailbox tree
1918 function rcmail_render_folder_tree_select(&$arrFolders, &$special, &$mbox_name, $maxlength, $nestLevel=0)
1920 global $IMAP, $OUTPUT;
1924 foreach ($arrFolders as $key=>$folder)
1926 $folder_lc = strtolower($folder['id']);
1927 if (in_array($folder_lc, $special))
1928 $foldername = rcube_label($folder_lc);
1931 $foldername = $folder['name'];
1933 // shorten the folder name to a given length
1934 if ($maxlength && $maxlength>1)
1935 $foldername = abbrevate_string($foldername, $maxlength);
1938 $out .= sprintf('<option value="%s">%s%s</option>'."\n",
1939 htmlspecialchars($folder['id']),
1940 str_repeat(' ', $nestLevel*4),
1943 if (!empty($folder['folders']))
1944 $out .= rcmail_render_folder_tree_select($folder['folders'], $special, $mbox_name, $maxlength, $nestLevel+1);