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