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

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