alecpl
2008-07-01 e6e5c60aae745a580a2d7fca1e2b7104c3907352
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  */
466 function asciiwords($str)
467 {
6ea6c9 468   return preg_replace('/[^a-z0-9._-]/i', '', $str);
d5342a 469 }
6d969b 470
e34ae1 471 /**
T 472  * Remove single and double quotes from given string
6d969b 473  *
T 474  * @param string Input value
475  * @return string Dequoted string
e34ae1 476  */
T 477 function strip_quotes($str)
478 {
479   return preg_replace('/[\'"]/', '', $str);
480 }
10a699 481
6d969b 482
3cf664 483 /**
T 484  * Remove new lines characters from given string
6d969b 485  *
T 486  * @param string Input value
487  * @return string Stripped string
3cf664 488  */
T 489 function strip_newlines($str)
490 {
491   return preg_replace('/[\r\n]/', '', $str);
f11541 492 }
4e17e6 493
T 494
6d969b 495 /**
T 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  */
d1d2c4 504 function rcube_table_output($attrib, $table_data, $a_show_cols, $id_col)
4e17e6 505   {
83a763 506   global $RCMAIL;
4e17e6 507   
83a763 508   $table = new html_table(/*array('cols' => count($a_show_cols))*/);
4e17e6 509     
83a763 510   // add table header
4e17e6 511   foreach ($a_show_cols as $col)
83a763 512     $table->add_header($col, Q(rcube_label($col)));
4e17e6 513   
T 514   $c = 0;
d1d2c4 515   if (!is_array($table_data)) 
83a763 516   {
T 517     $db = $RCMAIL->get_dbh();
518     while ($table_data && ($sql_arr = $db->fetch_assoc($table_data)))
4e17e6 519     {
83a763 520       $zebra_class = $c % 2 ? 'even' : 'odd';
T 521       $table->add_row(array('id' => 'rcmrow' . $sql_arr[$id_col], 'class' => "contact $zebra_class"));
d1d2c4 522
S 523       // format each col
524       foreach ($a_show_cols as $col)
83a763 525         $table->add($col, Q($sql_arr[$col]));
T 526       
d1d2c4 527       $c++;
S 528     }
83a763 529   }
d1d2c4 530   else 
83a763 531   {
d1d2c4 532     foreach ($table_data as $row_data)
83a763 533     {
T 534       $zebra_class = $c % 2 ? 'even' : 'odd';
535       $table->add_row(array('id' => 'rcmrow' . $row_data[$id_col], 'class' => "contact $zebra_class"));
d1d2c4 536
S 537       // format each col
538       foreach ($a_show_cols as $col)
83a763 539         $table->add($col, Q($row_data[$col]));
T 540         
d1d2c4 541       $c++;
4e17e6 542     }
83a763 543   }
4e17e6 544
83a763 545   return $table->show($attrib);
4e17e6 546   }
T 547
548
a0109c 549 /**
S 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  */
4e17e6 558 function rcmail_get_edit_field($col, $value, $attrib, $type='text')
T 559   {
560   $fname = '_'.$col;
561   $attrib['name'] = $fname;
562   
563   if ($type=='checkbox')
564     {
565     $attrib['value'] = '1';
47124c 566     $input = new html_checkbox($attrib);
4e17e6 567     }
T 568   else if ($type=='textarea')
569     {
570     $attrib['cols'] = $attrib['size'];
47124c 571     $input = new html_textarea($attrib);
4e17e6 572     }
T 573   else
47124c 574     $input = new html_inputfield($attrib);
4e17e6 575
T 576   // use value from post
597170 577   if (!empty($_POST[$fname]))
c57996 578     $value = get_input_value($fname, RCUBE_INPUT_POST);
4e17e6 579
T 580   $out = $input->show($value);
581          
582   return $out;
f11541 583   }
T 584
585
6d969b 586 /**
97bd2c 587  * Replace all css definitions with #container [def]
a3e5b4 588  * and remove css-inlined scripting
97bd2c 589  *
T 590  * @param string CSS source code
591  * @param string Container ID to use as prefix
592  * @return string Modified CSS source
593  */
594 function rcmail_mod_css_styles($source, $container_id, $base_url = '')
595   {
596   $a_css_values = array();
597   $last_pos = 0;
a3e5b4 598   
T 599   // ignore the whole block if evil styles are detected
600   if (stristr($source, 'expression') || stristr($source, 'behavior'))
601     return '';
97bd2c 602
T 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
a3e5b4 612   // remove html comments and add #container to each tag selector.
97bd2c 613   // also replace body definition because we also stripped off the <body> tag
T 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   }
fba1f5 633
97bd2c 634
T 635 /**
6d969b 636  * Compose a valid attribute string for HTML tags
T 637  *
638  * @param array Named tag attributes
639  * @param array List of allowed attributes
640  * @return string HTML formatted attribute string
641  */
4e17e6 642 function create_attrib_string($attrib, $allowed_attribs=array('id', 'class', 'style'))
T 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]))
fe79b1 648       $attrib_str .= sprintf(' %s="%s"', $a, str_replace('"', '&quot;', $attrib[$a]));
4e17e6 649
T 650   return $attrib_str;
651   }
652
653
6d969b 654 /**
T 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  */
fe79b1 660 function parse_attrib_string($str)
T 661   {
662   $attrib = array();
f02574 663   preg_match_all('/\s*([-_a-z]+)=(["\'])??(?(2)([^\2]+)\2|(\S+?))/Ui', stripslashes($str), $regs, PREG_SET_ORDER);
fe79b1 664
T 665   // convert attributes to an associative array (name => value)
666   if ($regs)
667     foreach ($regs as $attr)
653242 668       {
S 669       $attrib[strtolower($attr[1])] = $attr[3] . $attr[4];
670       }
fe79b1 671
T 672   return $attrib;
673   }
674
4e17e6 675
6d969b 676 /**
T 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  */
4e17e6 684 function format_date($date, $format=NULL)
T 685   {
197601 686   global $CONFIG;
4e17e6 687   
4647e1 688   $ts = NULL;
ea090c 689
4e17e6 690   if (is_numeric($date))
T 691     $ts = $date;
b076a4 692   else if (!empty($date))
ea090c 693     {
A 694     while (($ts = @strtotime($date))===false)
695       {
696         // if we have a date in non-rfc format
197601 697         // remove token from the end and try again
ea090c 698         $d = explode(' ', $date);
197601 699         array_pop($d);
T 700         if (!$d) break;
701         $date = implode(' ', $d);
ea090c 702       }
A 703     }
704
4647e1 705   if (empty($ts))
b076a4 706     return '';
4647e1 707    
T 708   // get user's timezone
709   $tz = $CONFIG['timezone'];
710   if ($CONFIG['dst_active'])
711     $tz++;
4e17e6 712
T 713   // convert time to user's timezone
4647e1 714   $timestamp = $ts - date('Z', $ts) + ($tz * 3600);
4e17e6 715   
T 716   // get current timestamp in user's timezone
717   $now = time();  // local time
718   $now -= (int)date('Z'); // make GMT time
4647e1 719   $now += ($tz * 3600); // user's time
c45eb5 720   $now_date = getdate($now);
4e17e6 721
749b07 722   $today_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday'], $now_date['year']);
T 723   $week_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday']-6, $now_date['year']);
4e17e6 724
30233b 725   // define date format depending on current time  
87b280 726   if ($CONFIG['prettydate'] && !$format && $timestamp > $today_limit && $timestamp < $now)
8c8b2a 727     return sprintf('%s %s', rcube_label('today'), date($CONFIG['date_today'] ? $CONFIG['date_today'] : 'H:i', $timestamp));
87b280 728   else if ($CONFIG['prettydate'] && !$format && $timestamp > $week_limit && $timestamp < $now)
4e17e6 729     $format = $CONFIG['date_short'] ? $CONFIG['date_short'] : 'D H:i';
T 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')
7479cc 756       $out .= rcube_label('long'.strtolower(date('M', $timestamp)));
4e17e6 757     else
T 758       $out .= date($format{$i}, $timestamp);
759     }
760   
761   return $out;
762   }
763
764
6d969b 765 /**
T 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  */
f11541 772 function format_email_recipient($email, $name='')
T 773   {
774   if ($name && $name != $email)
0c6f4b 775     {
T 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     }
f11541 779   else
T 780     return $email;
781   }
782
783
784
c39957 785 /****** debugging functions ********/
T 786
787
788 /**
789  * Print or write debug messages
790  *
791  * @param mixed Debug message or data
792  */
793 function console($msg)
794   {
8d4bcd 795   if (!is_string($msg))
c39957 796     $msg = var_export($msg, true);
T 797
798   if (!($GLOBALS['CONFIG']['debug_level'] & 4))
799     write_log('console', $msg);
197601 800   else if ($GLOBALS['OUTPUT']->ajax_call)
c39957 801     print "/*\n $msg \n*/\n";
T 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  *
653242 815  * @param $name name of log file
S 816  * @param line Line to append
c39957 817  */
T 818 function write_log($name, $line)
819   {
47124c 820   global $CONFIG;
e170b4 821
T 822   if (!is_string($line))
823     $line = var_export($line, true);
c39957 824   
T 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']))
47124c 830     $CONFIG['log_dir'] = INSTALL_PATH.'logs';
c39957 831       
T 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
cc9570 840
6d969b 841 /**
T 842  * @access private
843  */
15a9d1 844 function rcube_timer()
T 845   {
846   list($usec, $sec) = explode(" ", microtime());
847   return ((float)$usec + (float)$sec);
848   }
849   
850
6d969b 851 /**
T 852  * @access private
853  */
15a9d1 854 function rcube_print_time($timer, $label='Timer')
T 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
93be5b 868
6d969b 869 /**
T 870  * Return the mailboxlist in HTML
871  *
872  * @param array Named parameters
873  * @return string HTML code for the gui object
874  */
93be5b 875 function rcmail_mailbox_list($attrib)
S 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')
cb3bad 924     $out .= rcmail_render_folder_tree_select($a_mailboxes, $mbox_name, $attrib['maxlength']);
93be5b 925    else
cb3bad 926     $out .= rcmail_render_folder_tree_html($a_mailboxes, $mbox_name, $attrib['maxlength']);
93be5b 927
S 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
6d969b 940 /**
T 941  * Create a hierarchical array of the mailbox list
942  * @access private
943  */
93be5b 944 function rcmail_build_folder_tree(&$arrFolders, $folder, $delm='/', $path='')
S 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
6d969b 972 /**
T 973  * Return html for a structured list &lt;ul&gt; for the mailbox tree
974  * @access private
975  */
cb3bad 976 function rcmail_render_folder_tree_html(&$arrFolders, &$mbox_name, $maxlength, $nestLevel=0)
93be5b 977   {
S 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
cb3bad 987     if ($folder_class = rcmail_folder_classname($folder['id']))
T 988       $foldername = rcube_label($folder_class);
93be5b 989     else
S 990       {
991       $foldername = $folder['name'];
992
993       // shorten the folder name to a given length
994       if ($maxlength && $maxlength>1)
995         {
6f2f2d 996         $fname = abbreviate_string($foldername, $maxlength);
93be5b 997         if ($fname != $foldername)
S 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']);
cb3bad 1005     $class_name = preg_replace('/[^a-z0-9\-_]/', '', $folder_class ? $folder_class : strtolower($folder['id']));
93be5b 1006
S 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']));
0be1bc 1018     $out .= sprintf('<li id="rcmli%s" class="mailbox %s %s%s"><a href="%s"'.
93be5b 1019                     ' onclick="return %s.command(\'list\',\'%s\',this)"'.
S 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']))
cb3bad 1040       $out .= "\n<ul>\n" . rcmail_render_folder_tree_html($folder['folders'], $mbox_name, $maxlength, $nestLevel+1) . "</ul>\n";
93be5b 1041
S 1042     $out .= "</li>\n";
1043     $idx++;
1044     }
1045
1046   return $out;
1047   }
1048
1049
6d969b 1050 /**
T 1051  * Return html for a flat list <select> for the mailbox tree
1052  * @access private
1053  */
3c3032 1054 function rcmail_render_folder_tree_select(&$arrFolders, &$mbox_name, $maxlength, $nestLevel=0, $selected='')
93be5b 1055   {
S 1056   global $IMAP, $OUTPUT;
1057
1058   $idx = 0;
1059   $out = '';
1060   foreach ($arrFolders as $key=>$folder)
1061     {
cb3bad 1062     if ($folder_class = rcmail_folder_classname($folder['id']))
T 1063       $foldername = rcube_label($folder_class);
93be5b 1064     else
S 1065       {
1066       $foldername = $folder['name'];
1067       
1068       // shorten the folder name to a given length
1069       if ($maxlength && $maxlength>1)
6f2f2d 1070         $foldername = abbreviate_string($foldername, $maxlength);
93be5b 1071       }
S 1072
3c3032 1073     $out .= sprintf('<option value="%s"%s>%s%s</option>'."\n",
93be5b 1074                     htmlspecialchars($folder['id']),
3c3032 1075             ($selected == $foldername ? ' selected="selected"' : ''),
93be5b 1076                     str_repeat('&nbsp;', $nestLevel*4),
S 1077                     Q($foldername));
1078
1079     if (!empty($folder['folders']))
3c3032 1080       $out .= rcmail_render_folder_tree_select($folder['folders'], $mbox_name, $maxlength, $nestLevel+1, $selected);
93be5b 1081
S 1082     $idx++;
1083     }
1084
1085   return $out;
1086   }
1087
cb3bad 1088
T 1089 /**
1090  * Return internal name for the given folder if it matches the configured special folders
1091  * @access private
1092  */
1093 function 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
fed22f 1111 /**
T 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  */
1118 function 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
d1d2c4 1127 ?>