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