thomascube
2006-01-13 be2380fb47b05a222ec5b22deff36d5156a8c943
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
f3b659 443   $javascript .= sprintf("%s.gui_object('messagelist', '%s');\n", $JS_OBJECT_NAME, $attrib['id']);
4e17e6 444   $javascript .= sprintf("%s.set_env('messagecount', %d);\n", $JS_OBJECT_NAME, $message_count);
T 445   $javascript .= sprintf("%s.set_env('current_page', %d);\n", $JS_OBJECT_NAME, $IMAP->list_page);
446   $javascript .= sprintf("%s.set_env('pagecount', %d);\n", $JS_OBJECT_NAME, ceil($message_count/$IMAP->page_size));
b076a4 447   $javascript .= sprintf("%s.set_env('sort_col', '%s');\n", $JS_OBJECT_NAME, $sort_col);
T 448   $javascript .= sprintf("%s.set_env('sort_order', '%s');\n", $JS_OBJECT_NAME, $sort_order);
4e17e6 449   
T 450   if ($attrib['messageicon'])
451     $javascript .= sprintf("%s.set_env('messageicon', '%s%s');\n", $JS_OBJECT_NAME, $skin_path, $attrib['messageicon']);
452   if ($attrib['unreadicon'])
453     $javascript .= sprintf("%s.set_env('unreadicon', '%s%s');\n", $JS_OBJECT_NAME, $skin_path, $attrib['unreadicon']);
454   if ($attrib['repliedicon'])
455     $javascript .= sprintf("%s.set_env('repliedicon', '%s%s');\n", $JS_OBJECT_NAME, $skin_path, $attrib['repliedicon']);
456   if ($attrib['attachmenticon'])
457     $javascript .= sprintf("%s.set_env('attachmenticon', '%s%s');\n", $JS_OBJECT_NAME, $skin_path, $attrib['attachmenticon']);
458     
459   $javascript .= sprintf("%s.set_env('messages', %s);", $JS_OBJECT_NAME, array2js($a_js_message_arr));
460   
461   $OUTPUT->add_script($javascript);  
462   
463   return $out;
464   }
465
466
467
468
469 // return javascript commands to add rows to the message list
470 function rcmail_js_message_list($a_headers, $insert_top=FALSE)
471   {
472   global $CONFIG, $IMAP;
473
474   $commands = '';
475   $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
476
477   // show 'to' instead of from in sent messages
478   if (strtolower($IMAP->get_mailbox_name())=='sent' && ($f = array_search('from', $a_show_cols)))
479     $a_show_cols[$f] = 'to';
480
481   // loop through message headers
482   for ($n=0; $a_headers[$n]; $n++)
483     {
484     $header = $a_headers[$n];
485     $a_msg_cols = array();
486     $a_msg_flags = array();
487       
488     // format each col; similar as in rcmail_message_list()
489     foreach ($a_show_cols as $col)
490       {
491       if ($col=='from' || $col=='to')
492         $cont = rep_specialchars_output(rcmail_address_string($header->$col, 3));
493       else if ($col=='subject')
7902df 494         $cont = rep_specialchars_output($IMAP->decode_header($header->$col), 'html', 'all');
4e17e6 495       else if ($col=='size')
T 496         $cont = show_bytes($header->$col);
497       else if ($col=='date')
498         $cont = format_date($header->date); //date('m.d.Y G:i:s', strtotime($header->date));
499       else
7902df 500         $cont = rep_specialchars_output($header->$col, 'html', 'all');
4e17e6 501           
T 502       $a_msg_cols[$col] = $cont;
503       }
504
505     $a_msg_flags['unread'] = $header->seen ? 0 : 1;
506     $a_msg_flags['replied'] = $header->answered ? 1 : 0;
15a9d1 507     
T 508     if ($header->deleted)
509       $a_msg_flags['deleted'] = 1;
4e17e6 510   
15a9d1 511     $commands .= sprintf("this.add_message_row(%s, %s, %s, %b, %b);\n",
4e17e6 512                          $header->uid,
T 513                          array2js($a_msg_cols),
514                          array2js($a_msg_flags),
15a9d1 515                          preg_match("/multipart\/m/i", $header->ctype),
T 516                          $insert_top);
4e17e6 517     }
T 518
519   return $commands;
520   }
521
522
523
524 function rcmail_messagecount_display($attrib)
525   {
526   global $IMAP, $OUTPUT, $JS_OBJECT_NAME;
527   
528   if (!$attrib['id'])
529     $attrib['id'] = 'rcmcountdisplay';
530
531   $OUTPUT->add_script(sprintf("%s.gui_object('countdisplay', '%s');", $JS_OBJECT_NAME, $attrib['id']));
532
533   // allow the following attributes to be added to the <span> tag
534   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
535
536   
537   $out = '<span' . $attrib_str . '>';
538   $out .= rcmail_get_messagecount_text();
539   $out .= '</span>';
540   return $out;
541   }
542
543
544
545 function rcmail_get_messagecount_text()
546   {
547   global $IMAP, $MESSAGE;
548   
549   if (isset($MESSAGE['index']))
550     {
551     return rcube_label(array('name' => 'messagenrof',
552                              'vars' => array('nr'  => $MESSAGE['index']+1,
31b2ce 553                                              'count' => $IMAP->messagecount())));
4e17e6 554     }
31b2ce 555
4e17e6 556   $start_msg = ($IMAP->list_page-1) * $IMAP->page_size + 1;
T 557   $max = $IMAP->messagecount();
558
559   if ($max==0)
560     $out = rcube_label('mailboxempty');
561   else
562     $out = rcube_label(array('name' => 'messagesfromto',
563                               'vars' => array('from'  => $start_msg,
564                                               'to'    => min($max, $start_msg + $IMAP->page_size - 1),
565                                               'count' => $max)));
566
cd900d 567   return rep_specialchars_output($out);
4e17e6 568   }
T 569
570
571 function rcmail_print_body($part, $safe=FALSE, $plain=FALSE) // $body, $ctype_primary='text', $ctype_secondary='plain', $encoding='7bit', $safe=FALSE, $plain=FALSE)
572   {
573   global $IMAP, $REMOTE_OBJECTS, $JS_OBJECT_NAME;
574
575   // extract part properties: body, ctype_primary, ctype_secondary, encoding, parameters
576   extract($part);
577   
578   $block = $plain ? '%s' : '%s'; //'<div style="display:block;">%s</div>';
579   $body = $IMAP->mime_decode($body, $encoding);
580   $body = $IMAP->charset_decode($body, $parameters);
581
582
583   // text/html
584   if ($ctype_secondary=='html')
585     {
586     if (!$safe)  // remove remote images and scripts
587       {
588       $remote_patterns = array('/(src|background)=(["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)(\2|\s|>)/Ui',
589                            //  '/(src|background)=(["\']?)([\.\/]+[^"\'\s]+)(\2|\s|>)/Ui',
590                                '/(<base.*href=["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)([^<]*>)/i',
591                                '/(<link.*href=["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)([^<]*>)/i',
592                                '/url\s*\(["\']?([hftps]{3,5}:\/{2}[^"\'\s]+)["\']?\)/i',
593                                '/url\s*\(["\']?([\.\/]+[^"\'\s]+)["\']?\)/i',
594                                '/<script.+<\/script>/Umis');
595
7cc38e 596       $remote_replaces = array('',  // '\\1=\\2#\\4',
4e17e6 597                             // '\\1=\\2#\\4',
T 598                                '',
7cc38e 599                                '',  // '\\1#\\3',
4e17e6 600                                'none',
T 601                                'none',
602                                '');
603       
604       // set flag if message containes remote obejcts that where blocked
605       foreach ($remote_patterns as $pattern)
606         {
607         if (preg_match($pattern, $body))
608           {
609           $REMOTE_OBJECTS = TRUE;
610           break;
611           }
612         }
613
614       $body = preg_replace($remote_patterns, $remote_replaces, $body);
615       }
616
617     return sprintf($block, rep_specialchars_output($body, 'html', '', FALSE));
618     }
619
620   // text/enriched
621   if ($ctype_secondary=='enriched')
622     {
623     $body = enriched_to_html($body);
624     return sprintf($block, rep_specialchars_output($body, 'html'));
625     }
626   else
627     {
628     // make links and email-addresses clickable
629     $convert_patterns = $convert_replaces = $replace_strings = array();
630     
09941e 631     $url_chars = 'a-z0-9_\-\+\*\$\/&%=@#:';
4e17e6 632     $url_chars_within = '\?\.~,!';
T 633
634     $convert_patterns[] = "/([\w]+):\/\/([a-z0-9\-\.]+[a-z]{2,4}([$url_chars$url_chars_within]*[$url_chars])?)/ie";
20a1b3 635     $convert_replaces[] = "rcmail_str_replacement('<a href=\"\\1://\\2\" target=\"_blank\">\\1://\\2</a>', \$replace_strings)";
4e17e6 636
T 637     $convert_patterns[] = "/([^\/:]|\s)(www\.)([a-z0-9\-]{2,}[a-z]{2,4}([$url_chars$url_chars_within]*[$url_chars])?)/ie";
20a1b3 638     $convert_replaces[] = "rcmail_str_replacement('\\1<a href=\"http://\\2\\3\" target=\"_blank\">\\2\\3</a>', \$replace_strings)";
4e17e6 639     
T 640     $convert_patterns[] = '/([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9]([a-z0-9\-][.]?)*[a-z0-9]\\.[a-z]{2,5})/ie';
20a1b3 641     $convert_replaces[] = "rcmail_str_replacement('<a href=\"mailto:\\1\" onclick=\"return $JS_OBJECT_NAME.command(\'compose\',\'\\1\',this)\">\\1</a>', \$replace_strings)";
4e17e6 642
T 643     $body = wordwrap(trim($body), 80);
644     $body = preg_replace($convert_patterns, $convert_replaces, $body);
645
646     // split body into single lines
647     $a_lines = preg_split('/\r?\n/', $body);
648
649     // colorize quoted parts
650     for($n=0; $n<sizeof($a_lines); $n++)
651       {
652       $line = $a_lines[$n];
653
654       if ($line{2}=='>')
655         $color = 'red';
656       else if ($line{1}=='>')
657         $color = 'green';
658       else if ($line{0}=='>')
659         $color = 'blue';
660       else
661         $color = FALSE;
662
663       $line = rep_specialchars_output($line, 'html', 'replace', FALSE);
664         
665       if ($color)
666         $a_lines[$n] = sprintf('<font color="%s">%s</font>', $color, $line);
667       else
668         $a_lines[$n] = $line;
669       }
670
671     // insert the links for urls and mailtos
672     $body = preg_replace("/##string_replacement\{([0-9]+)\}##/e", "\$replace_strings[\\1]", join("\n", $a_lines));
673     
674     return sprintf($block, "<pre>\n".$body."\n</pre>");
675     }
676   }
677
678
679
680 // add a string to the replacement array and return a replacement string
681 function rcmail_str_replacement($str, &$rep)
682   {
683   static $count = 0;
684   $rep[$count] = stripslashes($str);
685   return "##string_replacement{".($count++)."}##";
686   }
687
688
689 function rcmail_parse_message($structure, $arg=array(), $recursive=FALSE)
690   {
691   global $IMAP;
692   static $sa_inline_objects = array();
693
694   // arguments are: (bool)$prefer_html, (string)$get_url
695   extract($arg);
696
697   $a_attachments = array();
698   $a_return_parts = array();
699   $out = '';
700
701   $message_ctype_primary = strtolower($structure->ctype_primary);
702   $message_ctype_secondary = strtolower($structure->ctype_secondary);
703
704   // show message headers
705   if ($recursive && is_array($structure->headers) && isset($structure->headers['subject']))
706     $a_return_parts[] = array('type' => 'headers',
707                               'headers' => $structure->headers);
708
709   // print body if message doesn't have multiple parts
710   if ($message_ctype_primary=='text')
711     {
712     $a_return_parts[] = array('type' => 'content',
713                               'body' => $structure->body,
714                               'ctype_primary' => $message_ctype_primary,
715                               'ctype_secondary' => $message_ctype_secondary,
a95e0e 716                               'parameters' => $structure->ctype_parameters,
4e17e6 717                               'encoding' => $structure->headers['content-transfer-encoding']);
T 718     }
719
720   // message contains alternative parts
721   else if ($message_ctype_primary=='multipart' && $message_ctype_secondary=='alternative' && is_array($structure->parts))
722     {
723     // get html/plaintext parts
724     $plain_part = $html_part = $print_part = $related_part = NULL;
725     
726     foreach ($structure->parts as $p => $sub_part)
727       {
728       $sub_ctype_primary = strtolower($sub_part->ctype_primary);
729       $sub_ctype_secondary = strtolower($sub_part->ctype_secondary);
730
731       // check if sub part is 
732       if ($sub_ctype_primary=='text' && $sub_ctype_secondary=='plain')
733         $plain_part = $p;
734       else if ($sub_ctype_primary=='text' && $sub_ctype_secondary=='html')
735         $html_part = $p;
736       else if ($sub_ctype_primary=='text' && $sub_ctype_secondary=='enriched')
737         $enriched_part = $p;
738       else if ($sub_ctype_primary=='multipart' && $sub_ctype_secondary=='related')
739         $related_part = $p;
740       }
741
742     // parse related part (alternative part could be in here)
743     if ($related_part!==NULL && $prefer_html)
744       {
745       list($parts, $attachmnts) = rcmail_parse_message($structure->parts[$related_part], $arg, TRUE);
746       $a_return_parts = array_merge($a_return_parts, $parts);
747       $a_attachments = array_merge($a_attachments, $attachmnts);
748       }
749
750     // print html/plain part
751     else if ($html_part!==NULL && $prefer_html)
752       $print_part = $structure->parts[$html_part];
753     else if ($enriched_part!==NULL)
754       $print_part = $structure->parts[$enriched_part];
755     else if ($plain_part!==NULL)
756       $print_part = $structure->parts[$plain_part];
757
758     // show message body
759     if (is_object($print_part))
760       $a_return_parts[] = array('type' => 'content',
761                                 'body' => $print_part->body,
762                                 'ctype_primary' => strtolower($print_part->ctype_primary),
763                                 'ctype_secondary' => strtolower($print_part->ctype_secondary),
764                                 'parameters' => $print_part->ctype_parameters,
765                                 'encoding' => $print_part->headers['content-transfer-encoding']);
766     // show plaintext warning
767     else if ($html_part!==NULL)
768       $a_return_parts[] = array('type' => 'content',
769                                 'body' => rcube_label('htmlmessage'),
770                                 'ctype_primary' => 'text',
771                                 'ctype_secondary' => 'plain');
772                                 
773     // add html part as attachment
774     if ($html_part!==NULL && $structure->parts[$html_part]!==$print_part)
775       {
776       $html_part = $structure->parts[$html_part];
777       $a_attachments[] = array('filename' => rcube_label('htmlmessage'),
778                                'encoding' => $html_part->headers['content-transfer-encoding'],
779                                'mimetype' => 'text/html',
780                                'part_id'  => $html_part->mime_id,
781                                'size'     => strlen($IMAP->mime_decode($html_part->body, $html_part->headers['content-transfer-encoding'])));
782       }
783     }
784
785   // message contains multiple parts
786   else if ($message_ctype_primary=='multipart' && is_array($structure->parts))
787     {
788     foreach ($structure->parts as $mail_part)
789       {
790       $primary_type = strtolower($mail_part->ctype_primary);
791       $secondary_type = strtolower($mail_part->ctype_secondary);
792
793       // multipart/alternative
794       if ($primary_type=='multipart') // && ($secondary_type=='alternative' || $secondary_type=='mixed' || $secondary_type=='related'))
795         {
796         list($parts, $attachmnts) = rcmail_parse_message($mail_part, $arg, TRUE);
797
798         $a_return_parts = array_merge($a_return_parts, $parts);
799         $a_attachments = array_merge($a_attachments, $attachmnts);
800         }
801
802       // part text/[plain|html] OR message/delivery-status
803       else if (($primary_type=='text' && ($secondary_type=='plain' || $secondary_type=='html')) ||
804                ($primary_type=='message' && $secondary_type=='delivery-status'))
805         {
806         $a_return_parts[] = array('type' => 'content',
807                                   'body' => $mail_part->body,
808                                   'ctype_primary' => $primary_type,
809                                   'ctype_secondary' => $secondary_type,
a95e0e 810                                   'parameters' => $mail_part->ctype_parameters,
4e17e6 811                                   'encoding' => $mail_part->headers['content-transfer-encoding']);
T 812         }
813
814       // part message/*
815       else if ($primary_type=='message')
816         {
817         /* don't parse headers here; they're parsed within the recursive call to rcmail_parse_message()
818         if ($mail_part->parts[0]->headers)
819           $a_return_parts[] = array('type' => 'headers',
820                                     'headers' => $mail_part->parts[0]->headers);
821         */
822                                       
823         list($parts, $attachmnts) = rcmail_parse_message($mail_part->parts[0], $arg, TRUE);
824
825         $a_return_parts = array_merge($a_return_parts, $parts);
826         $a_attachments = array_merge($a_attachments, $attachmnts);
827         }
828
829       // part is file/attachment
b595c9 830       else if ($mail_part->disposition=='attachment' || $mail_part->disposition=='inline' || $mail_part->headers['content-id'] ||
T 831                (empty($mail_part->disposition) && ($mail_part->d_parameters['filename'] || $mail_part->d_parameters['name'])))
4e17e6 832         {
T 833         if ($message_ctype_secondary=='related' && $mail_part->headers['content-id'])
4b0f65 834           $sa_inline_objects[] = array('filename' => rcube_imap::decode_mime_string($mail_part->d_parameters['filename']),
4e17e6 835                                        'mimetype' => strtolower("$primary_type/$secondary_type"),
T 836                                        'part_id'  => $mail_part->mime_id,
837                                        'content_id' => preg_replace(array('/^</', '/>$/'), '', $mail_part->headers['content-id']));
838
839         else if ($mail_part->d_parameters['filename'])
4b0f65 840           $a_attachments[] = array('filename' => rcube_imap::decode_mime_string($mail_part->d_parameters['filename']),
4e17e6 841                                    'encoding' => strtolower($mail_part->headers['content-transfer-encoding']),
T 842                                    'mimetype' => strtolower("$primary_type/$secondary_type"),
843                                    'part_id'  => $mail_part->mime_id,
844                                    'size'     => strlen($IMAP->mime_decode($mail_part->body, $mail_part->headers['content-transfer-encoding'])) /*,
845                                    'content'  => $mail_part->body */);
846                                    
847         else if ($mail_part->ctype_parameters['name'])
4b0f65 848           $a_attachments[] = array('filename' => rcube_imap::decode_mime_string($mail_part->ctype_parameters['name']),
4e17e6 849                                    'encoding' => strtolower($mail_part->headers['content-transfer-encoding']),
T 850                                    'mimetype' => strtolower("$primary_type/$secondary_type"),
851                                    'part_id'  => $mail_part->mime_id,
852                                    'size'     => strlen($IMAP->mime_decode($mail_part->body, $mail_part->headers['content-transfer-encoding'])) /*,
853                                    'content'  => $mail_part->body */);
854                                    
855                                    
856         }
857       }
858
859
860     // if this was a related part try to resolve references
861     if ($message_ctype_secondary=='related' && sizeof($sa_inline_objects))
862       {
863       $a_replace_patters = array();
864       $a_replace_strings = array();
865         
866       foreach ($sa_inline_objects as $inline_object)
867         {
868         $a_replace_patters[] = 'cid:'.$inline_object['content_id'];
869         $a_replace_strings[] = sprintf($get_url, $inline_object['part_id']);
870         }
871       
872       foreach ($a_return_parts as $i => $return_part)
873         {
874         if ($return_part['type']!='content')
875           continue;
876
877         // decode body and replace cid:...
878         $a_return_parts[$i]['body'] = str_replace($a_replace_patters, $a_replace_strings, $IMAP->mime_decode($return_part['body'], $return_part['encoding']));
879         $a_return_parts[$i]['encoding'] = '7bit';
880         }
881       }
882     }
883     
884
885   // join all parts together
886   //$out .= join($part_delimiter, $a_return_parts);
887
888   return array($a_return_parts, $a_attachments);
889   }
890
891
892
893
894 // return table with message headers
895 function rcmail_message_headers($attrib, $headers=NULL)
896   {
897   global $IMAP, $OUTPUT, $MESSAGE;
898   static $sa_attrib;
899   
900   // keep header table attrib
901   if (is_array($attrib) && !$sa_attrib)
902     $sa_attrib = $attrib;
903   else if (!is_array($attrib) && is_array($sa_attrib))
904     $attrib = $sa_attrib;
905   
906   
907   if (!isset($MESSAGE))
908     return FALSE;
909
910   // get associative array of headers object
911   if (!$headers)
912     $headers = is_object($MESSAGE['headers']) ? get_object_vars($MESSAGE['headers']) : $MESSAGE['headers'];
913     
914   $header_count = 0;
915   
916   // allow the following attributes to be added to the <table> tag
917   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
918   $out = '<table' . $attrib_str . ">\n";
919
920   // show these headers
921   $standard_headers = array('subject', 'from', 'organization', 'to', 'cc', 'reply-to', 'date');
922   
923   foreach ($standard_headers as $hkey)
924     {
925     if (!$headers[$hkey])
926       continue;
927
b076a4 928     if ($hkey=='date' && !empty($headers[$hkey]))
4e17e6 929       $header_value = format_date(strtotime($headers[$hkey]));
T 930     else if (in_array($hkey, array('from', 'to', 'cc', 'reply-to')))
931       $header_value = rep_specialchars_output(rcmail_address_string($IMAP->decode_header($headers[$hkey]), NULL, $attrib['addicon']));
932     else
933       $header_value = rep_specialchars_output($IMAP->decode_header($headers[$hkey]), '', 'all');
934
935     $out .= "\n<tr>\n";
1038d5 936     $out .= '<td class="header-title">'.rep_specialchars_output(rcube_label($hkey)).":&nbsp;</td>\n";
4e17e6 937     $out .= '<td class="'.$hkey.'" width="90%">'.$header_value."</td>\n</tr>";
T 938     $header_count++;
939     }
940
941   $out .= "\n</table>\n\n";
942
943   return $header_count ? $out : '';  
944   }
945
946
947
948 function rcmail_message_body($attrib)
949   {
950   global $CONFIG, $OUTPUT, $MESSAGE, $GET_URL, $REMOTE_OBJECTS, $JS_OBJECT_NAME;
951   
952   if (!is_array($MESSAGE['parts']) && !$MESSAGE['body'])
953     return '';
954     
955   if (!$attrib['id'])
956     $attrib['id'] = 'rcmailMsgBody';
957
958   $safe_mode = (bool)$_GET['_safe'];
959   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
960   $out = '<div '. $attrib_str . ">\n";
961   
962   $header_attrib = array();
963   foreach ($attrib as $attr => $value)
964     if (preg_match('/^headertable([a-z]+)$/i', $attr, $regs))
965       $header_attrib[$regs[1]] = $value;
966
967
968   // this is an ecrypted message
969   // -> create a plaintext body with the according message
970   if (!sizeof($MESSAGE['parts']) && $MESSAGE['headers']->ctype=='multipart/encrypted')
971     {
972     $MESSAGE['parts'][0] = array('type' => 'content',
973                                  'ctype_primary' => 'text',
974                                  'ctype_secondary' => 'plain',
975                                  'body' => rcube_label('encryptedmessage'));
976     }
977   
978   if ($MESSAGE['parts'])
979     {
980     foreach ($MESSAGE['parts'] as $i => $part)
981       {
982       if ($part['type']=='headers')
983         $out .= rcmail_message_headers(sizeof($header_attrib) ? $header_attrib : NULL, $part['headers']);
984       else if ($part['type']=='content')
985         {
a95e0e 986         if (empty($part['parameters']) || empty($part['parameters']['charset']))
T 987           $part['parameters']['charset'] = $MESSAGE['headers']->charset;
988         
4e17e6 989         // $body = rcmail_print_body($part['body'], $part['ctype_primary'], $part['ctype_secondary'], $part['encoding'], $safe_mode);
T 990         $body = rcmail_print_body($part, $safe_mode);
991         $out .= '<div class="message-part">';
992         $out .= rcmail_mod_html_body($body, $attrib['id']);
993         $out .= "</div>\n";
994         }
995       }
996     }
997   else
998     $out .= $MESSAGE['body'];
999
1000
1001   $ctype_primary = strtolower($MESSAGE['structure']->ctype_primary);
1002   $ctype_secondary = strtolower($MESSAGE['structure']->ctype_secondary);
1003   
1004   // list images after mail body
1005   if (get_boolean($attrib['showimages']) && $ctype_primary=='multipart' && $ctype_secondary=='mixed' &&
1006       sizeof($MESSAGE['attachments']) && !strstr($message_body, '<html') && strlen($GET_URL))
1007     {
1008     foreach ($MESSAGE['attachments'] as $attach_prop)
1009       {
1010       if (strpos($attach_prop['mimetype'], 'image/')===0)
1011         $out .= sprintf("\n<hr />\n<p align=\"center\"><img src=\"%s&_part=%s\" alt=\"%s\" title=\"%s\" /></p>\n",
1012                         $GET_URL, $attach_prop['part_id'],
1013                         $attach_prop['filename'],
1014                         $attach_prop['filename']);
1015       }
1016     }
1017   
1018   // tell client that there are blocked remote objects
1019   if ($REMOTE_OBJECTS && !$safe_mode)
1020     $OUTPUT->add_script(sprintf("%s.set_env('blockedobjects', true);", $JS_OBJECT_NAME));
1021
1022   $out .= "\n</div>";
1023   return $out;
1024   }
1025
1026
1027
1028 // modify a HTML message that it can be displayed inside a HTML page
1029 function rcmail_mod_html_body($body, $container_id)
1030   {
749b07 1031   // remove any null-byte characters before parsing
T 1032   $body = preg_replace('/\x00/', '', $body);
1033   
4e17e6 1034   $last_style_pos = 0;
T 1035   $body_lc = strtolower($body);
1036   
1037   // find STYLE tags
1038   while (($pos = strpos($body_lc, '<style', $last_style_pos)) && ($pos2 = strpos($body_lc, '</style>', $pos)))
1039     {
1040     $pos2 += 8;
1041     $body_pre = substr($body, 0, $pos);
1042     $styles = substr($body, $pos, $pos2-$pos);
1043     $body_post = substr($body, $pos2, strlen($body)-$pos2);
1044     
1045     // replace all css definitions with #container [def]
1046     $styles = rcmail_mod_css_styles($styles, $container_id);
1047     
1048     $body = $body_pre . $styles . $body_post;
1049     $last_style_pos = $pos2;
1050     }
1051
1052
1053   // remove SCRIPT tags
6a35c8 1054   foreach (array('script', 'applet', 'object', 'embed', 'iframe') as $tag)
4e17e6 1055     {
6a35c8 1056     while (($pos = strpos($body_lc, '<'.$tag)) && ($pos2 = strpos($body_lc, '</'.$tag.'>', $pos)))
T 1057       {
1058       $pos2 += 8;
1059       $body = substr($body, 0, $pos) . substr($body, $pos2, strlen($body)-$pos2);
1060       $body_lc = strtolower($body);
1061       }
4e17e6 1062     }
6a35c8 1063
T 1064   // replace event handlers on any object
1065   $body = preg_replace('/\s(on[a-z]+)=/im', ' __removed=', $body);  
4e17e6 1066
T 1067   // resolve <base href>
1068   $base_reg = '/(<base.*href=["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)([^<]*>)/i';
1069   if (preg_match($base_reg, $body, $regs))
1070     {
1071     $base_url = $regs[2];
1072     $body = preg_replace('/(src|background|href)=(["\']?)([\.\/]+[^"\'\s]+)(\2|\s|>)/Uie', "'\\1=\"'.make_absolute_url('\\3', '$base_url').'\"'", $body);
1073     $body = preg_replace('/(url\s*\()(["\']?)([\.\/]+[^"\'\)\s]+)(\2)\)/Uie', "'\\1\''.make_absolute_url('\\3', '$base_url').'\')'", $body);
1074     $body = preg_replace($base_reg, '', $body);
1075     }
1076
1077   // add comments arround html and other tags
1078   $out = preg_replace(array('/(<\/?html[^>]*>)/i',
1079                             '/(<\/?head[^>]*>)/i',
1080                             '/(<title[^>]*>.+<\/title>)/ui',
1081                             '/(<\/?meta[^>]*>)/i'),
1082                       '<!--\\1-->',
1083                       $body);
1084                       
1085   $out = preg_replace(array('/(<body[^>]*>)/i',
1086                             '/(<\/body>)/i'),
1087                       array('<div class="rcmBody">',
1088                             '</div>'),
1089                       $out);
1090
1091   
1092   return $out;
1093   }
1094
1095
1096
1097 // replace all css definitions with #container [def]
1098 function rcmail_mod_css_styles($source, $container_id)
1099   {
1100   $a_css_values = array();
1101   $last_pos = 0;
1102   
1103   // cut out all contents between { and }
1104   while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos)))
1105     {
1106     $key = sizeof($a_css_values);
1107     $a_css_values[$key] = substr($source, $pos+1, $pos2-($pos+1));
1108     $source = substr($source, 0, $pos+1) . "<<str_replacement[$key]>>" . substr($source, $pos2, strlen($source)-$pos2);
1109     $last_pos = $pos+2;
1110     }
1111   
1112   $styles = preg_replace('/(^\s*|,\s*)([a-z0-9\._][a-z0-9\.\-_]*)/im', "\\1#$container_id \\2", $source);
1113   $styles = preg_replace('/<<str_replacement\[([0-9]+)\]>>/e', "\$a_css_values[\\1]", $styles);
1114   
1115   // replace body definition because we also stripped off the <body> tag
1116   $styles = preg_replace("/$container_id\s+body/i", "$container_id div.rcmBody", $styles);
1117   
1118   return $styles;
1119   }
1120
1121
1122
1123 // return first text part of a message
1124 function rcmail_first_text_part($message_parts)
1125   {
1126   if (!is_array($message_parts))
1127     return FALSE;
1128     
1129   $html_part = NULL;
1130       
1131   // check all message parts
1132   foreach ($message_parts as $pid => $part)
1133     {
1134     $mimetype = strtolower($part->ctype_primary.'/'.$part->ctype_secondary);
1135     if ($mimetype=='text/plain')
1136       {
1137       $body = rcube_imap::mime_decode($part->body, $part->headers['content-transfer-encoding']);
1138       $body = rcube_imap::charset_decode($body, $part->ctype_parameters);
1139       return $body;
1140       }
1141     else if ($mimetype=='text/html')
1142       {
1143       $html_part = rcube_imap::mime_decode($part->body, $part->headers['content-transfer-encoding']);
1144       $html_part = rcube_imap::charset_decode($html_part, $part->ctype_parameters);
1145       }
1146     }
1147     
1148
1149   // convert HTML to plain text
1150   if ($html_part)
1151     {    
1152     // remove special chars encoding
1153     $trans = array_flip(get_html_translation_table(HTML_ENTITIES));
1154     $html_part = strtr($html_part, $trans);
1155
1156     // create instance of html2text class
1157     $txt = new html2text($html_part);
1158     return $txt->get_text();
1159     }
1160
1161   return FALSE;
1162   }
1163
1164
1165 // get source code of a specific message and cache it
1166 function rcmail_message_source($uid)
1167   {
1cded8 1168   global $IMAP, $DB, $CONFIG;
4e17e6 1169
1cded8 1170   // get message ID if uid is given
T 1171   $cache_key = $IMAP->mailbox.'.msg';
1172   $cached = $IMAP->get_cached_message($cache_key, $uid, FALSE);
1173   
1174   // message is cached in database
1175   if ($cached && !empty($cached->body))
1176     return $cached->body;
1177
1178   if (!$cached)
1179     $headers = $IMAP->get_headers($uid);
1180   else
1181     $headers = &$cached;
1182
749b07 1183   // create unique identifier based on message_id
T 1184   if (!empty($headers->messageID))
1185     $message_id = md5($headers->messageID);
1186   else
1187     $message_id = md5($headers->uid.'@'.$_SESSION['imap_host']);
4e17e6 1188   
1cded8 1189   $temp_dir = $CONFIG['temp_dir'].(!eregi('\/$', $CONFIG['temp_dir']) ? '/' : '');
T 1190   $cache_dir = $temp_dir.$_SESSION['client_id'];
1191   $cache_path = $cache_dir.'/'.$message_id;
4e17e6 1192
1cded8 1193   // message is cached in temp dir
749b07 1194   if ($CONFIG['enable_caching'] && is_dir($cache_dir) && is_file($cache_path))
4e17e6 1195     {
1cded8 1196     if ($fp = fopen($cache_path, 'r'))
T 1197       {
1198       $msg_source = fread($fp, filesize($cache_path));
1199       fclose($fp);
1200       return $msg_source;
1201       }
1202     }
1203
1204
1205   // get message from server
1206   $msg_source = $IMAP->get_raw_body($uid);
749b07 1207   
T 1208   // return message source without caching
1209   if (!$CONFIG['enable_caching'])
1210     return $msg_source;
1211
1cded8 1212
T 1213   // let's cache the message body within the database
749b07 1214   if ($cached && ($CONFIG['db_max_length'] -300) > $headers->size)
1cded8 1215     {
T 1216     $DB->query("UPDATE ".get_table_name('messages')."
1217                 SET    body=?
1218                 WHERE  user_id=?
1219                 AND    cache_key=?
1220                 AND    uid=?",
1221                $msg_source,
1222                $_SESSION['user_id'],
1223                $cache_key,
1224                $uid);
1225
1226     return $msg_source;
1227     }
1228
1229
1230   // create dir for caching
1231   if (!is_dir($cache_dir))
1232     $dir = mkdir($cache_dir);
1233   else
1234     $dir = true;
1235
1236   // attempt to write a file with the message body    
1237   if ($dir && ($fp = fopen($cache_path, 'w')))
1238     {
1239     fwrite($fp, $msg_source);
1240     fclose($fp);
1241     }
1242   else
1243     {
1244     raise_error(array('code' => 403, 'type' => 'php', 'line' => __LINE__, 'file' => __FILE__, 
1245                       'message' => "Failed to write to temp dir"), TRUE, FALSE);
4e17e6 1246     }
T 1247
1248   return $msg_source;
1249   }
1250
1251
1252 // decode address string and re-format it as HTML links
1253 function rcmail_address_string($input, $max=NULL, $addicon=NULL)
1254   {
1255   global $IMAP, $PRINT_MODE, $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $EMAIL_ADDRESS_PATTERN;
1256   
1257   $a_parts = $IMAP->decode_address_list($input);
1258
1259   if (!sizeof($a_parts))
1260     return $input;
1261
1262   $c = count($a_parts);
1263   $j = 0;
1264   $out = '';
1265
1266   foreach ($a_parts as $part)
1267     {
1268     $j++;
1269     if ($PRINT_MODE)
a95e0e 1270       $out .= sprintf('%s &lt;%s&gt;', rep_specialchars_output($part['name']), $part['mailto']);
4e17e6 1271     else if (preg_match($EMAIL_ADDRESS_PATTERN, $part['mailto']))
T 1272       {
1273       $out .= sprintf('<a href="mailto:%s" onclick="return %s.command(\'compose\',\'%s\',this)" class="rcmContactAddress" title="%s">%s</a>',
1274                       $part['mailto'],
1275                       $JS_OBJECT_NAME,
1276                       $part['mailto'],
1277                       $part['mailto'],
a95e0e 1278                       rep_specialchars_output($part['name']));
4e17e6 1279                       
T 1280       if ($addicon)
1281         $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>',
1282                         $JS_OBJECT_NAME,
1283                         urlencode($part['string']),
1284                         rcube_label('addtoaddressbook'),
1285                         $CONFIG['skin_path'],
1286                         $addicon);
1287       }
1288     else
1289       {
1290       if ($part['name'])
a95e0e 1291         $out .= rep_specialchars_output($part['name']);
4e17e6 1292       if ($part['mailto'])
T 1293         $out .= (strlen($out) ? ' ' : '') . sprintf('&lt;%s&gt;', $part['mailto']);
1294       }
1295       
1296     if ($c>$j)
1297       $out .= ','.($max ? '&nbsp;' : ' ');
1298         
1299     if ($max && $j==$max && $c>$j)
1300       {
1301       $out .= '...';
1302       break;
1303       }        
1304     }
1305     
1306   return $out;
1307   }
1308
1309
1310 function rcmail_message_part_controls()
1311   {
1312   global $CONFIG, $IMAP, $MESSAGE;
1313   
1314   if (!is_array($MESSAGE) || !is_array($MESSAGE['parts']) || !($_GET['_uid'] && $_GET['_part']) || !$MESSAGE['parts'][$_GET['_part']])
1315     return '';
1316     
1317   $part = $MESSAGE['parts'][$_GET['_part']];
1318   
1319   $attrib_str = create_attrib_string($attrib, array('id', 'class', 'style', 'cellspacing', 'cellpadding', 'border', 'summary'));
1320   $out = '<table '. $attrib_str . ">\n";
1321   
1322   $filename = $part->d_parameters['filename'] ? $part->d_parameters['filename'] : $part->ctype_parameters['name'];
1323   $filesize = strlen($IMAP->mime_decode($part->body, $part->headers['content-transfer-encoding']));
1324   
1325   if ($filename)
1326     {
1327     $out .= sprintf('<tr><td class="title">%s</td><td>%s</td><td>[<a href="./?%s">%s</a>]</tr>'."\n",
1328                     rcube_label('filename'),
1329                     rep_specialchars_output($filename),
1330                     str_replace('_frame=', '_download=', $_SERVER['QUERY_STRING']),
1331                     rcube_label('download'));
1332     }
1333     
1334   if ($filesize)
1335     $out .= sprintf('<tr><td class="title">%s</td><td>%s</td></tr>'."\n",
1336                     rcube_label('filesize'),
1337                     show_bytes($filesize));
1338   
1339   $out .= "\n</table>";
1340   
1341   return $out;
1342   }
1343
1344
1345
1346 function rcmail_message_part_frame($attrib)
1347   {
1348   global $MESSAGE;
1349   
1350   $part = $MESSAGE['parts'][$_GET['_part']];
1351   $ctype_primary = strtolower($part->ctype_primary);
1352
1353   $attrib['src'] = './?'.str_replace('_frame=', ($ctype_primary=='text' ? '_show=' : '_preload='), $_SERVER['QUERY_STRING']);
1354
1355   $attrib_str = create_attrib_string($attrib, array('id', 'class', 'style', 'src', 'width', 'height'));
1356   $out = '<iframe '. $attrib_str . "></ifame>";
1357     
1358   return $out;
1359   }
1360
1361
597170 1362 // create temp dir for attachments
T 1363 function rcmail_create_compose_tempdir()
1364   {
1365   global $CONFIG;
1366   
1367   if ($_SESSION['compose']['temp_dir'])
1368     return $_SESSION['compose']['temp_dir'];
1369   
1370   if (!empty($CONFIG['temp_dir']))
1371     $temp_dir = $CONFIG['temp_dir'].(!eregi('\/$', $CONFIG['temp_dir']) ? '/' : '').$_SESSION['compose']['id'];
1372
1373   // create temp-dir for uploaded attachments
1374   if (!empty($CONFIG['temp_dir']) && is_writeable($CONFIG['temp_dir']))
1375     {
1376     mkdir($temp_dir);
1377     $_SESSION['compose']['temp_dir'] = $temp_dir;
1378     }
1379
1380   return $_SESSION['compose']['temp_dir'];
1381   }
1382
4e17e6 1383
T 1384 // clear message composing settings
1385 function rcmail_compose_cleanup()
1386   {
1387   if (!isset($_SESSION['compose']))
1388     return;
1389   
1390   // remove attachment files from temp dir
1391   if (is_array($_SESSION['compose']['attachments']))
1392     foreach ($_SESSION['compose']['attachments'] as $attachment)
15a9d1 1393       @unlink($attachment['path']);
4e17e6 1394
T 1395   // kill temp dir
1396   if ($_SESSION['compose']['temp_dir'])
15a9d1 1397     @rmdir($_SESSION['compose']['temp_dir']);
4e17e6 1398   
T 1399   unset($_SESSION['compose']);
1400   }
1401   
1402   
1403 ?>