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

Last change on this file since 1836 was 1836, checked in by thomasb, 5 years ago

Treat US-ASCII as Latin-1 to give messages with wrong charset definition a chance

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