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