4 +-----------------------------------------------------------------------+
5 | program/include/main.inc |
7 | This file is part of the RoundCube Webmail client |
8 | Copyright (C) 2005-2009, 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 2483 2009-05-15 10:22:29Z 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');
32 // define constannts for input reading
33 define('RCUBE_INPUT_GET', 0x0101);
34 define('RCUBE_INPUT_POST', 0x0102);
35 define('RCUBE_INPUT_GPC', 0x0103);
40 * Return correct name for a specific database table
42 * @param string Table name
43 * @return string Translated table name
45 function get_table_name($table)
49 // return table name if configured
50 $config_key = 'db_table_'.$table;
52 if (strlen($CONFIG[$config_key]))
53 return $CONFIG[$config_key];
60 * Return correct name for a specific database sequence
61 * (used for Postgres only)
63 * @param string Secuence name
64 * @return string Translated sequence name
66 function get_sequence_name($sequence)
68 // return table name if configured
69 $config_key = 'db_sequence_'.$sequence;
70 $opt = rcmail::get_instance()->config->get($config_key);
80 * Get localized text in the desired language
81 * It's a global wrapper for rcmail::gettext()
83 * @param mixed Named parameters array or label name
84 * @return string Localized text
85 * @see rcmail::gettext()
87 function rcube_label($p)
89 return rcmail::get_instance()->gettext($p);
94 * Overwrite action variable
96 * @param string New action value
98 function rcmail_overwrite_action($action)
100 $app = rcmail::get_instance();
101 $app->action = $action;
102 $app->output->set_env('action', $action);
107 * Compose an URL for a specific action
109 * @param string Request action
110 * @param array More URL parameters
111 * @param string Request task (omit if the same)
112 * @return The application URL
114 function rcmail_url($action, $p=array(), $task=null)
116 $app = rcmail::get_instance();
117 return $app->url((array)$p + array('_action' => $action, 'task' => $task));
122 * Garbage collector function for temp files.
123 * Remove temp files older than two days
125 function rcmail_temp_gc()
127 $tmp = unslashify($CONFIG['temp_dir']);
128 $expire = mktime() - 172800; // expire in 48 hours
130 if ($dir = opendir($tmp))
132 while (($fname = readdir($dir)) !== false)
134 if ($fname{0} == '.')
137 if (filemtime($tmp.'/'.$fname) < $expire)
138 @unlink($tmp.'/'.$fname);
147 * Garbage collector for cache entries.
148 * Remove all expired message cache records
150 function rcmail_cache_gc()
152 $rcmail = rcmail::get_instance();
153 $db = $rcmail->get_dbh();
155 // get target timestamp
156 $ts = get_offset_time($rcmail->config->get('message_cache_lifetime', '30d'), -1);
158 $db->query("DELETE FROM ".get_table_name('messages')."
159 WHERE created < " . $db->fromunixtime($ts));
161 $db->query("DELETE FROM ".get_table_name('cache')."
162 WHERE created < " . $db->fromunixtime($ts));
167 * Convert a string from one charset to another.
168 * Uses mbstring and iconv functions if possible
170 * @param string Input string
171 * @param string Suspected charset of the input string
172 * @param string Target charset to convert to; defaults to RCMAIL_CHARSET
173 * @return Converted string
175 function rcube_charset_convert($str, $from, $to=NULL)
177 static $mbstring_loaded = null;
178 static $mbstring_list = null;
179 static $convert_warning = false;
181 $from = strtoupper($from);
182 $to = $to==NULL ? strtoupper(RCMAIL_CHARSET) : strtoupper($to);
183 $error = false; $conv = null;
186 if ($from == 'UNICODE-1-1-UTF-7')
188 if ($to == 'UNICODE-1-1-UTF-7')
191 if ($from == $to || empty($str) || empty($from))
195 'US-ASCII' => 'ISO-8859-1',
196 'ANSI_X3.110-1983' => 'ISO-8859-1',
197 'ANSI_X3.4-1968' => 'ISO-8859-1',
198 'UNKNOWN-8BIT' => 'ISO-8859-15',
199 'X-UNKNOWN' => 'ISO-8859-15',
200 'X-USER-DEFINED' => 'ISO-8859-15',
201 'ISO-8859-8-I' => 'ISO-8859-8',
202 'KS_C_5601-1987' => 'EUC-KR',
205 // convert charset using iconv module
206 if (function_exists('iconv') && $from != 'UTF-7' && $to != 'UTF-7') {
207 $aliases['GB2312'] = 'GB18030';
208 $_iconv = iconv(($aliases[$from] ? $aliases[$from] : $from), ($aliases[$to] ? $aliases[$to] : $to) . "//IGNORE", $str);
209 if ($_iconv !== false) {
214 if (is_null($mbstring_loaded))
215 $mbstring_loaded = extension_loaded('mbstring');
217 // convert charset using mbstring module
218 if ($mbstring_loaded) {
219 $aliases['UTF-7'] = 'UTF7-IMAP';
220 $aliases['WINDOWS-1257'] = 'ISO-8859-13';
222 if (is_null($mbstring_list)) {
223 $mbstring_list = mb_list_encodings();
224 $mbstring_list = array_map('strtoupper', $mbstring_list);
227 $mb_from = $aliases[$from] ? $aliases[$from] : $from;
228 $mb_to = $aliases[$to] ? $aliases[$to] : $to;
230 // return if encoding found, string matches encoding and convert succeeded
231 if (in_array($mb_from, $mbstring_list) && in_array($mb_to, $mbstring_list)) {
232 if (mb_check_encoding($str, $mb_from) && ($out = mb_convert_encoding($str, $mb_to, $mb_from)))
237 # try to convert with custom classes
238 if (class_exists('utf8'))
241 // convert string to UTF-8
242 if ($from == 'UTF-7') {
243 if ($_str = utf7_to_utf8($str))
248 else if (($from == 'ISO-8859-1') && function_exists('utf8_encode')) {
249 $str = utf8_encode($str);
251 else if ($from != 'UTF-8' && $conv) {
252 $conv->loadCharset($from);
253 $str = $conv->strToUtf8($str);
255 else if ($from != 'UTF-8')
258 // encode string for output
259 if ($to == 'UTF-7') {
260 return utf8_to_utf7($str);
262 else if ($to == 'ISO-8859-1' && function_exists('utf8_decode')) {
263 return utf8_decode($str);
265 else if ($to != 'UTF-8' && $conv) {
266 $conv->loadCharset($to);
267 return $conv->utf8ToStr($str);
269 else if ($to != 'UTF-8') {
274 if ($error && !$convert_warning){
279 'message' => "Could not convert string from $from to $to. Make sure iconv is installed or lib/utf8.class is available"
282 $convert_warning = true;
285 // return UTF-8 string
291 * Replacing specials characters to a specific encoding type
293 * @param string Input string
294 * @param string Encoding type: text|html|xml|js|url
295 * @param string Replace mode for tags: show|replace|remove
296 * @param boolean Convert newlines
297 * @return The quoted string
299 function rep_specialchars_output($str, $enctype='', $mode='', $newlines=TRUE)
302 static $html_encode_arr = false;
303 static $js_rep_table = false;
304 static $xml_rep_table = false;
306 $charset = $OUTPUT->get_charset();
307 $is_iso_8859_1 = false;
308 if ($charset == 'ISO-8859-1') {
309 $is_iso_8859_1 = true;
312 $enctype = $OUTPUT->type;
314 // encode for plaintext
315 if ($enctype=='text')
316 return str_replace("\r\n", "\n", $mode=='remove' ? strip_tags($str) : $str);
318 // encode for HTML output
319 if ($enctype=='html')
321 if (!$html_encode_arr)
323 $html_encode_arr = get_html_translation_table(HTML_SPECIALCHARS);
324 unset($html_encode_arr['?']);
327 $ltpos = strpos($str, '<');
328 $encode_arr = $html_encode_arr;
330 // don't replace quotes and html tags
331 if (($mode=='show' || $mode=='') && $ltpos!==false && strpos($str, '>', $ltpos)!==false)
333 unset($encode_arr['"']);
334 unset($encode_arr['<']);
335 unset($encode_arr['>']);
336 unset($encode_arr['&']);
338 else if ($mode=='remove')
339 $str = strip_tags($str);
341 // avoid douple quotation of &
342 $out = preg_replace('/&([A-Za-z]{2,6}|#[0-9]{2,4});/', '&\\1;', strtr($str, $encode_arr));
344 return $newlines ? nl2br($out) : $out;
348 return rawurlencode($str);
350 // if the replace tables for XML and JS are not yet defined
351 if ($js_rep_table===false)
353 $js_rep_table = $xml_rep_table = array();
354 $xml_rep_table['&'] = '&';
356 for ($c=160; $c<256; $c++) // can be increased to support more charsets
358 $xml_rep_table[Chr($c)] = "&#$c;";
361 $js_rep_table[Chr($c)] = sprintf("\\u%04x", $c);
364 $xml_rep_table['"'] = '"';
365 $js_rep_table['"'] = '\\"';
366 $js_rep_table["'"] = "\\'";
367 $js_rep_table["\\"] = "\\\\";
372 return strtr($str, $xml_rep_table);
374 // encode for javascript use
377 if ($charset!='UTF-8')
378 $str = rcube_charset_convert($str, RCMAIL_CHARSET,$charset);
380 return preg_replace(array("/\r?\n/", "/\r/", '/<\\//'), array('\n', '\n', '<\\/'), strtr($str, $js_rep_table));
383 // no encoding given -> return original string
388 * Quote a given string.
389 * Shortcut function for rep_specialchars_output
391 * @return string HTML-quoted string
392 * @see rep_specialchars_output()
394 function Q($str, $mode='strict', $newlines=TRUE)
396 return rep_specialchars_output($str, 'html', $mode, $newlines);
400 * Quote a given string for javascript output.
401 * Shortcut function for rep_specialchars_output
403 * @return string JS-quoted string
404 * @see rep_specialchars_output()
408 return rep_specialchars_output($str, 'js');
413 * Read input value and convert it for internal use
414 * Performs stripslashes() and charset conversion if necessary
416 * @param string Field name to read
417 * @param int Source to get value from (GPC)
418 * @param boolean Allow HTML tags in field value
419 * @param string Charset to convert into
420 * @return string Field value or NULL if not available
422 function get_input_value($fname, $source, $allow_html=FALSE, $charset=NULL)
427 if ($source==RCUBE_INPUT_GET && isset($_GET[$fname]))
428 $value = $_GET[$fname];
429 else if ($source==RCUBE_INPUT_POST && isset($_POST[$fname]))
430 $value = $_POST[$fname];
431 else if ($source==RCUBE_INPUT_GPC)
433 if (isset($_POST[$fname]))
434 $value = $_POST[$fname];
435 else if (isset($_GET[$fname]))
436 $value = $_GET[$fname];
437 else if (isset($_COOKIE[$fname]))
438 $value = $_COOKIE[$fname];
441 // strip single quotes if magic_quotes_sybase is enabled
442 if (ini_get('magic_quotes_sybase'))
443 $value = str_replace("''", "'", $value);
444 // strip slashes if magic_quotes enabled
445 else if (get_magic_quotes_gpc() || get_magic_quotes_runtime())
446 $value = stripslashes($value);
448 // remove HTML tags if not allowed
450 $value = strip_tags($value);
452 // convert to internal charset
453 if (is_object($OUTPUT))
454 return rcube_charset_convert($value, $OUTPUT->get_charset(), $charset);
460 * Remove all non-ascii and non-word chars
463 function asciiwords($str, $css_id = false)
465 $allowed = 'a-z0-9\_\-' . (!$css_id ? '\.' : '');
466 return preg_replace("/[^$allowed]/i", '', $str);
470 * Remove single and double quotes from given string
472 * @param string Input value
473 * @return string Dequoted string
475 function strip_quotes($str)
477 return preg_replace('/[\'"]/', '', $str);
482 * Remove new lines characters from given string
484 * @param string Input value
485 * @return string Stripped string
487 function strip_newlines($str)
489 return preg_replace('/[\r\n]/', '', $str);
494 * Create a HTML table based on the given data
496 * @param array Named table attributes
497 * @param mixed Table row data. Either a two-dimensional array or a valid SQL result set
498 * @param array List of cols to show
499 * @param string Name of the identifier col
500 * @return string HTML table code
502 function rcube_table_output($attrib, $table_data, $a_show_cols, $id_col)
506 $table = new html_table(/*array('cols' => count($a_show_cols))*/);
509 foreach ($a_show_cols as $col)
510 $table->add_header($col, Q(rcube_label($col)));
513 if (!is_array($table_data))
515 $db = $RCMAIL->get_dbh();
516 while ($table_data && ($sql_arr = $db->fetch_assoc($table_data)))
518 $zebra_class = $c % 2 ? 'even' : 'odd';
519 $table->add_row(array('id' => 'rcmrow' . $sql_arr[$id_col], 'class' => "contact $zebra_class"));
522 foreach ($a_show_cols as $col)
523 $table->add($col, Q($sql_arr[$col]));
530 foreach ($table_data as $row_data)
532 $zebra_class = $c % 2 ? 'even' : 'odd';
533 $table->add_row(array('id' => 'rcmrow' . $row_data[$id_col], 'class' => "contact $zebra_class"));
536 foreach ($a_show_cols as $col)
537 $table->add($col, Q($row_data[$col]));
543 return $table->show($attrib);
548 * Create an edit field for inclusion on a form
550 * @param string col field name
551 * @param string value field value
552 * @param array attrib HTML element attributes for field
553 * @param string type HTML element type (default 'text')
554 * @return string HTML field definition
556 function rcmail_get_edit_field($col, $value, $attrib, $type='text')
559 $attrib['name'] = $fname;
561 if ($type=='checkbox')
563 $attrib['value'] = '1';
564 $input = new html_checkbox($attrib);
566 else if ($type=='textarea')
568 $attrib['cols'] = $attrib['size'];
569 $input = new html_textarea($attrib);
572 $input = new html_inputfield($attrib);
574 // use value from post
575 if (!empty($_POST[$fname]))
576 $value = get_input_value($fname, RCUBE_INPUT_POST,
577 $type == 'textarea' && strpos($attrib['class'], 'mce_editor')!==false ? true : false);
579 $out = $input->show($value);
586 * Replace all css definitions with #container [def]
587 * and remove css-inlined scripting
589 * @param string CSS source code
590 * @param string Container ID to use as prefix
591 * @return string Modified CSS source
593 function rcmail_mod_css_styles($source, $container_id)
596 $replacements = new rcube_string_replacer;
598 // ignore the whole block if evil styles are detected
599 $stripped = preg_replace('/[^a-z\(:]/', '', rcmail_xss_entitiy_decode($source));
600 if (preg_match('/expression|behavior|url\(|import/', $stripped))
601 return '/* evil! */';
603 // cut out all contents between { and }
604 while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos)))
606 $key = $replacements->add(substr($source, $pos+1, $pos2-($pos+1)));
607 $source = substr($source, 0, $pos+1) . $replacements->get_replacement($key) . substr($source, $pos2, strlen($source)-$pos2);
611 // remove html comments and add #container to each tag selector.
612 // also replace body definition because we also stripped off the <body> tag
613 $styles = preg_replace(
615 '/(^\s*<!--)|(-->\s*$)/',
616 '/(^\s*|,\s*|\}\s*)([a-z0-9\._#][a-z0-9\.\-_]*)/im',
617 "/$container_id\s+body/i",
621 "\\1#$container_id \\2",
622 "$container_id div.rcmBody",
626 // put block contents back in
627 $styles = $replacements->resolve($styles);
634 * Decode escaped entities used by known XSS exploits.
635 * See http://downloads.securityfocus.com/vulnerabilities/exploits/26800.eml for examples
637 * @param string CSS content to decode
638 * @return string Decoded string
640 function rcmail_xss_entitiy_decode($content)
642 $out = html_entity_decode(html_entity_decode($content));
643 $out = preg_replace_callback('/\\\([0-9a-f]{4})/i', 'rcmail_xss_entitiy_decode_callback', $out);
644 $out = preg_replace('#/\*.*\*/#Um', '', $out);
650 * preg_replace_callback callback for rcmail_xss_entitiy_decode_callback
652 * @param array matches result from preg_replace_callback
653 * @return string decoded entity
655 function rcmail_xss_entitiy_decode_callback($matches)
657 return chr(hexdec($matches[1]));
661 * Compose a valid attribute string for HTML tags
663 * @param array Named tag attributes
664 * @param array List of allowed attributes
665 * @return string HTML formatted attribute string
667 function create_attrib_string($attrib, $allowed_attribs=array('id', 'class', 'style'))
669 // allow the following attributes to be added to the <iframe> tag
671 foreach ($allowed_attribs as $a)
672 if (isset($attrib[$a]))
673 $attrib_str .= sprintf(' %s="%s"', $a, str_replace('"', '"', $attrib[$a]));
680 * Convert a HTML attribute string attributes to an associative array (name => value)
682 * @param string Input string
683 * @return array Key-value pairs of parsed attributes
685 function parse_attrib_string($str)
688 preg_match_all('/\s*([-_a-z]+)=(["\'])??(?(2)([^\2]*)\2|(\S+?))/Ui', stripslashes($str), $regs, PREG_SET_ORDER);
690 // convert attributes to an associative array (name => value)
692 foreach ($regs as $attr)
694 $attrib[strtolower($attr[1])] = $attr[3] . $attr[4];
702 * Convert the given date to a human readable form
703 * This uses the date formatting properties from config
705 * @param mixed Date representation (string or timestamp)
706 * @param string Date format to use
707 * @return string Formatted date string
709 function format_date($date, $format=NULL)
715 if (is_numeric($date))
717 else if (!empty($date))
719 // support non-standard "GMTXXXX" literal
720 $date = preg_replace('/GMT\s*([+-][0-9]+)/', '\\1', $date);
721 // if date parsing fails, we have a date in non-rfc format.
722 // remove token from the end and try again
723 while ((($ts = @strtotime($date))===false) || ($ts < 0))
725 $d = explode(' ', $date);
728 $date = implode(' ', $d);
735 // get user's timezone
736 if ($CONFIG['timezone'] === 'auto')
737 $tz = isset($_SESSION['timezone']) ? $_SESSION['timezone'] : date('Z')/3600;
739 $tz = $CONFIG['timezone'];
740 if ($CONFIG['dst_active'])
744 // convert time to user's timezone
745 $timestamp = $ts - date('Z', $ts) + ($tz * 3600);
747 // get current timestamp in user's timezone
748 $now = time(); // local time
749 $now -= (int)date('Z'); // make GMT time
750 $now += ($tz * 3600); // user's time
751 $now_date = getdate($now);
753 $today_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday'], $now_date['year']);
754 $week_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday']-6, $now_date['year']);
756 // define date format depending on current time
757 if ($CONFIG['prettydate'] && !$format && $timestamp > $today_limit && $timestamp < $now)
758 return sprintf('%s %s', rcube_label('today'), date($CONFIG['date_today'] ? $CONFIG['date_today'] : 'H:i', $timestamp));
759 else if ($CONFIG['prettydate'] && !$format && $timestamp > $week_limit && $timestamp < $now)
760 $format = $CONFIG['date_short'] ? $CONFIG['date_short'] : 'D H:i';
762 $format = $CONFIG['date_long'] ? $CONFIG['date_long'] : 'd.m.Y H:i';
765 // parse format string manually in order to provide localized weekday and month names
766 // an alternative would be to convert the date() format string to fit with strftime()
768 for($i=0; $i<strlen($format); $i++)
770 if ($format{$i}=='\\') // skip escape chars
773 // write char "as-is"
774 if ($format{$i}==' ' || $format{$i-1}=='\\')
777 else if ($format{$i}=='D')
778 $out .= rcube_label(strtolower(date('D', $timestamp)));
780 else if ($format{$i}=='l')
781 $out .= rcube_label(strtolower(date('l', $timestamp)));
782 // month name (short)
783 else if ($format{$i}=='M')
784 $out .= rcube_label(strtolower(date('M', $timestamp)));
786 else if ($format{$i}=='F')
787 $out .= rcube_label('long'.strtolower(date('M', $timestamp)));
788 else if ($format{$i}=='x')
789 $out .= strftime('%x %X', $timestamp);
791 $out .= date($format{$i}, $timestamp);
799 * Compose a valid representaion of name and e-mail address
801 * @param string E-mail address
802 * @param string Person name
803 * @return string Formatted string
805 function format_email_recipient($email, $name='')
807 if ($name && $name != $email)
809 // Special chars as defined by RFC 822 need to in quoted string (or escaped).
810 return sprintf('%s <%s>', preg_match('/[\(\)\<\>\\\.\[\]@,;:"]/', $name) ? '"'.addcslashes($name, '"').'"' : $name, $email);
818 /****** debugging functions ********/
822 * Print or write debug messages
824 * @param mixed Debug message or data
829 foreach (func_get_args() as $arg)
830 $msg[] = !is_string($arg) ? var_export($arg, true) : $arg;
832 if (!($GLOBALS['CONFIG']['debug_level'] & 4))
833 write_log('console', join(";\n", $msg));
834 else if ($GLOBALS['OUTPUT']->ajax_call)
835 print "/*\n " . join(";\n", $msg) . " \n*/\n";
838 print '<div style="background:#eee; border:1px solid #ccc; margin-bottom:3px; padding:6px"><pre>';
839 print join(";<br/>\n", $msg);
840 print "</pre></div>\n";
846 * Append a line to a logfile in the logs directory.
847 * Date will be added automatically to the line.
849 * @param $name name of log file
850 * @param line Line to append
852 function write_log($name, $line)
856 if (!is_string($line))
857 $line = var_export($line, true);
859 $log_entry = sprintf("[%s]: %s\n",
860 date("d-M-Y H:i:s O", mktime()),
863 if ($CONFIG['log_driver'] == 'syslog') {
864 if ($name == 'errors')
868 syslog($prio, $log_entry);
870 // log_driver == 'file' is assumed here
871 if (empty($CONFIG['log_dir']))
872 $CONFIG['log_dir'] = INSTALL_PATH.'logs';
874 // try to open specific log file for writing
875 if ($fp = @fopen($CONFIG['log_dir'].'/'.$name, 'a')) {
876 fwrite($fp, $log_entry);
887 function rcube_timer()
889 list($usec, $sec) = explode(" ", microtime());
890 return ((float)$usec + (float)$sec);
897 function rcube_print_time($timer, $label='Timer')
899 static $print_count = 0;
902 $now = rcube_timer();
906 $label = 'Timer '.$print_count;
908 console(sprintf("%s: %0.4f sec", $label, $diff));
913 * Return the mailboxlist in HTML
915 * @param array Named parameters
916 * @return string HTML code for the gui object
918 function rcmail_mailbox_list($attrib)
923 $attrib += array('maxlength' => 100, 'relanames' => false);
925 // add some labels to client
926 $RCMAIL->output->add_label('purgefolderconfirm', 'deletemessagesconfirm');
928 $type = $attrib['type'] ? $attrib['type'] : 'ul';
929 unset($attrib['type']);
931 if ($type=='ul' && !$attrib['id'])
932 $attrib['id'] = 'rcmboxlist';
935 $mbox_name = $RCMAIL->imap->get_mailbox_name();
937 // build the folders tree
938 if (empty($a_mailboxes)) {
940 $a_folders = $RCMAIL->imap->list_mailboxes();
941 $delimiter = $RCMAIL->imap->get_hierarchy_delimiter();
942 $a_mailboxes = array();
944 foreach ($a_folders as $folder)
945 rcmail_build_folder_tree($a_mailboxes, $folder, $delimiter);
948 if ($type=='select') {
949 $select = new html_select($attrib);
951 // add no-selection option
952 if ($attrib['noselection'])
953 $select->add(rcube_label($attrib['noselection']), '0');
955 rcmail_render_folder_tree_select($a_mailboxes, $mbox_name, $attrib['maxlength'], $select, $attrib['realnames']);
956 $out = $select->show();
959 $js_mailboxlist = array();
960 $out = html::tag('ul', $attrib, rcmail_render_folder_tree_html($a_mailboxes, $mbox_name, $js_mailboxlist, $attrib), html::$common_attrib);
962 $RCMAIL->output->add_gui_object('mailboxlist', $attrib['id']);
963 $RCMAIL->output->set_env('mailboxes', $js_mailboxlist);
964 $RCMAIL->output->set_env('collapsed_folders', $RCMAIL->config->get('collapsed_folders'));
972 * Return the mailboxlist as html_select object
974 * @param array Named parameters
975 * @return object html_select HTML drop-down object
977 function rcmail_mailbox_select($p = array())
981 $p += array('maxlength' => 100, 'relanames' => false);
982 $a_mailboxes = array();
984 foreach ($RCMAIL->imap->list_mailboxes() as $folder)
985 rcmail_build_folder_tree($a_mailboxes, $folder, $RCMAIL->imap->get_hierarchy_delimiter());
987 $select = new html_select($p);
989 if ($p['noselection'])
990 $select->add($p['noselection'], '');
992 rcmail_render_folder_tree_select($a_mailboxes, $mbox, $p['maxlength'], $select, $p['realnames']);
999 * Create a hierarchical array of the mailbox list
1002 function rcmail_build_folder_tree(&$arrFolders, $folder, $delm='/', $path='')
1004 $pos = strpos($folder, $delm);
1005 if ($pos !== false) {
1006 $subFolders = substr($folder, $pos+1);
1007 $currentFolder = substr($folder, 0, $pos);
1008 $virtual = !isset($arrFolders[$currentFolder]);
1011 $subFolders = false;
1012 $currentFolder = $folder;
1016 $path .= $currentFolder;
1018 if (!isset($arrFolders[$currentFolder])) {
1019 $arrFolders[$currentFolder] = array(
1021 'name' => rcube_charset_convert($currentFolder, 'UTF-7'),
1022 'virtual' => $virtual,
1023 'folders' => array());
1026 $arrFolders[$currentFolder]['virtual'] = $virtual;
1028 if (!empty($subFolders))
1029 rcmail_build_folder_tree($arrFolders[$currentFolder]['folders'], $subFolders, $delm, $path.$delm);
1034 * Return html for a structured list <ul> for the mailbox tree
1037 function rcmail_render_folder_tree_html(&$arrFolders, &$mbox_name, &$jslist, $attrib, $nestLevel=0)
1039 global $RCMAIL, $CONFIG;
1041 $maxlength = intval($attrib['maxlength']);
1042 $realnames = (bool)$attrib['realnames'];
1043 $msgcounts = $RCMAIL->imap->get_cache('messagecount');
1047 foreach ($arrFolders as $key => $folder) {
1048 $zebra_class = (($nestLevel+1)*$idx) % 2 == 0 ? 'even' : 'odd';
1051 if (($folder_class = rcmail_folder_classname($folder['id'])) && !$realnames) {
1052 $foldername = rcube_label($folder_class);
1055 $foldername = $folder['name'];
1057 // shorten the folder name to a given length
1058 if ($maxlength && $maxlength > 1) {
1059 $fname = abbreviate_string($foldername, $maxlength);
1060 if ($fname != $foldername)
1061 $title = $foldername;
1062 $foldername = $fname;
1066 // make folder name safe for ids and class names
1067 $folder_id = asciiwords($folder['id'], true);
1068 $classes = array('mailbox');
1070 // set special class for Sent, Drafts, Trash and Junk
1071 if ($folder['id']==$CONFIG['sent_mbox'])
1072 $classes[] = 'sent';
1073 else if ($folder['id']==$CONFIG['drafts_mbox'])
1074 $classes[] = 'drafts';
1075 else if ($folder['id']==$CONFIG['trash_mbox'])
1076 $classes[] = 'trash';
1077 else if ($folder['id']==$CONFIG['junk_mbox'])
1078 $classes[] = 'junk';
1079 else if ($folder['id']=='INBOX')
1080 $classes[] = 'inbox';
1082 $classes[] = '_'.asciiwords($folder_class ? $folder_class : strtolower($folder['id']), true);
1084 $classes[] = $zebra_class;
1086 if ($folder['id'] == $mbox_name)
1087 $classes[] = 'selected';
1089 $collapsed = preg_match('/&'.rawurlencode($folder['id']).'&/', $RCMAIL->config->get('collapsed_folders'));
1090 $unread = $msgcounts ? intval($msgcounts[$folder['id']]['UNSEEN']) : 0;
1092 if ($folder['virtual'])
1093 $classes[] = 'virtual';
1095 $classes[] = 'unread';
1097 $js_name = JQ($folder['id']);
1098 $html_name = Q($foldername . ($unread ? " ($unread)" : ''));
1099 $link_attrib = $folder['virtual'] ? array() : array(
1100 'href' => rcmail_url('', array('_mbox' => $folder['id'])),
1101 'onclick' => sprintf("return %s.command('list','%s',this)", JS_OBJECT_NAME, $js_name),
1105 $out .= html::tag('li', array(
1106 'id' => "rcmli".$folder_id,
1107 'class' => join(' ', $classes),
1109 html::a($link_attrib, $html_name) .
1110 (!empty($folder['folders']) ? html::div(array(
1111 'class' => ($collapsed ? 'collapsed' : 'expanded'),
1112 'style' => "position:absolute",
1113 'onclick' => sprintf("%s.command('collapse-folder', '%s')", JS_OBJECT_NAME, $js_name)
1114 ), ' ') : ''));
1116 $jslist[$folder_id] = array('id' => $folder['id'], 'name' => $foldername, 'virtual' => $folder['virtual']);
1118 if (!empty($folder['folders'])) {
1119 $out .= html::tag('ul', array('style' => ($collapsed ? "display:none;" : null)),
1120 rcmail_render_folder_tree_html($folder['folders'], $mbox_name, $jslist, $attrib, $nestLevel+1));
1132 * Return html for a flat list <select> for the mailbox tree
1135 function rcmail_render_folder_tree_select(&$arrFolders, &$mbox_name, $maxlength, &$select, $realnames=false, $nestLevel=0)
1139 foreach ($arrFolders as $key=>$folder)
1141 if (!$realnames && ($folder_class = rcmail_folder_classname($folder['id'])))
1142 $foldername = rcube_label($folder_class);
1145 $foldername = $folder['name'];
1147 // shorten the folder name to a given length
1148 if ($maxlength && $maxlength>1)
1149 $foldername = abbreviate_string($foldername, $maxlength);
1152 $select->add(str_repeat(' ', $nestLevel*4) . $foldername, $folder['id']);
1154 if (!empty($folder['folders']))
1155 $out .= rcmail_render_folder_tree_select($folder['folders'], $mbox_name, $maxlength, $select, $realnames, $nestLevel+1);
1165 * Return internal name for the given folder if it matches the configured special folders
1168 function rcmail_folder_classname($folder_id)
1172 // for these mailboxes we have localized labels and css classes
1173 foreach (array('sent', 'drafts', 'trash', 'junk') as $smbx)
1175 if ($folder_id == $CONFIG[$smbx.'_mbox'])
1179 if ($folder_id == 'INBOX')
1185 * Try to localize the given IMAP folder name.
1186 * UTF-7 decode it in case no localized text was found
1188 * @param string Folder name
1189 * @return string Localized folder name in UTF-8 encoding
1191 function rcmail_localize_foldername($name)
1193 if ($folder_class = rcmail_folder_classname($name))
1194 return rcube_label($folder_class);
1196 return rcube_charset_convert($name, 'UTF-7');
1201 * Output HTML editor scripts
1203 * @param string Editor mode
1205 function rcube_html_editor($mode='')
1207 global $OUTPUT, $CONFIG;
1209 $lang = $tinylang = strtolower(substr($_SESSION['language'], 0, 2));
1210 if (!file_exists(INSTALL_PATH . 'program/js/tiny_mce/langs/'.$tinylang.'.js'))
1213 $OUTPUT->include_script('tiny_mce/tiny_mce.js');
1214 $OUTPUT->include_script('editor.js');
1215 $OUTPUT->add_script('rcmail_editor_init("$__skin_path", "'.JQ($tinylang).'", '.intval($CONFIG['enable_spellcheck']).', "'.$mode.'");');
1221 * Helper class to turn relative urls into absolute ones
1222 * using a predefined base
1224 class rcube_base_replacer
1228 public function __construct($base)
1230 $this->base_url = $base;
1233 public function callback($matches)
1235 return $matches[1] . '="' . make_absolute_url($matches[3], $this->base_url) . '"';