thomascube
2008-07-31 62e54249df84f7d8a1d9af2f6d5a978bbba78bb5
commit | author | age
4e17e6 1 <?php
T 2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/include/main.inc                                              |
6  |                                                                       |
7  | This file is part of the RoundCube Webmail client                     |
1a7f99 8  | Copyright (C) 2005-2008, RoundCube Dev, - Switzerland                 |
30233b 9  | Licensed under the GNU GPL                                            |
4e17e6 10  |                                                                       |
T 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
6d969b 22 /**
T 23  * RoundCube Webmail common functions
24  *
25  * @package Core
26  * @author Thomas Bruederli <roundcube@gmail.com>
27  */
28
0af7e8 29 require_once('lib/utf7.inc');
97bd2c 30 require_once('include/rcube_shared.inc');
4e17e6 31
1a7f99 32 // fallback if not PHP modules are available
T 33 @include_once('lib/des.inc');
34 @include_once('lib/utf8.class.php');
4e17e6 35
ea7c46 36 // define constannts for input reading
T 37 define('RCUBE_INPUT_GET', 0x0101);
38 define('RCUBE_INPUT_POST', 0x0102);
39 define('RCUBE_INPUT_GPC', 0x0103);
40
41
4e17e6 42
6d969b 43 /**
T 44  * Return correct name for a specific database table
45  *
46  * @param string Table name
47  * @return string Translated table name
48  */
4e17e6 49 function get_table_name($table)
T 50   {
51   global $CONFIG;
653242 52
4e17e6 53   // return table name if configured
T 54   $config_key = 'db_table_'.$table;
55
56   if (strlen($CONFIG[$config_key]))
57     return $CONFIG[$config_key];
653242 58
4e17e6 59   return $table;
T 60   }
61
62
6d969b 63 /**
T 64  * Return correct name for a specific database sequence
653242 65  * (used for Postgres only)
6d969b 66  *
T 67  * @param string Secuence name
68  * @return string Translated sequence name
69  */
1cded8 70 function get_sequence_name($sequence)
T 71   {
72   // return table name if configured
73   $config_key = 'db_sequence_'.$sequence;
54dd42 74   $opt = rcmail::get_instance()->config->get($config_key);
1cded8 75
54dd42 76   if (!empty($opt))
A 77     {
78     $db = &rcmail::get_instance()->db;
87242c 79     $dbclass = 'rcube_mdb2';
A 80     
81     if ($db->db_provider=='pgsql' && ($db instanceof $dbclass))
54dd42 82       {
A 83       $db->db_handle->setOption('disable_smart_seqname', true);
84       $db->db_handle->setOption('seqname_format', '%s');
3e8483 85       }
54dd42 86   
3e8483 87     return $opt;
54dd42 88     }
A 89     
ae8f19 90   return $sequence;
1cded8 91   }
0af7e8 92
T 93
6d969b 94 /**
1854c4 95  * Get localized text in the desired language
T 96  * It's a global wrapper for rcmail::gettext()
6d969b 97  *
1854c4 98  * @param mixed Named parameters array or label name
T 99  * @return string Localized text
100  * @see rcmail::gettext()
6d969b 101  */
1854c4 102 function rcube_label($p)
T 103 {
104   return rcmail::get_instance()->gettext($p);
105 }
4e17e6 106
T 107
6d969b 108 /**
T 109  * Overwrite action variable
110  *
111  * @param string New action value
112  */
10a699 113 function rcmail_overwrite_action($action)
T 114   {
197601 115   $app = rcmail::get_instance();
T 116   $app->action = $action;
117   $app->output->set_env('action', $action);
10a699 118   }
T 119
120
41bece 121 /**
T 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  */
129 function rcmail_url($action, $p=array(), $task=null)
f11541 130 {
197601 131   $app = rcmail::get_instance();
fde466 132   return $app->url((array)$p + array('_action' => $action, 'task' => $task));
f11541 133 }
9fee0e 134
4e17e6 135
6d969b 136 /**
T 137  * Add a localized label to the client environment
47124c 138  * @deprecated
6d969b 139  */
10a699 140 function rcube_add_label()
T 141   {
f11541 142   global $OUTPUT;
10a699 143   
T 144   $arg_list = func_get_args();
145   foreach ($arg_list as $i => $name)
47124c 146     $OUTPUT->add_label($name);
1cded8 147   }
T 148
149
6d969b 150 /**
T 151  * Garbage collector function for temp files.
152  * Remove temp files older than two days
153  */
70d4b9 154 function rcmail_temp_gc()
1cded8 155   {
70d4b9 156   $tmp = unslashify($CONFIG['temp_dir']);
T 157   $expire = mktime() - 172800;  // expire in 48 hours
1cded8 158
70d4b9 159   if ($dir = opendir($tmp))
1cded8 160     {
70d4b9 161     while (($fname = readdir($dir)) !== false)
T 162       {
163       if ($fname{0} == '.')
164         continue;
165
166       if (filemtime($tmp.'/'.$fname) < $expire)
167         @unlink($tmp.'/'.$fname);
168       }
169
170     closedir($dir);
171     }
1cded8 172   }
T 173
174
6d969b 175 /**
T 176  * Garbage collector for cache entries.
177  * Remove all expired message cache records
178  */
cc9570 179 function rcmail_message_cache_gc()
T 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
1cded8 194
2bca6e 195 /**
T 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
f11541 201  * @param  string Target charset to convert to; defaults to RCMAIL_CHARSET
2bca6e 202  * @return Converted string
T 203  */
3f9edb 204 function rcube_charset_convert($str, $from, $to=NULL)
0af7e8 205   {
197601 206   static $mbstring_loaded = null, $convert_warning = false;
f88d41 207
83dbb7 208   $from = strtoupper($from);
f11541 209   $to = $to==NULL ? strtoupper(RCMAIL_CHARSET) : strtoupper($to);
1a7f99 210   $error = false; $conv = null;
f88d41 211
2f2f15 212   if ($from==$to || $str=='' || empty($from))
3f9edb 213     return $str;
38b012 214     
T 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   );
5f56a5 222
b8e65c 223   // convert charset using iconv module  
T 224   if (function_exists('iconv') && $from != 'UTF-7' && $to != 'UTF-7')
0393da 225     {
7250d6 226     $aliases['GB2312'] = 'GB18030';
3bfab3 227     $_iconv = iconv(($aliases[$from] ? $aliases[$from] : $from), ($aliases[$to] ? $aliases[$to] : $to) . "//IGNORE", $str);
T 228     if ($_iconv !== false)
229       {
230         return $_iconv;
231       }
0393da 232     }
5f56a5 233
197601 234   // settings for mbstring module (by Tadashi Jokagi)
T 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)
b8e65c 242     {
b19536 243     $aliases['UTF-7'] = 'UTF7-IMAP';
T 244     $aliases['WINDOWS-1257'] = 'ISO-8859-13';
88f66e 245     
5f56a5 246     // return if convert succeeded
b19536 247     if (($out = mb_convert_encoding($str, ($aliases[$to] ? $aliases[$to] : $to), ($aliases[$from] ? $aliases[$from] : $from))) != '')
5f56a5 248       return $out;
83dbb7 249     }
1a7f99 250     
T 251   
252   if (class_exists('utf8'))
253     $conv = new utf8();
58e360 254
83dbb7 255   // convert string to UTF-8
1a7f99 256   if ($from == 'UTF-7')
c8c1a3 257     $str = utf7_to_utf8($str);
1a7f99 258   else if (($from == 'ISO-8859-1') && function_exists('utf8_encode'))
83dbb7 259     $str = utf8_encode($str);
1a7f99 260   else if ($from != 'UTF-8' && $conv)
83dbb7 261     {
58e360 262     $conv->loadCharset($from);
83dbb7 263     $str = $conv->strToUtf8($str);
T 264     }
1a7f99 265   else if ($from != 'UTF-8')
T 266     $error = true;
0af7e8 267
3f9edb 268   // encode string for output
1a7f99 269   if ($to == 'UTF-7')
c8c1a3 270     return utf8_to_utf7($str);
1a7f99 271   else if ($to == 'ISO-8859-1' && function_exists('utf8_decode'))
83dbb7 272     return utf8_decode($str);
1a7f99 273   else if ($to != 'UTF-8' && $conv)
83dbb7 274     {
58e360 275     $conv->loadCharset($to);
83dbb7 276     return $conv->utf8ToStr($str);
T 277     }
1a7f99 278   else if ($to != 'UTF-8')
T 279     $error = true;
3f9edb 280
1a7f99 281   // report error
T 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   
83dbb7 294   // return UTF-8 string
3f9edb 295   return $str;
0af7e8 296   }
3f9edb 297
0af7e8 298
2bca6e 299 /**
T 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  */
1cded8 308 function rep_specialchars_output($str, $enctype='', $mode='', $newlines=TRUE)
T 309   {
197601 310   global $OUTPUT;
257782 311   static $html_encode_arr = false;
A 312   static $js_rep_table = false;
313   static $xml_rep_table = false;
1cded8 314
257782 315   $charset = $OUTPUT->get_charset();
A 316   $is_iso_8859_1 = false;
317   if ($charset == 'ISO-8859-1') {
318     $is_iso_8859_1 = true;
319   }
1cded8 320   if (!$enctype)
T 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       {
0af7e8 332       $html_encode_arr = get_html_translation_table(HTML_SPECIALCHARS);        
1cded8 333       unset($html_encode_arr['?']);
T 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['>']);
10c92b 345       unset($encode_arr['&']);
1cded8 346       }
T 347     else if ($mode=='remove')
348       $str = strip_tags($str);
674a0f 349     
T 350     // avoid douple quotation of &
e6a406 351     $out = preg_replace('/&amp;([a-z]{2,5}|#[0-9]{2,4});/', '&\\1;', strtr($str, $encode_arr));
0af7e8 352       
1cded8 353     return $newlines ? nl2br($out) : $out;
T 354     }
355
356   if ($enctype=='url')
357     return rawurlencode($str);
358
2bca6e 359   // if the replace tables for XML and JS are not yet defined
257782 360   if ($js_rep_table===false)
1cded8 361     {
f91a49 362     $js_rep_table = $xml_rep_table = array();
88375f 363     $xml_rep_table['&'] = '&amp;';
1cded8 364
T 365     for ($c=160; $c<256; $c++)  // can be increased to support more charsets
366       {
367       $xml_rep_table[Chr($c)] = "&#$c;";
368       
257782 369       if ($is_iso_8859_1)
74ae88 370         $js_rep_table[Chr($c)] = sprintf("\\u%04x", $c);
1cded8 371       }
T 372
373     $xml_rep_table['"'] = '&quot;';
374     }
375
2bca6e 376   // encode for XML
1cded8 377   if ($enctype=='xml')
T 378     return strtr($str, $xml_rep_table);
379
380   // encode for javascript use
381   if ($enctype=='js')
13c1af 382     {
257782 383     if ($charset!='UTF-8')
A 384       $str = rcube_charset_convert($str, RCMAIL_CHARSET,$charset);
13c1af 385       
47124c 386     return preg_replace(array("/\r?\n/", "/\r/", '/<\\//'), array('\n', '\n', '<\\/'), addslashes(strtr($str, $js_rep_table)));
13c1af 387     }
1cded8 388
T 389   // no encoding given -> return original string
390   return $str;
2bca6e 391   }
f11541 392   
2bca6e 393 /**
6d969b 394  * Quote a given string.
T 395  * Shortcut function for rep_specialchars_output
396  *
397  * @return string HTML-quoted string
398  * @see rep_specialchars_output()
2bca6e 399  */
T 400 function Q($str, $mode='strict', $newlines=TRUE)
401   {
402   return rep_specialchars_output($str, 'html', $mode, $newlines);
403   }
404
405 /**
6d969b 406  * Quote a given string for javascript output.
T 407  * Shortcut function for rep_specialchars_output
408  * 
409  * @return string JS-quoted string
410  * @see rep_specialchars_output()
2bca6e 411  */
18e2a3 412 function JQ($str)
2bca6e 413   {
18e2a3 414   return rep_specialchars_output($str, 'js');
10a699 415   }
ea7c46 416
T 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  */
428 function 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     {
026d68 439     if (isset($_POST[$fname]))
ea7c46 440       $value = $_POST[$fname];
026d68 441     else if (isset($_GET[$fname]))
T 442       $value = $_GET[$fname];
ea7c46 443     else if (isset($_COOKIE[$fname]))
T 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
026d68 456   if (is_object($OUTPUT))
T 457     return rcube_charset_convert($value, $OUTPUT->get_charset(), $charset);
458   else
459     return $value;
ea7c46 460   }
T 461
d5342a 462 /**
T 463  * Remove all non-ascii and non-word chars
464  * except . and -
465  */
6d6e06 466 function asciiwords($str, $css_id = false)
d5342a 467 {
6d6e06 468   $allowed = 'a-z0-9\_\-' . (!$css_id ? '\.' : '');
T 469   return preg_replace("/[^$allowed]/i", '', $str);
d5342a 470 }
6d969b 471
e34ae1 472 /**
T 473  * Remove single and double quotes from given string
6d969b 474  *
T 475  * @param string Input value
476  * @return string Dequoted string
e34ae1 477  */
T 478 function strip_quotes($str)
479 {
480   return preg_replace('/[\'"]/', '', $str);
481 }
10a699 482
6d969b 483
3cf664 484 /**
T 485  * Remove new lines characters from given string
6d969b 486  *
T 487  * @param string Input value
488  * @return string Stripped string
3cf664 489  */
T 490 function strip_newlines($str)
491 {
492   return preg_replace('/[\r\n]/', '', $str);
f11541 493 }
4e17e6 494
T 495
6d969b 496 /**
T 497  * Create a HTML table based on the given data
498  *
499  * @param  array  Named table attributes
500  * @param  mixed  Table row data. Either a two-dimensional array or a valid SQL result set
501  * @param  array  List of cols to show
502  * @param  string Name of the identifier col
503  * @return string HTML table code
504  */
d1d2c4 505 function rcube_table_output($attrib, $table_data, $a_show_cols, $id_col)
4e17e6 506   {
83a763 507   global $RCMAIL;
4e17e6 508   
83a763 509   $table = new html_table(/*array('cols' => count($a_show_cols))*/);
4e17e6 510     
83a763 511   // add table header
4e17e6 512   foreach ($a_show_cols as $col)
83a763 513     $table->add_header($col, Q(rcube_label($col)));
4e17e6 514   
T 515   $c = 0;
d1d2c4 516   if (!is_array($table_data)) 
83a763 517   {
T 518     $db = $RCMAIL->get_dbh();
519     while ($table_data && ($sql_arr = $db->fetch_assoc($table_data)))
4e17e6 520     {
83a763 521       $zebra_class = $c % 2 ? 'even' : 'odd';
T 522       $table->add_row(array('id' => 'rcmrow' . $sql_arr[$id_col], 'class' => "contact $zebra_class"));
d1d2c4 523
S 524       // format each col
525       foreach ($a_show_cols as $col)
83a763 526         $table->add($col, Q($sql_arr[$col]));
T 527       
d1d2c4 528       $c++;
S 529     }
83a763 530   }
d1d2c4 531   else 
83a763 532   {
d1d2c4 533     foreach ($table_data as $row_data)
83a763 534     {
T 535       $zebra_class = $c % 2 ? 'even' : 'odd';
536       $table->add_row(array('id' => 'rcmrow' . $row_data[$id_col], 'class' => "contact $zebra_class"));
d1d2c4 537
S 538       // format each col
539       foreach ($a_show_cols as $col)
83a763 540         $table->add($col, Q($row_data[$col]));
T 541         
d1d2c4 542       $c++;
4e17e6 543     }
83a763 544   }
4e17e6 545
83a763 546   return $table->show($attrib);
4e17e6 547   }
T 548
549
a0109c 550 /**
S 551  * Create an edit field for inclusion on a form
552  * 
553  * @param string col field name
554  * @param string value field value
555  * @param array attrib HTML element attributes for field
556  * @param string type HTML element type (default 'text')
557  * @return string HTML field definition
558  */
4e17e6 559 function rcmail_get_edit_field($col, $value, $attrib, $type='text')
T 560   {
561   $fname = '_'.$col;
562   $attrib['name'] = $fname;
563   
564   if ($type=='checkbox')
565     {
566     $attrib['value'] = '1';
47124c 567     $input = new html_checkbox($attrib);
4e17e6 568     }
T 569   else if ($type=='textarea')
570     {
571     $attrib['cols'] = $attrib['size'];
47124c 572     $input = new html_textarea($attrib);
4e17e6 573     }
T 574   else
47124c 575     $input = new html_inputfield($attrib);
4e17e6 576
T 577   // use value from post
597170 578   if (!empty($_POST[$fname]))
c57996 579     $value = get_input_value($fname, RCUBE_INPUT_POST);
4e17e6 580
T 581   $out = $input->show($value);
582          
583   return $out;
f11541 584   }
T 585
586
6d969b 587 /**
97bd2c 588  * Replace all css definitions with #container [def]
a3e5b4 589  * and remove css-inlined scripting
97bd2c 590  *
T 591  * @param string CSS source code
592  * @param string Container ID to use as prefix
593  * @return string Modified CSS source
594  */
595 function rcmail_mod_css_styles($source, $container_id, $base_url = '')
596   {
597   $a_css_values = array();
598   $last_pos = 0;
a3e5b4 599   
T 600   // ignore the whole block if evil styles are detected
601   if (stristr($source, 'expression') || stristr($source, 'behavior'))
602     return '';
97bd2c 603
T 604   // cut out all contents between { and }
605   while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos)))
606   {
607     $key = sizeof($a_css_values);
608     $a_css_values[$key] = substr($source, $pos+1, $pos2-($pos+1));
609     $source = substr($source, 0, $pos+1) . "<<str_replacement[$key]>>" . substr($source, $pos2, strlen($source)-$pos2);
610     $last_pos = $pos+2;
611   }
612
a3e5b4 613   // remove html comments and add #container to each tag selector.
97bd2c 614   // also replace body definition because we also stripped off the <body> tag
T 615   $styles = preg_replace(
616     array(
617       '/(^\s*<!--)|(-->\s*$)/',
618       '/(^\s*|,\s*|\}\s*)([a-z0-9\._#][a-z0-9\.\-_]*)/im',
619       '/@import\s+(url\()?[\'"]?([^\)\'"]+)[\'"]?(\))?/ime',
620       '/<<str_replacement\[([0-9]+)\]>>/e',
621       "/$container_id\s+body/i"
622     ),
623     array(
624       '',
625       "\\1#$container_id \\2",
626       "sprintf(\"@import url('./bin/modcss.php?u=%s&c=%s')\", urlencode(make_absolute_url('\\2','$base_url')), urlencode($container_id))",
627       "\$a_css_values[\\1]",
628       "$container_id div.rcmBody"
629     ),
630     $source);
631
632   return $styles;
633   }
fba1f5 634
97bd2c 635
T 636 /**
6d969b 637  * Compose a valid attribute string for HTML tags
T 638  *
639  * @param array Named tag attributes
640  * @param array List of allowed attributes
641  * @return string HTML formatted attribute string
642  */
4e17e6 643 function create_attrib_string($attrib, $allowed_attribs=array('id', 'class', 'style'))
T 644   {
645   // allow the following attributes to be added to the <iframe> tag
646   $attrib_str = '';
647   foreach ($allowed_attribs as $a)
648     if (isset($attrib[$a]))
fe79b1 649       $attrib_str .= sprintf(' %s="%s"', $a, str_replace('"', '&quot;', $attrib[$a]));
4e17e6 650
T 651   return $attrib_str;
652   }
653
654
6d969b 655 /**
T 656  * Convert a HTML attribute string attributes to an associative array (name => value)
657  *
658  * @param string Input string
659  * @return array Key-value pairs of parsed attributes
660  */
fe79b1 661 function parse_attrib_string($str)
T 662   {
663   $attrib = array();
f02574 664   preg_match_all('/\s*([-_a-z]+)=(["\'])??(?(2)([^\2]+)\2|(\S+?))/Ui', stripslashes($str), $regs, PREG_SET_ORDER);
fe79b1 665
T 666   // convert attributes to an associative array (name => value)
667   if ($regs)
668     foreach ($regs as $attr)
653242 669       {
S 670       $attrib[strtolower($attr[1])] = $attr[3] . $attr[4];
671       }
fe79b1 672
T 673   return $attrib;
674   }
675
4e17e6 676
6d969b 677 /**
T 678  * Convert the given date to a human readable form
679  * This uses the date formatting properties from config
680  *
681  * @param mixed Date representation (string or timestamp)
682  * @param string Date format to use
683  * @return string Formatted date string
684  */
4e17e6 685 function format_date($date, $format=NULL)
T 686   {
197601 687   global $CONFIG;
4e17e6 688   
4647e1 689   $ts = NULL;
ea090c 690
4e17e6 691   if (is_numeric($date))
T 692     $ts = $date;
b076a4 693   else if (!empty($date))
ea090c 694     {
A 695     while (($ts = @strtotime($date))===false)
696       {
697         // if we have a date in non-rfc format
197601 698         // remove token from the end and try again
ea090c 699         $d = explode(' ', $date);
197601 700         array_pop($d);
T 701         if (!$d) break;
702         $date = implode(' ', $d);
ea090c 703       }
A 704     }
705
4647e1 706   if (empty($ts))
b076a4 707     return '';
4647e1 708    
T 709   // get user's timezone
710   $tz = $CONFIG['timezone'];
711   if ($CONFIG['dst_active'])
712     $tz++;
4e17e6 713
T 714   // convert time to user's timezone
4647e1 715   $timestamp = $ts - date('Z', $ts) + ($tz * 3600);
4e17e6 716   
T 717   // get current timestamp in user's timezone
718   $now = time();  // local time
719   $now -= (int)date('Z'); // make GMT time
4647e1 720   $now += ($tz * 3600); // user's time
c45eb5 721   $now_date = getdate($now);
4e17e6 722
749b07 723   $today_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday'], $now_date['year']);
T 724   $week_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday']-6, $now_date['year']);
4e17e6 725
30233b 726   // define date format depending on current time  
87b280 727   if ($CONFIG['prettydate'] && !$format && $timestamp > $today_limit && $timestamp < $now)
8c8b2a 728     return sprintf('%s %s', rcube_label('today'), date($CONFIG['date_today'] ? $CONFIG['date_today'] : 'H:i', $timestamp));
87b280 729   else if ($CONFIG['prettydate'] && !$format && $timestamp > $week_limit && $timestamp < $now)
4e17e6 730     $format = $CONFIG['date_short'] ? $CONFIG['date_short'] : 'D H:i';
T 731   else if (!$format)
732     $format = $CONFIG['date_long'] ? $CONFIG['date_long'] : 'd.m.Y H:i';
733
734
735   // parse format string manually in order to provide localized weekday and month names
736   // an alternative would be to convert the date() format string to fit with strftime()
737   $out = '';
738   for($i=0; $i<strlen($format); $i++)
739     {
740     if ($format{$i}=='\\')  // skip escape chars
741       continue;
742     
743     // write char "as-is"
744     if ($format{$i}==' ' || $format{$i-1}=='\\')
745       $out .= $format{$i};
746     // weekday (short)
747     else if ($format{$i}=='D')
748       $out .= rcube_label(strtolower(date('D', $timestamp)));
749     // weekday long
750     else if ($format{$i}=='l')
751       $out .= rcube_label(strtolower(date('l', $timestamp)));
752     // month name (short)
753     else if ($format{$i}=='M')
754       $out .= rcube_label(strtolower(date('M', $timestamp)));
755     // month name (long)
756     else if ($format{$i}=='F')
7479cc 757       $out .= rcube_label('long'.strtolower(date('M', $timestamp)));
5b1de5 758     else if ($format{$i}=='x')
A 759       $out .= strftime('%x %X', $timestamp);
4e17e6 760     else
T 761       $out .= date($format{$i}, $timestamp);
762     }
763   
764   return $out;
765   }
766
767
6d969b 768 /**
T 769  * Compose a valid representaion of name and e-mail address
770  *
771  * @param string E-mail address
772  * @param string Person name
773  * @return string Formatted string
774  */
f11541 775 function format_email_recipient($email, $name='')
T 776   {
777   if ($name && $name != $email)
0c6f4b 778     {
T 779     // Special chars as defined by RFC 822 need to in quoted string (or escaped).
780     return sprintf('%s <%s>', preg_match('/[\(\)\<\>\\\.\[\]@,;:"]/', $name) ? '"'.addcslashes($name, '"').'"' : $name, $email);
781     }
f11541 782   else
T 783     return $email;
784   }
785
786
787
c39957 788 /****** debugging functions ********/
T 789
790
791 /**
792  * Print or write debug messages
793  *
794  * @param mixed Debug message or data
795  */
796 function console($msg)
797   {
8d4bcd 798   if (!is_string($msg))
c39957 799     $msg = var_export($msg, true);
T 800
801   if (!($GLOBALS['CONFIG']['debug_level'] & 4))
802     write_log('console', $msg);
197601 803   else if ($GLOBALS['OUTPUT']->ajax_call)
c39957 804     print "/*\n $msg \n*/\n";
T 805   else
806     {
807     print '<div style="background:#eee; border:1px solid #ccc; margin-bottom:3px; padding:6px"><pre>';
808     print $msg;
809     print "</pre></div>\n";
810     }
811   }
812
813
814 /**
815  * Append a line to a logfile in the logs directory.
816  * Date will be added automatically to the line.
817  *
653242 818  * @param $name name of log file
S 819  * @param line Line to append
c39957 820  */
T 821 function write_log($name, $line)
822   {
47124c 823   global $CONFIG;
e170b4 824
T 825   if (!is_string($line))
826     $line = var_export($line, true);
c39957 827   
T 828   $log_entry = sprintf("[%s]: %s\n",
829                  date("d-M-Y H:i:s O", mktime()),
830                  $line);
831                  
832   if (empty($CONFIG['log_dir']))
47124c 833     $CONFIG['log_dir'] = INSTALL_PATH.'logs';
c39957 834       
T 835   // try to open specific log file for writing
836   if ($fp = @fopen($CONFIG['log_dir'].'/'.$name, 'a'))    
837     {
838     fwrite($fp, $log_entry);
839     fclose($fp);
840     }
841   }
842
cc9570 843
6d969b 844 /**
T 845  * @access private
846  */
15a9d1 847 function rcube_timer()
T 848   {
849   list($usec, $sec) = explode(" ", microtime());
850   return ((float)$usec + (float)$sec);
851   }
852   
853
6d969b 854 /**
T 855  * @access private
856  */
15a9d1 857 function rcube_print_time($timer, $label='Timer')
T 858   {
859   static $print_count = 0;
860   
861   $print_count++;
862   $now = rcube_timer();
863   $diff = $now-$timer;
864   
865   if (empty($label))
866     $label = 'Timer '.$print_count;
867   
868   console(sprintf("%s: %0.4f sec", $label, $diff));
869   }
870
93be5b 871
6d969b 872 /**
T 873  * Return the mailboxlist in HTML
874  *
875  * @param array Named parameters
876  * @return string HTML code for the gui object
877  */
93be5b 878 function rcmail_mailbox_list($attrib)
62e542 879 {
T 880   global $IMAP, $OUTPUT;
93be5b 881   static $a_mailboxes;
S 882
883   // add some labels to client
884   rcube_add_label('purgefolderconfirm');
885   rcube_add_label('deletemessagesconfirm');
886   
887   $type = $attrib['type'] ? $attrib['type'] : 'ul';
6d6e06 888   unset($attrib['type']);
T 889
93be5b 890   if ($type=='ul' && !$attrib['id'])
S 891     $attrib['id'] = 'rcmboxlist';
892
893   // get mailbox list
894   $mbox_name = $IMAP->get_mailbox_name();
895   
896   // build the folders tree
62e542 897   if (empty($a_mailboxes)) {
93be5b 898     // get mailbox list
S 899     $a_folders = $IMAP->list_mailboxes();
900     $delimiter = $IMAP->get_hierarchy_delimiter();
901     $a_mailboxes = array();
902
903     foreach ($a_folders as $folder)
904       rcmail_build_folder_tree($a_mailboxes, $folder, $delimiter);
62e542 905   }
93be5b 906
6d6e06 907   if ($type=='select') {
T 908     $select = new html_select($attrib);
909     
910     // add no-selection option
911     if ($attrib['noselection'])
912       $select->add(rcube_label($attrib['noselection']), '0');
913     
914     rcmail_render_folder_tree_select($a_mailboxes, $mbox_name, $attrib['maxlength'], $select);
62e542 915     $out = $select->show();
6d6e06 916   }
T 917   else {
918     $out = html::tag('ul', $attrib, rcmail_render_folder_tree_html($a_mailboxes, $mbox_name, $attrib['maxlength']), html::$common_attrib);
919   }
93be5b 920
S 921   if ($type=='ul')
922     $OUTPUT->add_gui_object('mailboxlist', $attrib['id']);
923
6d6e06 924   return $out;
62e542 925 }
93be5b 926
S 927
cb3538 928 /**
T 929  * Return the mailboxlist as html_select object
930  *
931  * @param array Named parameters
932  * @return object html_select HTML drop-down object
933  */
934 function rcmail_mailbox_select($p = array())
935 {
936   global $RCMAIL;
937   
938   $p += array('maxlength' => 100);
939   $a_mailboxes = array();
940   
941   foreach ($RCMAIL->imap->list_mailboxes() as $folder)
942     rcmail_build_folder_tree($a_mailboxes, $folder, $RCMAIL->imap->get_hierarchy_delimiter());
943
944   $select = new html_select($p);
945   
946   if ($p['noselection'])
947     $select->add($p['noselection'], '');
948     
949   rcmail_render_folder_tree_select($a_mailboxes, $mbox, $p['maxlength'], $select);
950   
951   return $select;
952 }
93be5b 953
S 954
6d969b 955 /**
T 956  * Create a hierarchical array of the mailbox list
957  * @access private
958  */
93be5b 959 function rcmail_build_folder_tree(&$arrFolders, $folder, $delm='/', $path='')
S 960   {
961   $pos = strpos($folder, $delm);
962   if ($pos !== false)
963     {
964     $subFolders = substr($folder, $pos+1);
965     $currentFolder = substr($folder, 0, $pos);
966     }
967   else
968     {
969     $subFolders = false;
970     $currentFolder = $folder;
971     }
972
973   $path .= $currentFolder;
974
975   if (!isset($arrFolders[$currentFolder]))
976     {
6d6e06 977     $arrFolders[$currentFolder] = array(
T 978       'id' => $path,
979       'name' => rcube_charset_convert($currentFolder, 'UTF-7'),
980       'folders' => array());
93be5b 981     }
S 982
983   if (!empty($subFolders))
984     rcmail_build_folder_tree($arrFolders[$currentFolder]['folders'], $subFolders, $delm, $path.$delm);
985   }
986   
987
6d969b 988 /**
T 989  * Return html for a structured list &lt;ul&gt; for the mailbox tree
990  * @access private
991  */
cb3bad 992 function rcmail_render_folder_tree_html(&$arrFolders, &$mbox_name, $maxlength, $nestLevel=0)
93be5b 993   {
S 994   global $COMM_PATH, $IMAP, $CONFIG, $OUTPUT;
995
996   $idx = 0;
997   $out = '';
998   foreach ($arrFolders as $key => $folder)
999     {
cb3538 1000     $zebra_class = (($nestLevel+1)*$idx) % 2 == 0 ? 'even' : 'odd';
6d6e06 1001     $title = null;
93be5b 1002
cb3bad 1003     if ($folder_class = rcmail_folder_classname($folder['id']))
T 1004       $foldername = rcube_label($folder_class);
93be5b 1005     else
S 1006       {
1007       $foldername = $folder['name'];
1008
1009       // shorten the folder name to a given length
1010       if ($maxlength && $maxlength>1)
1011         {
6f2f2d 1012         $fname = abbreviate_string($foldername, $maxlength);
93be5b 1013         if ($fname != $foldername)
6d6e06 1014           $title = $foldername;
93be5b 1015         $foldername = $fname;
S 1016         }
1017       }
1018
1019     // make folder name safe for ids and class names
6d6e06 1020     $folder_id = asciiwords($folder['id'], true);
T 1021     $classes = array('mailbox');
93be5b 1022
S 1023     // set special class for Sent, Drafts, Trash and Junk
1024     if ($folder['id']==$CONFIG['sent_mbox'])
6d6e06 1025       $classes[] = 'sent';
93be5b 1026     else if ($folder['id']==$CONFIG['drafts_mbox'])
6d6e06 1027       $classes[] = 'drafts';
93be5b 1028     else if ($folder['id']==$CONFIG['trash_mbox'])
6d6e06 1029       $classes[] = 'trash';
93be5b 1030     else if ($folder['id']==$CONFIG['junk_mbox'])
6d6e06 1031       $classes[] = 'junk';
T 1032     else
1033       $classes[] = asciiwords($folder_class ? $folder_class : strtolower($folder['id']), true);
1034       
1035     $classes[] = $zebra_class;
1036     
1037     if ($folder['id'] == $mbox_name)
1038       $classes[] = 'selected';
93be5b 1039
6d6e06 1040     $js_name = JQ($folder['id']);
T 1041     $out .= html::tag('li', array(
1042         'id' => "rcmli".$folder_id,
1043         'class' => join(' ', $classes),
1044         'noclose' => true),
1045       html::a(array(
1046         'href' => rcmail_url('', array('_mbox' => $folder['id'])),
1047         'onclick' => sprintf("return %s.command('list','%s',this)", JS_OBJECT_NAME, $js_name),
1048         'onmouseover' => sprintf("return %s.focus_folder('%s')", JS_OBJECT_NAME, $js_name),
1049         'onmouseout' => sprintf("return %s.unfocus_folder('%s')", JS_OBJECT_NAME, $js_name),
1050         'onmouseup' => sprintf("return %s.folder_mouse_up('%s')", JS_OBJECT_NAME, $js_name),
1051         'title' => $title,
1052       ), Q($foldername)));
1053     
93be5b 1054     if (!empty($folder['folders']))
cb3bad 1055       $out .= "\n<ul>\n" . rcmail_render_folder_tree_html($folder['folders'], $mbox_name, $maxlength, $nestLevel+1) . "</ul>\n";
93be5b 1056
S 1057     $out .= "</li>\n";
1058     $idx++;
1059     }
1060
1061   return $out;
1062   }
1063
1064
6d969b 1065 /**
T 1066  * Return html for a flat list <select> for the mailbox tree
1067  * @access private
1068  */
6d6e06 1069 function rcmail_render_folder_tree_select(&$arrFolders, &$mbox_name, $maxlength, &$select, $nestLevel=0)
93be5b 1070   {
S 1071   global $IMAP, $OUTPUT;
1072
1073   $idx = 0;
1074   $out = '';
1075   foreach ($arrFolders as $key=>$folder)
1076     {
cb3bad 1077     if ($folder_class = rcmail_folder_classname($folder['id']))
T 1078       $foldername = rcube_label($folder_class);
93be5b 1079     else
S 1080       {
1081       $foldername = $folder['name'];
1082       
1083       // shorten the folder name to a given length
1084       if ($maxlength && $maxlength>1)
6f2f2d 1085         $foldername = abbreviate_string($foldername, $maxlength);
93be5b 1086       }
S 1087
6d6e06 1088     $select->add(str_repeat('&nbsp;', $nestLevel*4) . $foldername, $folder['id']);
93be5b 1089
S 1090     if (!empty($folder['folders']))
6d6e06 1091       $out .= rcmail_render_folder_tree_select($folder['folders'], $mbox_name, $maxlength, $select, $nestLevel+1);
93be5b 1092
S 1093     $idx++;
1094     }
1095
1096   return $out;
1097   }
1098
cb3bad 1099
T 1100 /**
1101  * Return internal name for the given folder if it matches the configured special folders
1102  * @access private
1103  */
1104 function rcmail_folder_classname($folder_id)
1105 {
1106   global $CONFIG;
1107
1108   $cname = null;
1109   $folder_lc = strtolower($folder_id);
1110   
1111   // for these mailboxes we have localized labels and css classes
1112   foreach (array('inbox', 'sent', 'drafts', 'trash', 'junk') as $smbx)
1113   {
1114     if ($folder_lc == $smbx || $folder_id == $CONFIG[$smbx.'_mbox'])
1115       $cname = $smbx;
1116   }
1117   
1118   return $cname;
1119 }
1120
1121
fed22f 1122 /**
T 1123  * Try to localize the given IMAP folder name.
1124  * UTF-7 decode it in case no localized text was found
1125  *
1126  * @param string Folder name
1127  * @return string Localized folder name in UTF-8 encoding
1128  */
1129 function rcmail_localize_foldername($name)
1130 {
1131   if ($folder_class = rcmail_folder_classname($name))
1132     return rcube_label($folder_class);
1133   else
1134     return rcube_charset_convert($name, 'UTF-7');
1135 }
1136
1137
d1d2c4 1138 ?>