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

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

Don't use addslashes() which could produce unexpected results when magic_quotes_sybase is on

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