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

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