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