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