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

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

Fix charset conversion error logging

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