alecpl
2009-04-23 0ad27c384033977c86427011785d0182af91df4a
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                     |
cbbef3 8  | Copyright (C) 2005-2009, 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))
3e8483 77     return $opt;
54dd42 78     
ae8f19 79   return $sequence;
1cded8 80   }
0af7e8 81
T 82
6d969b 83 /**
1854c4 84  * Get localized text in the desired language
T 85  * It's a global wrapper for rcmail::gettext()
6d969b 86  *
1854c4 87  * @param mixed Named parameters array or label name
T 88  * @return string Localized text
89  * @see rcmail::gettext()
6d969b 90  */
cc97ea 91 function rcube_label($p, $domain=null)
1854c4 92 {
cc97ea 93   return rcmail::get_instance()->gettext($p, $domain);
1854c4 94 }
4e17e6 95
T 96
6d969b 97 /**
T 98  * Overwrite action variable
99  *
100  * @param string New action value
101  */
10a699 102 function rcmail_overwrite_action($action)
T 103   {
197601 104   $app = rcmail::get_instance();
T 105   $app->action = $action;
106   $app->output->set_env('action', $action);
10a699 107   }
T 108
109
41bece 110 /**
T 111  * Compose an URL for a specific action
112  *
113  * @param string  Request action
114  * @param array   More URL parameters
115  * @param string  Request task (omit if the same)
116  * @return The application URL
117  */
118 function rcmail_url($action, $p=array(), $task=null)
f11541 119 {
197601 120   $app = rcmail::get_instance();
fde466 121   return $app->url((array)$p + array('_action' => $action, 'task' => $task));
f11541 122 }
9fee0e 123
4e17e6 124
6d969b 125 /**
T 126  * Garbage collector function for temp files.
127  * Remove temp files older than two days
128  */
70d4b9 129 function rcmail_temp_gc()
1cded8 130   {
70d4b9 131   $tmp = unslashify($CONFIG['temp_dir']);
T 132   $expire = mktime() - 172800;  // expire in 48 hours
1cded8 133
70d4b9 134   if ($dir = opendir($tmp))
1cded8 135     {
70d4b9 136     while (($fname = readdir($dir)) !== false)
T 137       {
138       if ($fname{0} == '.')
139         continue;
140
141       if (filemtime($tmp.'/'.$fname) < $expire)
142         @unlink($tmp.'/'.$fname);
143       }
144
145     closedir($dir);
146     }
1cded8 147   }
T 148
149
6d969b 150 /**
T 151  * Garbage collector for cache entries.
152  * Remove all expired message cache records
153  */
29c64b 154 function rcmail_cache_gc()
cc9570 155   {
29c64b 156   $rcmail = rcmail::get_instance();
T 157   $db = $rcmail->get_dbh();
cc9570 158   
T 159   // get target timestamp
29c64b 160   $ts = get_offset_time($rcmail->config->get('message_cache_lifetime', '30d'), -1);
cc9570 161   
29c64b 162   $db->query("DELETE FROM ".get_table_name('messages')."
T 163              WHERE  created < " . $db->fromunixtime($ts));
164
165   $db->query("DELETE FROM ".get_table_name('cache')."
166               WHERE  created < " . $db->fromunixtime($ts));
cc9570 167   }
T 168
1cded8 169
2bca6e 170 /**
T 171  * Convert a string from one charset to another.
172  * Uses mbstring and iconv functions if possible
173  *
174  * @param  string Input string
175  * @param  string Suspected charset of the input string
f11541 176  * @param  string Target charset to convert to; defaults to RCMAIL_CHARSET
2bca6e 177  * @return Converted string
T 178  */
3f9edb 179 function rcube_charset_convert($str, $from, $to=NULL)
0af7e8 180   {
77e232 181   static $mbstring_loaded = null;
A 182   static $mbstring_list = null;
183   static $convert_warning = false;
f88d41 184
83dbb7 185   $from = strtoupper($from);
f11541 186   $to = $to==NULL ? strtoupper(RCMAIL_CHARSET) : strtoupper($to);
1a7f99 187   $error = false; $conv = null;
f88d41 188
65d710 189   # RFC1642
A 190   if ($from == 'UNICODE-1-1-UTF-7')
191     $from = 'UTF-7';
192   if ($to == 'UNICODE-1-1-UTF-7')
193     $to = 'UTF-7';
194
c9a2fa 195   if ($from == $to || empty($str) || empty($from))
3f9edb 196     return $str;
38b012 197     
T 198   $aliases = array(
c9ca6a 199     'US-ASCII'         => 'ISO-8859-1',
S 200     'ANSI_X3.110-1983' => 'ISO-8859-1',
201     'ANSI_X3.4-1968'   => 'ISO-8859-1',
202     'UNKNOWN-8BIT'     => 'ISO-8859-15',
203     'X-UNKNOWN'        => 'ISO-8859-15',
204     'X-USER-DEFINED'   => 'ISO-8859-15',
205     'ISO-8859-8-I'     => 'ISO-8859-8',
206     'KS_C_5601-1987'   => 'EUC-KR',
38b012 207   );
5f56a5 208
b8e65c 209   // convert charset using iconv module  
ae8a60 210   if (function_exists('iconv') && $from != 'UTF-7' && $to != 'UTF-7') {
7250d6 211     $aliases['GB2312'] = 'GB18030';
3bfab3 212     $_iconv = iconv(($aliases[$from] ? $aliases[$from] : $from), ($aliases[$to] ? $aliases[$to] : $to) . "//IGNORE", $str);
ae8a60 213     if ($_iconv !== false) {
3bfab3 214         return $_iconv;
0393da 215     }
ae8a60 216   }
5f56a5 217
d99b93 218   if (is_null($mbstring_loaded))
A 219     $mbstring_loaded = extension_loaded('mbstring');
220     
197601 221   // convert charset using mbstring module
ae8a60 222   if ($mbstring_loaded) {
b19536 223     $aliases['UTF-7'] = 'UTF7-IMAP';
T 224     $aliases['WINDOWS-1257'] = 'ISO-8859-13';
88f66e 225     
77e232 226     if (is_null($mbstring_list)) {
A 227       $mbstring_list = mb_list_encodings();
228       $mbstring_list = array_map('strtoupper', $mbstring_list);
229     }
230     
231     $mb_from = $aliases[$from] ? $aliases[$from] : $from;
232     $mb_to = $aliases[$to] ? $aliases[$to] : $to;
233     
234     // return if encoding found, string matches encoding and convert succeeded
ae8a60 235     if (in_array($mb_from, $mbstring_list) && in_array($mb_to, $mbstring_list)) {
T 236       if (mb_check_encoding($str, $mb_from) && ($out = mb_convert_encoding($str, $mb_to, $mb_from)))
237         return $out;
83dbb7 238     }
ae8a60 239   }
65d710 240
A 241   # try to convert with custom classes
1a7f99 242   if (class_exists('utf8'))
T 243     $conv = new utf8();
58e360 244
83dbb7 245   // convert string to UTF-8
ae8a60 246   if ($from == 'UTF-7') {
T 247     if ($_str = utf7_to_utf8($str))
248       $str = $_str;
c9a2fa 249     else
T 250       $error = true;
ae8a60 251   }
T 252   else if (($from == 'ISO-8859-1') && function_exists('utf8_encode')) {
83dbb7 253     $str = utf8_encode($str);
ae8a60 254   }
T 255   else if ($from != 'UTF-8' && $conv) {
58e360 256     $conv->loadCharset($from);
83dbb7 257     $str = $conv->strToUtf8($str);
ae8a60 258   }
c9a2fa 259   else if ($from != 'UTF-8')
1a7f99 260     $error = true;
0af7e8 261
3f9edb 262   // encode string for output
ae8a60 263   if ($to == 'UTF-7') {
c8c1a3 264     return utf8_to_utf7($str);
ae8a60 265   }
T 266   else if ($to == 'ISO-8859-1' && function_exists('utf8_decode')) {
83dbb7 267     return utf8_decode($str);
ae8a60 268   }
T 269   else if ($to != 'UTF-8' && $conv) {
58e360 270     $conv->loadCharset($to);
83dbb7 271     return $conv->utf8ToStr($str);
ae8a60 272   }
T 273   else if ($to != 'UTF-8') {
1a7f99 274     $error = true;
ae8a60 275   }
T 276   
1a7f99 277   // report error
ae8a60 278   if ($error && !$convert_warning){
1a7f99 279     raise_error(array(
T 280       'code' => 500,
281       'type' => 'php',
282       'file' => __FILE__,
c9a2fa 283       'message' => "Could not convert string from $from to $to. Make sure iconv is installed or lib/utf8.class is available"
1a7f99 284       ), true, false);
T 285     
286     $convert_warning = true;
ae8a60 287   }
1a7f99 288   
83dbb7 289   // return UTF-8 string
3f9edb 290   return $str;
0af7e8 291   }
3f9edb 292
0af7e8 293
2bca6e 294 /**
T 295  * Replacing specials characters to a specific encoding type
296  *
297  * @param  string  Input string
298  * @param  string  Encoding type: text|html|xml|js|url
299  * @param  string  Replace mode for tags: show|replace|remove
300  * @param  boolean Convert newlines
301  * @return The quoted string
302  */
1cded8 303 function rep_specialchars_output($str, $enctype='', $mode='', $newlines=TRUE)
T 304   {
257782 305   static $html_encode_arr = false;
A 306   static $js_rep_table = false;
307   static $xml_rep_table = false;
1cded8 308
cc97ea 309   $charset = rcmail::get_instance()->config->get('charset', RCMAIL_CHARSET);
257782 310   $is_iso_8859_1 = false;
A 311   if ($charset == 'ISO-8859-1') {
312     $is_iso_8859_1 = true;
313   }
1cded8 314   if (!$enctype)
c8a21d 315     $enctype = $OUTPUT->type;
1cded8 316
T 317   // encode for plaintext
318   if ($enctype=='text')
319     return str_replace("\r\n", "\n", $mode=='remove' ? strip_tags($str) : $str);
320
321   // encode for HTML output
322   if ($enctype=='html')
323     {
324     if (!$html_encode_arr)
325       {
0af7e8 326       $html_encode_arr = get_html_translation_table(HTML_SPECIALCHARS);        
1cded8 327       unset($html_encode_arr['?']);
T 328       }
329
330     $ltpos = strpos($str, '<');
331     $encode_arr = $html_encode_arr;
332
333     // don't replace quotes and html tags
334     if (($mode=='show' || $mode=='') && $ltpos!==false && strpos($str, '>', $ltpos)!==false)
335       {
336       unset($encode_arr['"']);
337       unset($encode_arr['<']);
338       unset($encode_arr['>']);
10c92b 339       unset($encode_arr['&']);
1cded8 340       }
T 341     else if ($mode=='remove')
342       $str = strip_tags($str);
674a0f 343     
T 344     // avoid douple quotation of &
fdebae 345     $out = preg_replace('/&amp;([A-Za-z]{2,6}|#[0-9]{2,4});/', '&\\1;', strtr($str, $encode_arr));
0af7e8 346       
1cded8 347     return $newlines ? nl2br($out) : $out;
T 348     }
349
350   if ($enctype=='url')
351     return rawurlencode($str);
352
2bca6e 353   // if the replace tables for XML and JS are not yet defined
257782 354   if ($js_rep_table===false)
1cded8 355     {
f91a49 356     $js_rep_table = $xml_rep_table = array();
88375f 357     $xml_rep_table['&'] = '&amp;';
1cded8 358
T 359     for ($c=160; $c<256; $c++)  // can be increased to support more charsets
360       {
361       $xml_rep_table[Chr($c)] = "&#$c;";
362       
257782 363       if ($is_iso_8859_1)
74ae88 364         $js_rep_table[Chr($c)] = sprintf("\\u%04x", $c);
1cded8 365       }
T 366
367     $xml_rep_table['"'] = '&quot;';
c21d6d 368     $js_rep_table['"'] = '\\"';
T 369     $js_rep_table["'"] = "\\'";
3d54e6 370     $js_rep_table["\\"] = "\\\\";
1cded8 371     }
T 372
2bca6e 373   // encode for XML
1cded8 374   if ($enctype=='xml')
T 375     return strtr($str, $xml_rep_table);
376
377   // encode for javascript use
378   if ($enctype=='js')
13c1af 379     {
257782 380     if ($charset!='UTF-8')
A 381       $str = rcube_charset_convert($str, RCMAIL_CHARSET,$charset);
13c1af 382       
c21d6d 383     return preg_replace(array("/\r?\n/", "/\r/", '/<\\//'), array('\n', '\n', '<\\/'), strtr($str, $js_rep_table));
13c1af 384     }
1cded8 385
T 386   // no encoding given -> return original string
387   return $str;
2bca6e 388   }
f11541 389   
2bca6e 390 /**
6d969b 391  * Quote a given string.
T 392  * Shortcut function for rep_specialchars_output
393  *
394  * @return string HTML-quoted string
395  * @see rep_specialchars_output()
2bca6e 396  */
T 397 function Q($str, $mode='strict', $newlines=TRUE)
398   {
399   return rep_specialchars_output($str, 'html', $mode, $newlines);
400   }
401
402 /**
6d969b 403  * Quote a given string for javascript output.
T 404  * Shortcut function for rep_specialchars_output
405  * 
406  * @return string JS-quoted string
407  * @see rep_specialchars_output()
2bca6e 408  */
18e2a3 409 function JQ($str)
2bca6e 410   {
18e2a3 411   return rep_specialchars_output($str, 'js');
10a699 412   }
ea7c46 413
T 414
415 /**
416  * Read input value and convert it for internal use
417  * Performs stripslashes() and charset conversion if necessary
418  * 
419  * @param  string   Field name to read
420  * @param  int      Source to get value from (GPC)
421  * @param  boolean  Allow HTML tags in field value
422  * @param  string   Charset to convert into
423  * @return string   Field value or NULL if not available
424  */
425 function get_input_value($fname, $source, $allow_html=FALSE, $charset=NULL)
426   {
427   global $OUTPUT;
428   $value = NULL;
429   
430   if ($source==RCUBE_INPUT_GET && isset($_GET[$fname]))
431     $value = $_GET[$fname];
432   else if ($source==RCUBE_INPUT_POST && isset($_POST[$fname]))
433     $value = $_POST[$fname];
434   else if ($source==RCUBE_INPUT_GPC)
435     {
026d68 436     if (isset($_POST[$fname]))
ea7c46 437       $value = $_POST[$fname];
026d68 438     else if (isset($_GET[$fname]))
T 439       $value = $_GET[$fname];
ea7c46 440     else if (isset($_COOKIE[$fname]))
T 441       $value = $_COOKIE[$fname];
442     }
443   
6e47c0 444   // strip single quotes if magic_quotes_sybase is enabled
T 445   if (ini_get('magic_quotes_sybase'))
446     $value = str_replace("''", "'", $value);
ea7c46 447   // strip slashes if magic_quotes enabled
6e47c0 448   else if (get_magic_quotes_gpc() || get_magic_quotes_runtime())
ea7c46 449     $value = stripslashes($value);
T 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]))
407dcf 579     $value = get_input_value($fname, RCUBE_INPUT_POST,
A 580         $type == 'textarea' && strpos($attrib['class'], 'mce_editor')!==false ? true : false);
4e17e6 581
T 582   $out = $input->show($value);
583          
584   return $out;
f11541 585   }
T 586
587
6d969b 588 /**
97bd2c 589  * Replace all css definitions with #container [def]
a3e5b4 590  * and remove css-inlined scripting
97bd2c 591  *
T 592  * @param string CSS source code
593  * @param string Container ID to use as prefix
594  * @return string Modified CSS source
595  */
aa055c 596 function rcmail_mod_css_styles($source, $container_id)
97bd2c 597   {
T 598   $last_pos = 0;
aa055c 599   $replacements = new rcube_string_replacer;
a3e5b4 600   
T 601   // ignore the whole block if evil styles are detected
1c499a 602   $stripped = preg_replace('/[^a-z\(:]/', '', rcmail_xss_entitiy_decode($source));
T 603   if (preg_match('/expression|behavior|url\(|import/', $stripped))
aa055c 604     return '/* evil! */';
97bd2c 605
T 606   // cut out all contents between { and }
607   while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos)))
608   {
aa055c 609     $key = $replacements->add(substr($source, $pos+1, $pos2-($pos+1)));
T 610     $source = substr($source, 0, $pos+1) . $replacements->get_replacement($key) . substr($source, $pos2, strlen($source)-$pos2);
97bd2c 611     $last_pos = $pos+2;
T 612   }
aa055c 613   
a3e5b4 614   // remove html comments and add #container to each tag selector.
97bd2c 615   // also replace body definition because we also stripped off the <body> tag
T 616   $styles = preg_replace(
617     array(
618       '/(^\s*<!--)|(-->\s*$)/',
619       '/(^\s*|,\s*|\}\s*)([a-z0-9\._#][a-z0-9\.\-_]*)/im',
1608f4 620       "/$container_id\s+body/i",
97bd2c 621     ),
T 622     array(
623       '',
624       "\\1#$container_id \\2",
1608f4 625       "$container_id div.rcmBody",
97bd2c 626     ),
T 627     $source);
1608f4 628   
T 629   // put block contents back in
aa055c 630   $styles = $replacements->resolve($styles);
97bd2c 631
T 632   return $styles;
633   }
fba1f5 634
97bd2c 635
T 636 /**
1c499a 637  * Decode escaped entities used by known XSS exploits.
T 638  * See http://downloads.securityfocus.com/vulnerabilities/exploits/26800.eml for examples
639  *
640  * @param string CSS content to decode
641  * @return string Decoded string
642  */
643 function rcmail_xss_entitiy_decode($content)
644 {
645   $out = html_entity_decode(html_entity_decode($content));
aa055c 646   $out = preg_replace_callback('/\\\([0-9a-f]{4})/i', 'rcmail_xss_entitiy_decode_callback', $out);
85a913 647   $out = preg_replace('#/\*.*\*/#Um', '', $out);
1c499a 648   return $out;
T 649 }
650
aa055c 651
T 652 /**
653  * preg_replace_callback callback for rcmail_xss_entitiy_decode_callback
654  *
655  * @param array matches result from preg_replace_callback
656  * @return string decoded entity
657  */ 
658 function rcmail_xss_entitiy_decode_callback($matches)
659
660   return chr(hexdec($matches[1]));
661 }
1c499a 662
T 663 /**
6d969b 664  * Compose a valid attribute string for HTML tags
T 665  *
666  * @param array Named tag attributes
667  * @param array List of allowed attributes
668  * @return string HTML formatted attribute string
669  */
4e17e6 670 function create_attrib_string($attrib, $allowed_attribs=array('id', 'class', 'style'))
T 671   {
672   // allow the following attributes to be added to the <iframe> tag
673   $attrib_str = '';
674   foreach ($allowed_attribs as $a)
675     if (isset($attrib[$a]))
fe79b1 676       $attrib_str .= sprintf(' %s="%s"', $a, str_replace('"', '&quot;', $attrib[$a]));
4e17e6 677
T 678   return $attrib_str;
679   }
680
681
6d969b 682 /**
T 683  * Convert a HTML attribute string attributes to an associative array (name => value)
684  *
685  * @param string Input string
686  * @return array Key-value pairs of parsed attributes
687  */
fe79b1 688 function parse_attrib_string($str)
T 689   {
690   $attrib = array();
d59aaa 691   preg_match_all('/\s*([-_a-z]+)=(["\'])??(?(2)([^\2]*)\2|(\S+?))/Ui', stripslashes($str), $regs, PREG_SET_ORDER);
fe79b1 692
T 693   // convert attributes to an associative array (name => value)
cc97ea 694   if ($regs) {
T 695     foreach ($regs as $attr) {
696       $attrib[strtolower($attr[1])] = html_entity_decode($attr[3] . $attr[4]);
697     }
698   }
fe79b1 699
T 700   return $attrib;
701   }
702
4e17e6 703
6d969b 704 /**
T 705  * Convert the given date to a human readable form
706  * This uses the date formatting properties from config
707  *
708  * @param mixed Date representation (string or timestamp)
709  * @param string Date format to use
710  * @return string Formatted date string
711  */
4e17e6 712 function format_date($date, $format=NULL)
T 713   {
197601 714   global $CONFIG;
4e17e6 715   
4647e1 716   $ts = NULL;
ea090c 717
4e17e6 718   if (is_numeric($date))
T 719     $ts = $date;
b076a4 720   else if (!empty($date))
ea090c 721     {
33875d 722     // support non-standard "GMTXXXX" literal
A 723     $date = preg_replace('/GMT\s*([+-][0-9]+)/', '\\1', $date);
c9ca6a 724     // if date parsing fails, we have a date in non-rfc format.
S 725     // remove token from the end and try again
726     while ((($ts = @strtotime($date))===false) || ($ts < 0))
ea090c 727       {
A 728         $d = explode(' ', $date);
197601 729         array_pop($d);
T 730         if (!$d) break;
731         $date = implode(' ', $d);
ea090c 732       }
A 733     }
734
4647e1 735   if (empty($ts))
b076a4 736     return '';
4647e1 737    
T 738   // get user's timezone
62784a 739   if ($CONFIG['timezone'] === 'auto')
T 740     $tz = isset($_SESSION['timezone']) ? $_SESSION['timezone'] : date('Z')/3600;
c8ae24 741   else {
T 742     $tz = $CONFIG['timezone'];
743     if ($CONFIG['dst_active'])
744       $tz++;
745   }
4e17e6 746
T 747   // convert time to user's timezone
4647e1 748   $timestamp = $ts - date('Z', $ts) + ($tz * 3600);
4e17e6 749   
T 750   // get current timestamp in user's timezone
751   $now = time();  // local time
752   $now -= (int)date('Z'); // make GMT time
4647e1 753   $now += ($tz * 3600); // user's time
c45eb5 754   $now_date = getdate($now);
4e17e6 755
749b07 756   $today_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday'], $now_date['year']);
T 757   $week_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday']-6, $now_date['year']);
4e17e6 758
30233b 759   // define date format depending on current time  
87b280 760   if ($CONFIG['prettydate'] && !$format && $timestamp > $today_limit && $timestamp < $now)
8c8b2a 761     return sprintf('%s %s', rcube_label('today'), date($CONFIG['date_today'] ? $CONFIG['date_today'] : 'H:i', $timestamp));
87b280 762   else if ($CONFIG['prettydate'] && !$format && $timestamp > $week_limit && $timestamp < $now)
4e17e6 763     $format = $CONFIG['date_short'] ? $CONFIG['date_short'] : 'D H:i';
T 764   else if (!$format)
765     $format = $CONFIG['date_long'] ? $CONFIG['date_long'] : 'd.m.Y H:i';
766
767
768   // parse format string manually in order to provide localized weekday and month names
769   // an alternative would be to convert the date() format string to fit with strftime()
770   $out = '';
771   for($i=0; $i<strlen($format); $i++)
772     {
773     if ($format{$i}=='\\')  // skip escape chars
774       continue;
775     
776     // write char "as-is"
777     if ($format{$i}==' ' || $format{$i-1}=='\\')
778       $out .= $format{$i};
779     // weekday (short)
780     else if ($format{$i}=='D')
781       $out .= rcube_label(strtolower(date('D', $timestamp)));
782     // weekday long
783     else if ($format{$i}=='l')
784       $out .= rcube_label(strtolower(date('l', $timestamp)));
785     // month name (short)
786     else if ($format{$i}=='M')
787       $out .= rcube_label(strtolower(date('M', $timestamp)));
788     // month name (long)
789     else if ($format{$i}=='F')
7479cc 790       $out .= rcube_label('long'.strtolower(date('M', $timestamp)));
5b1de5 791     else if ($format{$i}=='x')
A 792       $out .= strftime('%x %X', $timestamp);
4e17e6 793     else
T 794       $out .= date($format{$i}, $timestamp);
795     }
796   
797   return $out;
798   }
799
800
6d969b 801 /**
T 802  * Compose a valid representaion of name and e-mail address
803  *
804  * @param string E-mail address
805  * @param string Person name
806  * @return string Formatted string
807  */
f11541 808 function format_email_recipient($email, $name='')
T 809   {
810   if ($name && $name != $email)
0c6f4b 811     {
T 812     // Special chars as defined by RFC 822 need to in quoted string (or escaped).
813     return sprintf('%s <%s>', preg_match('/[\(\)\<\>\\\.\[\]@,;:"]/', $name) ? '"'.addcslashes($name, '"').'"' : $name, $email);
814     }
f11541 815   else
T 816     return $email;
817   }
818
819
820
c39957 821 /****** debugging functions ********/
T 822
823
824 /**
825  * Print or write debug messages
826  *
827  * @param mixed Debug message or data
828  */
ed132e 829 function console()
c39957 830   {
cc97ea 831   $args = func_get_args();
T 832   if (class_exists('rcmail', false))
833       rcmail::get_instance()->plugins->exec_hook('console', $args);
834
ed132e 835   $msg = array();
cc97ea 836   foreach ($args as $arg)
T 837      $msg[] = !is_string($arg) ? var_export($arg, true) : $arg;
c39957 838
T 839   if (!($GLOBALS['CONFIG']['debug_level'] & 4))
ed132e 840     write_log('console', join(";\n", $msg));
197601 841   else if ($GLOBALS['OUTPUT']->ajax_call)
ed132e 842     print "/*\n " . join(";\n", $msg) . " \n*/\n";
c39957 843   else
T 844     {
845     print '<div style="background:#eee; border:1px solid #ccc; margin-bottom:3px; padding:6px"><pre>';
ed132e 846     print join(";<br/>\n", $msg);
c39957 847     print "</pre></div>\n";
T 848     }
849   }
850
851
852 /**
853  * Append a line to a logfile in the logs directory.
854  * Date will be added automatically to the line.
855  *
653242 856  * @param $name name of log file
S 857  * @param line Line to append
c39957 858  */
T 859 function write_log($name, $line)
860   {
47124c 861   global $CONFIG;
e170b4 862
T 863   if (!is_string($line))
864     $line = var_export($line, true);
0ad27c 865  
A 866   if (empty($CONFIG['log_date_format']))
867     $CONFIG['log_date_format'] = 'd-M-Y H:i:s O';
868  
869   $log_entry = sprintf("[%s]: %s\n", date($CONFIG['log_date_format']), $line);
c9ca6a 870
b77d0d 871   if ($CONFIG['log_driver'] == 'syslog') {
A 872     if ($name == 'errors')
873       $prio = LOG_ERR;
874     else
875       $prio = LOG_INFO;
876     syslog($prio, $log_entry);
877   } else {
878     // log_driver == 'file' is assumed here
879     if (empty($CONFIG['log_dir']))
880       $CONFIG['log_dir'] = INSTALL_PATH.'logs';
c9ca6a 881
b77d0d 882     // try to open specific log file for writing
A 883     if ($fp = @fopen($CONFIG['log_dir'].'/'.$name, 'a')) {
884       fwrite($fp, $log_entry);
c9ca6a 885       fflush($fp);
b77d0d 886       fclose($fp);
c39957 887     }
T 888   }
b77d0d 889 }
c39957 890
cc9570 891
6d969b 892 /**
T 893  * @access private
894  */
15a9d1 895 function rcube_timer()
T 896   {
897   list($usec, $sec) = explode(" ", microtime());
898   return ((float)$usec + (float)$sec);
899   }
900   
901
6d969b 902 /**
T 903  * @access private
904  */
15a9d1 905 function rcube_print_time($timer, $label='Timer')
T 906   {
907   static $print_count = 0;
908   
909   $print_count++;
910   $now = rcube_timer();
911   $diff = $now-$timer;
912   
913   if (empty($label))
914     $label = 'Timer '.$print_count;
915   
916   console(sprintf("%s: %0.4f sec", $label, $diff));
917   }
918
93be5b 919
6d969b 920 /**
T 921  * Return the mailboxlist in HTML
922  *
923  * @param array Named parameters
924  * @return string HTML code for the gui object
925  */
93be5b 926 function rcmail_mailbox_list($attrib)
62e542 927 {
25f80d 928   global $RCMAIL;
93be5b 929   static $a_mailboxes;
64f20d 930   
T 931   $attrib += array('maxlength' => 100, 'relanames' => false);
93be5b 932
S 933   // add some labels to client
112c91 934   $RCMAIL->output->add_label('purgefolderconfirm', 'deletemessagesconfirm');
93be5b 935   
S 936   $type = $attrib['type'] ? $attrib['type'] : 'ul';
6d6e06 937   unset($attrib['type']);
T 938
93be5b 939   if ($type=='ul' && !$attrib['id'])
S 940     $attrib['id'] = 'rcmboxlist';
941
942   // get mailbox list
25f80d 943   $mbox_name = $RCMAIL->imap->get_mailbox_name();
93be5b 944   
S 945   // build the folders tree
62e542 946   if (empty($a_mailboxes)) {
93be5b 947     // get mailbox list
25f80d 948     $a_folders = $RCMAIL->imap->list_mailboxes();
T 949     $delimiter = $RCMAIL->imap->get_hierarchy_delimiter();
93be5b 950     $a_mailboxes = array();
S 951
952     foreach ($a_folders as $folder)
953       rcmail_build_folder_tree($a_mailboxes, $folder, $delimiter);
62e542 954   }
93be5b 955
6d6e06 956   if ($type=='select') {
T 957     $select = new html_select($attrib);
958     
959     // add no-selection option
960     if ($attrib['noselection'])
961       $select->add(rcube_label($attrib['noselection']), '0');
962     
64f20d 963     rcmail_render_folder_tree_select($a_mailboxes, $mbox_name, $attrib['maxlength'], $select, $attrib['realnames']);
62e542 964     $out = $select->show();
6d6e06 965   }
T 966   else {
f89f03 967     $js_mailboxlist = array();
T 968     $out = html::tag('ul', $attrib, rcmail_render_folder_tree_html($a_mailboxes, $mbox_name, $js_mailboxlist, $attrib), html::$common_attrib);
969     
25f80d 970     $RCMAIL->output->add_gui_object('mailboxlist', $attrib['id']);
f89f03 971     $RCMAIL->output->set_env('mailboxes', $js_mailboxlist);
25f80d 972     $RCMAIL->output->set_env('collapsed_folders', $RCMAIL->config->get('collapsed_folders'));
T 973   }
93be5b 974
6d6e06 975   return $out;
62e542 976 }
93be5b 977
S 978
cb3538 979 /**
T 980  * Return the mailboxlist as html_select object
981  *
982  * @param array Named parameters
983  * @return object html_select HTML drop-down object
984  */
985 function rcmail_mailbox_select($p = array())
986 {
987   global $RCMAIL;
988   
64f20d 989   $p += array('maxlength' => 100, 'relanames' => false);
cb3538 990   $a_mailboxes = array();
T 991   
992   foreach ($RCMAIL->imap->list_mailboxes() as $folder)
993     rcmail_build_folder_tree($a_mailboxes, $folder, $RCMAIL->imap->get_hierarchy_delimiter());
994
995   $select = new html_select($p);
996   
997   if ($p['noselection'])
998     $select->add($p['noselection'], '');
999     
64f20d 1000   rcmail_render_folder_tree_select($a_mailboxes, $mbox, $p['maxlength'], $select, $p['realnames']);
cb3538 1001   
T 1002   return $select;
1003 }
93be5b 1004
S 1005
6d969b 1006 /**
T 1007  * Create a hierarchical array of the mailbox list
1008  * @access private
1009  */
93be5b 1010 function rcmail_build_folder_tree(&$arrFolders, $folder, $delm='/', $path='')
f89f03 1011 {
93be5b 1012   $pos = strpos($folder, $delm);
f89f03 1013   if ($pos !== false) {
93be5b 1014     $subFolders = substr($folder, $pos+1);
S 1015     $currentFolder = substr($folder, 0, $pos);
f89f03 1016     $virtual = !isset($arrFolders[$currentFolder]);
T 1017   }
1018   else {
93be5b 1019     $subFolders = false;
S 1020     $currentFolder = $folder;
f89f03 1021     $virtual = false;
T 1022   }
93be5b 1023
S 1024   $path .= $currentFolder;
1025
f89f03 1026   if (!isset($arrFolders[$currentFolder])) {
6d6e06 1027     $arrFolders[$currentFolder] = array(
T 1028       'id' => $path,
1029       'name' => rcube_charset_convert($currentFolder, 'UTF-7'),
f89f03 1030       'virtual' => $virtual,
6d6e06 1031       'folders' => array());
f89f03 1032   }
T 1033   else
1034     $arrFolders[$currentFolder]['virtual'] = $virtual;
93be5b 1035
S 1036   if (!empty($subFolders))
1037     rcmail_build_folder_tree($arrFolders[$currentFolder]['folders'], $subFolders, $delm, $path.$delm);
f89f03 1038 }
93be5b 1039   
S 1040
6d969b 1041 /**
T 1042  * Return html for a structured list &lt;ul&gt; for the mailbox tree
1043  * @access private
1044  */
f89f03 1045 function rcmail_render_folder_tree_html(&$arrFolders, &$mbox_name, &$jslist, $attrib, $nestLevel=0)
T 1046 {
25f80d 1047   global $RCMAIL, $CONFIG;
f89f03 1048   
T 1049   $maxlength = intval($attrib['maxlength']);
1050   $realnames = (bool)$attrib['realnames'];
1051   $msgcounts = $RCMAIL->imap->get_cache('messagecount');
93be5b 1052
S 1053   $idx = 0;
1054   $out = '';
f89f03 1055   foreach ($arrFolders as $key => $folder) {
cb3538 1056     $zebra_class = (($nestLevel+1)*$idx) % 2 == 0 ? 'even' : 'odd';
6d6e06 1057     $title = null;
93be5b 1058
f89f03 1059     if (($folder_class = rcmail_folder_classname($folder['id'])) && !$realnames) {
cb3bad 1060       $foldername = rcube_label($folder_class);
f89f03 1061     }
T 1062     else {
93be5b 1063       $foldername = $folder['name'];
S 1064
1065       // shorten the folder name to a given length
f89f03 1066       if ($maxlength && $maxlength > 1) {
6f2f2d 1067         $fname = abbreviate_string($foldername, $maxlength);
93be5b 1068         if ($fname != $foldername)
6d6e06 1069           $title = $foldername;
93be5b 1070         $foldername = $fname;
S 1071       }
f89f03 1072     }
93be5b 1073
S 1074     // make folder name safe for ids and class names
6d6e06 1075     $folder_id = asciiwords($folder['id'], true);
T 1076     $classes = array('mailbox');
93be5b 1077
S 1078     // set special class for Sent, Drafts, Trash and Junk
1079     if ($folder['id']==$CONFIG['sent_mbox'])
6d6e06 1080       $classes[] = 'sent';
93be5b 1081     else if ($folder['id']==$CONFIG['drafts_mbox'])
6d6e06 1082       $classes[] = 'drafts';
93be5b 1083     else if ($folder['id']==$CONFIG['trash_mbox'])
6d6e06 1084       $classes[] = 'trash';
93be5b 1085     else if ($folder['id']==$CONFIG['junk_mbox'])
6d6e06 1086       $classes[] = 'junk';
d6497f 1087     else if ($folder['id']=='INBOX')
A 1088       $classes[] = 'inbox';
6d6e06 1089     else
d6497f 1090       $classes[] = '_'.asciiwords($folder_class ? $folder_class : strtolower($folder['id']), true);
6d6e06 1091       
T 1092     $classes[] = $zebra_class;
1093     
1094     if ($folder['id'] == $mbox_name)
1095       $classes[] = 'selected';
93be5b 1096
f5aa16 1097     $collapsed = preg_match('/&'.rawurlencode($folder['id']).'&/', $RCMAIL->config->get('collapsed_folders'));
f89f03 1098     $unread = $msgcounts ? intval($msgcounts[$folder['id']]['UNSEEN']) : 0;
T 1099     
1100     if ($folder['virtual'])
1101       $classes[] = 'virtual';
1102     else if ($unread)
1103       $classes[] = 'unread';
f5aa16 1104
6d6e06 1105     $js_name = JQ($folder['id']);
f89f03 1106     $html_name = Q($foldername . ($unread ? " ($unread)" : ''));
T 1107     $link_attrib = $folder['virtual'] ? array() : array(
1108       'href' => rcmail_url('', array('_mbox' => $folder['id'])),
1109       'onclick' => sprintf("return %s.command('list','%s',this)", JS_OBJECT_NAME, $js_name),
1110       'title' => $title,
1111     );
1112
6d6e06 1113     $out .= html::tag('li', array(
T 1114         'id' => "rcmli".$folder_id,
1115         'class' => join(' ', $classes),
1116         'noclose' => true),
f89f03 1117       html::a($link_attrib, $html_name) .
e1eb70 1118       (!empty($folder['folders']) ? html::div(array(
T 1119         'class' => ($collapsed ? 'collapsed' : 'expanded'),
1120         'style' => "position:absolute",
1121         'onclick' => sprintf("%s.command('collapse-folder', '%s')", JS_OBJECT_NAME, $js_name)
1122       ), '&nbsp;') : ''));
6d6e06 1123     
f89f03 1124     $jslist[$folder_id] = array('id' => $folder['id'], 'name' => $foldername, 'virtual' => $folder['virtual']);
T 1125     
1126     if (!empty($folder['folders'])) {
1127       $out .= html::tag('ul', array('style' => ($collapsed ? "display:none;" : null)),
1128         rcmail_render_folder_tree_html($folder['folders'], $mbox_name, $jslist, $attrib, $nestLevel+1));
1129     }
93be5b 1130
S 1131     $out .= "</li>\n";
1132     $idx++;
f89f03 1133   }
93be5b 1134
S 1135   return $out;
f89f03 1136 }
93be5b 1137
S 1138
6d969b 1139 /**
T 1140  * Return html for a flat list <select> for the mailbox tree
1141  * @access private
1142  */
64f20d 1143 function rcmail_render_folder_tree_select(&$arrFolders, &$mbox_name, $maxlength, &$select, $realnames=false, $nestLevel=0)
93be5b 1144   {
S 1145   $idx = 0;
1146   $out = '';
1147   foreach ($arrFolders as $key=>$folder)
1148     {
64f20d 1149     if (!$realnames && ($folder_class = rcmail_folder_classname($folder['id'])))
cb3bad 1150       $foldername = rcube_label($folder_class);
93be5b 1151     else
S 1152       {
1153       $foldername = $folder['name'];
1154       
1155       // shorten the folder name to a given length
1156       if ($maxlength && $maxlength>1)
6f2f2d 1157         $foldername = abbreviate_string($foldername, $maxlength);
93be5b 1158       }
S 1159
6d6e06 1160     $select->add(str_repeat('&nbsp;', $nestLevel*4) . $foldername, $folder['id']);
93be5b 1161
S 1162     if (!empty($folder['folders']))
64f20d 1163       $out .= rcmail_render_folder_tree_select($folder['folders'], $mbox_name, $maxlength, $select, $realnames, $nestLevel+1);
93be5b 1164
S 1165     $idx++;
1166     }
1167
1168   return $out;
1169   }
1170
cb3bad 1171
T 1172 /**
1173  * Return internal name for the given folder if it matches the configured special folders
1174  * @access private
1175  */
1176 function rcmail_folder_classname($folder_id)
1177 {
1178   global $CONFIG;
1179
1180   // for these mailboxes we have localized labels and css classes
64c9b5 1181   foreach (array('sent', 'drafts', 'trash', 'junk') as $smbx)
cb3bad 1182   {
f94629 1183     if ($folder_id == $CONFIG[$smbx.'_mbox'])
64c9b5 1184       return $smbx;
cb3bad 1185   }
64c9b5 1186
A 1187   if ($folder_id == 'INBOX')
1188     return 'inbox';
cb3bad 1189 }
T 1190
1191
fed22f 1192 /**
T 1193  * Try to localize the given IMAP folder name.
1194  * UTF-7 decode it in case no localized text was found
1195  *
1196  * @param string Folder name
1197  * @return string Localized folder name in UTF-8 encoding
1198  */
1199 function rcmail_localize_foldername($name)
1200 {
1201   if ($folder_class = rcmail_folder_classname($name))
1202     return rcube_label($folder_class);
1203   else
1204     return rcube_charset_convert($name, 'UTF-7');
1205 }
1206
1207
b8ae50 1208 /**
A 1209  * Output HTML editor scripts
1210  *
be5d4a 1211  * @param string Editor mode
b8ae50 1212  */
A 1213 function rcube_html_editor($mode='')
1214 {
1215   global $OUTPUT, $CONFIG;
1216
1217   $lang = $tinylang = strtolower(substr($_SESSION['language'], 0, 2));
1218   if (!file_exists(INSTALL_PATH . 'program/js/tiny_mce/langs/'.$tinylang.'.js'))
1219     $tinylang = 'en';
1220
1221   $OUTPUT->include_script('tiny_mce/tiny_mce.js');
1222   $OUTPUT->include_script('editor.js');
1223   $OUTPUT->add_script('rcmail_editor_init("$__skin_path", "'.JQ($tinylang).'", '.intval($CONFIG['enable_spellcheck']).', "'.$mode.'");');
1224 }
1225
aa055c 1226
T 1227
1228 /**
1229  * Helper class to turn relative urls into absolute ones
1230  * using a predefined base
1231  */
1232 class rcube_base_replacer
1233 {
1234   private $base_url;
1235   
1236   public function __construct($base)
1237   {
1238     $this->base_url = $base;
1239   }
1240   
1241   public function callback($matches)
1242   {
1243     return $matches[1] . '="' . make_absolute_url($matches[3], $this->base_url) . '"';
1244   }
1245 }
1246
d1d2c4 1247 ?>