thomascube
2006-05-01 6204390af16bcf50f82da61a1aefc2ad0c0adf94
commit | author | age
4e17e6 1 <?php
T 2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/steps/mail/func.inc                                           |
6  |                                                                       |
7  | This file is part of the RoundCube Webmail client                     |
8  | Copyright (C) 2005, RoundCube Dev. - Switzerland                      |
30233b 9  | Licensed under the GNU GPL                                            |
4e17e6 10  |                                                                       |
T 11  | PURPOSE:                                                              |
12  |   Provide webmail functionality and GUI objects                       |
13  |                                                                       |
14  +-----------------------------------------------------------------------+
15  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16  +-----------------------------------------------------------------------+
17
18  $Id$
19
20 */
21
22 require_once('lib/html2text.inc');
23 require_once('lib/enriched.inc');
24
25
26 $EMAIL_ADDRESS_PATTERN = '/([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9]([a-z0-9\-][.]?)*[a-z0-9]\\.[a-z]{2,5})/i';
27
28 // set imap properties and session vars
29 if (strlen($_GET['_mbox']))
30   {
31   $IMAP->set_mailbox($_GET['_mbox']);
32   $_SESSION['mbox'] = $_GET['_mbox'];
33   }
34
35 if (strlen($_GET['_page']))
36   {
37   $IMAP->set_page($_GET['_page']);
38   $_SESSION['page'] = $_GET['_page'];
39   }
40
41
6a35c8 42 // set default sort col/order to session
T 43 if (!isset($_SESSION['sort_col']))
44   $_SESSION['sort_col'] = $CONFIG['message_sort_col'];
45 if (!isset($_SESSION['sort_order']))
46   $_SESSION['sort_order'] = $CONFIG['message_sort_order'];
47   
48
4e17e6 49 // define url for getting message parts
T 50 if (strlen($_GET['_uid']))
51   $GET_URL = sprintf('%s&_action=get&_mbox=%s&_uid=%d', $COMM_PATH, $IMAP->get_mailbox_name(), $_GET['_uid']);
52
53
54 // set current mailbox in client environment
55 $OUTPUT->add_script(sprintf("%s.set_env('mailbox', '%s');", $JS_OBJECT_NAME, $IMAP->get_mailbox_name()));
56
57
58 if ($CONFIG['trash_mbox'])
59   $OUTPUT->add_script(sprintf("%s.set_env('trash_mailbox', '%s');", $JS_OBJECT_NAME, $CONFIG['trash_mbox']));
60
61
62
63 // return the mailboxlist in HTML
64 function rcmail_mailbox_list($attrib)
65   {
66   global $IMAP, $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $COMM_PATH;
67   static $s_added_script = FALSE;
597170 68   static $a_mailboxes;
5e3512 69
T 70   // add some labels to client
71   rcube_add_label('purgefolderconfirm');
4e17e6 72   
15a9d1 73 // $mboxlist_start = rcube_timer();
T 74   
4e17e6 75   $type = $attrib['type'] ? $attrib['type'] : 'ul';
T 76   $add_attrib = $type=='select' ? array('style', 'class', 'id', 'name', 'onchange') :
77                                   array('style', 'class', 'id');
78                                   
79   if ($type=='ul' && !$attrib['id'])
80     $attrib['id'] = 'rcmboxlist';
81
82   // allow the following attributes to be added to the <ul> tag
83   $attrib_str = create_attrib_string($attrib, $add_attrib);
84  
85   $out = '<' . $type . $attrib_str . ">\n";
86   
87   // add no-selection option
88   if ($type=='select' && $attrib['noselection'])
89     $out .= sprintf('<option value="0">%s</option>'."\n",
90                     rcube_label($attrib['noselection']));
91   
92   // get mailbox list
93   $mbox = $IMAP->get_mailbox_name();
94   
95   // for these mailboxes we have localized labels
96   $special_mailboxes = array('inbox', 'sent', 'drafts', 'trash', 'junk');
97
597170 98
T 99   // build the folders tree
100   if (empty($a_mailboxes))
101     {
102     // get mailbox list
103     $a_folders = $IMAP->list_mailboxes();
104     $delimiter = $IMAP->get_hierarchy_delimiter();
105     $a_mailboxes = array();
15a9d1 106
T 107 // rcube_print_time($mboxlist_start, 'list_mailboxes()');
108
597170 109     foreach ($a_folders as $folder)
T 110       rcmail_build_folder_tree($a_mailboxes, $folder, $delimiter);
111     }
112
113 // var_dump($a_mailboxes);
114
115   if ($type=='select')
cd900d 116     $out .= rcmail_render_folder_tree_select($a_mailboxes, $special_mailboxes, $mbox, $attrib['maxlength']);
597170 117    else
cd900d 118     $out .= rcmail_render_folder_tree_html($a_mailboxes, $special_mailboxes, $mbox, $attrib['maxlength']);
15a9d1 119
T 120 // rcube_print_time($mboxlist_start, 'render_folder_tree()');
597170 121
4e17e6 122
T 123   if ($type=='ul')
124     $OUTPUT->add_script(sprintf("%s.gui_object('mailboxlist', '%s');", $JS_OBJECT_NAME, $attrib['id']));
125
126   return $out . "</$type>";
597170 127   }
T 128
129
130
131
132 // create a hierarchical array of the mailbox list
133 function rcmail_build_folder_tree(&$arrFolders, $folder, $delm='/', $path='')
134   {
135   $pos = strpos($folder, $delm);
136   if ($pos !== false)
137     {
138     $subFolders = substr($folder, $pos+1);
139     $currentFolder = substr($folder, 0, $pos);
140     }
141   else
142     {
143     $subFolders = false;
144     $currentFolder = $folder;
145     }
146
147   $path .= $currentFolder;
148
149   if (!isset($arrFolders[$currentFolder]))
150     {
151     $arrFolders[$currentFolder] = array('id' => $path,
3f9edb 152                                         'name' => rcube_charset_convert($currentFolder, 'UTF-7'),
597170 153                                         'folders' => array());
T 154     }
155
156   if (!empty($subFolders))
157     rcmail_build_folder_tree($arrFolders[$currentFolder]['folders'], $subFolders, $delm, $path.$delm);
158   }
159   
160
161 // return html for a structured list <ul> for the mailbox tree
cd900d 162 function rcmail_render_folder_tree_html(&$arrFolders, &$special, &$mbox, $maxlength, $nestLevel=0)
597170 163   {
8c2e58 164   global $JS_OBJECT_NAME, $COMM_PATH, $IMAP, $CONFIG, $OUTPUT;
597170 165
T 166   $idx = 0;
167   $out = '';
168   foreach ($arrFolders as $key => $folder)
169     {
170     $zebra_class = ($nestLevel*$idx)%2 ? 'even' : 'odd';
749b07 171     $title = '';
597170 172
T 173     $folder_lc = strtolower($folder['id']);
174     if (in_array($folder_lc, $special))
175       $foldername = rcube_label($folder_lc);
176     else
a95e0e 177       {
3f9edb 178       $foldername = $folder['name'];
597170 179
a95e0e 180       // shorten the folder name to a given length
T 181       if ($maxlength && $maxlength>1)
749b07 182         {
T 183         $fname = abbrevate_string($foldername, $maxlength);
184         if ($fname != $foldername)
185           $title = ' title="'.rep_specialchars_output($foldername, 'html', 'all').'"';
186         $foldername = $fname;
187         }
a95e0e 188       }
cd900d 189
a95e0e 190     // add unread message count display
15a9d1 191     if ($unread_count = $IMAP->messagecount($folder['id'], 'RECENT', ($folder['id']==$mbox)))
597170 192       $foldername .= sprintf(' (%d)', $unread_count);
8c2e58 193
6a35c8 194     // make folder name safe for ids and class names
T 195     $folder_css = $class_name = preg_replace('/[^a-z0-9\-_]/', '', $folder_lc);
597170 196
6a35c8 197     // set special class for Sent, Drafts, Trash and Junk
T 198     if ($folder['id']==$CONFIG['sent_mbox'])
199       $class_name = 'sent';
200     else if ($folder['id']==$CONFIG['drafts_mbox'])
201       $class_name = 'drafts';
202     else if ($folder['id']==$CONFIG['trash_mbox'])
203       $class_name = 'trash';
204     else if ($folder['id']==$CONFIG['junk_mbox'])
205       $class_name = 'junk';
206
8c2e58 207     $out .= sprintf('<li id="rcmbx%s" class="mailbox %s %s%s%s"><a href="%s&_mbox=%s"'.
T 208                     ' onclick="return %s.command(\'list\',\'%s\')"'.
209                     ' onmouseup="return %s.mbox_mouse_up(\'%s\')"%s>%s</a>',
6a35c8 210                     $folder_css,
T 211                     $class_name,
597170 212                     $zebra_class,
T 213                     $unread_count ? ' unread' : '',
214                     $folder['id']==$mbox ? ' selected' : '',
8c2e58 215                     $COMM_PATH,
T 216                     urlencode($folder['id']),
597170 217                     $JS_OBJECT_NAME,
T 218                     $folder['id'],
219                     $JS_OBJECT_NAME,
220                     $folder['id'],
749b07 221                     $title,
a95e0e 222                     rep_specialchars_output($foldername, 'html', 'all'));
597170 223
T 224     if (!empty($folder['folders']))
6a35c8 225       $out .= "\n<ul>\n" . rcmail_render_folder_tree_html($folder['folders'], $special, $mbox, $maxlength, $nestLevel+1) . "</ul>\n";
597170 226
T 227     $out .= "</li>\n";
228     $idx++;
229     }
230
231   return $out;
232   }
233
234
235 // return html for a flat list <select> for the mailbox tree
cd900d 236 function rcmail_render_folder_tree_select(&$arrFolders, &$special, &$mbox, $maxlength, $nestLevel=0)
597170 237   {
c03095 238   global $IMAP, $OUTPUT;
597170 239
T 240   $idx = 0;
241   $out = '';
242   foreach ($arrFolders as $key=>$folder)
243     {
7902df 244     $folder_lc = strtolower($folder['id']);
T 245     if (in_array($folder_lc, $special))
246       $foldername = rcube_label($folder_lc);
cd900d 247     else
a95e0e 248       {
3f9edb 249       $foldername = $folder['name'];
a95e0e 250       
T 251       // shorten the folder name to a given length
252       if ($maxlength && $maxlength>1)
253         $foldername = abbrevate_string($foldername, $maxlength);
254       }
cd900d 255
597170 256     $out .= sprintf('<option value="%s">%s%s</option>'."\n",
T 257                     $folder['id'],
258                     str_repeat('&nbsp;', $nestLevel*4),
a95e0e 259                     rep_specialchars_output($foldername, 'html', 'all'));
597170 260
T 261     if (!empty($folder['folders']))
cd900d 262       $out .= rcmail_render_folder_tree_select($folder['folders'], $special, $mbox, $maxlength, $nestLevel+1);
597170 263
T 264     $idx++;
265     }
266
267   return $out;
4e17e6 268   }
T 269
270
271 // return the message list as HTML table
272 function rcmail_message_list($attrib)
273   {
274   global $IMAP, $CONFIG, $COMM_PATH, $OUTPUT, $JS_OBJECT_NAME;
b076a4 275
4e17e6 276   $skin_path = $CONFIG['skin_path'];
T 277   $image_tag = '<img src="%s%s" alt="%s" border="0" />';
b076a4 278
f3b659 279   // check to see if we have some settings for sorting
6a35c8 280   $sort_col   = $_SESSION['sort_col'];
T 281   $sort_order = $_SESSION['sort_order'];
f3b659 282
4e17e6 283   // get message headers
f3b659 284   $a_headers = $IMAP->list_headers('', '', $sort_col, $sort_order);
4e17e6 285
T 286   // add id to message list table if not specified
287   if (!strlen($attrib['id']))
288     $attrib['id'] = 'rcubemessagelist';
289
290   // allow the following attributes to be added to the <table> tag
291   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
292
293   $out = '<table' . $attrib_str . ">\n";
e0ddd4 294
T 295
4e17e6 296   // define list of cols to be displayed
T 297   $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
b076a4 298   $a_sort_cols = array('subject', 'date', 'from', 'to');
4e17e6 299   
T 300   // show 'to' instead of from in sent messages
8c2e58 301   if (strtolower($IMAP->get_mailbox_name())=='sent' && ($f = array_search('from', $a_show_cols))
T 302       && !array_search('to', $a_show_cols))
4e17e6 303     $a_show_cols[$f] = 'to';
8c2e58 304   
e0ddd4 305   // add col definition
T 306   $out .= '<colgroup>';
01c86f 307   $out .= '<col class="icon" />';
e0ddd4 308
T 309   foreach ($a_show_cols as $col)
01c86f 310     $out .= sprintf('<col class="%s" />', $col);
e0ddd4 311
01c86f 312   $out .= '<col class="icon" />';
e0ddd4 313   $out .= "</colgroup>\n";
4e17e6 314
T 315   // add table title
316   $out .= "<thead><tr>\n<td class=\"icon\">&nbsp;</td>\n";
b076a4 317
f3b659 318   $javascript = '';
4e17e6 319   foreach ($a_show_cols as $col)
f3b659 320     {
T 321     // get column name
322     $col_name = rep_specialchars_output(rcube_label($col));
323
324     // make sort links
325     $sort = '';
1cded8 326     if ($IMAP->get_capability('sort') && in_array($col, $a_sort_cols))
f3b659 327       {
1cded8 328       // have buttons configured
T 329       if (!empty($attrib['sortdescbutton']) || !empty($attrib['sortascbutton']))
330         {
331         $sort = '&nbsp;&nbsp;';
b076a4 332
1cded8 333         // asc link
T 334         if (!empty($attrib['sortascbutton']))
335           {
336           $sort .= rcube_button(array('command' => 'sort',
337                                       'prop' => $col.'_ASC',
338                                       'image' => $attrib['sortascbutton'],
339                                       'align' => 'absmiddle',
340                                       'title' => 'sortasc'));
341           }       
b076a4 342         
1cded8 343         // desc link
T 344         if (!empty($attrib['sortdescbutton']))
345           {
346           $sort .= rcube_button(array('command' => 'sort',
347                                       'prop' => $col.'_DESC',
348                                       'image' => $attrib['sortdescbutton'],
349                                       'align' => 'absmiddle',
350                                       'title' => 'sortdesc'));        
351           }
352         }
353       // just add a link tag to the header
354       else
b076a4 355         {
1cded8 356         $col_name = sprintf('<a href="./#sort" onclick="return %s.command(\'sort\',\'%s\',this)" title="%s">%s</a>',
T 357                             $JS_OBJECT_NAME,
358                             $col,
359                             rcube_label('sortby'),
360                             $col_name);
b076a4 361         }
f3b659 362       }
b076a4 363       
T 364     $sort_class = $col==$sort_col ? " sorted$sort_order" : '';
f3b659 365
T 366     // put it all together
b076a4 367     $out .= '<td class="'.$col.$sort_class.'" id="rcmHead'.$col.'">' . "$col_name$sort</td>\n";    
f3b659 368     }
4e17e6 369
T 370   $out .= '<td class="icon">'.($attrib['attachmenticon'] ? sprintf($image_tag, $skin_path, $attrib['attachmenticon'], '') : '')."</td>\n";
371   $out .= "</tr></thead>\n<tbody>\n";
372
373   // no messages in this mailbox
374   if (!sizeof($a_headers))
375     {
122329 376     $out .= rep_specialchars_output(
S 377                 sprintf('<tr><td colspan="%d">%s</td></tr>',
4e17e6 378                    sizeof($a_show_cols)+2,
122329 379                    rcube_label('nomessagesfound')));
4e17e6 380     }
T 381
382
383   $a_js_message_arr = array();
384
385   // create row for each message
386   foreach ($a_headers as $i => $header)  //while (list($i, $header) = each($a_headers))
387     {
388     $message_icon = $attach_icon = '';
389     $js_row_arr = array();
390     $zebra_class = $i%2 ? 'even' : 'odd';
391
392     // set messag attributes to javascript array
393     if (!$header->seen)
394       $js_row_arr['unread'] = true;
395     if ($header->answered)
396       $js_row_arr['replied'] = true;
397
398     // set message icon    
399     if ($attrib['unreadicon'] && !$header->seen)
400       $message_icon = $attrib['unreadicon'];
401     else if ($attrib['repliedicon'] && $header->answered)
402       $message_icon = $attrib['repliedicon'];
403     else if ($attrib['messageicon'])
404       $message_icon = $attrib['messageicon'];
405     
406     // set attachment icon
407     if ($attrib['attachmenticon'] && preg_match("/multipart\/m/i", $header->ctype))
408       $attach_icon = $attrib['attachmenticon'];
409         
15a9d1 410     $out .= sprintf('<tr id="rcmrow%d" class="message%s%s %s">'."\n",
T 411                     $header->uid,
412                     $header->seen ? '' : ' unread',
413                     $header->deleted ? ' deleted' : '',
414                     $zebra_class);    
415     
4e17e6 416     $out .= sprintf("<td class=\"icon\">%s</td>\n", $message_icon ? sprintf($image_tag, $skin_path, $message_icon, '') : '');
T 417         
418     // format each col
419     foreach ($a_show_cols as $col)
420       {
421       if ($col=='from' || $col=='to')
422         $cont = rep_specialchars_output(rcmail_address_string($header->$col, 3, $attrib['addicon']));
423       else if ($col=='subject')
7902df 424         $cont = rep_specialchars_output($IMAP->decode_header($header->$col), 'html', 'all');
4e17e6 425       else if ($col=='size')
T 426         $cont = show_bytes($header->$col);
427       else if ($col=='date')
428         $cont = format_date($header->date); //date('m.d.Y G:i:s', strtotime($header->date));
429       else
7902df 430         $cont = rep_specialchars_output($header->$col, 'html', 'all');
4e17e6 431         
T 432       $out .= '<td class="'.$col.'">' . $cont . "</td>\n";
433       }
434
435     $out .= sprintf("<td class=\"icon\">%s</td>\n", $attach_icon ? sprintf($image_tag, $skin_path, $attach_icon, '') : '');
436     $out .= "</tr>\n";
437     
438     if (sizeof($js_row_arr))
439       $a_js_message_arr[$header->uid] = $js_row_arr;
440     }
441   
442   // complete message table
443   $out .= "</tbody></table>\n";
444   
445   
446   $message_count = $IMAP->messagecount();
447   
448   // set client env
9d04c2 449   $javascript .= sprintf("%s.gui_object('mailcontframe', '%s');\n", $JS_OBJECT_NAME, 'mailcontframe');
f3b659 450   $javascript .= sprintf("%s.gui_object('messagelist', '%s');\n", $JS_OBJECT_NAME, $attrib['id']);
4e17e6 451   $javascript .= sprintf("%s.set_env('messagecount', %d);\n", $JS_OBJECT_NAME, $message_count);
T 452   $javascript .= sprintf("%s.set_env('current_page', %d);\n", $JS_OBJECT_NAME, $IMAP->list_page);
453   $javascript .= sprintf("%s.set_env('pagecount', %d);\n", $JS_OBJECT_NAME, ceil($message_count/$IMAP->page_size));
b076a4 454   $javascript .= sprintf("%s.set_env('sort_col', '%s');\n", $JS_OBJECT_NAME, $sort_col);
T 455   $javascript .= sprintf("%s.set_env('sort_order', '%s');\n", $JS_OBJECT_NAME, $sort_order);
4e17e6 456   
T 457   if ($attrib['messageicon'])
458     $javascript .= sprintf("%s.set_env('messageicon', '%s%s');\n", $JS_OBJECT_NAME, $skin_path, $attrib['messageicon']);
459   if ($attrib['unreadicon'])
460     $javascript .= sprintf("%s.set_env('unreadicon', '%s%s');\n", $JS_OBJECT_NAME, $skin_path, $attrib['unreadicon']);
461   if ($attrib['repliedicon'])
462     $javascript .= sprintf("%s.set_env('repliedicon', '%s%s');\n", $JS_OBJECT_NAME, $skin_path, $attrib['repliedicon']);
463   if ($attrib['attachmenticon'])
464     $javascript .= sprintf("%s.set_env('attachmenticon', '%s%s');\n", $JS_OBJECT_NAME, $skin_path, $attrib['attachmenticon']);
465     
466   $javascript .= sprintf("%s.set_env('messages', %s);", $JS_OBJECT_NAME, array2js($a_js_message_arr));
467   
468   $OUTPUT->add_script($javascript);  
469   
470   return $out;
471   }
472
473
474
475
476 // return javascript commands to add rows to the message list
477 function rcmail_js_message_list($a_headers, $insert_top=FALSE)
478   {
479   global $CONFIG, $IMAP;
480
481   $commands = '';
482   $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
483
484   // show 'to' instead of from in sent messages
8c2e58 485   if (strtolower($IMAP->get_mailbox_name())=='sent' && ($f = array_search('from', $a_show_cols))
T 486       && !array_search('to', $a_show_cols))
4e17e6 487     $a_show_cols[$f] = 'to';
T 488
489   // loop through message headers
490   for ($n=0; $a_headers[$n]; $n++)
491     {
492     $header = $a_headers[$n];
493     $a_msg_cols = array();
494     $a_msg_flags = array();
495       
496     // format each col; similar as in rcmail_message_list()
497     foreach ($a_show_cols as $col)
498       {
499       if ($col=='from' || $col=='to')
500         $cont = rep_specialchars_output(rcmail_address_string($header->$col, 3));
501       else if ($col=='subject')
7902df 502         $cont = rep_specialchars_output($IMAP->decode_header($header->$col), 'html', 'all');
4e17e6 503       else if ($col=='size')
T 504         $cont = show_bytes($header->$col);
505       else if ($col=='date')
506         $cont = format_date($header->date); //date('m.d.Y G:i:s', strtotime($header->date));
507       else
7902df 508         $cont = rep_specialchars_output($header->$col, 'html', 'all');
4e17e6 509           
T 510       $a_msg_cols[$col] = $cont;
511       }
512
513     $a_msg_flags['unread'] = $header->seen ? 0 : 1;
514     $a_msg_flags['replied'] = $header->answered ? 1 : 0;
15a9d1 515     
T 516     if ($header->deleted)
517       $a_msg_flags['deleted'] = 1;
4e17e6 518   
15a9d1 519     $commands .= sprintf("this.add_message_row(%s, %s, %s, %b, %b);\n",
4e17e6 520                          $header->uid,
T 521                          array2js($a_msg_cols),
522                          array2js($a_msg_flags),
15a9d1 523                          preg_match("/multipart\/m/i", $header->ctype),
T 524                          $insert_top);
4e17e6 525     }
T 526
527   return $commands;
528   }
529
530
4647e1 531 // return code for search function
T 532 function rcmail_search_form($attrib)
533   {
534   global $OUTPUT, $JS_OBJECT_NAME;
535
536   // add some labels to client
537   rcube_add_label('searching');
538
539   $attrib['name'] = '_q';
540   
541   if (empty($attrib['id']))
542     $attrib['id'] = 'rcmqsearchbox';
543   
544   $input_q = new textfield($attrib);
545   $out = $input_q->show();
546
547   $OUTPUT->add_script(sprintf("%s.gui_object('qsearchbox', '%s');",
548                               $JS_OBJECT_NAME,
549                               $attrib['id']));
550
551   // add form tag around text field
552   if (empty($attrib['form']))
553     $out = sprintf('<form name="rcmqsearchform" action="./" '.
554                    'onsubmit="%s.command(\'search\');return false" style="display:inline;">%s</form>',
555                    $JS_OBJECT_NAME,
556                    $out);
557
558   return $out;
559   } 
560
4e17e6 561
T 562 function rcmail_messagecount_display($attrib)
563   {
564   global $IMAP, $OUTPUT, $JS_OBJECT_NAME;
565   
566   if (!$attrib['id'])
567     $attrib['id'] = 'rcmcountdisplay';
568
4647e1 569   $OUTPUT->add_script(sprintf("%s.gui_object('countdisplay', '%s');",
T 570                               $JS_OBJECT_NAME,
571                               $attrib['id']));
4e17e6 572
T 573   // allow the following attributes to be added to the <span> tag
574   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
575
576   
577   $out = '<span' . $attrib_str . '>';
578   $out .= rcmail_get_messagecount_text();
579   $out .= '</span>';
580   return $out;
581   }
582
583
58e360 584 function rcmail_quota_display($attrib)
T 585   {
586   global $IMAP, $OUTPUT, $JS_OBJECT_NAME;
587
588   if (!$attrib['id'])
589     $attrib['id'] = 'rcmquotadisplay';
590
591   $OUTPUT->add_script(sprintf("%s.gui_object('quotadisplay', '%s');", $JS_OBJECT_NAME, $attrib['id']));
592
593   // allow the following attributes to be added to the <span> tag
594   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
4647e1 595   
T 596   if (!$IMAP->get_capability('QUOTA'))
597     $quota_text = rcube_label('unknown');
598   else if (!($quota_text = $IMAP->get_quota()))
599     $quota_text = rcube_label('unlimited');
58e360 600
T 601   $out = '<span' . $attrib_str . '>';
4647e1 602   $out .= $quota_text;
58e360 603   $out .= '</span>';
T 604   return $out;
605   }
606
4e17e6 607
4647e1 608 function rcmail_get_messagecount_text($count=NULL, $page=NULL)
4e17e6 609   {
T 610   global $IMAP, $MESSAGE;
611   
612   if (isset($MESSAGE['index']))
613     {
614     return rcube_label(array('name' => 'messagenrof',
615                              'vars' => array('nr'  => $MESSAGE['index']+1,
4647e1 616                                              'count' => $count!==NULL ? $count : $IMAP->messagecount())));
4e17e6 617     }
31b2ce 618
4647e1 619   if ($page===NULL)
T 620     $page = $IMAP->list_page;
621     
622   $start_msg = ($page-1) * $IMAP->page_size + 1;
623   $max = $count!==NULL ? $count : $IMAP->messagecount();
4e17e6 624
T 625   if ($max==0)
626     $out = rcube_label('mailboxempty');
627   else
628     $out = rcube_label(array('name' => 'messagesfromto',
629                               'vars' => array('from'  => $start_msg,
630                                               'to'    => min($max, $start_msg + $IMAP->page_size - 1),
631                                               'count' => $max)));
632
cd900d 633   return rep_specialchars_output($out);
4e17e6 634   }
T 635
636
637 function rcmail_print_body($part, $safe=FALSE, $plain=FALSE) // $body, $ctype_primary='text', $ctype_secondary='plain', $encoding='7bit', $safe=FALSE, $plain=FALSE)
638   {
639   global $IMAP, $REMOTE_OBJECTS, $JS_OBJECT_NAME;
640
641   // extract part properties: body, ctype_primary, ctype_secondary, encoding, parameters
642   extract($part);
643   
644   $block = $plain ? '%s' : '%s'; //'<div style="display:block;">%s</div>';
58e360 645   $body = $IMAP->mime_decode($body, $encoding);  
4e17e6 646   $body = $IMAP->charset_decode($body, $parameters);
T 647
648   // text/html
649   if ($ctype_secondary=='html')
650     {
651     if (!$safe)  // remove remote images and scripts
652       {
653       $remote_patterns = array('/(src|background)=(["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)(\2|\s|>)/Ui',
654                            //  '/(src|background)=(["\']?)([\.\/]+[^"\'\s]+)(\2|\s|>)/Ui',
655                                '/(<base.*href=["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)([^<]*>)/i',
656                                '/(<link.*href=["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)([^<]*>)/i',
657                                '/url\s*\(["\']?([hftps]{3,5}:\/{2}[^"\'\s]+)["\']?\)/i',
658                                '/url\s*\(["\']?([\.\/]+[^"\'\s]+)["\']?\)/i',
659                                '/<script.+<\/script>/Umis');
660
7cc38e 661       $remote_replaces = array('',  // '\\1=\\2#\\4',
4e17e6 662                             // '\\1=\\2#\\4',
T 663                                '',
7cc38e 664                                '',  // '\\1#\\3',
4e17e6 665                                'none',
T 666                                'none',
667                                '');
668       
669       // set flag if message containes remote obejcts that where blocked
670       foreach ($remote_patterns as $pattern)
671         {
672         if (preg_match($pattern, $body))
673           {
674           $REMOTE_OBJECTS = TRUE;
675           break;
676           }
677         }
678
679       $body = preg_replace($remote_patterns, $remote_replaces, $body);
680       }
681
682     return sprintf($block, rep_specialchars_output($body, 'html', '', FALSE));
683     }
684
685   // text/enriched
686   if ($ctype_secondary=='enriched')
687     {
688     $body = enriched_to_html($body);
689     return sprintf($block, rep_specialchars_output($body, 'html'));
690     }
691   else
692     {
693     // make links and email-addresses clickable
694     $convert_patterns = $convert_replaces = $replace_strings = array();
695     
09941e 696     $url_chars = 'a-z0-9_\-\+\*\$\/&%=@#:';
4e17e6 697     $url_chars_within = '\?\.~,!';
T 698
699     $convert_patterns[] = "/([\w]+):\/\/([a-z0-9\-\.]+[a-z]{2,4}([$url_chars$url_chars_within]*[$url_chars])?)/ie";
20a1b3 700     $convert_replaces[] = "rcmail_str_replacement('<a href=\"\\1://\\2\" target=\"_blank\">\\1://\\2</a>', \$replace_strings)";
4e17e6 701
T 702     $convert_patterns[] = "/([^\/:]|\s)(www\.)([a-z0-9\-]{2,}[a-z]{2,4}([$url_chars$url_chars_within]*[$url_chars])?)/ie";
20a1b3 703     $convert_replaces[] = "rcmail_str_replacement('\\1<a href=\"http://\\2\\3\" target=\"_blank\">\\2\\3</a>', \$replace_strings)";
4e17e6 704     
T 705     $convert_patterns[] = '/([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9]([a-z0-9\-][.]?)*[a-z0-9]\\.[a-z]{2,5})/ie';
20a1b3 706     $convert_replaces[] = "rcmail_str_replacement('<a href=\"mailto:\\1\" onclick=\"return $JS_OBJECT_NAME.command(\'compose\',\'\\1\',this)\">\\1</a>', \$replace_strings)";
4e17e6 707
T 708     $body = wordwrap(trim($body), 80);
709     $body = preg_replace($convert_patterns, $convert_replaces, $body);
710
711     // split body into single lines
712     $a_lines = preg_split('/\r?\n/', $body);
713
714     // colorize quoted parts
715     for($n=0; $n<sizeof($a_lines); $n++)
716       {
717       $line = $a_lines[$n];
718
719       if ($line{2}=='>')
720         $color = 'red';
721       else if ($line{1}=='>')
722         $color = 'green';
723       else if ($line{0}=='>')
724         $color = 'blue';
725       else
726         $color = FALSE;
727
728       $line = rep_specialchars_output($line, 'html', 'replace', FALSE);
729         
730       if ($color)
731         $a_lines[$n] = sprintf('<font color="%s">%s</font>', $color, $line);
732       else
733         $a_lines[$n] = $line;
734       }
735
736     // insert the links for urls and mailtos
737     $body = preg_replace("/##string_replacement\{([0-9]+)\}##/e", "\$replace_strings[\\1]", join("\n", $a_lines));
738     
739     return sprintf($block, "<pre>\n".$body."\n</pre>");
740     }
741   }
742
743
744
745 // add a string to the replacement array and return a replacement string
746 function rcmail_str_replacement($str, &$rep)
747   {
748   static $count = 0;
749   $rep[$count] = stripslashes($str);
750   return "##string_replacement{".($count++)."}##";
751   }
752
753
754 function rcmail_parse_message($structure, $arg=array(), $recursive=FALSE)
755   {
756   global $IMAP;
757   static $sa_inline_objects = array();
758
759   // arguments are: (bool)$prefer_html, (string)$get_url
760   extract($arg);
761
762   $a_attachments = array();
763   $a_return_parts = array();
764   $out = '';
765
766   $message_ctype_primary = strtolower($structure->ctype_primary);
767   $message_ctype_secondary = strtolower($structure->ctype_secondary);
768
769   // show message headers
770   if ($recursive && is_array($structure->headers) && isset($structure->headers['subject']))
771     $a_return_parts[] = array('type' => 'headers',
772                               'headers' => $structure->headers);
773
774   // print body if message doesn't have multiple parts
775   if ($message_ctype_primary=='text')
776     {
777     $a_return_parts[] = array('type' => 'content',
778                               'body' => $structure->body,
779                               'ctype_primary' => $message_ctype_primary,
780                               'ctype_secondary' => $message_ctype_secondary,
a95e0e 781                               'parameters' => $structure->ctype_parameters,
4e17e6 782                               'encoding' => $structure->headers['content-transfer-encoding']);
T 783     }
784
785   // message contains alternative parts
786   else if ($message_ctype_primary=='multipart' && $message_ctype_secondary=='alternative' && is_array($structure->parts))
787     {
788     // get html/plaintext parts
789     $plain_part = $html_part = $print_part = $related_part = NULL;
790     
791     foreach ($structure->parts as $p => $sub_part)
792       {
793       $sub_ctype_primary = strtolower($sub_part->ctype_primary);
794       $sub_ctype_secondary = strtolower($sub_part->ctype_secondary);
795
796       // check if sub part is 
797       if ($sub_ctype_primary=='text' && $sub_ctype_secondary=='plain')
798         $plain_part = $p;
799       else if ($sub_ctype_primary=='text' && $sub_ctype_secondary=='html')
800         $html_part = $p;
801       else if ($sub_ctype_primary=='text' && $sub_ctype_secondary=='enriched')
802         $enriched_part = $p;
803       else if ($sub_ctype_primary=='multipart' && $sub_ctype_secondary=='related')
804         $related_part = $p;
805       }
806
807     // parse related part (alternative part could be in here)
808     if ($related_part!==NULL && $prefer_html)
809       {
810       list($parts, $attachmnts) = rcmail_parse_message($structure->parts[$related_part], $arg, TRUE);
811       $a_return_parts = array_merge($a_return_parts, $parts);
812       $a_attachments = array_merge($a_attachments, $attachmnts);
813       }
814
815     // print html/plain part
816     else if ($html_part!==NULL && $prefer_html)
817       $print_part = $structure->parts[$html_part];
818     else if ($enriched_part!==NULL)
819       $print_part = $structure->parts[$enriched_part];
820     else if ($plain_part!==NULL)
821       $print_part = $structure->parts[$plain_part];
822
823     // show message body
824     if (is_object($print_part))
825       $a_return_parts[] = array('type' => 'content',
826                                 'body' => $print_part->body,
827                                 'ctype_primary' => strtolower($print_part->ctype_primary),
828                                 'ctype_secondary' => strtolower($print_part->ctype_secondary),
829                                 'parameters' => $print_part->ctype_parameters,
830                                 'encoding' => $print_part->headers['content-transfer-encoding']);
831     // show plaintext warning
832     else if ($html_part!==NULL)
833       $a_return_parts[] = array('type' => 'content',
834                                 'body' => rcube_label('htmlmessage'),
835                                 'ctype_primary' => 'text',
836                                 'ctype_secondary' => 'plain');
837                                 
838     // add html part as attachment
839     if ($html_part!==NULL && $structure->parts[$html_part]!==$print_part)
840       {
841       $html_part = $structure->parts[$html_part];
842       $a_attachments[] = array('filename' => rcube_label('htmlmessage'),
843                                'encoding' => $html_part->headers['content-transfer-encoding'],
844                                'mimetype' => 'text/html',
845                                'part_id'  => $html_part->mime_id,
846                                'size'     => strlen($IMAP->mime_decode($html_part->body, $html_part->headers['content-transfer-encoding'])));
847       }
848     }
849
850   // message contains multiple parts
851   else if ($message_ctype_primary=='multipart' && is_array($structure->parts))
852     {
853     foreach ($structure->parts as $mail_part)
854       {
855       $primary_type = strtolower($mail_part->ctype_primary);
856       $secondary_type = strtolower($mail_part->ctype_secondary);
857
858       // multipart/alternative
859       if ($primary_type=='multipart') // && ($secondary_type=='alternative' || $secondary_type=='mixed' || $secondary_type=='related'))
860         {
861         list($parts, $attachmnts) = rcmail_parse_message($mail_part, $arg, TRUE);
862
863         $a_return_parts = array_merge($a_return_parts, $parts);
864         $a_attachments = array_merge($a_attachments, $attachmnts);
865         }
866
867       // part text/[plain|html] OR message/delivery-status
58e360 868       else if (($primary_type=='text' && ($secondary_type=='plain' || $secondary_type=='html') && $mail_part->disposition!='attachment') ||
4e17e6 869                ($primary_type=='message' && $secondary_type=='delivery-status'))
T 870         {
871         $a_return_parts[] = array('type' => 'content',
872                                   'body' => $mail_part->body,
873                                   'ctype_primary' => $primary_type,
874                                   'ctype_secondary' => $secondary_type,
a95e0e 875                                   'parameters' => $mail_part->ctype_parameters,
4e17e6 876                                   'encoding' => $mail_part->headers['content-transfer-encoding']);
T 877         }
878
879       // part message/*
880       else if ($primary_type=='message')
881         {
882         /* don't parse headers here; they're parsed within the recursive call to rcmail_parse_message()
883         if ($mail_part->parts[0]->headers)
884           $a_return_parts[] = array('type' => 'headers',
885                                     'headers' => $mail_part->parts[0]->headers);
886         */
887                                       
888         list($parts, $attachmnts) = rcmail_parse_message($mail_part->parts[0], $arg, TRUE);
889
890         $a_return_parts = array_merge($a_return_parts, $parts);
891         $a_attachments = array_merge($a_attachments, $attachmnts);
892         }
893
894       // part is file/attachment
b595c9 895       else if ($mail_part->disposition=='attachment' || $mail_part->disposition=='inline' || $mail_part->headers['content-id'] ||
2e2fe0 896                (empty($mail_part->disposition) && ($mail_part->d_parameters['filename'] || $mail_part->ctype_parameters['name'])))
4e17e6 897         {
T 898         if ($message_ctype_secondary=='related' && $mail_part->headers['content-id'])
4b0f65 899           $sa_inline_objects[] = array('filename' => rcube_imap::decode_mime_string($mail_part->d_parameters['filename']),
4e17e6 900                                        'mimetype' => strtolower("$primary_type/$secondary_type"),
T 901                                        'part_id'  => $mail_part->mime_id,
902                                        'content_id' => preg_replace(array('/^</', '/>$/'), '', $mail_part->headers['content-id']));
903
904         else if ($mail_part->d_parameters['filename'])
4b0f65 905           $a_attachments[] = array('filename' => rcube_imap::decode_mime_string($mail_part->d_parameters['filename']),
4e17e6 906                                    'encoding' => strtolower($mail_part->headers['content-transfer-encoding']),
T 907                                    'mimetype' => strtolower("$primary_type/$secondary_type"),
908                                    'part_id'  => $mail_part->mime_id,
909                                    'size'     => strlen($IMAP->mime_decode($mail_part->body, $mail_part->headers['content-transfer-encoding'])) /*,
910                                    'content'  => $mail_part->body */);
911                                    
912         else if ($mail_part->ctype_parameters['name'])
4b0f65 913           $a_attachments[] = array('filename' => rcube_imap::decode_mime_string($mail_part->ctype_parameters['name']),
4e17e6 914                                    'encoding' => strtolower($mail_part->headers['content-transfer-encoding']),
T 915                                    'mimetype' => strtolower("$primary_type/$secondary_type"),
916                                    'part_id'  => $mail_part->mime_id,
917                                    'size'     => strlen($IMAP->mime_decode($mail_part->body, $mail_part->headers['content-transfer-encoding'])) /*,
918                                    'content'  => $mail_part->body */);
919                                    
f1bed7 920         else if ($mail_part->headers['content-description'])
S 921       $a_attachments[] = array('filename' => rcube_imap::decode_mime_string($mail_part->headers['content-description']),
922                      'encoding' => strtolower($mail_part->headers['content-transfer-encoding']),
923                                    'mimetype' => strtolower("$primary_type/$secondary_type"),
924                                    'part_id'  => $mail_part->mime_id,
925                                    'size'     => strlen($IMAP->mime_decode($mail_part->body, $mail_part->headers['content-transfer-encoding'])) /*,
926                                    'content'  => $mail_part->body */);
4e17e6 927         }
T 928       }
929
930
931     // if this was a related part try to resolve references
932     if ($message_ctype_secondary=='related' && sizeof($sa_inline_objects))
933       {
934       $a_replace_patters = array();
935       $a_replace_strings = array();
936         
937       foreach ($sa_inline_objects as $inline_object)
938         {
939         $a_replace_patters[] = 'cid:'.$inline_object['content_id'];
940         $a_replace_strings[] = sprintf($get_url, $inline_object['part_id']);
941         }
942       
943       foreach ($a_return_parts as $i => $return_part)
944         {
945         if ($return_part['type']!='content')
946           continue;
947
948         // decode body and replace cid:...
949         $a_return_parts[$i]['body'] = str_replace($a_replace_patters, $a_replace_strings, $IMAP->mime_decode($return_part['body'], $return_part['encoding']));
950         $a_return_parts[$i]['encoding'] = '7bit';
951         }
952       }
953     }
954     
955
956   // join all parts together
957   //$out .= join($part_delimiter, $a_return_parts);
958
959   return array($a_return_parts, $a_attachments);
960   }
961
962
963
964
965 // return table with message headers
966 function rcmail_message_headers($attrib, $headers=NULL)
967   {
968   global $IMAP, $OUTPUT, $MESSAGE;
969   static $sa_attrib;
970   
971   // keep header table attrib
972   if (is_array($attrib) && !$sa_attrib)
973     $sa_attrib = $attrib;
974   else if (!is_array($attrib) && is_array($sa_attrib))
975     $attrib = $sa_attrib;
976   
977   
978   if (!isset($MESSAGE))
979     return FALSE;
980
981   // get associative array of headers object
982   if (!$headers)
983     $headers = is_object($MESSAGE['headers']) ? get_object_vars($MESSAGE['headers']) : $MESSAGE['headers'];
984     
985   $header_count = 0;
986   
987   // allow the following attributes to be added to the <table> tag
988   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
989   $out = '<table' . $attrib_str . ">\n";
990
991   // show these headers
bde645 992   $standard_headers = array('subject', 'from', 'organization', 'to', 'cc', 'bcc', 'reply-to', 'date');
4e17e6 993   
T 994   foreach ($standard_headers as $hkey)
995     {
996     if (!$headers[$hkey])
997       continue;
998
b076a4 999     if ($hkey=='date' && !empty($headers[$hkey]))
4e17e6 1000       $header_value = format_date(strtotime($headers[$hkey]));
bde645 1001     else if (in_array($hkey, array('from', 'to', 'cc', 'bcc', 'reply-to')))
4e17e6 1002       $header_value = rep_specialchars_output(rcmail_address_string($IMAP->decode_header($headers[$hkey]), NULL, $attrib['addicon']));
T 1003     else
1004       $header_value = rep_specialchars_output($IMAP->decode_header($headers[$hkey]), '', 'all');
1005
1006     $out .= "\n<tr>\n";
1038d5 1007     $out .= '<td class="header-title">'.rep_specialchars_output(rcube_label($hkey)).":&nbsp;</td>\n";
4e17e6 1008     $out .= '<td class="'.$hkey.'" width="90%">'.$header_value."</td>\n</tr>";
T 1009     $header_count++;
1010     }
1011
1012   $out .= "\n</table>\n\n";
1013
1014   return $header_count ? $out : '';  
1015   }
1016
1017
1018
1019 function rcmail_message_body($attrib)
1020   {
1021   global $CONFIG, $OUTPUT, $MESSAGE, $GET_URL, $REMOTE_OBJECTS, $JS_OBJECT_NAME;
1022   
1023   if (!is_array($MESSAGE['parts']) && !$MESSAGE['body'])
1024     return '';
1025     
1026   if (!$attrib['id'])
1027     $attrib['id'] = 'rcmailMsgBody';
1028
1029   $safe_mode = (bool)$_GET['_safe'];
1030   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
1031   $out = '<div '. $attrib_str . ">\n";
1032   
1033   $header_attrib = array();
1034   foreach ($attrib as $attr => $value)
1035     if (preg_match('/^headertable([a-z]+)$/i', $attr, $regs))
1036       $header_attrib[$regs[1]] = $value;
1037
1038
1039   // this is an ecrypted message
1040   // -> create a plaintext body with the according message
1041   if (!sizeof($MESSAGE['parts']) && $MESSAGE['headers']->ctype=='multipart/encrypted')
1042     {
1043     $MESSAGE['parts'][0] = array('type' => 'content',
1044                                  'ctype_primary' => 'text',
1045                                  'ctype_secondary' => 'plain',
1046                                  'body' => rcube_label('encryptedmessage'));
1047     }
1048   
1049   if ($MESSAGE['parts'])
1050     {
1051     foreach ($MESSAGE['parts'] as $i => $part)
1052       {
1053       if ($part['type']=='headers')
1054         $out .= rcmail_message_headers(sizeof($header_attrib) ? $header_attrib : NULL, $part['headers']);
1055       else if ($part['type']=='content')
1056         {
a95e0e 1057         if (empty($part['parameters']) || empty($part['parameters']['charset']))
T 1058           $part['parameters']['charset'] = $MESSAGE['headers']->charset;
1059         
4e17e6 1060         // $body = rcmail_print_body($part['body'], $part['ctype_primary'], $part['ctype_secondary'], $part['encoding'], $safe_mode);
T 1061         $body = rcmail_print_body($part, $safe_mode);
1062         $out .= '<div class="message-part">';
a2f2c5 1063         
T 1064         if ($part['ctype_secondary']!='plain')
1065           $out .= rcmail_mod_html_body($body, $attrib['id']);
1066         else
1067           $out .= $body;
1068
4e17e6 1069         $out .= "</div>\n";
T 1070         }
1071       }
1072     }
1073   else
1074     $out .= $MESSAGE['body'];
1075
1076
1077   $ctype_primary = strtolower($MESSAGE['structure']->ctype_primary);
1078   $ctype_secondary = strtolower($MESSAGE['structure']->ctype_secondary);
1079   
1080   // list images after mail body
1081   if (get_boolean($attrib['showimages']) && $ctype_primary=='multipart' && $ctype_secondary=='mixed' &&
1082       sizeof($MESSAGE['attachments']) && !strstr($message_body, '<html') && strlen($GET_URL))
1083     {
1084     foreach ($MESSAGE['attachments'] as $attach_prop)
1085       {
1086       if (strpos($attach_prop['mimetype'], 'image/')===0)
1087         $out .= sprintf("\n<hr />\n<p align=\"center\"><img src=\"%s&_part=%s\" alt=\"%s\" title=\"%s\" /></p>\n",
1088                         $GET_URL, $attach_prop['part_id'],
1089                         $attach_prop['filename'],
1090                         $attach_prop['filename']);
1091       }
1092     }
1093   
1094   // tell client that there are blocked remote objects
1095   if ($REMOTE_OBJECTS && !$safe_mode)
1096     $OUTPUT->add_script(sprintf("%s.set_env('blockedobjects', true);", $JS_OBJECT_NAME));
1097
1098   $out .= "\n</div>";
1099   return $out;
1100   }
1101
1102
1103
1104 // modify a HTML message that it can be displayed inside a HTML page
1105 function rcmail_mod_html_body($body, $container_id)
1106   {
749b07 1107   // remove any null-byte characters before parsing
T 1108   $body = preg_replace('/\x00/', '', $body);
1109   
4e17e6 1110   $last_style_pos = 0;
T 1111   $body_lc = strtolower($body);
1112   
1113   // find STYLE tags
1114   while (($pos = strpos($body_lc, '<style', $last_style_pos)) && ($pos2 = strpos($body_lc, '</style>', $pos)))
1115     {
1116     $pos2 += 8;
1117     $body_pre = substr($body, 0, $pos);
1118     $styles = substr($body, $pos, $pos2-$pos);
1119     $body_post = substr($body, $pos2, strlen($body)-$pos2);
1120     
1121     // replace all css definitions with #container [def]
1122     $styles = rcmail_mod_css_styles($styles, $container_id);
1123     
1124     $body = $body_pre . $styles . $body_post;
1125     $last_style_pos = $pos2;
1126     }
1127
1128
1129   // remove SCRIPT tags
6a35c8 1130   foreach (array('script', 'applet', 'object', 'embed', 'iframe') as $tag)
4e17e6 1131     {
6a35c8 1132     while (($pos = strpos($body_lc, '<'.$tag)) && ($pos2 = strpos($body_lc, '</'.$tag.'>', $pos)))
T 1133       {
1134       $pos2 += 8;
1135       $body = substr($body, 0, $pos) . substr($body, $pos2, strlen($body)-$pos2);
1136       $body_lc = strtolower($body);
1137       }
4e17e6 1138     }
6a35c8 1139
T 1140   // replace event handlers on any object
1141   $body = preg_replace('/\s(on[a-z]+)=/im', ' __removed=', $body);  
4e17e6 1142
T 1143   // resolve <base href>
1144   $base_reg = '/(<base.*href=["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)([^<]*>)/i';
1145   if (preg_match($base_reg, $body, $regs))
1146     {
1147     $base_url = $regs[2];
1148     $body = preg_replace('/(src|background|href)=(["\']?)([\.\/]+[^"\'\s]+)(\2|\s|>)/Uie', "'\\1=\"'.make_absolute_url('\\3', '$base_url').'\"'", $body);
1149     $body = preg_replace('/(url\s*\()(["\']?)([\.\/]+[^"\'\)\s]+)(\2)\)/Uie', "'\\1\''.make_absolute_url('\\3', '$base_url').'\')'", $body);
1150     $body = preg_replace($base_reg, '', $body);
1151     }
1152
1153   // add comments arround html and other tags
1154   $out = preg_replace(array('/(<\/?html[^>]*>)/i',
1155                             '/(<\/?head[^>]*>)/i',
1156                             '/(<title[^>]*>.+<\/title>)/ui',
1157                             '/(<\/?meta[^>]*>)/i'),
1158                       '<!--\\1-->',
1159                       $body);
1160                       
1161   $out = preg_replace(array('/(<body[^>]*>)/i',
1162                             '/(<\/body>)/i'),
1163                       array('<div class="rcmBody">',
1164                             '</div>'),
1165                       $out);
1166
1167   
1168   return $out;
1169   }
1170
1171
1172
1173 // replace all css definitions with #container [def]
1174 function rcmail_mod_css_styles($source, $container_id)
1175   {
1176   $a_css_values = array();
1177   $last_pos = 0;
1178   
1179   // cut out all contents between { and }
1180   while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos)))
1181     {
1182     $key = sizeof($a_css_values);
1183     $a_css_values[$key] = substr($source, $pos+1, $pos2-($pos+1));
1184     $source = substr($source, 0, $pos+1) . "<<str_replacement[$key]>>" . substr($source, $pos2, strlen($source)-$pos2);
1185     $last_pos = $pos+2;
1186     }
1187   
1188   $styles = preg_replace('/(^\s*|,\s*)([a-z0-9\._][a-z0-9\.\-_]*)/im', "\\1#$container_id \\2", $source);
1189   $styles = preg_replace('/<<str_replacement\[([0-9]+)\]>>/e', "\$a_css_values[\\1]", $styles);
1190   
1191   // replace body definition because we also stripped off the <body> tag
1192   $styles = preg_replace("/$container_id\s+body/i", "$container_id div.rcmBody", $styles);
1193   
1194   return $styles;
1195   }
1196
1197
1198
1199 // return first text part of a message
1200 function rcmail_first_text_part($message_parts)
1201   {
1202   if (!is_array($message_parts))
1203     return FALSE;
1204     
1205   $html_part = NULL;
1206       
1207   // check all message parts
1208   foreach ($message_parts as $pid => $part)
1209     {
1210     $mimetype = strtolower($part->ctype_primary.'/'.$part->ctype_secondary);
1211     if ($mimetype=='text/plain')
1212       {
1213       $body = rcube_imap::mime_decode($part->body, $part->headers['content-transfer-encoding']);
1214       $body = rcube_imap::charset_decode($body, $part->ctype_parameters);
1215       return $body;
1216       }
1217     else if ($mimetype=='text/html')
1218       {
1219       $html_part = rcube_imap::mime_decode($part->body, $part->headers['content-transfer-encoding']);
1220       $html_part = rcube_imap::charset_decode($html_part, $part->ctype_parameters);
1221       }
1222     }
1223     
1224
1225   // convert HTML to plain text
1226   if ($html_part)
1227     {    
1228     // remove special chars encoding
1229     $trans = array_flip(get_html_translation_table(HTML_ENTITIES));
1230     $html_part = strtr($html_part, $trans);
1231
1232     // create instance of html2text class
1233     $txt = new html2text($html_part);
1234     return $txt->get_text();
1235     }
1236
1237   return FALSE;
1238   }
1239
1240
1241 // get source code of a specific message and cache it
1242 function rcmail_message_source($uid)
1243   {
1cded8 1244   global $IMAP, $DB, $CONFIG;
4e17e6 1245
1cded8 1246   // get message ID if uid is given
T 1247   $cache_key = $IMAP->mailbox.'.msg';
1248   $cached = $IMAP->get_cached_message($cache_key, $uid, FALSE);
1249   
1250   // message is cached in database
1251   if ($cached && !empty($cached->body))
1252     return $cached->body;
1253
1254   if (!$cached)
1255     $headers = $IMAP->get_headers($uid);
1256   else
1257     $headers = &$cached;
1258
749b07 1259   // create unique identifier based on message_id
T 1260   if (!empty($headers->messageID))
1261     $message_id = md5($headers->messageID);
1262   else
1263     $message_id = md5($headers->uid.'@'.$_SESSION['imap_host']);
4e17e6 1264   
1cded8 1265   $temp_dir = $CONFIG['temp_dir'].(!eregi('\/$', $CONFIG['temp_dir']) ? '/' : '');
T 1266   $cache_dir = $temp_dir.$_SESSION['client_id'];
1267   $cache_path = $cache_dir.'/'.$message_id;
4e17e6 1268
1cded8 1269   // message is cached in temp dir
749b07 1270   if ($CONFIG['enable_caching'] && is_dir($cache_dir) && is_file($cache_path))
4e17e6 1271     {
1cded8 1272     if ($fp = fopen($cache_path, 'r'))
T 1273       {
1274       $msg_source = fread($fp, filesize($cache_path));
1275       fclose($fp);
1276       return $msg_source;
1277       }
1278     }
1279
1280
1281   // get message from server
1282   $msg_source = $IMAP->get_raw_body($uid);
749b07 1283   
T 1284   // return message source without caching
1285   if (!$CONFIG['enable_caching'])
1286     return $msg_source;
1287
1cded8 1288
T 1289   // let's cache the message body within the database
749b07 1290   if ($cached && ($CONFIG['db_max_length'] -300) > $headers->size)
1cded8 1291     {
T 1292     $DB->query("UPDATE ".get_table_name('messages')."
1293                 SET    body=?
1294                 WHERE  user_id=?
1295                 AND    cache_key=?
1296                 AND    uid=?",
1297                $msg_source,
1298                $_SESSION['user_id'],
1299                $cache_key,
1300                $uid);
1301
1302     return $msg_source;
1303     }
1304
1305
1306   // create dir for caching
1307   if (!is_dir($cache_dir))
1308     $dir = mkdir($cache_dir);
1309   else
1310     $dir = true;
1311
1312   // attempt to write a file with the message body    
1313   if ($dir && ($fp = fopen($cache_path, 'w')))
1314     {
1315     fwrite($fp, $msg_source);
1316     fclose($fp);
1317     }
1318   else
1319     {
1320     raise_error(array('code' => 403, 'type' => 'php', 'line' => __LINE__, 'file' => __FILE__, 
1321                       'message' => "Failed to write to temp dir"), TRUE, FALSE);
4e17e6 1322     }
T 1323
1324   return $msg_source;
1325   }
1326
1327
1328 // decode address string and re-format it as HTML links
1329 function rcmail_address_string($input, $max=NULL, $addicon=NULL)
1330   {
1331   global $IMAP, $PRINT_MODE, $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $EMAIL_ADDRESS_PATTERN;
1332   
1333   $a_parts = $IMAP->decode_address_list($input);
1334
1335   if (!sizeof($a_parts))
1336     return $input;
1337
1338   $c = count($a_parts);
1339   $j = 0;
1340   $out = '';
1341
1342   foreach ($a_parts as $part)
1343     {
1344     $j++;
1345     if ($PRINT_MODE)
a95e0e 1346       $out .= sprintf('%s &lt;%s&gt;', rep_specialchars_output($part['name']), $part['mailto']);
4e17e6 1347     else if (preg_match($EMAIL_ADDRESS_PATTERN, $part['mailto']))
T 1348       {
1349       $out .= sprintf('<a href="mailto:%s" onclick="return %s.command(\'compose\',\'%s\',this)" class="rcmContactAddress" title="%s">%s</a>',
1350                       $part['mailto'],
1351                       $JS_OBJECT_NAME,
1352                       $part['mailto'],
1353                       $part['mailto'],
a95e0e 1354                       rep_specialchars_output($part['name']));
4e17e6 1355                       
T 1356       if ($addicon)
1357         $out .= sprintf('&nbsp;<a href="#add" onclick="return %s.command(\'add-contact\',\'%s\',this)" title="%s"><img src="%s%s" alt="add" border="0" /></a>',
1358                         $JS_OBJECT_NAME,
1359                         urlencode($part['string']),
1360                         rcube_label('addtoaddressbook'),
1361                         $CONFIG['skin_path'],
1362                         $addicon);
1363       }
1364     else
1365       {
1366       if ($part['name'])
a95e0e 1367         $out .= rep_specialchars_output($part['name']);
4e17e6 1368       if ($part['mailto'])
T 1369         $out .= (strlen($out) ? ' ' : '') . sprintf('&lt;%s&gt;', $part['mailto']);
1370       }
1371       
1372     if ($c>$j)
1373       $out .= ','.($max ? '&nbsp;' : ' ');
1374         
1375     if ($max && $j==$max && $c>$j)
1376       {
1377       $out .= '...';
1378       break;
1379       }        
1380     }
1381     
1382   return $out;
1383   }
1384
1385
1386 function rcmail_message_part_controls()
1387   {
1388   global $CONFIG, $IMAP, $MESSAGE;
1389   
1390   if (!is_array($MESSAGE) || !is_array($MESSAGE['parts']) || !($_GET['_uid'] && $_GET['_part']) || !$MESSAGE['parts'][$_GET['_part']])
1391     return '';
1392     
1393   $part = $MESSAGE['parts'][$_GET['_part']];
1394   
1395   $attrib_str = create_attrib_string($attrib, array('id', 'class', 'style', 'cellspacing', 'cellpadding', 'border', 'summary'));
1396   $out = '<table '. $attrib_str . ">\n";
1397   
1398   $filename = $part->d_parameters['filename'] ? $part->d_parameters['filename'] : $part->ctype_parameters['name'];
1399   $filesize = strlen($IMAP->mime_decode($part->body, $part->headers['content-transfer-encoding']));
1400   
1401   if ($filename)
1402     {
1403     $out .= sprintf('<tr><td class="title">%s</td><td>%s</td><td>[<a href="./?%s">%s</a>]</tr>'."\n",
1404                     rcube_label('filename'),
1405                     rep_specialchars_output($filename),
1406                     str_replace('_frame=', '_download=', $_SERVER['QUERY_STRING']),
1407                     rcube_label('download'));
1408     }
1409     
1410   if ($filesize)
1411     $out .= sprintf('<tr><td class="title">%s</td><td>%s</td></tr>'."\n",
1412                     rcube_label('filesize'),
1413                     show_bytes($filesize));
1414   
1415   $out .= "\n</table>";
1416   
1417   return $out;
1418   }
1419
1420
1421
1422 function rcmail_message_part_frame($attrib)
1423   {
1424   global $MESSAGE;
1425   
1426   $part = $MESSAGE['parts'][$_GET['_part']];
1427   $ctype_primary = strtolower($part->ctype_primary);
1428
1429   $attrib['src'] = './?'.str_replace('_frame=', ($ctype_primary=='text' ? '_show=' : '_preload='), $_SERVER['QUERY_STRING']);
1430
1431   $attrib_str = create_attrib_string($attrib, array('id', 'class', 'style', 'src', 'width', 'height'));
1432   $out = '<iframe '. $attrib_str . "></ifame>";
1433     
1434   return $out;
1435   }
1436
1437
597170 1438 // create temp dir for attachments
T 1439 function rcmail_create_compose_tempdir()
1440   {
1441   global $CONFIG;
1442   
1443   if ($_SESSION['compose']['temp_dir'])
1444     return $_SESSION['compose']['temp_dir'];
1445   
1446   if (!empty($CONFIG['temp_dir']))
1447     $temp_dir = $CONFIG['temp_dir'].(!eregi('\/$', $CONFIG['temp_dir']) ? '/' : '').$_SESSION['compose']['id'];
1448
1449   // create temp-dir for uploaded attachments
1450   if (!empty($CONFIG['temp_dir']) && is_writeable($CONFIG['temp_dir']))
1451     {
1452     mkdir($temp_dir);
1453     $_SESSION['compose']['temp_dir'] = $temp_dir;
1454     }
1455
1456   return $_SESSION['compose']['temp_dir'];
1457   }
1458
4e17e6 1459
T 1460 // clear message composing settings
1461 function rcmail_compose_cleanup()
1462   {
1463   if (!isset($_SESSION['compose']))
1464     return;
1465   
1466   // remove attachment files from temp dir
1467   if (is_array($_SESSION['compose']['attachments']))
1468     foreach ($_SESSION['compose']['attachments'] as $attachment)
15a9d1 1469       @unlink($attachment['path']);
4e17e6 1470
T 1471   // kill temp dir
1472   if ($_SESSION['compose']['temp_dir'])
15a9d1 1473     @rmdir($_SESSION['compose']['temp_dir']);
4e17e6 1474   
T 1475   unset($_SESSION['compose']);
1476   }
1477   
1478   
1479 ?>