svncommit
2006-11-21 84f9312e1d17725db6040554a993db38292d46bd
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
8c2e58 516   if (strtolower($IMAP->get_mailbox_name())=='sent' && ($f = array_search('from', $a_show_cols))
T 517       && !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
4647e1 561 // return code for search function
T 562 function rcmail_search_form($attrib)
563   {
564   global $OUTPUT, $JS_OBJECT_NAME;
565
566   // add some labels to client
567   rcube_add_label('searching');
568
569   $attrib['name'] = '_q';
570   
571   if (empty($attrib['id']))
572     $attrib['id'] = 'rcmqsearchbox';
573   
574   $input_q = new textfield($attrib);
575   $out = $input_q->show();
576
577   $OUTPUT->add_script(sprintf("%s.gui_object('qsearchbox', '%s');",
578                               $JS_OBJECT_NAME,
579                               $attrib['id']));
580
581   // add form tag around text field
582   if (empty($attrib['form']))
583     $out = sprintf('<form name="rcmqsearchform" action="./" '.
584                    'onsubmit="%s.command(\'search\');return false" style="display:inline;">%s</form>',
585                    $JS_OBJECT_NAME,
586                    $out);
587
588   return $out;
589   } 
590
4e17e6 591
T 592 function rcmail_messagecount_display($attrib)
593   {
594   global $IMAP, $OUTPUT, $JS_OBJECT_NAME;
595   
596   if (!$attrib['id'])
597     $attrib['id'] = 'rcmcountdisplay';
598
4647e1 599   $OUTPUT->add_script(sprintf("%s.gui_object('countdisplay', '%s');",
T 600                               $JS_OBJECT_NAME,
601                               $attrib['id']));
4e17e6 602
T 603   // allow the following attributes to be added to the <span> tag
604   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
605
606   
607   $out = '<span' . $attrib_str . '>';
608   $out .= rcmail_get_messagecount_text();
609   $out .= '</span>';
610   return $out;
611   }
612
613
58e360 614 function rcmail_quota_display($attrib)
T 615   {
3ea0e3 616   global $IMAP, $OUTPUT, $JS_OBJECT_NAME, $COMM_PATH;
58e360 617
T 618   if (!$attrib['id'])
619     $attrib['id'] = 'rcmquotadisplay';
620
621   $OUTPUT->add_script(sprintf("%s.gui_object('quotadisplay', '%s');", $JS_OBJECT_NAME, $attrib['id']));
622
623   // allow the following attributes to be added to the <span> tag
624   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
3ea0e3 625
4647e1 626   if (!$IMAP->get_capability('QUOTA'))
T 627     $quota_text = rcube_label('unknown');
3ea0e3 628   else if ($quota = $IMAP->get_quota())
T 629     {
630     $quota_text = sprintf("%s / %s (%.0f%%)",
631                           show_bytes($quota["used"] * 1024),
632                           show_bytes($quota["total"] * 1024),
633                           $quota["percent"]);
634
635     // show quota as image (by Brett Patterson)
636     if ($attrib['display'] == 'image' && function_exists('imagegif'))
637       {
fda695 638       $attrib += array('width' => 100, 'height' => 14);
T 639       $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 640                             $COMM_PATH,
T 641                             $quota['used'], $quota['total'],
fda695 642                             $attrib['width'], $attrib['height'],
T 643                             $attrib['width'], $attrib['height'],
644                             $quota_text,
645                             show_bytes($quota["used"] * 1024),
646                             show_bytes($quota["total"] * 1024));
3ea0e3 647       }
T 648     }
649   else
4647e1 650     $quota_text = rcube_label('unlimited');
3ea0e3 651     
58e360 652
T 653   $out = '<span' . $attrib_str . '>';
4647e1 654   $out .= $quota_text;
58e360 655   $out .= '</span>';
T 656   return $out;
657   }
658
4e17e6 659
4647e1 660 function rcmail_get_messagecount_text($count=NULL, $page=NULL)
4e17e6 661   {
T 662   global $IMAP, $MESSAGE;
663   
664   if (isset($MESSAGE['index']))
665     {
666     return rcube_label(array('name' => 'messagenrof',
667                              'vars' => array('nr'  => $MESSAGE['index']+1,
4647e1 668                                              'count' => $count!==NULL ? $count : $IMAP->messagecount())));
4e17e6 669     }
31b2ce 670
4647e1 671   if ($page===NULL)
T 672     $page = $IMAP->list_page;
673     
674   $start_msg = ($page-1) * $IMAP->page_size + 1;
675   $max = $count!==NULL ? $count : $IMAP->messagecount();
4e17e6 676
T 677   if ($max==0)
678     $out = rcube_label('mailboxempty');
679   else
680     $out = rcube_label(array('name' => 'messagesfromto',
681                               'vars' => array('from'  => $start_msg,
682                                               'to'    => min($max, $start_msg + $IMAP->page_size - 1),
683                                               'count' => $max)));
684
cd900d 685   return rep_specialchars_output($out);
4e17e6 686   }
T 687
688
8d4bcd 689 function rcmail_print_body($part, $safe=FALSE, $plain=FALSE)
4e17e6 690   {
T 691   global $IMAP, $REMOTE_OBJECTS, $JS_OBJECT_NAME;
692   
8d4bcd 693   $body = is_array($part->replaces) ? strtr($part->body, $part->replaces) : $part->body;
a0109c 694
4e17e6 695   // text/html
8d4bcd 696   if ($part->ctype_secondary=='html')
4e17e6 697     {
f7bfec 698     // remove charset specification in HTML message
T 699     $body = preg_replace('/charset=[a-z0-9\-]+/i', '', $body);
700
4e17e6 701     if (!$safe)  // remove remote images and scripts
T 702       {
ea206d 703       $remote_patterns = array('/<img\s+(.*)src=(["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)(\2|\s|>)/Ui',
T 704                                '/(src|background)=(["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)(\2|\s|>)/Ui',
4e17e6 705                                '/(<base.*href=["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)([^<]*>)/i',
T 706                                '/(<link.*href=["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)([^<]*>)/i',
707                                '/url\s*\(["\']?([hftps]{3,5}:\/{2}[^"\'\s]+)["\']?\)/i',
708                                '/url\s*\(["\']?([\.\/]+[^"\'\s]+)["\']?\)/i',
709                                '/<script.+<\/script>/Umis');
710
ea206d 711       $remote_replaces = array('<img \\1src=\\2./program/blank.gif\\4',
4e17e6 712                                '',
ea206d 713                                '',
T 714                                '',
4e17e6 715                                'none',
T 716                                'none',
717                                '');
718       
719       // set flag if message containes remote obejcts that where blocked
720       foreach ($remote_patterns as $pattern)
721         {
722         if (preg_match($pattern, $body))
723           {
724           $REMOTE_OBJECTS = TRUE;
725           break;
726           }
727         }
728
729       $body = preg_replace($remote_patterns, $remote_replaces, $body);
730       }
731
8d4bcd 732     return rep_specialchars_output($body, 'html', '', FALSE);
4e17e6 733     }
T 734
735   // text/enriched
8d4bcd 736   if ($part->ctype_secondary=='enriched')
4e17e6 737     {
8d4bcd 738     return rep_specialchars_output(enriched_to_html($body), 'html');
4e17e6 739     }
T 740   else
741     {
742     // make links and email-addresses clickable
743     $convert_patterns = $convert_replaces = $replace_strings = array();
744     
949dea 745     $url_chars = 'a-z0-9_\-\+\*\$\/&%=@#:;';
4e17e6 746     $url_chars_within = '\?\.~,!';
T 747
748     $convert_patterns[] = "/([\w]+):\/\/([a-z0-9\-\.]+[a-z]{2,4}([$url_chars$url_chars_within]*[$url_chars])?)/ie";
20a1b3 749     $convert_replaces[] = "rcmail_str_replacement('<a href=\"\\1://\\2\" target=\"_blank\">\\1://\\2</a>', \$replace_strings)";
4e17e6 750
T 751     $convert_patterns[] = "/([^\/:]|\s)(www\.)([a-z0-9\-]{2,}[a-z]{2,4}([$url_chars$url_chars_within]*[$url_chars])?)/ie";
20a1b3 752     $convert_replaces[] = "rcmail_str_replacement('\\1<a href=\"http://\\2\\3\" target=\"_blank\">\\2\\3</a>', \$replace_strings)";
4e17e6 753     
T 754     $convert_patterns[] = '/([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9]([a-z0-9\-][.]?)*[a-z0-9]\\.[a-z]{2,5})/ie';
20a1b3 755     $convert_replaces[] = "rcmail_str_replacement('<a href=\"mailto:\\1\" onclick=\"return $JS_OBJECT_NAME.command(\'compose\',\'\\1\',this)\">\\1</a>', \$replace_strings)";
10c92b 756     
T 757     if ($part->ctype_parameters['format'] != 'flowed')
758       $body = wordwrap(trim($body), 80);
4e17e6 759
T 760     $body = preg_replace($convert_patterns, $convert_replaces, $body);
761
762     // split body into single lines
763     $a_lines = preg_split('/\r?\n/', $body);
10c92b 764     $quote_level = 0;
4e17e6 765
T 766     // colorize quoted parts
767     for($n=0; $n<sizeof($a_lines); $n++)
768       {
769       $line = $a_lines[$n];
10c92b 770       $quotation = '';
T 771       $q = 0;
772       
773       if (preg_match('/^(>+\s*)/', $line, $regs))
774         {
775         $q = strlen(preg_replace('/\s/', '', $regs[1]));
776         $line = substr($line, strlen($regs[1]));
4e17e6 777
10c92b 778         if ($q > $quote_level)
T 779           $quotation = str_repeat('<blockquote>', $q - $quote_level);
780         else if ($q < $quote_level)
781           $quotation = str_repeat("</blockquote>", $quote_level - $q);
782         }
783       else if ($quote_level > 0)
784         $quotation = str_repeat("</blockquote>", $quote_level);
4e17e6 785
10c92b 786       $quote_level = $q;
T 787       $a_lines[$n] = $quotation . rep_specialchars_output($line, 'html', 'replace', FALSE);
4e17e6 788       }
T 789
790     // insert the links for urls and mailtos
791     $body = preg_replace("/##string_replacement\{([0-9]+)\}##/e", "\$replace_strings[\\1]", join("\n", $a_lines));
792     
ea206d 793     return "<div class=\"pre\">".$body."\n</div>";
4e17e6 794     }
T 795   }
796
797
798
799 // add a string to the replacement array and return a replacement string
800 function rcmail_str_replacement($str, &$rep)
801   {
802   static $count = 0;
803   $rep[$count] = stripslashes($str);
804   return "##string_replacement{".($count++)."}##";
805   }
806
807
8d4bcd 808 function rcmail_parse_message(&$structure, $arg=array(), $recursive=FALSE)
4e17e6 809   {
T 810   global $IMAP;
811   static $sa_inline_objects = array();
812
813   // arguments are: (bool)$prefer_html, (string)$get_url
814   extract($arg);
815
816   $a_attachments = array();
817   $a_return_parts = array();
818   $out = '';
819
820   $message_ctype_primary = strtolower($structure->ctype_primary);
821   $message_ctype_secondary = strtolower($structure->ctype_secondary);
822
823   // show message headers
824   if ($recursive && is_array($structure->headers) && isset($structure->headers['subject']))
8d4bcd 825     {
T 826     $c = new stdClass;
827     $c->type = 'headers';
828     $c->headers = &$structure->headers;
829     $a_return_parts[] = $c;
830     }
4e17e6 831
T 832   // print body if message doesn't have multiple parts
833   if ($message_ctype_primary=='text')
834     {
8d4bcd 835     $structure->type = 'content';
T 836     $a_return_parts[] = &$structure;
4e17e6 837     }
T 838
839   // message contains alternative parts
840   else if ($message_ctype_primary=='multipart' && $message_ctype_secondary=='alternative' && is_array($structure->parts))
841     {
842     // get html/plaintext parts
843     $plain_part = $html_part = $print_part = $related_part = NULL;
844     
845     foreach ($structure->parts as $p => $sub_part)
846       {
847       $sub_ctype_primary = strtolower($sub_part->ctype_primary);
848       $sub_ctype_secondary = strtolower($sub_part->ctype_secondary);
849
850       // check if sub part is 
851       if ($sub_ctype_primary=='text' && $sub_ctype_secondary=='plain')
852         $plain_part = $p;
853       else if ($sub_ctype_primary=='text' && $sub_ctype_secondary=='html')
854         $html_part = $p;
855       else if ($sub_ctype_primary=='text' && $sub_ctype_secondary=='enriched')
856         $enriched_part = $p;
857       else if ($sub_ctype_primary=='multipart' && $sub_ctype_secondary=='related')
858         $related_part = $p;
859       }
860
861     // parse related part (alternative part could be in here)
862     if ($related_part!==NULL && $prefer_html)
863       {
864       list($parts, $attachmnts) = rcmail_parse_message($structure->parts[$related_part], $arg, TRUE);
865       $a_return_parts = array_merge($a_return_parts, $parts);
866       $a_attachments = array_merge($a_attachments, $attachmnts);
867       }
868
869     // print html/plain part
870     else if ($html_part!==NULL && $prefer_html)
8d4bcd 871       $print_part = &$structure->parts[$html_part];
4e17e6 872     else if ($enriched_part!==NULL)
8d4bcd 873       $print_part = &$structure->parts[$enriched_part];
4e17e6 874     else if ($plain_part!==NULL)
8d4bcd 875       $print_part = &$structure->parts[$plain_part];
4e17e6 876
T 877     // show message body
878     if (is_object($print_part))
8d4bcd 879       {
T 880       $print_part->type = 'content';
881       $a_return_parts[] = $print_part;
882       }
4e17e6 883     // show plaintext warning
T 884     else if ($html_part!==NULL)
8d4bcd 885       {
T 886       $c = new stdClass;
887       $c->type = 'content';
888       $c->body = rcube_label('htmlmessage');
889       $c->ctype_primary = 'text';
890       $c->ctype_secondary = 'plain';
891       
892       $a_return_parts[] = $c;
893       }
4e17e6 894                                 
T 895     // add html part as attachment
896     if ($html_part!==NULL && $structure->parts[$html_part]!==$print_part)
897       {
8d4bcd 898       $html_part = &$structure->parts[$html_part];
T 899       $html_part->filename = rcube_label('htmlmessage');
900       $html_part->mimetype = 'text/html';
901       
902       $a_attachments[] = $html_part;
4e17e6 903       }
T 904     }
905
906   // message contains multiple parts
8d4bcd 907   else if (is_array($structure->parts) && !empty($structure->parts))
4e17e6 908     {
8d4bcd 909     for ($i=0; $i<count($structure->parts); $i++)
4e17e6 910       {
8d4bcd 911       $mail_part = &$structure->parts[$i];
4e17e6 912       $primary_type = strtolower($mail_part->ctype_primary);
T 913       $secondary_type = strtolower($mail_part->ctype_secondary);
914
915       // multipart/alternative
8d4bcd 916       if ($primary_type=='multipart')
4e17e6 917         {
T 918         list($parts, $attachmnts) = rcmail_parse_message($mail_part, $arg, TRUE);
919
920         $a_return_parts = array_merge($a_return_parts, $parts);
921         $a_attachments = array_merge($a_attachments, $attachmnts);
922         }
923
924       // part text/[plain|html] OR message/delivery-status
58e360 925       else if (($primary_type=='text' && ($secondary_type=='plain' || $secondary_type=='html') && $mail_part->disposition!='attachment') ||
4e17e6 926                ($primary_type=='message' && $secondary_type=='delivery-status'))
T 927         {
8d4bcd 928         $mail_part->type = 'content';
T 929         $a_return_parts[] = $mail_part;
4e17e6 930         }
T 931
932       // part message/*
933       else if ($primary_type=='message')
934         {
8d4bcd 935         list($parts, $attachmnts) = rcmail_parse_message($mail_part, $arg, TRUE);
T 936           
4e17e6 937         $a_return_parts = array_merge($a_return_parts, $parts);
T 938         $a_attachments = array_merge($a_attachments, $attachmnts);
939         }
940
941       // part is file/attachment
b595c9 942       else if ($mail_part->disposition=='attachment' || $mail_part->disposition=='inline' || $mail_part->headers['content-id'] ||
2e2fe0 943                (empty($mail_part->disposition) && ($mail_part->d_parameters['filename'] || $mail_part->ctype_parameters['name'])))
4e17e6 944         {
8d4bcd 945         // skip apple ressource files
T 946         if ($message_ctype_secondary=='appledouble' && $secondary_type=='applefile')
947           continue;
4e17e6 948
8d4bcd 949         // part belongs to a related message
T 950         if ($message_ctype_secondary=='related' && $mail_part->headers['content-id'])
951           {
952           $mail_part->filename = rcube_imap::decode_mime_string($mail_part->d_parameters['filename']);
953           $mail_part->content_id = preg_replace(array('/^</', '/>$/'), '', $mail_part->headers['content-id']);
954           $sa_inline_objects[] = $mail_part;
955           }
956         // is regular attachment
957         else if (($fname = $mail_part->d_parameters['filename']) ||
958                  ($fname = $mail_part->ctype_parameters['name']) ||
959                  ($fname = $mail_part->headers['content-description']))
960           {
961           $mail_part->filename = rcube_imap::decode_mime_string($fname);
962           $a_attachments[] = $mail_part;
963           }
4e17e6 964         }
T 965       }
966
967
968     // if this was a related part try to resolve references
969     if ($message_ctype_secondary=='related' && sizeof($sa_inline_objects))
970       {
8d4bcd 971       $a_replaces = array();
4e17e6 972         
T 973       foreach ($sa_inline_objects as $inline_object)
ea206d 974         $a_replaces['cid:'.$inline_object->content_id] = htmlspecialchars(sprintf($get_url, $inline_object->mime_id));
4e17e6 975       
8d4bcd 976       // add replace array to each content part
T 977       // (will be applied later when part body is available)
978       for ($i=0; $i<count($a_return_parts); $i++)
4e17e6 979         {
8d4bcd 980         if ($a_return_parts[$i]->type=='content')
T 981           $a_return_parts[$i]->replaces = $a_replaces;
4e17e6 982         }
T 983       }
984     }
985
986   return array($a_return_parts, $a_attachments);
987   }
988
989
990
991
992 // return table with message headers
993 function rcmail_message_headers($attrib, $headers=NULL)
994   {
995   global $IMAP, $OUTPUT, $MESSAGE;
996   static $sa_attrib;
997   
998   // keep header table attrib
999   if (is_array($attrib) && !$sa_attrib)
1000     $sa_attrib = $attrib;
1001   else if (!is_array($attrib) && is_array($sa_attrib))
1002     $attrib = $sa_attrib;
1003   
1004   
1005   if (!isset($MESSAGE))
1006     return FALSE;
1007
1008   // get associative array of headers object
1009   if (!$headers)
1010     $headers = is_object($MESSAGE['headers']) ? get_object_vars($MESSAGE['headers']) : $MESSAGE['headers'];
1011     
1012   $header_count = 0;
1013   
1014   // allow the following attributes to be added to the <table> tag
1015   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
1016   $out = '<table' . $attrib_str . ">\n";
1017
1018   // show these headers
bde645 1019   $standard_headers = array('subject', 'from', 'organization', 'to', 'cc', 'bcc', 'reply-to', 'date');
4e17e6 1020   
T 1021   foreach ($standard_headers as $hkey)
1022     {
1023     if (!$headers[$hkey])
1024       continue;
1025
b076a4 1026     if ($hkey=='date' && !empty($headers[$hkey]))
4e17e6 1027       $header_value = format_date(strtotime($headers[$hkey]));
bde645 1028     else if (in_array($hkey, array('from', 'to', 'cc', 'bcc', 'reply-to')))
bac7d1 1029       $header_value = rep_specialchars_output(rcmail_address_string($headers[$hkey], NULL, $attrib['addicon']));
4e17e6 1030     else
T 1031       $header_value = rep_specialchars_output($IMAP->decode_header($headers[$hkey]), '', 'all');
1032
1033     $out .= "\n<tr>\n";
1038d5 1034     $out .= '<td class="header-title">'.rep_specialchars_output(rcube_label($hkey)).":&nbsp;</td>\n";
4e17e6 1035     $out .= '<td class="'.$hkey.'" width="90%">'.$header_value."</td>\n</tr>";
T 1036     $header_count++;
1037     }
1038
1039   $out .= "\n</table>\n\n";
1040
1041   return $header_count ? $out : '';  
1042   }
1043
1044
1045
1046 function rcmail_message_body($attrib)
1047   {
8d4bcd 1048   global $CONFIG, $OUTPUT, $MESSAGE, $IMAP, $GET_URL, $REMOTE_OBJECTS, $JS_OBJECT_NAME;
4e17e6 1049   
T 1050   if (!is_array($MESSAGE['parts']) && !$MESSAGE['body'])
1051     return '';
1052     
1053   if (!$attrib['id'])
1054     $attrib['id'] = 'rcmailMsgBody';
1055
1056   $safe_mode = (bool)$_GET['_safe'];
1057   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
1058   $out = '<div '. $attrib_str . ">\n";
1059   
1060   $header_attrib = array();
1061   foreach ($attrib as $attr => $value)
1062     if (preg_match('/^headertable([a-z]+)$/i', $attr, $regs))
1063       $header_attrib[$regs[1]] = $value;
1064
1065
1066   // this is an ecrypted message
1067   // -> create a plaintext body with the according message
1068   if (!sizeof($MESSAGE['parts']) && $MESSAGE['headers']->ctype=='multipart/encrypted')
1069     {
8d4bcd 1070     $p = new stdClass;
T 1071     $p->type = 'content';
1072     $p->ctype_primary = 'text';
1073     $p->ctype_secondary = 'plain';
1074     $p->body = rcube_label('encryptedmessage');
1075     $MESSAGE['parts'][0] = $p;
4e17e6 1076     }
T 1077   
1078   if ($MESSAGE['parts'])
1079     {
1080     foreach ($MESSAGE['parts'] as $i => $part)
1081       {
8d4bcd 1082       if ($part->type=='headers')
T 1083         $out .= rcmail_message_headers(sizeof($header_attrib) ? $header_attrib : NULL, $part->headers);
1084       else if ($part->type=='content')
4e17e6 1085         {
8d4bcd 1086         if (empty($part->ctype_parameters) || empty($part->ctype_parameters['charset']))
2c9298 1087           $part->ctype_parameters['charset'] = $MESSAGE['headers']->charset;
a0109c 1088
8d4bcd 1089         // fetch part if not available
T 1090         if (!isset($part->body))
1091           $part->body = $IMAP->get_message_part($MESSAGE['UID'], $part->mime_id, $part);
a0109c 1092
4e17e6 1093         $body = rcmail_print_body($part, $safe_mode);
T 1094         $out .= '<div class="message-part">';
a2f2c5 1095         
8d4bcd 1096         if ($part->ctype_secondary != 'plain')
a2f2c5 1097           $out .= rcmail_mod_html_body($body, $attrib['id']);
T 1098         else
1099           $out .= $body;
1100
4e17e6 1101         $out .= "</div>\n";
T 1102         }
1103       }
1104     }
1105   else
1106     $out .= $MESSAGE['body'];
1107
1108
1109   $ctype_primary = strtolower($MESSAGE['structure']->ctype_primary);
1110   $ctype_secondary = strtolower($MESSAGE['structure']->ctype_secondary);
1111   
1112   // list images after mail body
1113   if (get_boolean($attrib['showimages']) && $ctype_primary=='multipart' && $ctype_secondary=='mixed' &&
1114       sizeof($MESSAGE['attachments']) && !strstr($message_body, '<html') && strlen($GET_URL))
1115     {
1116     foreach ($MESSAGE['attachments'] as $attach_prop)
1117       {
8d4bcd 1118       if (strpos($attach_prop->mimetype, 'image/')===0)
ea206d 1119         $out .= sprintf("\n<hr />\n<p align=\"center\"><img src=\"%s&amp;_part=%s\" alt=\"%s\" title=\"%s\" /></p>\n",
T 1120                         htmlspecialchars($GET_URL), $attach_prop->mime_id,
8d4bcd 1121                         $attach_prop->filename,
T 1122                         $attach_prop->filename);
4e17e6 1123       }
T 1124     }
1125   
1126   // tell client that there are blocked remote objects
1127   if ($REMOTE_OBJECTS && !$safe_mode)
1128     $OUTPUT->add_script(sprintf("%s.set_env('blockedobjects', true);", $JS_OBJECT_NAME));
1129
1130   $out .= "\n</div>";
1131   return $out;
1132   }
1133
1134
1135
1136 // modify a HTML message that it can be displayed inside a HTML page
1137 function rcmail_mod_html_body($body, $container_id)
1138   {
749b07 1139   // remove any null-byte characters before parsing
T 1140   $body = preg_replace('/\x00/', '', $body);
1141   
4e17e6 1142   $last_style_pos = 0;
T 1143   $body_lc = strtolower($body);
1144   
1145   // find STYLE tags
1146   while (($pos = strpos($body_lc, '<style', $last_style_pos)) && ($pos2 = strpos($body_lc, '</style>', $pos)))
1147     {
ea206d 1148     $pos = strpos($body_lc, '>', $pos)+1;
T 1149
4e17e6 1150     // replace all css definitions with #container [def]
ea206d 1151     $styles = rcmail_mod_css_styles(substr($body, $pos, $pos2-$pos), $container_id);
T 1152
1153     $body = substr($body, 0, $pos) . $styles . substr($body, $pos2);    
4e17e6 1154     $last_style_pos = $pos2;
T 1155     }
1156
1157
1158   // remove SCRIPT tags
6a35c8 1159   foreach (array('script', 'applet', 'object', 'embed', 'iframe') as $tag)
4e17e6 1160     {
6a35c8 1161     while (($pos = strpos($body_lc, '<'.$tag)) && ($pos2 = strpos($body_lc, '</'.$tag.'>', $pos)))
T 1162       {
1163       $pos2 += 8;
1164       $body = substr($body, 0, $pos) . substr($body, $pos2, strlen($body)-$pos2);
1165       $body_lc = strtolower($body);
1166       }
4e17e6 1167     }
6a35c8 1168
T 1169   // replace event handlers on any object
1170   $body = preg_replace('/\s(on[a-z]+)=/im', ' __removed=', $body);  
4e17e6 1171
T 1172   // resolve <base href>
1173   $base_reg = '/(<base.*href=["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)([^<]*>)/i';
1174   if (preg_match($base_reg, $body, $regs))
1175     {
1176     $base_url = $regs[2];
1177     $body = preg_replace('/(src|background|href)=(["\']?)([\.\/]+[^"\'\s]+)(\2|\s|>)/Uie', "'\\1=\"'.make_absolute_url('\\3', '$base_url').'\"'", $body);
1178     $body = preg_replace('/(url\s*\()(["\']?)([\.\/]+[^"\'\)\s]+)(\2)\)/Uie', "'\\1\''.make_absolute_url('\\3', '$base_url').'\')'", $body);
1179     $body = preg_replace($base_reg, '', $body);
1180     }
fe79b1 1181     
T 1182   // modify HTML links to open a new window if clicked
1183   $body = preg_replace('/<a\s+([^>]+)>/Uie', "rcmail_alter_html_link('\\1');", $body);
4e17e6 1184
T 1185   // add comments arround html and other tags
1186   $out = preg_replace(array('/(<\/?html[^>]*>)/i',
1187                             '/(<\/?head[^>]*>)/i',
fe79b1 1188                             '/(<title[^>]*>.*<\/title>)/Ui',
4e17e6 1189                             '/(<\/?meta[^>]*>)/i'),
T 1190                       '<!--\\1-->',
1191                       $body);
a0109c 1192
4e17e6 1193   $out = preg_replace(array('/(<body[^>]*>)/i',
T 1194                             '/(<\/body>)/i'),
1195                       array('<div class="rcmBody">',
1196                             '</div>'),
1197                       $out);
a0109c 1198
4e17e6 1199   return $out;
T 1200   }
1201
1202
fe79b1 1203 // parse link attributes and set correct target
T 1204 function rcmail_alter_html_link($in)
1205   {
1206   $attrib = parse_attrib_string($in);
1207
1208   if (stristr((string)$attrib['href'], 'mailto:'))
1209     $attrib['onclick'] = sprintf("return %s.command('compose','%s',this)",
1210                                  $GLOBALS['JS_OBJECT_NAME'],
1211                                  substr($attrib['href'], 7));
1212   else if (!empty($attrib['href']) && $attrib['href']{0}!='#')
1213     $attrib['target'] = '_blank';
1214   
1215   return '<a' . create_attrib_string($attrib, array('href', 'name', 'target', 'onclick', 'id', 'class', 'style', 'title')) . '>';
1216   }
1217
4e17e6 1218
T 1219 // replace all css definitions with #container [def]
1220 function rcmail_mod_css_styles($source, $container_id)
1221   {
1222   $a_css_values = array();
1223   $last_pos = 0;
1224   
1225   // cut out all contents between { and }
1226   while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos)))
1227     {
1228     $key = sizeof($a_css_values);
1229     $a_css_values[$key] = substr($source, $pos+1, $pos2-($pos+1));
1230     $source = substr($source, 0, $pos+1) . "<<str_replacement[$key]>>" . substr($source, $pos2, strlen($source)-$pos2);
1231     $last_pos = $pos+2;
1232     }
1233   
1234   $styles = preg_replace('/(^\s*|,\s*)([a-z0-9\._][a-z0-9\.\-_]*)/im', "\\1#$container_id \\2", $source);
1235   $styles = preg_replace('/<<str_replacement\[([0-9]+)\]>>/e', "\$a_css_values[\\1]", $styles);
1236   
1237   // replace body definition because we also stripped off the <body> tag
1238   $styles = preg_replace("/$container_id\s+body/i", "$container_id div.rcmBody", $styles);
1239   
1240   return $styles;
1241   }
1242
1243
a0109c 1244 function rcmail_has_html_part($message_parts)
S 1245 {
1246    if (!is_array($message_parts))
1247       return FALSE;
1248
1249    // check all message parts
1250    foreach ($message_parts as $pid => $part)
1251    {
1252       $mimetype = strtolower($part->ctype_primary.'/'.$part->ctype_secondary);
1253       if ($mimetype=='text/html')
1254       {
1255          return TRUE;
1256       }
1257    }
1258     
1259    return FALSE;
1260 }
1261
1262 // return first HTML part of a message
1263 function rcmail_first_html_part($message_struct)
1264   {
1265   global $IMAP;
1266
1267   if (!is_array($message_struct['parts']))
1268     return FALSE;
1269     
1270   $html_part = NULL;
1271
1272   // check all message parts
1273   foreach ($message_struct['parts'] as $pid => $part)
1274     {
1275     $mimetype = strtolower($part->ctype_primary.'/'.$part->ctype_secondary);
1276     if ($mimetype=='text/html')
1277       {
1278       $html_part = $IMAP->get_message_part($message_struct['UID'], $pid, $part);
1279       }
1280     }
1281
1282   if ($html_part)
1283     {
1284     // remove special chars encoding
1285     //$trans = array_flip(get_html_translation_table(HTML_ENTITIES));
1286     //$html_part = strtr($html_part, $trans);
1287
1288     return $html_part;
1289     }
1290
1291   return FALSE;
1292 }
1293
4e17e6 1294
T 1295 // return first text part of a message
8d4bcd 1296 function rcmail_first_text_part($message_struct)
4e17e6 1297   {
8d4bcd 1298   global $IMAP;
T 1299
e170b4 1300   if (empty($message_struct['parts']))
T 1301     return $message_struct['UID'] ? $IMAP->get_body($message_struct['UID']) : false;
1302
4e17e6 1303   // check all message parts
8d4bcd 1304   foreach ($message_struct['parts'] as $pid => $part)
4e17e6 1305     {
T 1306     $mimetype = strtolower($part->ctype_primary.'/'.$part->ctype_secondary);
8d4bcd 1307
4e17e6 1308     if ($mimetype=='text/plain')
8d4bcd 1309       return $IMAP->get_message_part($message_struct['UID'], $pid, $part);
T 1310
4e17e6 1311     else if ($mimetype=='text/html')
T 1312       {
8d4bcd 1313       $html_part = $IMAP->get_message_part($message_struct['UID'], $pid, $part);
T 1314       
1315       // remove special chars encoding
1316       $trans = array_flip(get_html_translation_table(HTML_ENTITIES));
1317       $html_part = strtr($html_part, $trans);
1318
1319       // create instance of html2text class
1320       $txt = new html2text($html_part);
1321       return $txt->get_text();
4e17e6 1322       }
T 1323     }
1324
1325   return FALSE;
1326   }
1327
1328
1329 // decode address string and re-format it as HTML links
1330 function rcmail_address_string($input, $max=NULL, $addicon=NULL)
1331   {
1332   global $IMAP, $PRINT_MODE, $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $EMAIL_ADDRESS_PATTERN;
1333   
1334   $a_parts = $IMAP->decode_address_list($input);
1335
1336   if (!sizeof($a_parts))
1337     return $input;
1338
1339   $c = count($a_parts);
1340   $j = 0;
1341   $out = '';
1342
1343   foreach ($a_parts as $part)
1344     {
1345     $j++;
1346     if ($PRINT_MODE)
a95e0e 1347       $out .= sprintf('%s &lt;%s&gt;', rep_specialchars_output($part['name']), $part['mailto']);
4e17e6 1348     else if (preg_match($EMAIL_ADDRESS_PATTERN, $part['mailto']))
T 1349       {
1350       $out .= sprintf('<a href="mailto:%s" onclick="return %s.command(\'compose\',\'%s\',this)" class="rcmContactAddress" title="%s">%s</a>',
1351                       $part['mailto'],
1352                       $JS_OBJECT_NAME,
1353                       $part['mailto'],
1354                       $part['mailto'],
a95e0e 1355                       rep_specialchars_output($part['name']));
4e17e6 1356                       
T 1357       if ($addicon)
1358         $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>',
1359                         $JS_OBJECT_NAME,
1360                         urlencode($part['string']),
1361                         rcube_label('addtoaddressbook'),
1362                         $CONFIG['skin_path'],
1363                         $addicon);
1364       }
1365     else
1366       {
1367       if ($part['name'])
a95e0e 1368         $out .= rep_specialchars_output($part['name']);
4e17e6 1369       if ($part['mailto'])
T 1370         $out .= (strlen($out) ? ' ' : '') . sprintf('&lt;%s&gt;', $part['mailto']);
1371       }
1372       
1373     if ($c>$j)
1374       $out .= ','.($max ? '&nbsp;' : ' ');
1375         
1376     if ($max && $j==$max && $c>$j)
1377       {
1378       $out .= '...';
1379       break;
1380       }        
1381     }
1382     
1383   return $out;
1384   }
1385
1386
1387 function rcmail_message_part_controls()
1388   {
1389   global $CONFIG, $IMAP, $MESSAGE;
1390   
1391   if (!is_array($MESSAGE) || !is_array($MESSAGE['parts']) || !($_GET['_uid'] && $_GET['_part']) || !$MESSAGE['parts'][$_GET['_part']])
1392     return '';
1393     
8d4bcd 1394   $part = &$MESSAGE['parts'][$_GET['_part']];
4e17e6 1395   
T 1396   $attrib_str = create_attrib_string($attrib, array('id', 'class', 'style', 'cellspacing', 'cellpadding', 'border', 'summary'));
1397   $out = '<table '. $attrib_str . ">\n";
1398   
1399   $filename = $part->d_parameters['filename'] ? $part->d_parameters['filename'] : $part->ctype_parameters['name'];
8d4bcd 1400   $filesize = $part->size;
4e17e6 1401   
T 1402   if ($filename)
1403     {
1404     $out .= sprintf('<tr><td class="title">%s</td><td>%s</td><td>[<a href="./?%s">%s</a>]</tr>'."\n",
1405                     rcube_label('filename'),
f7bfec 1406                     rep_specialchars_output(rcube_imap::decode_mime_string($filename)),
4e17e6 1407                     str_replace('_frame=', '_download=', $_SERVER['QUERY_STRING']),
T 1408                     rcube_label('download'));
1409     }
1410     
1411   if ($filesize)
1412     $out .= sprintf('<tr><td class="title">%s</td><td>%s</td></tr>'."\n",
1413                     rcube_label('filesize'),
1414                     show_bytes($filesize));
1415   
1416   $out .= "\n</table>";
1417   
1418   return $out;
1419   }
1420
1421
1422
1423 function rcmail_message_part_frame($attrib)
1424   {
1425   global $MESSAGE;
1426   
1427   $part = $MESSAGE['parts'][$_GET['_part']];
1428   $ctype_primary = strtolower($part->ctype_primary);
1429
1430   $attrib['src'] = './?'.str_replace('_frame=', ($ctype_primary=='text' ? '_show=' : '_preload='), $_SERVER['QUERY_STRING']);
1431
1432   $attrib_str = create_attrib_string($attrib, array('id', 'class', 'style', 'src', 'width', 'height'));
90022e 1433   $out = '<iframe '. $attrib_str . "></iframe>";
4e17e6 1434     
T 1435   return $out;
1436   }
1437
1438
1439 // clear message composing settings
1440 function rcmail_compose_cleanup()
1441   {
1442   if (!isset($_SESSION['compose']))
1443     return;
70d4b9 1444
4e17e6 1445   // remove attachment files from temp dir
T 1446   if (is_array($_SESSION['compose']['attachments']))
1447     foreach ($_SESSION['compose']['attachments'] as $attachment)
15a9d1 1448       @unlink($attachment['path']);
4e17e6 1449   
T 1450   unset($_SESSION['compose']);
1451   }
1452   
1453   
1966c5 1454 ?>