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

Last change on this file since 1459 was 1459, checked in by alec, 5 years ago

-removed not existing variable

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