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

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

#1485602: fix INBOX folder localization

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