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