]> git.donarmstrong.com Git - roundcube.git/blob - program/include/main.inc
Imported Upstream version 0.2.2
[roundcube.git] / program / include / main.inc
1 <?php
2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/include/main.inc                                              |
6  |                                                                       |
7  | This file is part of the RoundCube Webmail client                     |
8  | Copyright (C) 2005-2009, RoundCube Dev, - Switzerland                 |
9  | Licensed under the GNU GPL                                            |
10  |                                                                       |
11  | PURPOSE:                                                              |
12  |   Provide basic functions for the webmail package                     |
13  |                                                                       |
14  +-----------------------------------------------------------------------+
15  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16  +-----------------------------------------------------------------------+
17
18  $Id: main.inc 2483 2009-05-15 10:22:29Z thomasb $
19
20 */
21
22 /**
23  * RoundCube Webmail common functions
24  *
25  * @package Core
26  * @author Thomas Bruederli <roundcube@gmail.com>
27  */
28
29 require_once('lib/utf7.inc');
30 require_once('include/rcube_shared.inc');
31
32 // define constannts for input reading
33 define('RCUBE_INPUT_GET', 0x0101);
34 define('RCUBE_INPUT_POST', 0x0102);
35 define('RCUBE_INPUT_GPC', 0x0103);
36
37
38
39 /**
40  * Return correct name for a specific database table
41  *
42  * @param string Table name
43  * @return string Translated table name
44  */
45 function get_table_name($table)
46   {
47   global $CONFIG;
48
49   // return table name if configured
50   $config_key = 'db_table_'.$table;
51
52   if (strlen($CONFIG[$config_key]))
53     return $CONFIG[$config_key];
54
55   return $table;
56   }
57
58
59 /**
60  * Return correct name for a specific database sequence
61  * (used for Postgres only)
62  *
63  * @param string Secuence name
64  * @return string Translated sequence name
65  */
66 function get_sequence_name($sequence)
67   {
68   // return table name if configured
69   $config_key = 'db_sequence_'.$sequence;
70   $opt = rcmail::get_instance()->config->get($config_key);
71
72   if (!empty($opt))
73     return $opt;
74     
75   return $sequence;
76   }
77
78
79 /**
80  * Get localized text in the desired language
81  * It's a global wrapper for rcmail::gettext()
82  *
83  * @param mixed Named parameters array or label name
84  * @return string Localized text
85  * @see rcmail::gettext()
86  */
87 function rcube_label($p)
88 {
89   return rcmail::get_instance()->gettext($p);
90 }
91
92
93 /**
94  * Overwrite action variable
95  *
96  * @param string New action value
97  */
98 function rcmail_overwrite_action($action)
99   {
100   $app = rcmail::get_instance();
101   $app->action = $action;
102   $app->output->set_env('action', $action);
103   }
104
105
106 /**
107  * Compose an URL for a specific action
108  *
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
113  */
114 function rcmail_url($action, $p=array(), $task=null)
115 {
116   $app = rcmail::get_instance();
117   return $app->url((array)$p + array('_action' => $action, 'task' => $task));
118 }
119
120
121 /**
122  * Garbage collector function for temp files.
123  * Remove temp files older than two days
124  */
125 function rcmail_temp_gc()
126   {
127   $tmp = unslashify($CONFIG['temp_dir']);
128   $expire = mktime() - 172800;  // expire in 48 hours
129
130   if ($dir = opendir($tmp))
131     {
132     while (($fname = readdir($dir)) !== false)
133       {
134       if ($fname{0} == '.')
135         continue;
136
137       if (filemtime($tmp.'/'.$fname) < $expire)
138         @unlink($tmp.'/'.$fname);
139       }
140
141     closedir($dir);
142     }
143   }
144
145
146 /**
147  * Garbage collector for cache entries.
148  * Remove all expired message cache records
149  */
150 function rcmail_cache_gc()
151   {
152   $rcmail = rcmail::get_instance();
153   $db = $rcmail->get_dbh();
154   
155   // get target timestamp
156   $ts = get_offset_time($rcmail->config->get('message_cache_lifetime', '30d'), -1);
157   
158   $db->query("DELETE FROM ".get_table_name('messages')."
159              WHERE  created < " . $db->fromunixtime($ts));
160
161   $db->query("DELETE FROM ".get_table_name('cache')."
162               WHERE  created < " . $db->fromunixtime($ts));
163   }
164
165
166 /**
167  * Convert a string from one charset to another.
168  * Uses mbstring and iconv functions if possible
169  *
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
174  */
175 function rcube_charset_convert($str, $from, $to=NULL)
176   {
177   static $mbstring_loaded = null;
178   static $mbstring_list = null;
179   static $convert_warning = false;
180
181   $from = strtoupper($from);
182   $to = $to==NULL ? strtoupper(RCMAIL_CHARSET) : strtoupper($to);
183   $error = false; $conv = null;
184
185   # RFC1642
186   if ($from == 'UNICODE-1-1-UTF-7')
187     $from = 'UTF-7';
188   if ($to == 'UNICODE-1-1-UTF-7')
189     $to = 'UTF-7';
190
191   if ($from == $to || empty($str) || empty($from))
192     return $str;
193     
194   $aliases = array(
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',
203   );
204
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) {
210         return $_iconv;
211     }
212   }
213
214   if (is_null($mbstring_loaded))
215     $mbstring_loaded = extension_loaded('mbstring');
216     
217   // convert charset using mbstring module
218   if ($mbstring_loaded) {
219     $aliases['UTF-7'] = 'UTF7-IMAP';
220     $aliases['WINDOWS-1257'] = 'ISO-8859-13';
221     
222     if (is_null($mbstring_list)) {
223       $mbstring_list = mb_list_encodings();
224       $mbstring_list = array_map('strtoupper', $mbstring_list);
225     }
226     
227     $mb_from = $aliases[$from] ? $aliases[$from] : $from;
228     $mb_to = $aliases[$to] ? $aliases[$to] : $to;
229     
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)))
233         return $out;
234     }
235   }
236
237   # try to convert with custom classes
238   if (class_exists('utf8'))
239     $conv = new utf8();
240
241   // convert string to UTF-8
242   if ($from == 'UTF-7') {
243     if ($_str = utf7_to_utf8($str))
244       $str = $_str;
245     else
246       $error = true;
247   }
248   else if (($from == 'ISO-8859-1') && function_exists('utf8_encode')) {
249     $str = utf8_encode($str);
250   }
251   else if ($from != 'UTF-8' && $conv) {
252     $conv->loadCharset($from);
253     $str = $conv->strToUtf8($str);
254   }
255   else if ($from != 'UTF-8')
256     $error = true;
257
258   // encode string for output
259   if ($to == 'UTF-7') {
260     return utf8_to_utf7($str);
261   }
262   else if ($to == 'ISO-8859-1' && function_exists('utf8_decode')) {
263     return utf8_decode($str);
264   }
265   else if ($to != 'UTF-8' && $conv) {
266     $conv->loadCharset($to);
267     return $conv->utf8ToStr($str);
268   }
269   else if ($to != 'UTF-8') {
270     $error = true;
271   }
272   
273   // report error
274   if ($error && !$convert_warning){
275     raise_error(array(
276       'code' => 500,
277       'type' => 'php',
278       'file' => __FILE__,
279       'message' => "Could not convert string from $from to $to. Make sure iconv is installed or lib/utf8.class is available"
280       ), true, false);
281     
282     $convert_warning = true;
283   }
284   
285   // return UTF-8 string
286   return $str;
287   }
288
289
290 /**
291  * Replacing specials characters to a specific encoding type
292  *
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
298  */
299 function rep_specialchars_output($str, $enctype='', $mode='', $newlines=TRUE)
300   {
301   global $OUTPUT;
302   static $html_encode_arr = false;
303   static $js_rep_table = false;
304   static $xml_rep_table = false;
305
306   $charset = $OUTPUT->get_charset();
307   $is_iso_8859_1 = false;
308   if ($charset == 'ISO-8859-1') {
309     $is_iso_8859_1 = true;
310   }
311   if (!$enctype)
312     $enctype = $OUTPUT->type;
313
314   // encode for plaintext
315   if ($enctype=='text')
316     return str_replace("\r\n", "\n", $mode=='remove' ? strip_tags($str) : $str);
317
318   // encode for HTML output
319   if ($enctype=='html')
320     {
321     if (!$html_encode_arr)
322       {
323       $html_encode_arr = get_html_translation_table(HTML_SPECIALCHARS);        
324       unset($html_encode_arr['?']);
325       }
326
327     $ltpos = strpos($str, '<');
328     $encode_arr = $html_encode_arr;
329
330     // don't replace quotes and html tags
331     if (($mode=='show' || $mode=='') && $ltpos!==false && strpos($str, '>', $ltpos)!==false)
332       {
333       unset($encode_arr['"']);
334       unset($encode_arr['<']);
335       unset($encode_arr['>']);
336       unset($encode_arr['&']);
337       }
338     else if ($mode=='remove')
339       $str = strip_tags($str);
340     
341     // avoid douple quotation of &
342     $out = preg_replace('/&amp;([A-Za-z]{2,6}|#[0-9]{2,4});/', '&\\1;', strtr($str, $encode_arr));
343       
344     return $newlines ? nl2br($out) : $out;
345     }
346
347   if ($enctype=='url')
348     return rawurlencode($str);
349
350   // if the replace tables for XML and JS are not yet defined
351   if ($js_rep_table===false)
352     {
353     $js_rep_table = $xml_rep_table = array();
354     $xml_rep_table['&'] = '&amp;';
355
356     for ($c=160; $c<256; $c++)  // can be increased to support more charsets
357       {
358       $xml_rep_table[Chr($c)] = "&#$c;";
359       
360       if ($is_iso_8859_1)
361         $js_rep_table[Chr($c)] = sprintf("\\u%04x", $c);
362       }
363
364     $xml_rep_table['"'] = '&quot;';
365     $js_rep_table['"'] = '\\"';
366     $js_rep_table["'"] = "\\'";
367     $js_rep_table["\\"] = "\\\\";
368     }
369
370   // encode for XML
371   if ($enctype=='xml')
372     return strtr($str, $xml_rep_table);
373
374   // encode for javascript use
375   if ($enctype=='js')
376     {
377     if ($charset!='UTF-8')
378       $str = rcube_charset_convert($str, RCMAIL_CHARSET,$charset);
379       
380     return preg_replace(array("/\r?\n/", "/\r/", '/<\\//'), array('\n', '\n', '<\\/'), strtr($str, $js_rep_table));
381     }
382
383   // no encoding given -> return original string
384   return $str;
385   }
386   
387 /**
388  * Quote a given string.
389  * Shortcut function for rep_specialchars_output
390  *
391  * @return string HTML-quoted string
392  * @see rep_specialchars_output()
393  */
394 function Q($str, $mode='strict', $newlines=TRUE)
395   {
396   return rep_specialchars_output($str, 'html', $mode, $newlines);
397   }
398
399 /**
400  * Quote a given string for javascript output.
401  * Shortcut function for rep_specialchars_output
402  * 
403  * @return string JS-quoted string
404  * @see rep_specialchars_output()
405  */
406 function JQ($str)
407   {
408   return rep_specialchars_output($str, 'js');
409   }
410
411
412 /**
413  * Read input value and convert it for internal use
414  * Performs stripslashes() and charset conversion if necessary
415  * 
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
421  */
422 function get_input_value($fname, $source, $allow_html=FALSE, $charset=NULL)
423   {
424   global $OUTPUT;
425   $value = NULL;
426   
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)
432     {
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];
439     }
440   
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);
447
448   // remove HTML tags if not allowed    
449   if (!$allow_html)
450     $value = strip_tags($value);
451   
452   // convert to internal charset
453   if (is_object($OUTPUT))
454     return rcube_charset_convert($value, $OUTPUT->get_charset(), $charset);
455   else
456     return $value;
457   }
458
459 /**
460  * Remove all non-ascii and non-word chars
461  * except . and -
462  */
463 function asciiwords($str, $css_id = false)
464 {
465   $allowed = 'a-z0-9\_\-' . (!$css_id ? '\.' : '');
466   return preg_replace("/[^$allowed]/i", '', $str);
467 }
468
469 /**
470  * Remove single and double quotes from given string
471  *
472  * @param string Input value
473  * @return string Dequoted string
474  */
475 function strip_quotes($str)
476 {
477   return preg_replace('/[\'"]/', '', $str);
478 }
479
480
481 /**
482  * Remove new lines characters from given string
483  *
484  * @param string Input value
485  * @return string Stripped string
486  */
487 function strip_newlines($str)
488 {
489   return preg_replace('/[\r\n]/', '', $str);
490 }
491
492
493 /**
494  * Create a HTML table based on the given data
495  *
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
501  */
502 function rcube_table_output($attrib, $table_data, $a_show_cols, $id_col)
503   {
504   global $RCMAIL;
505   
506   $table = new html_table(/*array('cols' => count($a_show_cols))*/);
507     
508   // add table header
509   foreach ($a_show_cols as $col)
510     $table->add_header($col, Q(rcube_label($col)));
511   
512   $c = 0;
513   if (!is_array($table_data)) 
514   {
515     $db = $RCMAIL->get_dbh();
516     while ($table_data && ($sql_arr = $db->fetch_assoc($table_data)))
517     {
518       $zebra_class = $c % 2 ? 'even' : 'odd';
519       $table->add_row(array('id' => 'rcmrow' . $sql_arr[$id_col], 'class' => "contact $zebra_class"));
520
521       // format each col
522       foreach ($a_show_cols as $col)
523         $table->add($col, Q($sql_arr[$col]));
524       
525       $c++;
526     }
527   }
528   else 
529   {
530     foreach ($table_data as $row_data)
531     {
532       $zebra_class = $c % 2 ? 'even' : 'odd';
533       $table->add_row(array('id' => 'rcmrow' . $row_data[$id_col], 'class' => "contact $zebra_class"));
534
535       // format each col
536       foreach ($a_show_cols as $col)
537         $table->add($col, Q($row_data[$col]));
538         
539       $c++;
540     }
541   }
542
543   return $table->show($attrib);
544   }
545
546
547 /**
548  * Create an edit field for inclusion on a form
549  * 
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
555  */
556 function rcmail_get_edit_field($col, $value, $attrib, $type='text')
557   {
558   $fname = '_'.$col;
559   $attrib['name'] = $fname;
560   
561   if ($type=='checkbox')
562     {
563     $attrib['value'] = '1';
564     $input = new html_checkbox($attrib);
565     }
566   else if ($type=='textarea')
567     {
568     $attrib['cols'] = $attrib['size'];
569     $input = new html_textarea($attrib);
570     }
571   else
572     $input = new html_inputfield($attrib);
573
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);
578
579   $out = $input->show($value);
580          
581   return $out;
582   }
583
584
585 /**
586  * Replace all css definitions with #container [def]
587  * and remove css-inlined scripting
588  *
589  * @param string CSS source code
590  * @param string Container ID to use as prefix
591  * @return string Modified CSS source
592  */
593 function rcmail_mod_css_styles($source, $container_id)
594   {
595   $last_pos = 0;
596   $replacements = new rcube_string_replacer;
597   
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! */';
602
603   // cut out all contents between { and }
604   while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos)))
605   {
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);
608     $last_pos = $pos+2;
609   }
610   
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(
614     array(
615       '/(^\s*<!--)|(-->\s*$)/',
616       '/(^\s*|,\s*|\}\s*)([a-z0-9\._#][a-z0-9\.\-_]*)/im',
617       "/$container_id\s+body/i",
618     ),
619     array(
620       '',
621       "\\1#$container_id \\2",
622       "$container_id div.rcmBody",
623     ),
624     $source);
625   
626   // put block contents back in
627   $styles = $replacements->resolve($styles);
628
629   return $styles;
630   }
631
632
633 /**
634  * Decode escaped entities used by known XSS exploits.
635  * See http://downloads.securityfocus.com/vulnerabilities/exploits/26800.eml for examples
636  *
637  * @param string CSS content to decode
638  * @return string Decoded string
639  */
640 function rcmail_xss_entitiy_decode($content)
641 {
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);
645   return $out;
646 }
647
648
649 /**
650  * preg_replace_callback callback for rcmail_xss_entitiy_decode_callback
651  *
652  * @param array matches result from preg_replace_callback
653  * @return string decoded entity
654  */ 
655 function rcmail_xss_entitiy_decode_callback($matches)
656
657   return chr(hexdec($matches[1]));
658 }
659
660 /**
661  * Compose a valid attribute string for HTML tags
662  *
663  * @param array Named tag attributes
664  * @param array List of allowed attributes
665  * @return string HTML formatted attribute string
666  */
667 function create_attrib_string($attrib, $allowed_attribs=array('id', 'class', 'style'))
668   {
669   // allow the following attributes to be added to the <iframe> tag
670   $attrib_str = '';
671   foreach ($allowed_attribs as $a)
672     if (isset($attrib[$a]))
673       $attrib_str .= sprintf(' %s="%s"', $a, str_replace('"', '&quot;', $attrib[$a]));
674
675   return $attrib_str;
676   }
677
678
679 /**
680  * Convert a HTML attribute string attributes to an associative array (name => value)
681  *
682  * @param string Input string
683  * @return array Key-value pairs of parsed attributes
684  */
685 function parse_attrib_string($str)
686   {
687   $attrib = array();
688   preg_match_all('/\s*([-_a-z]+)=(["\'])??(?(2)([^\2]*)\2|(\S+?))/Ui', stripslashes($str), $regs, PREG_SET_ORDER);
689
690   // convert attributes to an associative array (name => value)
691   if ($regs)
692     foreach ($regs as $attr)
693       {
694       $attrib[strtolower($attr[1])] = $attr[3] . $attr[4];
695       }
696
697   return $attrib;
698   }
699
700
701 /**
702  * Convert the given date to a human readable form
703  * This uses the date formatting properties from config
704  *
705  * @param mixed Date representation (string or timestamp)
706  * @param string Date format to use
707  * @return string Formatted date string
708  */
709 function format_date($date, $format=NULL)
710   {
711   global $CONFIG;
712   
713   $ts = NULL;
714
715   if (is_numeric($date))
716     $ts = $date;
717   else if (!empty($date))
718     {
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))
724       {
725         $d = explode(' ', $date);
726         array_pop($d);
727         if (!$d) break;
728         $date = implode(' ', $d);
729       }
730     }
731
732   if (empty($ts))
733     return '';
734    
735   // get user's timezone
736   if ($CONFIG['timezone'] === 'auto')
737     $tz = isset($_SESSION['timezone']) ? $_SESSION['timezone'] : date('Z')/3600;
738   else {
739     $tz = $CONFIG['timezone'];
740     if ($CONFIG['dst_active'])
741       $tz++;
742   }
743
744   // convert time to user's timezone
745   $timestamp = $ts - date('Z', $ts) + ($tz * 3600);
746   
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);
752
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']);
755
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';
761   else if (!$format)
762     $format = $CONFIG['date_long'] ? $CONFIG['date_long'] : 'd.m.Y H:i';
763
764
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()
767   $out = '';
768   for($i=0; $i<strlen($format); $i++)
769     {
770     if ($format{$i}=='\\')  // skip escape chars
771       continue;
772     
773     // write char "as-is"
774     if ($format{$i}==' ' || $format{$i-1}=='\\')
775       $out .= $format{$i};
776     // weekday (short)
777     else if ($format{$i}=='D')
778       $out .= rcube_label(strtolower(date('D', $timestamp)));
779     // weekday long
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)));
785     // month name (long)
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);
790     else
791       $out .= date($format{$i}, $timestamp);
792     }
793   
794   return $out;
795   }
796
797
798 /**
799  * Compose a valid representaion of name and e-mail address
800  *
801  * @param string E-mail address
802  * @param string Person name
803  * @return string Formatted string
804  */
805 function format_email_recipient($email, $name='')
806   {
807   if ($name && $name != $email)
808     {
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);
811     }
812   else
813     return $email;
814   }
815
816
817
818 /****** debugging functions ********/
819
820
821 /**
822  * Print or write debug messages
823  *
824  * @param mixed Debug message or data
825  */
826 function console()
827   {
828   $msg = array();
829   foreach (func_get_args() as $arg)
830     $msg[] = !is_string($arg) ? var_export($arg, true) : $arg;
831
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";
836   else
837     {
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";
841     }
842   }
843
844
845 /**
846  * Append a line to a logfile in the logs directory.
847  * Date will be added automatically to the line.
848  *
849  * @param $name name of log file
850  * @param line Line to append
851  */
852 function write_log($name, $line)
853   {
854   global $CONFIG;
855
856   if (!is_string($line))
857     $line = var_export($line, true);
858   
859   $log_entry = sprintf("[%s]: %s\n",
860                  date("d-M-Y H:i:s O", mktime()),
861                  $line);
862
863   if ($CONFIG['log_driver'] == 'syslog') {
864     if ($name == 'errors')
865       $prio = LOG_ERR;
866     else
867       $prio = LOG_INFO;
868     syslog($prio, $log_entry);
869   } else {
870     // log_driver == 'file' is assumed here
871     if (empty($CONFIG['log_dir']))
872       $CONFIG['log_dir'] = INSTALL_PATH.'logs';
873
874     // try to open specific log file for writing
875     if ($fp = @fopen($CONFIG['log_dir'].'/'.$name, 'a')) {
876       fwrite($fp, $log_entry);
877       fflush($fp);
878       fclose($fp);
879     }
880   }
881 }
882
883
884 /**
885  * @access private
886  */
887 function rcube_timer()
888   {
889   list($usec, $sec) = explode(" ", microtime());
890   return ((float)$usec + (float)$sec);
891   }
892   
893
894 /**
895  * @access private
896  */
897 function rcube_print_time($timer, $label='Timer')
898   {
899   static $print_count = 0;
900   
901   $print_count++;
902   $now = rcube_timer();
903   $diff = $now-$timer;
904   
905   if (empty($label))
906     $label = 'Timer '.$print_count;
907   
908   console(sprintf("%s: %0.4f sec", $label, $diff));
909   }
910
911
912 /**
913  * Return the mailboxlist in HTML
914  *
915  * @param array Named parameters
916  * @return string HTML code for the gui object
917  */
918 function rcmail_mailbox_list($attrib)
919 {
920   global $RCMAIL;
921   static $a_mailboxes;
922   
923   $attrib += array('maxlength' => 100, 'relanames' => false);
924
925   // add some labels to client
926   $RCMAIL->output->add_label('purgefolderconfirm', 'deletemessagesconfirm');
927   
928   $type = $attrib['type'] ? $attrib['type'] : 'ul';
929   unset($attrib['type']);
930
931   if ($type=='ul' && !$attrib['id'])
932     $attrib['id'] = 'rcmboxlist';
933
934   // get mailbox list
935   $mbox_name = $RCMAIL->imap->get_mailbox_name();
936   
937   // build the folders tree
938   if (empty($a_mailboxes)) {
939     // get mailbox list
940     $a_folders = $RCMAIL->imap->list_mailboxes();
941     $delimiter = $RCMAIL->imap->get_hierarchy_delimiter();
942     $a_mailboxes = array();
943
944     foreach ($a_folders as $folder)
945       rcmail_build_folder_tree($a_mailboxes, $folder, $delimiter);
946   }
947
948   if ($type=='select') {
949     $select = new html_select($attrib);
950     
951     // add no-selection option
952     if ($attrib['noselection'])
953       $select->add(rcube_label($attrib['noselection']), '0');
954     
955     rcmail_render_folder_tree_select($a_mailboxes, $mbox_name, $attrib['maxlength'], $select, $attrib['realnames']);
956     $out = $select->show();
957   }
958   else {
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);
961     
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'));
965   }
966
967   return $out;
968 }
969
970
971 /**
972  * Return the mailboxlist as html_select object
973  *
974  * @param array Named parameters
975  * @return object html_select HTML drop-down object
976  */
977 function rcmail_mailbox_select($p = array())
978 {
979   global $RCMAIL;
980   
981   $p += array('maxlength' => 100, 'relanames' => false);
982   $a_mailboxes = array();
983   
984   foreach ($RCMAIL->imap->list_mailboxes() as $folder)
985     rcmail_build_folder_tree($a_mailboxes, $folder, $RCMAIL->imap->get_hierarchy_delimiter());
986
987   $select = new html_select($p);
988   
989   if ($p['noselection'])
990     $select->add($p['noselection'], '');
991     
992   rcmail_render_folder_tree_select($a_mailboxes, $mbox, $p['maxlength'], $select, $p['realnames']);
993   
994   return $select;
995 }
996
997
998 /**
999  * Create a hierarchical array of the mailbox list
1000  * @access private
1001  */
1002 function rcmail_build_folder_tree(&$arrFolders, $folder, $delm='/', $path='')
1003 {
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]);
1009   }
1010   else {
1011     $subFolders = false;
1012     $currentFolder = $folder;
1013     $virtual = false;
1014   }
1015
1016   $path .= $currentFolder;
1017
1018   if (!isset($arrFolders[$currentFolder])) {
1019     $arrFolders[$currentFolder] = array(
1020       'id' => $path,
1021       'name' => rcube_charset_convert($currentFolder, 'UTF-7'),
1022       'virtual' => $virtual,
1023       'folders' => array());
1024   }
1025   else
1026     $arrFolders[$currentFolder]['virtual'] = $virtual;
1027
1028   if (!empty($subFolders))
1029     rcmail_build_folder_tree($arrFolders[$currentFolder]['folders'], $subFolders, $delm, $path.$delm);
1030 }
1031   
1032
1033 /**
1034  * Return html for a structured list &lt;ul&gt; for the mailbox tree
1035  * @access private
1036  */
1037 function rcmail_render_folder_tree_html(&$arrFolders, &$mbox_name, &$jslist, $attrib, $nestLevel=0)
1038 {
1039   global $RCMAIL, $CONFIG;
1040   
1041   $maxlength = intval($attrib['maxlength']);
1042   $realnames = (bool)$attrib['realnames'];
1043   $msgcounts = $RCMAIL->imap->get_cache('messagecount');
1044
1045   $idx = 0;
1046   $out = '';
1047   foreach ($arrFolders as $key => $folder) {
1048     $zebra_class = (($nestLevel+1)*$idx) % 2 == 0 ? 'even' : 'odd';
1049     $title = null;
1050
1051     if (($folder_class = rcmail_folder_classname($folder['id'])) && !$realnames) {
1052       $foldername = rcube_label($folder_class);
1053     }
1054     else {
1055       $foldername = $folder['name'];
1056
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;
1063       }
1064     }
1065
1066     // make folder name safe for ids and class names
1067     $folder_id = asciiwords($folder['id'], true);
1068     $classes = array('mailbox');
1069
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';
1081     else
1082       $classes[] = '_'.asciiwords($folder_class ? $folder_class : strtolower($folder['id']), true);
1083       
1084     $classes[] = $zebra_class;
1085     
1086     if ($folder['id'] == $mbox_name)
1087       $classes[] = 'selected';
1088
1089     $collapsed = preg_match('/&'.rawurlencode($folder['id']).'&/', $RCMAIL->config->get('collapsed_folders'));
1090     $unread = $msgcounts ? intval($msgcounts[$folder['id']]['UNSEEN']) : 0;
1091     
1092     if ($folder['virtual'])
1093       $classes[] = 'virtual';
1094     else if ($unread)
1095       $classes[] = 'unread';
1096
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),
1102       'title' => $title,
1103     );
1104
1105     $out .= html::tag('li', array(
1106         'id' => "rcmli".$folder_id,
1107         'class' => join(' ', $classes),
1108         'noclose' => true),
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       ), '&nbsp;') : ''));
1115     
1116     $jslist[$folder_id] = array('id' => $folder['id'], 'name' => $foldername, 'virtual' => $folder['virtual']);
1117     
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));
1121     }
1122
1123     $out .= "</li>\n";
1124     $idx++;
1125   }
1126
1127   return $out;
1128 }
1129
1130
1131 /**
1132  * Return html for a flat list <select> for the mailbox tree
1133  * @access private
1134  */
1135 function rcmail_render_folder_tree_select(&$arrFolders, &$mbox_name, $maxlength, &$select, $realnames=false, $nestLevel=0)
1136   {
1137   $idx = 0;
1138   $out = '';
1139   foreach ($arrFolders as $key=>$folder)
1140     {
1141     if (!$realnames && ($folder_class = rcmail_folder_classname($folder['id'])))
1142       $foldername = rcube_label($folder_class);
1143     else
1144       {
1145       $foldername = $folder['name'];
1146       
1147       // shorten the folder name to a given length
1148       if ($maxlength && $maxlength>1)
1149         $foldername = abbreviate_string($foldername, $maxlength);
1150       }
1151
1152     $select->add(str_repeat('&nbsp;', $nestLevel*4) . $foldername, $folder['id']);
1153
1154     if (!empty($folder['folders']))
1155       $out .= rcmail_render_folder_tree_select($folder['folders'], $mbox_name, $maxlength, $select, $realnames, $nestLevel+1);
1156
1157     $idx++;
1158     }
1159
1160   return $out;
1161   }
1162
1163
1164 /**
1165  * Return internal name for the given folder if it matches the configured special folders
1166  * @access private
1167  */
1168 function rcmail_folder_classname($folder_id)
1169 {
1170   global $CONFIG;
1171
1172   // for these mailboxes we have localized labels and css classes
1173   foreach (array('sent', 'drafts', 'trash', 'junk') as $smbx)
1174   {
1175     if ($folder_id == $CONFIG[$smbx.'_mbox'])
1176       return $smbx;
1177   }
1178
1179   if ($folder_id == 'INBOX')
1180     return 'inbox';
1181 }
1182
1183
1184 /**
1185  * Try to localize the given IMAP folder name.
1186  * UTF-7 decode it in case no localized text was found
1187  *
1188  * @param string Folder name
1189  * @return string Localized folder name in UTF-8 encoding
1190  */
1191 function rcmail_localize_foldername($name)
1192 {
1193   if ($folder_class = rcmail_folder_classname($name))
1194     return rcube_label($folder_class);
1195   else
1196     return rcube_charset_convert($name, 'UTF-7');
1197 }
1198
1199
1200 /**
1201  * Output HTML editor scripts
1202  *
1203  * @param string Editor mode
1204  */
1205 function rcube_html_editor($mode='')
1206 {
1207   global $OUTPUT, $CONFIG;
1208
1209   $lang = $tinylang = strtolower(substr($_SESSION['language'], 0, 2));
1210   if (!file_exists(INSTALL_PATH . 'program/js/tiny_mce/langs/'.$tinylang.'.js'))
1211     $tinylang = 'en';
1212
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.'");');
1216 }
1217
1218
1219
1220 /**
1221  * Helper class to turn relative urls into absolute ones
1222  * using a predefined base
1223  */
1224 class rcube_base_replacer
1225 {
1226   private $base_url;
1227   
1228   public function __construct($base)
1229   {
1230     $this->base_url = $base;
1231   }
1232   
1233   public function callback($matches)
1234   {
1235     return $matches[1] . '="' . make_absolute_url($matches[3], $this->base_url) . '"';
1236   }
1237 }
1238
1239 ?>