alecpl
2008-09-20 c17dc6aa31aaa6e7f61bd25993be55354e428996
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     
9e8e5f 80     if ($db->db_provider=='pgsql')
54dd42 81       {
A 82       $db->db_handle->setOption('disable_smart_seqname', true);
83       $db->db_handle->setOption('seqname_format', '%s');
3e8483 84       }
54dd42 85   
3e8483 86     return $opt;
54dd42 87     }
A 88     
ae8f19 89   return $sequence;
1cded8 90   }
0af7e8 91
T 92
6d969b 93 /**
1854c4 94  * Get localized text in the desired language
T 95  * It's a global wrapper for rcmail::gettext()
6d969b 96  *
1854c4 97  * @param mixed Named parameters array or label name
T 98  * @return string Localized text
99  * @see rcmail::gettext()
6d969b 100  */
1854c4 101 function rcube_label($p)
T 102 {
103   return rcmail::get_instance()->gettext($p);
104 }
4e17e6 105
T 106
6d969b 107 /**
T 108  * Overwrite action variable
109  *
110  * @param string New action value
111  */
10a699 112 function rcmail_overwrite_action($action)
T 113   {
197601 114   $app = rcmail::get_instance();
T 115   $app->action = $action;
116   $app->output->set_env('action', $action);
10a699 117   }
T 118
119
41bece 120 /**
T 121  * Compose an URL for a specific action
122  *
123  * @param string  Request action
124  * @param array   More URL parameters
125  * @param string  Request task (omit if the same)
126  * @return The application URL
127  */
128 function rcmail_url($action, $p=array(), $task=null)
f11541 129 {
197601 130   $app = rcmail::get_instance();
fde466 131   return $app->url((array)$p + array('_action' => $action, 'task' => $task));
f11541 132 }
9fee0e 133
4e17e6 134
6d969b 135 /**
T 136  * Add a localized label to the client environment
47124c 137  * @deprecated
6d969b 138  */
10a699 139 function rcube_add_label()
T 140   {
f11541 141   global $OUTPUT;
10a699 142   
T 143   $arg_list = func_get_args();
144   foreach ($arg_list as $i => $name)
47124c 145     $OUTPUT->add_label($name);
1cded8 146   }
T 147
148
6d969b 149 /**
T 150  * Garbage collector function for temp files.
151  * Remove temp files older than two days
152  */
70d4b9 153 function rcmail_temp_gc()
1cded8 154   {
70d4b9 155   $tmp = unslashify($CONFIG['temp_dir']);
T 156   $expire = mktime() - 172800;  // expire in 48 hours
1cded8 157
70d4b9 158   if ($dir = opendir($tmp))
1cded8 159     {
70d4b9 160     while (($fname = readdir($dir)) !== false)
T 161       {
162       if ($fname{0} == '.')
163         continue;
164
165       if (filemtime($tmp.'/'.$fname) < $expire)
166         @unlink($tmp.'/'.$fname);
167       }
168
169     closedir($dir);
170     }
1cded8 171   }
T 172
173
6d969b 174 /**
T 175  * Garbage collector for cache entries.
176  * Remove all expired message cache records
177  */
cc9570 178 function rcmail_message_cache_gc()
T 179   {
180   global $DB, $CONFIG;
181   
182   // no cache lifetime configured
183   if (empty($CONFIG['message_cache_lifetime']))
184     return;
185   
186   // get target timestamp
187   $ts = get_offset_time($CONFIG['message_cache_lifetime'], -1);
188   
189   $DB->query("DELETE FROM ".get_table_name('messages')."
190              WHERE  created < ".$DB->fromunixtime($ts));
191   }
192
1cded8 193
2bca6e 194 /**
T 195  * Convert a string from one charset to another.
196  * Uses mbstring and iconv functions if possible
197  *
198  * @param  string Input string
199  * @param  string Suspected charset of the input string
f11541 200  * @param  string Target charset to convert to; defaults to RCMAIL_CHARSET
2bca6e 201  * @return Converted string
T 202  */
3f9edb 203 function rcube_charset_convert($str, $from, $to=NULL)
0af7e8 204   {
197601 205   static $mbstring_loaded = null, $convert_warning = false;
f88d41 206
83dbb7 207   $from = strtoupper($from);
f11541 208   $to = $to==NULL ? strtoupper(RCMAIL_CHARSET) : strtoupper($to);
1a7f99 209   $error = false; $conv = null;
f88d41 210
2f2f15 211   if ($from==$to || $str=='' || empty($from))
3f9edb 212     return $str;
38b012 213     
T 214   $aliases = array(
b6a27f 215     'US-ASCII'       => 'ISO-8859-1',
38b012 216     'UNKNOWN-8BIT'   => 'ISO-8859-15',
T 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)
c8a21d 321     $enctype = $OUTPUT->type;
1cded8 322
T 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 &
fdebae 351     $out = preg_replace('/&amp;([A-Za-z]{2,6}|#[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
1c499a 601   $stripped = preg_replace('/[^a-z\(:]/', '', rcmail_xss_entitiy_decode($source));
T 602   if (preg_match('/expression|behavior|url\(|import/', $stripped))
a3e5b4 603     return '';
97bd2c 604
T 605   // cut out all contents between { and }
606   while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos)))
607   {
608     $key = sizeof($a_css_values);
609     $a_css_values[$key] = substr($source, $pos+1, $pos2-($pos+1));
610     $source = substr($source, 0, $pos+1) . "<<str_replacement[$key]>>" . substr($source, $pos2, strlen($source)-$pos2);
611     $last_pos = $pos+2;
612   }
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',
620       '/@import\s+(url\()?[\'"]?([^\)\'"]+)[\'"]?(\))?/ime',
621       '/<<str_replacement\[([0-9]+)\]>>/e',
622       "/$container_id\s+body/i"
623     ),
624     array(
625       '',
626       "\\1#$container_id \\2",
627       "sprintf(\"@import url('./bin/modcss.php?u=%s&c=%s')\", urlencode(make_absolute_url('\\2','$base_url')), urlencode($container_id))",
628       "\$a_css_values[\\1]",
629       "$container_id div.rcmBody"
630     ),
631     $source);
632
633   return $styles;
634   }
fba1f5 635
97bd2c 636
T 637 /**
1c499a 638  * Decode escaped entities used by known XSS exploits.
T 639  * See http://downloads.securityfocus.com/vulnerabilities/exploits/26800.eml for examples
640  *
641  * @param string CSS content to decode
642  * @return string Decoded string
643  */
644 function rcmail_xss_entitiy_decode($content)
645 {
646   $out = html_entity_decode(html_entity_decode($content));
14c5b8 647   $out = preg_replace('/\\\([0-9a-f]{4})/ie', "chr(hexdec('\\1'))", $out);
85a913 648   $out = preg_replace('#/\*.*\*/#Um', '', $out);
1c499a 649   return $out;
T 650 }
651
652
653 /**
6d969b 654  * Compose a valid attribute string for HTML tags
T 655  *
656  * @param array Named tag attributes
657  * @param array List of allowed attributes
658  * @return string HTML formatted attribute string
659  */
4e17e6 660 function create_attrib_string($attrib, $allowed_attribs=array('id', 'class', 'style'))
T 661   {
662   // allow the following attributes to be added to the <iframe> tag
663   $attrib_str = '';
664   foreach ($allowed_attribs as $a)
665     if (isset($attrib[$a]))
fe79b1 666       $attrib_str .= sprintf(' %s="%s"', $a, str_replace('"', '&quot;', $attrib[$a]));
4e17e6 667
T 668   return $attrib_str;
669   }
670
671
6d969b 672 /**
T 673  * Convert a HTML attribute string attributes to an associative array (name => value)
674  *
675  * @param string Input string
676  * @return array Key-value pairs of parsed attributes
677  */
fe79b1 678 function parse_attrib_string($str)
T 679   {
680   $attrib = array();
f02574 681   preg_match_all('/\s*([-_a-z]+)=(["\'])??(?(2)([^\2]+)\2|(\S+?))/Ui', stripslashes($str), $regs, PREG_SET_ORDER);
fe79b1 682
T 683   // convert attributes to an associative array (name => value)
684   if ($regs)
685     foreach ($regs as $attr)
653242 686       {
S 687       $attrib[strtolower($attr[1])] = $attr[3] . $attr[4];
688       }
fe79b1 689
T 690   return $attrib;
691   }
692
4e17e6 693
6d969b 694 /**
T 695  * Convert the given date to a human readable form
696  * This uses the date formatting properties from config
697  *
698  * @param mixed Date representation (string or timestamp)
699  * @param string Date format to use
700  * @return string Formatted date string
701  */
4e17e6 702 function format_date($date, $format=NULL)
T 703   {
197601 704   global $CONFIG;
4e17e6 705   
4647e1 706   $ts = NULL;
ea090c 707
4e17e6 708   if (is_numeric($date))
T 709     $ts = $date;
b076a4 710   else if (!empty($date))
ea090c 711     {
A 712     while (($ts = @strtotime($date))===false)
713       {
714         // if we have a date in non-rfc format
197601 715         // remove token from the end and try again
ea090c 716         $d = explode(' ', $date);
197601 717         array_pop($d);
T 718         if (!$d) break;
719         $date = implode(' ', $d);
ea090c 720       }
A 721     }
722
4647e1 723   if (empty($ts))
b076a4 724     return '';
4647e1 725    
T 726   // get user's timezone
62784a 727   if ($CONFIG['timezone'] === 'auto')
T 728     $tz = isset($_SESSION['timezone']) ? $_SESSION['timezone'] : date('Z')/3600;
c8ae24 729   else {
T 730     $tz = $CONFIG['timezone'];
731     if ($CONFIG['dst_active'])
732       $tz++;
733   }
4e17e6 734
T 735   // convert time to user's timezone
4647e1 736   $timestamp = $ts - date('Z', $ts) + ($tz * 3600);
4e17e6 737   
T 738   // get current timestamp in user's timezone
739   $now = time();  // local time
740   $now -= (int)date('Z'); // make GMT time
4647e1 741   $now += ($tz * 3600); // user's time
c45eb5 742   $now_date = getdate($now);
4e17e6 743
749b07 744   $today_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday'], $now_date['year']);
T 745   $week_limit = mktime(0, 0, 0, $now_date['mon'], $now_date['mday']-6, $now_date['year']);
4e17e6 746
30233b 747   // define date format depending on current time  
87b280 748   if ($CONFIG['prettydate'] && !$format && $timestamp > $today_limit && $timestamp < $now)
8c8b2a 749     return sprintf('%s %s', rcube_label('today'), date($CONFIG['date_today'] ? $CONFIG['date_today'] : 'H:i', $timestamp));
87b280 750   else if ($CONFIG['prettydate'] && !$format && $timestamp > $week_limit && $timestamp < $now)
4e17e6 751     $format = $CONFIG['date_short'] ? $CONFIG['date_short'] : 'D H:i';
T 752   else if (!$format)
753     $format = $CONFIG['date_long'] ? $CONFIG['date_long'] : 'd.m.Y H:i';
754
755
756   // parse format string manually in order to provide localized weekday and month names
757   // an alternative would be to convert the date() format string to fit with strftime()
758   $out = '';
759   for($i=0; $i<strlen($format); $i++)
760     {
761     if ($format{$i}=='\\')  // skip escape chars
762       continue;
763     
764     // write char "as-is"
765     if ($format{$i}==' ' || $format{$i-1}=='\\')
766       $out .= $format{$i};
767     // weekday (short)
768     else if ($format{$i}=='D')
769       $out .= rcube_label(strtolower(date('D', $timestamp)));
770     // weekday long
771     else if ($format{$i}=='l')
772       $out .= rcube_label(strtolower(date('l', $timestamp)));
773     // month name (short)
774     else if ($format{$i}=='M')
775       $out .= rcube_label(strtolower(date('M', $timestamp)));
776     // month name (long)
777     else if ($format{$i}=='F')
7479cc 778       $out .= rcube_label('long'.strtolower(date('M', $timestamp)));
5b1de5 779     else if ($format{$i}=='x')
A 780       $out .= strftime('%x %X', $timestamp);
4e17e6 781     else
T 782       $out .= date($format{$i}, $timestamp);
783     }
784   
785   return $out;
786   }
787
788
6d969b 789 /**
T 790  * Compose a valid representaion of name and e-mail address
791  *
792  * @param string E-mail address
793  * @param string Person name
794  * @return string Formatted string
795  */
f11541 796 function format_email_recipient($email, $name='')
T 797   {
798   if ($name && $name != $email)
0c6f4b 799     {
T 800     // Special chars as defined by RFC 822 need to in quoted string (or escaped).
801     return sprintf('%s <%s>', preg_match('/[\(\)\<\>\\\.\[\]@,;:"]/', $name) ? '"'.addcslashes($name, '"').'"' : $name, $email);
802     }
f11541 803   else
T 804     return $email;
805   }
806
807
808
c39957 809 /****** debugging functions ********/
T 810
811
812 /**
813  * Print or write debug messages
814  *
815  * @param mixed Debug message or data
816  */
ed132e 817 function console()
c39957 818   {
ed132e 819   $msg = array();
T 820   foreach (func_get_args() as $arg)
821     $msg[] = !is_string($arg) ? var_export($arg, true) : $arg;
c39957 822
T 823   if (!($GLOBALS['CONFIG']['debug_level'] & 4))
ed132e 824     write_log('console', join(";\n", $msg));
197601 825   else if ($GLOBALS['OUTPUT']->ajax_call)
ed132e 826     print "/*\n " . join(";\n", $msg) . " \n*/\n";
c39957 827   else
T 828     {
829     print '<div style="background:#eee; border:1px solid #ccc; margin-bottom:3px; padding:6px"><pre>';
ed132e 830     print join(";<br/>\n", $msg);
c39957 831     print "</pre></div>\n";
T 832     }
833   }
834
835
836 /**
837  * Append a line to a logfile in the logs directory.
838  * Date will be added automatically to the line.
839  *
653242 840  * @param $name name of log file
S 841  * @param line Line to append
c39957 842  */
T 843 function write_log($name, $line)
844   {
47124c 845   global $CONFIG;
e170b4 846
T 847   if (!is_string($line))
848     $line = var_export($line, true);
c39957 849   
T 850   $log_entry = sprintf("[%s]: %s\n",
851                  date("d-M-Y H:i:s O", mktime()),
852                  $line);
853                  
b77d0d 854   if ($CONFIG['log_driver'] == 'syslog') {
A 855     if ($name == 'errors')
856       $prio = LOG_ERR;
857     else
858       $prio = LOG_INFO;
859     syslog($prio, $log_entry);
860   } else {
861     // log_driver == 'file' is assumed here
862     if (empty($CONFIG['log_dir']))
863       $CONFIG['log_dir'] = INSTALL_PATH.'logs';
c39957 864       
b77d0d 865     // try to open specific log file for writing
A 866     if ($fp = @fopen($CONFIG['log_dir'].'/'.$name, 'a')) {
867       fwrite($fp, $log_entry);
868       fclose($fp);
c39957 869     }
T 870   }
b77d0d 871 }
c39957 872
cc9570 873
6d969b 874 /**
T 875  * @access private
876  */
15a9d1 877 function rcube_timer()
T 878   {
879   list($usec, $sec) = explode(" ", microtime());
880   return ((float)$usec + (float)$sec);
881   }
882   
883
6d969b 884 /**
T 885  * @access private
886  */
15a9d1 887 function rcube_print_time($timer, $label='Timer')
T 888   {
889   static $print_count = 0;
890   
891   $print_count++;
892   $now = rcube_timer();
893   $diff = $now-$timer;
894   
895   if (empty($label))
896     $label = 'Timer '.$print_count;
897   
898   console(sprintf("%s: %0.4f sec", $label, $diff));
899   }
900
93be5b 901
6d969b 902 /**
T 903  * Return the mailboxlist in HTML
904  *
905  * @param array Named parameters
906  * @return string HTML code for the gui object
907  */
93be5b 908 function rcmail_mailbox_list($attrib)
62e542 909 {
25f80d 910   global $RCMAIL;
93be5b 911   static $a_mailboxes;
64f20d 912   
T 913   $attrib += array('maxlength' => 100, 'relanames' => false);
93be5b 914
S 915   // add some labels to client
916   rcube_add_label('purgefolderconfirm');
917   rcube_add_label('deletemessagesconfirm');
918   
919   $type = $attrib['type'] ? $attrib['type'] : 'ul';
6d6e06 920   unset($attrib['type']);
T 921
93be5b 922   if ($type=='ul' && !$attrib['id'])
S 923     $attrib['id'] = 'rcmboxlist';
924
925   // get mailbox list
25f80d 926   $mbox_name = $RCMAIL->imap->get_mailbox_name();
93be5b 927   
S 928   // build the folders tree
62e542 929   if (empty($a_mailboxes)) {
93be5b 930     // get mailbox list
25f80d 931     $a_folders = $RCMAIL->imap->list_mailboxes();
T 932     $delimiter = $RCMAIL->imap->get_hierarchy_delimiter();
93be5b 933     $a_mailboxes = array();
S 934
935     foreach ($a_folders as $folder)
936       rcmail_build_folder_tree($a_mailboxes, $folder, $delimiter);
62e542 937   }
93be5b 938
6d6e06 939   if ($type=='select') {
T 940     $select = new html_select($attrib);
941     
942     // add no-selection option
943     if ($attrib['noselection'])
944       $select->add(rcube_label($attrib['noselection']), '0');
945     
64f20d 946     rcmail_render_folder_tree_select($a_mailboxes, $mbox_name, $attrib['maxlength'], $select, $attrib['realnames']);
62e542 947     $out = $select->show();
6d6e06 948   }
T 949   else {
f89f03 950     $js_mailboxlist = array();
T 951     $out = html::tag('ul', $attrib, rcmail_render_folder_tree_html($a_mailboxes, $mbox_name, $js_mailboxlist, $attrib), html::$common_attrib);
952     
25f80d 953     $RCMAIL->output->add_gui_object('mailboxlist', $attrib['id']);
f89f03 954     $RCMAIL->output->set_env('mailboxes', $js_mailboxlist);
25f80d 955     $RCMAIL->output->set_env('collapsed_folders', $RCMAIL->config->get('collapsed_folders'));
T 956   }
93be5b 957
6d6e06 958   return $out;
62e542 959 }
93be5b 960
S 961
cb3538 962 /**
T 963  * Return the mailboxlist as html_select object
964  *
965  * @param array Named parameters
966  * @return object html_select HTML drop-down object
967  */
968 function rcmail_mailbox_select($p = array())
969 {
970   global $RCMAIL;
971   
64f20d 972   $p += array('maxlength' => 100, 'relanames' => false);
cb3538 973   $a_mailboxes = array();
T 974   
975   foreach ($RCMAIL->imap->list_mailboxes() as $folder)
976     rcmail_build_folder_tree($a_mailboxes, $folder, $RCMAIL->imap->get_hierarchy_delimiter());
977
978   $select = new html_select($p);
979   
980   if ($p['noselection'])
981     $select->add($p['noselection'], '');
982     
64f20d 983   rcmail_render_folder_tree_select($a_mailboxes, $mbox, $p['maxlength'], $select, $p['realnames']);
cb3538 984   
T 985   return $select;
986 }
93be5b 987
S 988
6d969b 989 /**
T 990  * Create a hierarchical array of the mailbox list
991  * @access private
992  */
93be5b 993 function rcmail_build_folder_tree(&$arrFolders, $folder, $delm='/', $path='')
f89f03 994 {
93be5b 995   $pos = strpos($folder, $delm);
f89f03 996   if ($pos !== false) {
93be5b 997     $subFolders = substr($folder, $pos+1);
S 998     $currentFolder = substr($folder, 0, $pos);
f89f03 999     $virtual = !isset($arrFolders[$currentFolder]);
T 1000   }
1001   else {
93be5b 1002     $subFolders = false;
S 1003     $currentFolder = $folder;
f89f03 1004     $virtual = false;
T 1005   }
93be5b 1006
S 1007   $path .= $currentFolder;
1008
f89f03 1009   if (!isset($arrFolders[$currentFolder])) {
6d6e06 1010     $arrFolders[$currentFolder] = array(
T 1011       'id' => $path,
1012       'name' => rcube_charset_convert($currentFolder, 'UTF-7'),
f89f03 1013       'virtual' => $virtual,
6d6e06 1014       'folders' => array());
f89f03 1015   }
T 1016   else
1017     $arrFolders[$currentFolder]['virtual'] = $virtual;
93be5b 1018
S 1019   if (!empty($subFolders))
1020     rcmail_build_folder_tree($arrFolders[$currentFolder]['folders'], $subFolders, $delm, $path.$delm);
f89f03 1021 }
93be5b 1022   
S 1023
6d969b 1024 /**
T 1025  * Return html for a structured list &lt;ul&gt; for the mailbox tree
1026  * @access private
1027  */
f89f03 1028 function rcmail_render_folder_tree_html(&$arrFolders, &$mbox_name, &$jslist, $attrib, $nestLevel=0)
T 1029 {
25f80d 1030   global $RCMAIL, $CONFIG;
f89f03 1031   
T 1032   $maxlength = intval($attrib['maxlength']);
1033   $realnames = (bool)$attrib['realnames'];
1034   $msgcounts = $RCMAIL->imap->get_cache('messagecount');
93be5b 1035
S 1036   $idx = 0;
1037   $out = '';
f89f03 1038   foreach ($arrFolders as $key => $folder) {
cb3538 1039     $zebra_class = (($nestLevel+1)*$idx) % 2 == 0 ? 'even' : 'odd';
6d6e06 1040     $title = null;
93be5b 1041
f89f03 1042     if (($folder_class = rcmail_folder_classname($folder['id'])) && !$realnames) {
cb3bad 1043       $foldername = rcube_label($folder_class);
f89f03 1044     }
T 1045     else {
93be5b 1046       $foldername = $folder['name'];
S 1047
1048       // shorten the folder name to a given length
f89f03 1049       if ($maxlength && $maxlength > 1) {
6f2f2d 1050         $fname = abbreviate_string($foldername, $maxlength);
93be5b 1051         if ($fname != $foldername)
6d6e06 1052           $title = $foldername;
93be5b 1053         $foldername = $fname;
S 1054       }
f89f03 1055     }
93be5b 1056
S 1057     // make folder name safe for ids and class names
6d6e06 1058     $folder_id = asciiwords($folder['id'], true);
T 1059     $classes = array('mailbox');
93be5b 1060
S 1061     // set special class for Sent, Drafts, Trash and Junk
1062     if ($folder['id']==$CONFIG['sent_mbox'])
6d6e06 1063       $classes[] = 'sent';
93be5b 1064     else if ($folder['id']==$CONFIG['drafts_mbox'])
6d6e06 1065       $classes[] = 'drafts';
93be5b 1066     else if ($folder['id']==$CONFIG['trash_mbox'])
6d6e06 1067       $classes[] = 'trash';
93be5b 1068     else if ($folder['id']==$CONFIG['junk_mbox'])
6d6e06 1069       $classes[] = 'junk';
T 1070     else
1071       $classes[] = asciiwords($folder_class ? $folder_class : strtolower($folder['id']), true);
1072       
1073     $classes[] = $zebra_class;
1074     
1075     if ($folder['id'] == $mbox_name)
1076       $classes[] = 'selected';
93be5b 1077
f5aa16 1078     $collapsed = preg_match('/&'.rawurlencode($folder['id']).'&/', $RCMAIL->config->get('collapsed_folders'));
f89f03 1079     $unread = $msgcounts ? intval($msgcounts[$folder['id']]['UNSEEN']) : 0;
T 1080     
1081     if ($folder['virtual'])
1082       $classes[] = 'virtual';
1083     else if ($unread)
1084       $classes[] = 'unread';
f5aa16 1085
6d6e06 1086     $js_name = JQ($folder['id']);
f89f03 1087     $html_name = Q($foldername . ($unread ? " ($unread)" : ''));
T 1088     $link_attrib = $folder['virtual'] ? array() : array(
1089       'href' => rcmail_url('', array('_mbox' => $folder['id'])),
1090       'onclick' => sprintf("return %s.command('list','%s',this)", JS_OBJECT_NAME, $js_name),
1091       'title' => $title,
1092     );
1093
6d6e06 1094     $out .= html::tag('li', array(
T 1095         'id' => "rcmli".$folder_id,
1096         'class' => join(' ', $classes),
1097         'noclose' => true),
f89f03 1098       html::a($link_attrib, $html_name) .
e1eb70 1099       (!empty($folder['folders']) ? html::div(array(
T 1100         'class' => ($collapsed ? 'collapsed' : 'expanded'),
1101         'style' => "position:absolute",
1102         'onclick' => sprintf("%s.command('collapse-folder', '%s')", JS_OBJECT_NAME, $js_name)
1103       ), '&nbsp;') : ''));
6d6e06 1104     
f89f03 1105     $jslist[$folder_id] = array('id' => $folder['id'], 'name' => $foldername, 'virtual' => $folder['virtual']);
T 1106     
1107     if (!empty($folder['folders'])) {
1108       $out .= html::tag('ul', array('style' => ($collapsed ? "display:none;" : null)),
1109         rcmail_render_folder_tree_html($folder['folders'], $mbox_name, $jslist, $attrib, $nestLevel+1));
1110     }
93be5b 1111
S 1112     $out .= "</li>\n";
1113     $idx++;
f89f03 1114   }
93be5b 1115
S 1116   return $out;
f89f03 1117 }
93be5b 1118
S 1119
6d969b 1120 /**
T 1121  * Return html for a flat list <select> for the mailbox tree
1122  * @access private
1123  */
64f20d 1124 function rcmail_render_folder_tree_select(&$arrFolders, &$mbox_name, $maxlength, &$select, $realnames=false, $nestLevel=0)
93be5b 1125   {
S 1126   $idx = 0;
1127   $out = '';
1128   foreach ($arrFolders as $key=>$folder)
1129     {
64f20d 1130     if (!$realnames && ($folder_class = rcmail_folder_classname($folder['id'])))
cb3bad 1131       $foldername = rcube_label($folder_class);
93be5b 1132     else
S 1133       {
1134       $foldername = $folder['name'];
1135       
1136       // shorten the folder name to a given length
1137       if ($maxlength && $maxlength>1)
6f2f2d 1138         $foldername = abbreviate_string($foldername, $maxlength);
93be5b 1139       }
S 1140
6d6e06 1141     $select->add(str_repeat('&nbsp;', $nestLevel*4) . $foldername, $folder['id']);
93be5b 1142
S 1143     if (!empty($folder['folders']))
64f20d 1144       $out .= rcmail_render_folder_tree_select($folder['folders'], $mbox_name, $maxlength, $select, $realnames, $nestLevel+1);
93be5b 1145
S 1146     $idx++;
1147     }
1148
1149   return $out;
1150   }
1151
cb3bad 1152
T 1153 /**
1154  * Return internal name for the given folder if it matches the configured special folders
1155  * @access private
1156  */
1157 function rcmail_folder_classname($folder_id)
1158 {
1159   global $CONFIG;
1160
1161   $cname = null;
1162   $folder_lc = strtolower($folder_id);
1163   
1164   // for these mailboxes we have localized labels and css classes
1165   foreach (array('inbox', 'sent', 'drafts', 'trash', 'junk') as $smbx)
1166   {
1167     if ($folder_lc == $smbx || $folder_id == $CONFIG[$smbx.'_mbox'])
1168       $cname = $smbx;
1169   }
1170   
1171   return $cname;
1172 }
1173
1174
fed22f 1175 /**
T 1176  * Try to localize the given IMAP folder name.
1177  * UTF-7 decode it in case no localized text was found
1178  *
1179  * @param string Folder name
1180  * @return string Localized folder name in UTF-8 encoding
1181  */
1182 function rcmail_localize_foldername($name)
1183 {
1184   if ($folder_class = rcmail_folder_classname($name))
1185     return rcube_label($folder_class);
1186   else
1187     return rcube_charset_convert($name, 'UTF-7');
1188 }
1189
1190
d1d2c4 1191 ?>