]> git.donarmstrong.com Git - roundcube.git/blob - program/include/main.inc
Imported Upstream version 0.2.1
[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 2321 2009-03-01 08:14:14Z alec $
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 || $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   }
246   else if (($from == 'ISO-8859-1') && function_exists('utf8_encode')) {
247     $str = utf8_encode($str);
248   }
249   else if ($from != 'UTF-8' && $conv) {
250     $conv->loadCharset($from);
251     $str = $conv->strToUtf8($str);
252   }
253   else if ($from != 'UTF-8') {}
254     $error = true;
255
256   // encode string for output
257   if ($to == 'UTF-7') {
258     return utf8_to_utf7($str);
259   }
260   else if ($to == 'ISO-8859-1' && function_exists('utf8_decode')) {
261     return utf8_decode($str);
262   }
263   else if ($to != 'UTF-8' && $conv) {
264     $conv->loadCharset($to);
265     return $conv->utf8ToStr($str);
266   }
267   else if ($to != 'UTF-8') {
268     $error = true;
269   }
270   
271   // report error
272   if ($error && !$convert_warning){
273     raise_error(array(
274       'code' => 500,
275       'type' => 'php',
276       'file' => __FILE__,
277       'message' => "Could not convert string charset. Make sure iconv is installed or lib/utf8.class is available"
278       ), true, false);
279     
280     $convert_warning = true;
281   }
282   
283   // return UTF-8 string
284   return $str;
285   }
286
287
288 /**
289  * Replacing specials characters to a specific encoding type
290  *
291  * @param  string  Input string
292  * @param  string  Encoding type: text|html|xml|js|url
293  * @param  string  Replace mode for tags: show|replace|remove
294  * @param  boolean Convert newlines
295  * @return The quoted string
296  */
297 function rep_specialchars_output($str, $enctype='', $mode='', $newlines=TRUE)
298   {
299   global $OUTPUT;
300   static $html_encode_arr = false;
301   static $js_rep_table = false;
302   static $xml_rep_table = false;
303
304   $charset = $OUTPUT->get_charset();
305   $is_iso_8859_1 = false;
306   if ($charset == 'ISO-8859-1') {
307     $is_iso_8859_1 = true;
308   }
309   if (!$enctype)
310     $enctype = $OUTPUT->type;
311
312   // encode for plaintext
313   if ($enctype=='text')
314     return str_replace("\r\n", "\n", $mode=='remove' ? strip_tags($str) : $str);
315
316   // encode for HTML output
317   if ($enctype=='html')
318     {
319     if (!$html_encode_arr)
320       {
321       $html_encode_arr = get_html_translation_table(HTML_SPECIALCHARS);        
322       unset($html_encode_arr['?']);
323       }
324
325     $ltpos = strpos($str, '<');
326     $encode_arr = $html_encode_arr;
327
328     // don't replace quotes and html tags
329     if (($mode=='show' || $mode=='') && $ltpos!==false && strpos($str, '>', $ltpos)!==false)
330       {
331       unset($encode_arr['"']);
332       unset($encode_arr['<']);
333       unset($encode_arr['>']);
334       unset($encode_arr['&']);
335       }
336     else if ($mode=='remove')
337       $str = strip_tags($str);
338     
339     // avoid douple quotation of &
340     $out = preg_replace('/&amp;([A-Za-z]{2,6}|#[0-9]{2,4});/', '&\\1;', strtr($str, $encode_arr));
341       
342     return $newlines ? nl2br($out) : $out;
343     }
344
345   if ($enctype=='url')
346     return rawurlencode($str);
347
348   // if the replace tables for XML and JS are not yet defined
349   if ($js_rep_table===false)
350     {
351     $js_rep_table = $xml_rep_table = array();
352     $xml_rep_table['&'] = '&amp;';
353
354     for ($c=160; $c<256; $c++)  // can be increased to support more charsets
355       {
356       $xml_rep_table[Chr($c)] = "&#$c;";
357       
358       if ($is_iso_8859_1)
359         $js_rep_table[Chr($c)] = sprintf("\\u%04x", $c);
360       }
361
362     $xml_rep_table['"'] = '&quot;';
363     $js_rep_table['"'] = '\\"';
364     $js_rep_table["'"] = "\\'";
365     $js_rep_table["\\"] = "\\\\";
366     }
367
368   // encode for XML
369   if ($enctype=='xml')
370     return strtr($str, $xml_rep_table);
371
372   // encode for javascript use
373   if ($enctype=='js')
374     {
375     if ($charset!='UTF-8')
376       $str = rcube_charset_convert($str, RCMAIL_CHARSET,$charset);
377       
378     return preg_replace(array("/\r?\n/", "/\r/", '/<\\//'), array('\n', '\n', '<\\/'), strtr($str, $js_rep_table));
379     }
380
381   // no encoding given -> return original string
382   return $str;
383   }
384   
385 /**
386  * Quote a given string.
387  * Shortcut function for rep_specialchars_output
388  *
389  * @return string HTML-quoted string
390  * @see rep_specialchars_output()
391  */
392 function Q($str, $mode='strict', $newlines=TRUE)
393   {
394   return rep_specialchars_output($str, 'html', $mode, $newlines);
395   }
396
397 /**
398  * Quote a given string for javascript output.
399  * Shortcut function for rep_specialchars_output
400  * 
401  * @return string JS-quoted string
402  * @see rep_specialchars_output()
403  */
404 function JQ($str)
405   {
406   return rep_specialchars_output($str, 'js');
407   }
408
409
410 /**
411  * Read input value and convert it for internal use
412  * Performs stripslashes() and charset conversion if necessary
413  * 
414  * @param  string   Field name to read
415  * @param  int      Source to get value from (GPC)
416  * @param  boolean  Allow HTML tags in field value
417  * @param  string   Charset to convert into
418  * @return string   Field value or NULL if not available
419  */
420 function get_input_value($fname, $source, $allow_html=FALSE, $charset=NULL)
421   {
422   global $OUTPUT;
423   $value = NULL;
424   
425   if ($source==RCUBE_INPUT_GET && isset($_GET[$fname]))
426     $value = $_GET[$fname];
427   else if ($source==RCUBE_INPUT_POST && isset($_POST[$fname]))
428     $value = $_POST[$fname];
429   else if ($source==RCUBE_INPUT_GPC)
430     {
431     if (isset($_POST[$fname]))
432       $value = $_POST[$fname];
433     else if (isset($_GET[$fname]))
434       $value = $_GET[$fname];
435     else if (isset($_COOKIE[$fname]))
436       $value = $_COOKIE[$fname];
437     }
438   
439   // strip single quotes if magic_quotes_sybase is enabled
440   if (ini_get('magic_quotes_sybase'))
441     $value = str_replace("''", "'", $value);
442   // strip slashes if magic_quotes enabled
443   else if (get_magic_quotes_gpc() || get_magic_quotes_runtime())
444     $value = stripslashes($value);
445
446   // remove HTML tags if not allowed    
447   if (!$allow_html)
448     $value = strip_tags($value);
449   
450   // convert to internal charset
451   if (is_object($OUTPUT))
452     return rcube_charset_convert($value, $OUTPUT->get_charset(), $charset);
453   else
454     return $value;
455   }
456
457 /**
458  * Remove all non-ascii and non-word chars
459  * except . and -
460  */
461 function asciiwords($str, $css_id = false)
462 {
463   $allowed = 'a-z0-9\_\-' . (!$css_id ? '\.' : '');
464   return preg_replace("/[^$allowed]/i", '', $str);
465 }
466
467 /**
468  * Remove single and double quotes from given string
469  *
470  * @param string Input value
471  * @return string Dequoted string
472  */
473 function strip_quotes($str)
474 {
475   return preg_replace('/[\'"]/', '', $str);
476 }
477
478
479 /**
480  * Remove new lines characters from given string
481  *
482  * @param string Input value
483  * @return string Stripped string
484  */
485 function strip_newlines($str)
486 {
487   return preg_replace('/[\r\n]/', '', $str);
488 }
489
490
491 /**
492  * Create a HTML table based on the given data
493  *
494  * @param  array  Named table attributes
495  * @param  mixed  Table row data. Either a two-dimensional array or a valid SQL result set
496  * @param  array  List of cols to show
497  * @param  string Name of the identifier col
498  * @return string HTML table code
499  */
500 function rcube_table_output($attrib, $table_data, $a_show_cols, $id_col)
501   {
502   global $RCMAIL;
503   
504   $table = new html_table(/*array('cols' => count($a_show_cols))*/);
505     
506   // add table header
507   foreach ($a_show_cols as $col)
508     $table->add_header($col, Q(rcube_label($col)));
509   
510   $c = 0;
511   if (!is_array($table_data)) 
512   {
513     $db = $RCMAIL->get_dbh();
514     while ($table_data && ($sql_arr = $db->fetch_assoc($table_data)))
515     {
516       $zebra_class = $c % 2 ? 'even' : 'odd';
517       $table->add_row(array('id' => 'rcmrow' . $sql_arr[$id_col], 'class' => "contact $zebra_class"));
518
519       // format each col
520       foreach ($a_show_cols as $col)
521         $table->add($col, Q($sql_arr[$col]));
522       
523       $c++;
524     }
525   }
526   else 
527   {
528     foreach ($table_data as $row_data)
529     {
530       $zebra_class = $c % 2 ? 'even' : 'odd';
531       $table->add_row(array('id' => 'rcmrow' . $row_data[$id_col], 'class' => "contact $zebra_class"));
532
533       // format each col
534       foreach ($a_show_cols as $col)
535         $table->add($col, Q($row_data[$col]));
536         
537       $c++;
538     }
539   }
540
541   return $table->show($attrib);
542   }
543
544
545 /**
546  * Create an edit field for inclusion on a form
547  * 
548  * @param string col field name
549  * @param string value field value
550  * @param array attrib HTML element attributes for field
551  * @param string type HTML element type (default 'text')
552  * @return string HTML field definition
553  */
554 function rcmail_get_edit_field($col, $value, $attrib, $type='text')
555   {
556   $fname = '_'.$col;
557   $attrib['name'] = $fname;
558   
559   if ($type=='checkbox')
560     {
561     $attrib['value'] = '1';
562     $input = new html_checkbox($attrib);
563     }
564   else if ($type=='textarea')
565     {
566     $attrib['cols'] = $attrib['size'];
567     $input = new html_textarea($attrib);
568     }
569   else
570     $input = new html_inputfield($attrib);
571
572   // use value from post
573   if (!empty($_POST[$fname]))
574     $value = get_input_value($fname, RCUBE_INPUT_POST,
575             $type == 'textarea' && strpos($attrib['class'], 'mce_editor')!==false ? true : false);
576
577   $out = $input->show($value);
578          
579   return $out;
580   }
581
582
583 /**
584  * Replace all css definitions with #container [def]
585  * and remove css-inlined scripting
586  *
587  * @param string CSS source code
588  * @param string Container ID to use as prefix
589  * @return string Modified CSS source
590  */
591 function rcmail_mod_css_styles($source, $container_id)
592   {
593   $last_pos = 0;
594   $replacements = new rcube_string_replacer;
595   
596   // ignore the whole block if evil styles are detected
597   $stripped = preg_replace('/[^a-z\(:]/', '', rcmail_xss_entitiy_decode($source));
598   if (preg_match('/expression|behavior|url\(|import/', $stripped))
599     return '/* evil! */';
600
601   // cut out all contents between { and }
602   while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos)))
603   {
604     $key = $replacements->add(substr($source, $pos+1, $pos2-($pos+1)));
605     $source = substr($source, 0, $pos+1) . $replacements->get_replacement($key) . substr($source, $pos2, strlen($source)-$pos2);
606     $last_pos = $pos+2;
607   }
608   
609   // remove html comments and add #container to each tag selector.
610   // also replace body definition because we also stripped off the <body> tag
611   $styles = preg_replace(
612     array(
613       '/(^\s*<!--)|(-->\s*$)/',
614       '/(^\s*|,\s*|\}\s*)([a-z0-9\._#][a-z0-9\.\-_]*)/im',
615       "/$container_id\s+body/i",
616     ),
617     array(
618       '',
619       "\\1#$container_id \\2",
620       "$container_id div.rcmBody",
621     ),
622     $source);
623   
624   // put block contents back in
625   $styles = $replacements->resolve($styles);
626
627   return $styles;
628   }
629
630
631 /**
632  * Decode escaped entities used by known XSS exploits.
633  * See http://downloads.securityfocus.com/vulnerabilities/exploits/26800.eml for examples
634  *
635  * @param string CSS content to decode
636  * @return string Decoded string
637  */
638 function rcmail_xss_entitiy_decode($content)
639 {
640   $out = html_entity_decode(html_entity_decode($content));
641   $out = preg_replace_callback('/\\\([0-9a-f]{4})/i', 'rcmail_xss_entitiy_decode_callback', $out);
642   $out = preg_replace('#/\*.*\*/#Um', '', $out);
643   return $out;
644 }
645
646
647 /**
648  * preg_replace_callback callback for rcmail_xss_entitiy_decode_callback
649  *
650  * @param array matches result from preg_replace_callback
651  * @return string decoded entity
652  */ 
653 function rcmail_xss_entitiy_decode_callback($matches)
654
655   return chr(hexdec($matches[1]));
656 }
657
658 /**
659  * Compose a valid attribute string for HTML tags
660  *
661  * @param array Named tag attributes
662  * @param array List of allowed attributes
663  * @return string HTML formatted attribute string
664  */
665 function create_attrib_string($attrib, $allowed_attribs=array('id', 'class', 'style'))
666   {
667   // allow the following attributes to be added to the <iframe> tag
668   $attrib_str = '';
669   foreach ($allowed_attribs as $a)
670     if (isset($attrib[$a]))
671       $attrib_str .= sprintf(' %s="%s"', $a, str_replace('"', '&quot;', $attrib[$a]));
672
673   return $attrib_str;
674   }
675
676
677 /**
678  * Convert a HTML attribute string attributes to an associative array (name => value)
679  *
680  * @param string Input string
681  * @return array Key-value pairs of parsed attributes
682  */
683 function parse_attrib_string($str)
684   {
685   $attrib = array();
686   preg_match_all('/\s*([-_a-z]+)=(["\'])??(?(2)([^\2]*)\2|(\S+?))/Ui', stripslashes($str), $regs, PREG_SET_ORDER);
687
688   // convert attributes to an associative array (name => value)
689   if ($regs)
690     foreach ($regs as $attr)
691       {
692       $attrib[strtolower($attr[1])] = $attr[3] . $attr[4];
693       }
694
695   return $attrib;
696   }
697
698
699 /**
700  * Convert the given date to a human readable form
701  * This uses the date formatting properties from config
702  *
703  * @param mixed Date representation (string or timestamp)
704  * @param string Date format to use
705  * @return string Formatted date string
706  */
707 function format_date($date, $format=NULL)
708   {
709   global $CONFIG;
710   
711   $ts = NULL;
712
713   if (is_numeric($date))
714     $ts = $date;
715   else if (!empty($date))
716     {
717     // support non-standard "GMTXXXX" literal
718     $date = preg_replace('/GMT\s*([+-][0-9]+)/', '\\1', $date);
719     // if date parsing fails, we have a date in non-rfc format.
720     // remove token from the end and try again
721     while ((($ts = @strtotime($date))===false) || ($ts < 0))
722       {
723         $d = explode(' ', $date);
724         array_pop($d);
725         if (!$d) break;
726         $date = implode(' ', $d);
727       }
728     }
729
730   if (empty($ts))
731     return '';
732    
733   // get user's timezone
734   if ($CONFIG['timezone'] === 'auto')
735     $tz = isset($_SESSION['timezone']) ? $_SESSION['timezone'] : date('Z')/3600;
736   else {
737     $tz = $CONFIG['timezone'];
738     if ($CONFIG['dst_active'])
739       $tz++;
740   }
741
742   // convert time to user's timezone
743   $timestamp = $ts - date('Z', $ts) + ($tz * 3600);
744   
745   // get current timestamp in user's timezone
746   $now = time();  // local time
747   $now -= (int)date('Z'); // make GMT time
748   $now += ($tz * 3600); // user's time
749   $now_date = getdate($now);
750
751   $today_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday'], $now_date['year']);
752   $week_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday']-6, $now_date['year']);
753
754   // define date format depending on current time  
755   if ($CONFIG['prettydate'] && !$format && $timestamp > $today_limit && $timestamp < $now)
756     return sprintf('%s %s', rcube_label('today'), date($CONFIG['date_today'] ? $CONFIG['date_today'] : 'H:i', $timestamp));
757   else if ($CONFIG['prettydate'] && !$format && $timestamp > $week_limit && $timestamp < $now)
758     $format = $CONFIG['date_short'] ? $CONFIG['date_short'] : 'D H:i';
759   else if (!$format)
760     $format = $CONFIG['date_long'] ? $CONFIG['date_long'] : 'd.m.Y H:i';
761
762
763   // parse format string manually in order to provide localized weekday and month names
764   // an alternative would be to convert the date() format string to fit with strftime()
765   $out = '';
766   for($i=0; $i<strlen($format); $i++)
767     {
768     if ($format{$i}=='\\')  // skip escape chars
769       continue;
770     
771     // write char "as-is"
772     if ($format{$i}==' ' || $format{$i-1}=='\\')
773       $out .= $format{$i};
774     // weekday (short)
775     else if ($format{$i}=='D')
776       $out .= rcube_label(strtolower(date('D', $timestamp)));
777     // weekday long
778     else if ($format{$i}=='l')
779       $out .= rcube_label(strtolower(date('l', $timestamp)));
780     // month name (short)
781     else if ($format{$i}=='M')
782       $out .= rcube_label(strtolower(date('M', $timestamp)));
783     // month name (long)
784     else if ($format{$i}=='F')
785       $out .= rcube_label('long'.strtolower(date('M', $timestamp)));
786     else if ($format{$i}=='x')
787       $out .= strftime('%x %X', $timestamp);
788     else
789       $out .= date($format{$i}, $timestamp);
790     }
791   
792   return $out;
793   }
794
795
796 /**
797  * Compose a valid representaion of name and e-mail address
798  *
799  * @param string E-mail address
800  * @param string Person name
801  * @return string Formatted string
802  */
803 function format_email_recipient($email, $name='')
804   {
805   if ($name && $name != $email)
806     {
807     // Special chars as defined by RFC 822 need to in quoted string (or escaped).
808     return sprintf('%s <%s>', preg_match('/[\(\)\<\>\\\.\[\]@,;:"]/', $name) ? '"'.addcslashes($name, '"').'"' : $name, $email);
809     }
810   else
811     return $email;
812   }
813
814
815
816 /****** debugging functions ********/
817
818
819 /**
820  * Print or write debug messages
821  *
822  * @param mixed Debug message or data
823  */
824 function console()
825   {
826   $msg = array();
827   foreach (func_get_args() as $arg)
828     $msg[] = !is_string($arg) ? var_export($arg, true) : $arg;
829
830   if (!($GLOBALS['CONFIG']['debug_level'] & 4))
831     write_log('console', join(";\n", $msg));
832   else if ($GLOBALS['OUTPUT']->ajax_call)
833     print "/*\n " . join(";\n", $msg) . " \n*/\n";
834   else
835     {
836     print '<div style="background:#eee; border:1px solid #ccc; margin-bottom:3px; padding:6px"><pre>';
837     print join(";<br/>\n", $msg);
838     print "</pre></div>\n";
839     }
840   }
841
842
843 /**
844  * Append a line to a logfile in the logs directory.
845  * Date will be added automatically to the line.
846  *
847  * @param $name name of log file
848  * @param line Line to append
849  */
850 function write_log($name, $line)
851   {
852   global $CONFIG;
853
854   if (!is_string($line))
855     $line = var_export($line, true);
856   
857   $log_entry = sprintf("[%s]: %s\n",
858                  date("d-M-Y H:i:s O", mktime()),
859                  $line);
860
861   if ($CONFIG['log_driver'] == 'syslog') {
862     if ($name == 'errors')
863       $prio = LOG_ERR;
864     else
865       $prio = LOG_INFO;
866     syslog($prio, $log_entry);
867   } else {
868     // log_driver == 'file' is assumed here
869     if (empty($CONFIG['log_dir']))
870       $CONFIG['log_dir'] = INSTALL_PATH.'logs';
871
872     // try to open specific log file for writing
873     if ($fp = @fopen($CONFIG['log_dir'].'/'.$name, 'a')) {
874       fwrite($fp, $log_entry);
875       fflush($fp);
876       fclose($fp);
877     }
878   }
879 }
880
881
882 /**
883  * @access private
884  */
885 function rcube_timer()
886   {
887   list($usec, $sec) = explode(" ", microtime());
888   return ((float)$usec + (float)$sec);
889   }
890   
891
892 /**
893  * @access private
894  */
895 function rcube_print_time($timer, $label='Timer')
896   {
897   static $print_count = 0;
898   
899   $print_count++;
900   $now = rcube_timer();
901   $diff = $now-$timer;
902   
903   if (empty($label))
904     $label = 'Timer '.$print_count;
905   
906   console(sprintf("%s: %0.4f sec", $label, $diff));
907   }
908
909
910 /**
911  * Return the mailboxlist in HTML
912  *
913  * @param array Named parameters
914  * @return string HTML code for the gui object
915  */
916 function rcmail_mailbox_list($attrib)
917 {
918   global $RCMAIL;
919   static $a_mailboxes;
920   
921   $attrib += array('maxlength' => 100, 'relanames' => false);
922
923   // add some labels to client
924   $RCMAIL->output->add_label('purgefolderconfirm', 'deletemessagesconfirm');
925   
926   $type = $attrib['type'] ? $attrib['type'] : 'ul';
927   unset($attrib['type']);
928
929   if ($type=='ul' && !$attrib['id'])
930     $attrib['id'] = 'rcmboxlist';
931
932   // get mailbox list
933   $mbox_name = $RCMAIL->imap->get_mailbox_name();
934   
935   // build the folders tree
936   if (empty($a_mailboxes)) {
937     // get mailbox list
938     $a_folders = $RCMAIL->imap->list_mailboxes();
939     $delimiter = $RCMAIL->imap->get_hierarchy_delimiter();
940     $a_mailboxes = array();
941
942     foreach ($a_folders as $folder)
943       rcmail_build_folder_tree($a_mailboxes, $folder, $delimiter);
944   }
945
946   if ($type=='select') {
947     $select = new html_select($attrib);
948     
949     // add no-selection option
950     if ($attrib['noselection'])
951       $select->add(rcube_label($attrib['noselection']), '0');
952     
953     rcmail_render_folder_tree_select($a_mailboxes, $mbox_name, $attrib['maxlength'], $select, $attrib['realnames']);
954     $out = $select->show();
955   }
956   else {
957     $js_mailboxlist = array();
958     $out = html::tag('ul', $attrib, rcmail_render_folder_tree_html($a_mailboxes, $mbox_name, $js_mailboxlist, $attrib), html::$common_attrib);
959     
960     $RCMAIL->output->add_gui_object('mailboxlist', $attrib['id']);
961     $RCMAIL->output->set_env('mailboxes', $js_mailboxlist);
962     $RCMAIL->output->set_env('collapsed_folders', $RCMAIL->config->get('collapsed_folders'));
963   }
964
965   return $out;
966 }
967
968
969 /**
970  * Return the mailboxlist as html_select object
971  *
972  * @param array Named parameters
973  * @return object html_select HTML drop-down object
974  */
975 function rcmail_mailbox_select($p = array())
976 {
977   global $RCMAIL;
978   
979   $p += array('maxlength' => 100, 'relanames' => false);
980   $a_mailboxes = array();
981   
982   foreach ($RCMAIL->imap->list_mailboxes() as $folder)
983     rcmail_build_folder_tree($a_mailboxes, $folder, $RCMAIL->imap->get_hierarchy_delimiter());
984
985   $select = new html_select($p);
986   
987   if ($p['noselection'])
988     $select->add($p['noselection'], '');
989     
990   rcmail_render_folder_tree_select($a_mailboxes, $mbox, $p['maxlength'], $select, $p['realnames']);
991   
992   return $select;
993 }
994
995
996 /**
997  * Create a hierarchical array of the mailbox list
998  * @access private
999  */
1000 function rcmail_build_folder_tree(&$arrFolders, $folder, $delm='/', $path='')
1001 {
1002   $pos = strpos($folder, $delm);
1003   if ($pos !== false) {
1004     $subFolders = substr($folder, $pos+1);
1005     $currentFolder = substr($folder, 0, $pos);
1006     $virtual = !isset($arrFolders[$currentFolder]);
1007   }
1008   else {
1009     $subFolders = false;
1010     $currentFolder = $folder;
1011     $virtual = false;
1012   }
1013
1014   $path .= $currentFolder;
1015
1016   if (!isset($arrFolders[$currentFolder])) {
1017     $arrFolders[$currentFolder] = array(
1018       'id' => $path,
1019       'name' => rcube_charset_convert($currentFolder, 'UTF-7'),
1020       'virtual' => $virtual,
1021       'folders' => array());
1022   }
1023   else
1024     $arrFolders[$currentFolder]['virtual'] = $virtual;
1025
1026   if (!empty($subFolders))
1027     rcmail_build_folder_tree($arrFolders[$currentFolder]['folders'], $subFolders, $delm, $path.$delm);
1028 }
1029   
1030
1031 /**
1032  * Return html for a structured list &lt;ul&gt; for the mailbox tree
1033  * @access private
1034  */
1035 function rcmail_render_folder_tree_html(&$arrFolders, &$mbox_name, &$jslist, $attrib, $nestLevel=0)
1036 {
1037   global $RCMAIL, $CONFIG;
1038   
1039   $maxlength = intval($attrib['maxlength']);
1040   $realnames = (bool)$attrib['realnames'];
1041   $msgcounts = $RCMAIL->imap->get_cache('messagecount');
1042
1043   $idx = 0;
1044   $out = '';
1045   foreach ($arrFolders as $key => $folder) {
1046     $zebra_class = (($nestLevel+1)*$idx) % 2 == 0 ? 'even' : 'odd';
1047     $title = null;
1048
1049     if (($folder_class = rcmail_folder_classname($folder['id'])) && !$realnames) {
1050       $foldername = rcube_label($folder_class);
1051     }
1052     else {
1053       $foldername = $folder['name'];
1054
1055       // shorten the folder name to a given length
1056       if ($maxlength && $maxlength > 1) {
1057         $fname = abbreviate_string($foldername, $maxlength);
1058         if ($fname != $foldername)
1059           $title = $foldername;
1060         $foldername = $fname;
1061       }
1062     }
1063
1064     // make folder name safe for ids and class names
1065     $folder_id = asciiwords($folder['id'], true);
1066     $classes = array('mailbox');
1067
1068     // set special class for Sent, Drafts, Trash and Junk
1069     if ($folder['id']==$CONFIG['sent_mbox'])
1070       $classes[] = 'sent';
1071     else if ($folder['id']==$CONFIG['drafts_mbox'])
1072       $classes[] = 'drafts';
1073     else if ($folder['id']==$CONFIG['trash_mbox'])
1074       $classes[] = 'trash';
1075     else if ($folder['id']==$CONFIG['junk_mbox'])
1076       $classes[] = 'junk';
1077     else if ($folder['id']=='INBOX')
1078       $classes[] = 'inbox';
1079     else
1080       $classes[] = '_'.asciiwords($folder_class ? $folder_class : strtolower($folder['id']), true);
1081       
1082     $classes[] = $zebra_class;
1083     
1084     if ($folder['id'] == $mbox_name)
1085       $classes[] = 'selected';
1086
1087     $collapsed = preg_match('/&'.rawurlencode($folder['id']).'&/', $RCMAIL->config->get('collapsed_folders'));
1088     $unread = $msgcounts ? intval($msgcounts[$folder['id']]['UNSEEN']) : 0;
1089     
1090     if ($folder['virtual'])
1091       $classes[] = 'virtual';
1092     else if ($unread)
1093       $classes[] = 'unread';
1094
1095     $js_name = JQ($folder['id']);
1096     $html_name = Q($foldername . ($unread ? " ($unread)" : ''));
1097     $link_attrib = $folder['virtual'] ? array() : array(
1098       'href' => rcmail_url('', array('_mbox' => $folder['id'])),
1099       'onclick' => sprintf("return %s.command('list','%s',this)", JS_OBJECT_NAME, $js_name),
1100       'title' => $title,
1101     );
1102
1103     $out .= html::tag('li', array(
1104         'id' => "rcmli".$folder_id,
1105         'class' => join(' ', $classes),
1106         'noclose' => true),
1107       html::a($link_attrib, $html_name) .
1108       (!empty($folder['folders']) ? html::div(array(
1109         'class' => ($collapsed ? 'collapsed' : 'expanded'),
1110         'style' => "position:absolute",
1111         'onclick' => sprintf("%s.command('collapse-folder', '%s')", JS_OBJECT_NAME, $js_name)
1112       ), '&nbsp;') : ''));
1113     
1114     $jslist[$folder_id] = array('id' => $folder['id'], 'name' => $foldername, 'virtual' => $folder['virtual']);
1115     
1116     if (!empty($folder['folders'])) {
1117       $out .= html::tag('ul', array('style' => ($collapsed ? "display:none;" : null)),
1118         rcmail_render_folder_tree_html($folder['folders'], $mbox_name, $jslist, $attrib, $nestLevel+1));
1119     }
1120
1121     $out .= "</li>\n";
1122     $idx++;
1123   }
1124
1125   return $out;
1126 }
1127
1128
1129 /**
1130  * Return html for a flat list <select> for the mailbox tree
1131  * @access private
1132  */
1133 function rcmail_render_folder_tree_select(&$arrFolders, &$mbox_name, $maxlength, &$select, $realnames=false, $nestLevel=0)
1134   {
1135   $idx = 0;
1136   $out = '';
1137   foreach ($arrFolders as $key=>$folder)
1138     {
1139     if (!$realnames && ($folder_class = rcmail_folder_classname($folder['id'])))
1140       $foldername = rcube_label($folder_class);
1141     else
1142       {
1143       $foldername = $folder['name'];
1144       
1145       // shorten the folder name to a given length
1146       if ($maxlength && $maxlength>1)
1147         $foldername = abbreviate_string($foldername, $maxlength);
1148       }
1149
1150     $select->add(str_repeat('&nbsp;', $nestLevel*4) . $foldername, $folder['id']);
1151
1152     if (!empty($folder['folders']))
1153       $out .= rcmail_render_folder_tree_select($folder['folders'], $mbox_name, $maxlength, $select, $realnames, $nestLevel+1);
1154
1155     $idx++;
1156     }
1157
1158   return $out;
1159   }
1160
1161
1162 /**
1163  * Return internal name for the given folder if it matches the configured special folders
1164  * @access private
1165  */
1166 function rcmail_folder_classname($folder_id)
1167 {
1168   global $CONFIG;
1169
1170   // for these mailboxes we have localized labels and css classes
1171   foreach (array('sent', 'drafts', 'trash', 'junk') as $smbx)
1172   {
1173     if ($folder_id == $CONFIG[$smbx.'_mbox'])
1174       return $smbx;
1175   }
1176
1177   if ($folder_id == 'INBOX')
1178     return 'inbox';
1179 }
1180
1181
1182 /**
1183  * Try to localize the given IMAP folder name.
1184  * UTF-7 decode it in case no localized text was found
1185  *
1186  * @param string Folder name
1187  * @return string Localized folder name in UTF-8 encoding
1188  */
1189 function rcmail_localize_foldername($name)
1190 {
1191   if ($folder_class = rcmail_folder_classname($name))
1192     return rcube_label($folder_class);
1193   else
1194     return rcube_charset_convert($name, 'UTF-7');
1195 }
1196
1197
1198 /**
1199  * Output HTML editor scripts
1200  *
1201  * @param string Editor mode
1202  */
1203 function rcube_html_editor($mode='')
1204 {
1205   global $OUTPUT, $CONFIG;
1206
1207   $lang = $tinylang = strtolower(substr($_SESSION['language'], 0, 2));
1208   if (!file_exists(INSTALL_PATH . 'program/js/tiny_mce/langs/'.$tinylang.'.js'))
1209     $tinylang = 'en';
1210
1211   $OUTPUT->include_script('tiny_mce/tiny_mce.js');
1212   $OUTPUT->include_script('editor.js');
1213   $OUTPUT->add_script('rcmail_editor_init("$__skin_path", "'.JQ($tinylang).'", '.intval($CONFIG['enable_spellcheck']).', "'.$mode.'");');
1214 }
1215
1216
1217
1218 /**
1219  * Helper class to turn relative urls into absolute ones
1220  * using a predefined base
1221  */
1222 class rcube_base_replacer
1223 {
1224   private $base_url;
1225   
1226   public function __construct($base)
1227   {
1228     $this->base_url = $base;
1229   }
1230   
1231   public function callback($matches)
1232   {
1233     return $matches[1] . '="' . make_absolute_url($matches[3], $this->base_url) . '"';
1234   }
1235 }
1236
1237 ?>