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