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