source: github/program/include/main.inc @ fdebae8

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since fdebae8 was fdebae8, checked in by thomascube <thomas@…>, 5 years ago

Better detection of HTML double-encoded entities

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