source: subversion/trunk/roundcubemail/program/include/main.inc @ 2252

Last change on this file since 2252 was 2252, checked in by thomasb, 4 years ago

Get rid of vulnerable preg_replace eval and create_function (#1485686) + correctly handle base and link tags in html messages

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