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