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

Last change on this file since 2306 was 2306, checked in by alec, 4 years ago

#1485741: fix installer after some last changes

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