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

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