]> git.donarmstrong.com Git - roundcube.git/blob - program/steps/mail/func.inc
Imported Upstream version 0.2~stable
[roundcube.git] / program / steps / mail / func.inc
1 <?php
2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/steps/mail/func.inc                                           |
6  |                                                                       |
7  | This file is part of the RoundCube Webmail client                     |
8  | Copyright (C) 2005-2008, RoundCube Dev. - Switzerland                 |
9  | Licensed under the GNU GPL                                            |
10  |                                                                       |
11  | PURPOSE:                                                              |
12  |   Provide webmail functionality and GUI objects                       |
13  |                                                                       |
14  +-----------------------------------------------------------------------+
15  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16  +-----------------------------------------------------------------------+
17
18  $Id: func.inc 2197 2008-12-30 13:30:20Z thomasb $
19
20 */
21
22 require_once('lib/enriched.inc');
23 require_once('include/rcube_smtp.inc');
24
25 $EMAIL_ADDRESS_PATTERN = '/([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9]([a-z0-9\-][.]?)*[a-z0-9]\\.[a-z]{2,5})/i';
26
27 // actions that do not require imap connection
28 $NOIMAP_ACTIONS = array('spell', 'addcontact', 'autocomplete', 'upload', 'display-attachment', 'remove-attachment');
29
30
31 // log in to imap server
32 if (!in_array($RCMAIL->action, $NOIMAP_ACTIONS) && !$RCMAIL->imap_connect()) {
33   $RCMAIL->kill_session();
34
35   if ($OUTPUT->ajax_call)
36     $OUTPUT->redirect(array(), 2000);
37
38   $OUTPUT->set_env('task', 'login');
39   $OUTPUT->send('login');
40 }
41
42
43 // set imap properties and session vars
44 if ($mbox = get_input_value('_mbox', RCUBE_INPUT_GPC))
45   $IMAP->set_mailbox(($_SESSION['mbox'] = $mbox));
46 else
47   $_SESSION['mbox'] = $IMAP->get_mailbox_name();
48
49 if (!empty($_GET['_page']))
50   $IMAP->set_page(($_SESSION['page'] = intval($_GET['_page'])));
51
52 // set default sort col/order to session
53 if (!isset($_SESSION['sort_col']))
54   $_SESSION['sort_col'] = $CONFIG['message_sort_col'];
55 if (!isset($_SESSION['sort_order']))
56   $_SESSION['sort_order'] = $CONFIG['message_sort_order'];
57
58 // set message set for search result
59 if (!empty($_REQUEST['_search']) && isset($_SESSION['search'][$_REQUEST['_search']]))
60   {
61   $IMAP->set_search_set($_SESSION['search'][$_REQUEST['_search']]);
62   $OUTPUT->set_env('search_request', $_REQUEST['_search']);
63   $OUTPUT->set_env('search_text', $_SESSION['last_text_search']);
64   }
65
66 // set main env variables, labels and page title
67 if (empty($RCMAIL->action) || $RCMAIL->action == 'list')
68   {
69   $mbox_name = $IMAP->get_mailbox_name();
70
71   if (empty($RCMAIL->action))
72     {
73     // initialize searching result if search_filter is used
74     if ($_SESSION['search_filter'] && $_SESSION['search_filter'] != 'ALL')
75       {
76       $search_request = md5($mbox_name.$_SESSION['search_filter']);
77   
78       $IMAP->search($mbox_name, $_SESSION['search_filter'], RCMAIL_CHARSET, $_SESSION['sort_col']);
79       $_SESSION['search'][$search_request] = $IMAP->get_search_set();
80       $OUTPUT->set_env('search_request', $search_request);
81       }
82     
83       // make sure the message count is refreshed (for default view)
84       $IMAP->messagecount($mbox_name, 'ALL', true);
85     }
86         
87   // set current mailbox in client environment
88   $OUTPUT->set_env('mailbox', $mbox_name);
89   $OUTPUT->set_env('quota', $IMAP->get_capability('quota'));
90   $OUTPUT->set_env('delimiter', $IMAP->get_hierarchy_delimiter());
91
92   if ($CONFIG['trash_mbox'])
93     $OUTPUT->set_env('trash_mailbox', $CONFIG['trash_mbox']);
94   if ($CONFIG['drafts_mbox'])
95     $OUTPUT->set_env('drafts_mailbox', $CONFIG['drafts_mbox']);
96   if ($CONFIG['junk_mbox'])
97     $OUTPUT->set_env('junk_mailbox', $CONFIG['junk_mbox']);
98
99   if (!$OUTPUT->ajax_call)
100     $OUTPUT->add_label('checkingmail', 'deletemessage', 'movemessagetotrash', 'movingmessage');
101
102   $OUTPUT->set_pagetitle(rcmail_localize_foldername($mbox_name));
103   }
104
105
106 /**
107  * return the message list as HTML table
108  */
109 function rcmail_message_list($attrib)
110   {
111   global $IMAP, $CONFIG, $COMM_PATH, $OUTPUT;
112
113   $skin_path = $CONFIG['skin_path'];
114   $image_tag = '<img src="%s%s" alt="%s" />';
115
116   // check to see if we have some settings for sorting
117   $sort_col   = $_SESSION['sort_col'];
118   $sort_order = $_SESSION['sort_order'];
119   
120   // add some labels to client
121   $OUTPUT->add_label('from', 'to');
122
123   // get message headers
124   $a_headers = $IMAP->list_headers('', '', $sort_col, $sort_order);
125
126   // add id to message list table if not specified
127   if (!strlen($attrib['id']))
128     $attrib['id'] = 'rcubemessagelist';
129
130   // allow the following attributes to be added to the <table> tag
131   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
132
133   $out = '<table' . $attrib_str . ">\n";
134
135   // define list of cols to be displayed based on parameter or config
136   if (empty($attrib['columns']))
137       $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
138   else
139       $a_show_cols = preg_split('/[\s,;]+/', strip_quotes($attrib['columns']));
140
141   // store column list in a session-variable
142   $_SESSION['list_columns'] = $a_show_cols;
143   
144   // define sortable columns
145   $a_sort_cols = array('subject', 'date', 'from', 'to', 'size');
146
147   $mbox = $IMAP->get_mailbox_name();
148   
149   // show 'to' instead of from in sent messages
150   if (($mbox==$CONFIG['sent_mbox'] || $mbox==$CONFIG['drafts_mbox']) && ($f = array_search('from', $a_show_cols))
151       && !array_search('to', $a_show_cols))
152     $a_show_cols[$f] = 'to';
153   
154   // add col definition
155   $out .= '<colgroup>';
156   $out .= '<col class="icon" />';
157
158   foreach ($a_show_cols as $col)
159     $out .= ($col!='attachment') ? sprintf('<col class="%s" />', $col) : '<col class="icon" />';
160
161   $out .= "</colgroup>\n";
162
163   // add table title
164   $out .= "<thead><tr>\n<td class=\"icon\">&nbsp;</td>\n";
165
166   $javascript = '';
167   foreach ($a_show_cols as $col)
168     {
169     // get column name
170     switch ($col)
171       {
172       case 'flag':
173         $col_name = sprintf($image_tag, $skin_path, $attrib['unflaggedicon'], '');
174         break;
175       case 'attachment':
176         $col_name = sprintf($image_tag, $skin_path, $attrib['attachmenticon'], '');
177         break;
178       default:
179         $col_name = Q(rcube_label($col));
180     }
181
182     // make sort links
183     $sort = '';
184     if (in_array($col, $a_sort_cols))
185       {
186       // have buttons configured
187       if (!empty($attrib['sortdescbutton']) || !empty($attrib['sortascbutton']))
188         {
189         $sort = '&nbsp;&nbsp;';
190
191         // asc link
192         if (!empty($attrib['sortascbutton']))
193           {
194           $sort .= $OUTPUT->button(array(
195             'command' => 'sort',
196             'prop' => $col.'_ASC',
197             'image' => $attrib['sortascbutton'],
198             'align' => 'absmiddle',
199             'title' => 'sortasc'));
200           }       
201         
202         // desc link
203         if (!empty($attrib['sortdescbutton']))
204           {
205           $sort .= $OUTPUT->button(array(
206             'command' => 'sort',
207             'prop' => $col.'_DESC',
208             'image' => $attrib['sortdescbutton'],
209             'align' => 'absmiddle',
210             'title' => 'sortdesc'));
211           }
212         }
213       // just add a link tag to the header
214       else
215         {
216         $col_name = sprintf(
217           '<a href="./#sort" onclick="return %s.command(\'sort\',\'%s\',this)" title="%s">%s</a>',
218           JS_OBJECT_NAME,
219           $col,
220           rcube_label('sortby'),
221           $col_name);
222         }
223       }
224       
225     $sort_class = $col==$sort_col ? " sorted$sort_order" : '';
226
227     // put it all together
228     if ($col!='attachment')
229       $out .= '<td class="'.$col.$sort_class.'" id="rcm'.$col.'">' . "$col_name$sort</td>\n";
230     else    
231       $out .= '<td class="icon" id="rcm'.$col.'">' . "$col_name$sort</td>\n";
232     }
233
234   $out .= "</tr></thead>\n<tbody>\n";
235
236   // no messages in this mailbox
237   if (!sizeof($a_headers))
238     $OUTPUT->show_message('nomessagesfound', 'notice');
239
240
241   $a_js_message_arr = array();
242
243   // create row for each message
244   foreach ($a_headers as $i => $header)  //while (list($i, $header) = each($a_headers))
245     {
246     $message_icon = $attach_icon = $flagged_icon = '';
247     $js_row_arr = array();
248     $zebra_class = $i%2 ? ' even' : ' odd';
249
250     // set messag attributes to javascript array
251     if ($header->deleted)
252       $js_row_arr['deleted'] = true;
253     if (!$header->seen)
254       $js_row_arr['unread'] = true;
255     if ($header->answered)
256       $js_row_arr['replied'] = true;
257     if ($header->forwarded)
258       $js_row_arr['forwarded'] = true;
259     if ($header->flagged)
260       $js_row_arr['flagged'] = true;
261
262     // set message icon  
263     if ($attrib['deletedicon'] && $header->deleted)
264       $message_icon = $attrib['deletedicon'];
265     else if ($attrib['repliedicon'] && $header->answered)
266       {
267       if ($attrib['forwardedrepliedicon'] && $header->forwarded)
268         $message_icon = $attrib['forwardedrepliedicon'];
269       else
270         $message_icon = $attrib['repliedicon'];
271       }
272     else if ($attrib['forwardedicon'] && $header->forwarded)
273       $message_icon = $attrib['forwardedicon'];
274     else if ($attrib['unreadicon'] && !$header->seen)
275       $message_icon = $attrib['unreadicon'];
276     else if ($attrib['messageicon'])
277       $message_icon = $attrib['messageicon'];
278
279     if ($attrib['flaggedicon'] && $header->flagged)
280       $flagged_icon = $attrib['flaggedicon'];
281     else if ($attrib['unflaggedicon'] && !$header->flagged)
282       $flagged_icon = $attrib['unflaggedicon'];
283     
284     // set attachment icon
285     if ($attrib['attachmenticon'] && preg_match("/multipart\/m/i", $header->ctype))
286       $attach_icon = $attrib['attachmenticon'];
287         
288     $out .= sprintf('<tr id="rcmrow%d" class="message%s%s%s%s">'."\n",
289                     $header->uid,
290                     $header->seen ? '' : ' unread',
291                     $header->deleted ? ' deleted' : '',
292                     $header->flagged ? ' flagged' : '',
293                     $zebra_class);
294     
295     $out .= sprintf("<td class=\"icon\">%s</td>\n", $message_icon ? sprintf($image_tag, $skin_path, $message_icon, '') : '');
296
297
298     if (!empty($header->charset))
299       $IMAP->set_charset($header->charset);
300   
301     // format each col
302     foreach ($a_show_cols as $col)
303       {
304       if ($col=='from' || $col=='to')
305         $cont = Q(rcmail_address_string($header->$col, 3, false, $attrib['addicon']), 'show');
306       else if ($col=='subject')
307         {
308         $action = $mbox==$CONFIG['drafts_mbox'] ? 'compose' : 'show';
309         $uid_param = $mbox==$CONFIG['drafts_mbox'] ? '_draft_uid' : '_uid';
310         $cont = abbreviate_string(trim($IMAP->decode_header($header->$col)), 160);
311         if (empty($cont)) $cont = rcube_label('nosubject');
312         $cont = sprintf('<a href="%s" onclick="return rcube_event.cancel(event)">%s</a>', Q(rcmail_url($action, array($uid_param=>$header->uid, '_mbox'=>$mbox))), Q($cont));
313         }
314       else if ($col=='flag')
315         $cont = $flagged_icon ? sprintf($image_tag, $skin_path, $flagged_icon, '') : '';
316       else if ($col=='size')
317         $cont = show_bytes($header->$col);
318       else if ($col=='date')
319         $cont = format_date($header->date);
320       else
321         $cont = Q($header->$col);
322         
323       if ($col!='attachment')
324         $out .= '<td class="'.$col.'">' . $cont . "</td>\n";
325       else
326         $out .= sprintf("<td class=\"icon\">%s</td>\n", $attach_icon ? sprintf($image_tag, $skin_path, $attach_icon, '') : '&nbsp;');
327       }
328
329     $out .= "</tr>\n";
330     
331     if (sizeof($js_row_arr))
332       $a_js_message_arr[$header->uid] = $js_row_arr;
333     }
334   
335   // complete message table
336   $out .= "</tbody></table>\n";
337   
338   $message_count = $IMAP->messagecount();
339   
340   // set client env
341   $OUTPUT->add_gui_object('mailcontframe', 'mailcontframe');
342   $OUTPUT->add_gui_object('messagelist', $attrib['id']);
343   $OUTPUT->set_env('messagecount', $message_count);
344   $OUTPUT->set_env('current_page', $IMAP->list_page);
345   $OUTPUT->set_env('pagecount', ceil($message_count/$IMAP->page_size));
346   $OUTPUT->set_env('sort_col', $sort_col);
347   $OUTPUT->set_env('sort_order', $sort_order);
348   
349   if ($attrib['messageicon'])
350     $OUTPUT->set_env('messageicon', $skin_path . $attrib['messageicon']);
351   if ($attrib['deletedicon'])
352     $OUTPUT->set_env('deletedicon', $skin_path . $attrib['deletedicon']);
353   if ($attrib['unreadicon'])
354     $OUTPUT->set_env('unreadicon', $skin_path . $attrib['unreadicon']);
355   if ($attrib['repliedicon'])
356     $OUTPUT->set_env('repliedicon', $skin_path . $attrib['repliedicon']);
357   if ($attrib['forwardedicon'])
358     $OUTPUT->set_env('forwardedicon', $skin_path . $attrib['forwardedicon']);
359   if ($attrib['forwardedrepliedicon'])
360     $OUTPUT->set_env('forwardedrepliedicon', $skin_path . $attrib['forwardedrepliedicon']);
361   if ($attrib['attachmenticon'])
362     $OUTPUT->set_env('attachmenticon', $skin_path . $attrib['attachmenticon']);
363   if ($attrib['flaggedicon'])
364     $OUTPUT->set_env('flaggedicon', $skin_path . $attrib['flaggedicon']);
365   if ($attrib['unflaggedicon'])
366     $OUTPUT->set_env('unflaggedicon', $skin_path . $attrib['unflaggedicon']);
367   
368   $OUTPUT->set_env('messages', $a_js_message_arr);
369   $OUTPUT->set_env('coltypes', $a_show_cols);
370   
371   $OUTPUT->include_script('list.js');
372   
373   return $out;
374   }
375
376
377 /**
378  * return javascript commands to add rows to the message list
379  */
380 function rcmail_js_message_list($a_headers, $insert_top=FALSE)
381   {
382   global $CONFIG, $IMAP, $OUTPUT;
383
384   if (empty($_SESSION['list_columns']))
385     $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
386   else
387     $a_show_cols = $_SESSION['list_columns'];
388
389   $mbox = $IMAP->get_mailbox_name();
390
391   // show 'to' instead of from in sent messages
392   if (($mbox == $CONFIG['sent_mbox'] || $mbox == $CONFIG['drafts_mbox'])
393       && (($f = array_search('from', $a_show_cols)) !== false) && array_search('to', $a_show_cols) === false)
394     $a_show_cols[$f] = 'to';
395
396   $OUTPUT->command('set_message_coltypes', $a_show_cols);
397
398   // loop through message headers
399   foreach ($a_headers as $n => $header)
400     {
401     $a_msg_cols = array();
402     $a_msg_flags = array();
403     
404     if (empty($header))
405       continue;
406
407     if (!empty($header->charset))
408       $IMAP->set_charset($header->charset);
409
410     // remove 'attachment' and 'flag' columns, we don't need them here
411     if(($key = array_search('attachment', $a_show_cols)) !== FALSE)
412       unset($a_show_cols[$key]);
413     if(($key = array_search('flag', $a_show_cols)) !== FALSE)
414       unset($a_show_cols[$key]);
415
416     // format each col; similar as in rcmail_message_list()
417     foreach ($a_show_cols as $col)
418       {
419       if ($col=='from' || $col=='to')
420         $cont = Q(rcmail_address_string($header->$col, 3), 'show');
421       else if ($col=='subject')
422         {
423         $action = $mbox==$CONFIG['drafts_mbox'] ? 'compose' : 'show';
424         $uid_param = $mbox==$CONFIG['drafts_mbox'] ? '_draft_uid' : '_uid';
425         $cont = abbreviate_string(trim($IMAP->decode_header($header->$col)), 160);
426         if (!$cont) $cont = rcube_label('nosubject');
427         $cont = sprintf('<a href="%s" onclick="return rcube_event.cancel(event)">%s</a>', Q(rcmail_url($action, array($uid_param=>$header->uid, '_mbox'=>$mbox))), Q($cont));
428         }
429       else if ($col=='size')
430         $cont = show_bytes($header->$col);
431       else if ($col=='date')
432         $cont = format_date($header->date);
433       else
434         $cont = Q($header->$col);
435           
436       $a_msg_cols[$col] = $cont;
437       }
438
439     $a_msg_flags['deleted'] = $header->deleted ? 1 : 0;
440     $a_msg_flags['unread'] = $header->seen ? 0 : 1;
441     $a_msg_flags['replied'] = $header->answered ? 1 : 0;
442     $a_msg_flags['forwarded'] = $header->forwarded ? 1 : 0;
443     $a_msg_flags['flagged'] = $header->flagged ? 1 : 0;
444     
445     $OUTPUT->command('add_message_row',
446       $header->uid,
447       $a_msg_cols,
448       $a_msg_flags,
449       preg_match("/multipart\/m/i", $header->ctype),
450       $insert_top);
451     }
452   }
453
454
455 /**
456  * return an HTML iframe for loading mail content
457  */
458 function rcmail_messagecontent_frame($attrib)
459   {
460   global $OUTPUT;
461   
462   if (empty($attrib['id']))
463     $attrib['id'] = 'rcmailcontentwindow';
464
465   $attrib['name'] = $attrib['id'];
466
467   $OUTPUT->set_env('contentframe', $attrib['id']);
468   $OUTPUT->set_env('blankpage', $attrib['src'] ? $OUTPUT->abs_url($attrib['src']) : 'program/blank.gif');
469
470   return html::iframe($attrib);
471   }
472
473
474 /**
475  *
476  */
477 function rcmail_messagecount_display($attrib)
478   {
479   global $IMAP, $OUTPUT;
480   
481   if (!$attrib['id'])
482     $attrib['id'] = 'rcmcountdisplay';
483
484   $OUTPUT->add_gui_object('countdisplay', $attrib['id']);
485
486   return html::span($attrib, rcmail_get_messagecount_text());
487   }
488
489
490 /**
491  *
492  */
493 function rcmail_quota_display($attrib)
494   {
495   global $OUTPUT, $COMM_PATH;
496
497   if (!$attrib['id'])
498     $attrib['id'] = 'rcmquotadisplay';
499
500   if(isset($attrib['display']))
501     $_SESSION['quota_display'] = $attrib['display'];
502
503   $OUTPUT->add_gui_object('quotadisplay', $attrib['id']);
504
505   return html::span($attrib, rcmail_quota_content(NULL, $attrib));
506   }
507
508
509 /**
510  *
511  */
512 function rcmail_quota_content($quota=NULL, $attrib=NULL)
513   {
514   global $IMAP, $COMM_PATH, $RCMAIL;
515
516   $display = isset($_SESSION['quota_display']) ? $_SESSION['quota_display'] : '';
517
518   if (is_array($quota) && !empty($quota['used']) && !empty($quota['total']))
519     {
520       if (!isset($quota['percent']))
521         $quota['percent'] = $quota['used'] / $quota['total'];
522     }
523   elseif (!$IMAP->get_capability('QUOTA'))
524     return rcube_label('unknown');
525   else
526     $quota = $IMAP->get_quota();
527
528   if ($quota && !($quota['total']==0 && $RCMAIL->config->get('quota_zero_as_unlimited')))
529     {
530     $quota_text = sprintf('%s / %s (%.0f%%)',
531                           show_bytes($quota['used'] * 1024),
532                           show_bytes($quota['total'] * 1024),
533                           $quota['percent']);
534
535     // show quota as image (by Brett Patterson)
536     if ($display == 'image' && function_exists('imagegif'))
537       {
538       if (!$attrib['width'])
539         $attrib['width'] = isset($_SESSION['quota_width']) ? $_SESSION['quota_width'] : 100;
540       else
541         $_SESSION['quota_width'] = $attrib['width'];
542
543       if (!$attrib['height'])
544         $attrib['height'] = isset($_SESSION['quota_height']) ? $_SESSION['quota_height'] : 14;
545       else
546         $_SESSION['quota_height'] = $attrib['height'];
547             
548       $quota_text = sprintf('<img src="./bin/quotaimg.php?u=%s&amp;q=%d&amp;w=%d&amp;h=%d" width="%d" height="%d" alt="%s" title="%s / %s" />',
549                             $quota['used'], $quota['total'],
550                             $attrib['width'], $attrib['height'],
551                             $attrib['width'], $attrib['height'],
552                             $quota_text,
553                             show_bytes($quota['used'] * 1024),
554                             show_bytes($quota['total'] * 1024));
555       }
556     }
557   else
558     $quota_text = rcube_label('unlimited');
559
560   return $quota_text;
561   }
562
563
564 /**
565  *
566  */
567 function rcmail_get_messagecount_text($count=NULL, $page=NULL)
568   {
569   global $IMAP, $MESSAGE;
570   
571   if (isset($MESSAGE->index))
572     {
573     return rcube_label(array('name' => 'messagenrof',
574                              'vars' => array('nr'  => $MESSAGE->index+1,
575                                              'count' => $count!==NULL ? $count : $IMAP->messagecount())));
576     }
577
578   if ($page===NULL)
579     $page = $IMAP->list_page;
580     
581   $start_msg = ($page-1) * $IMAP->page_size + 1;
582   $max = $count!==NULL ? $count : $IMAP->messagecount();
583
584   if ($max==0)
585     $out = rcube_label('mailboxempty');
586   else
587     $out = rcube_label(array('name' => 'messagesfromto',
588                               'vars' => array('from'  => $start_msg,
589                                               'to'    => min($max, $start_msg + $IMAP->page_size - 1),
590                                               'count' => $max)));
591
592   return Q($out);
593   }
594
595 /**
596  *
597  */
598 function rcmail_mailbox_name_display($attrib)
599 {
600     global $RCMAIL;
601
602     if (!$attrib['id'])
603         $attrib['id'] = 'rcmmailboxname';
604
605     $RCMAIL->output->add_gui_object('mailboxname', $attrib['id']);
606
607     return html::span($attrib, rcmail_get_mailbox_name_text());
608 }
609
610 function rcmail_get_mailbox_name_text()
611 {
612     global $RCMAIL;
613     return rcmail_localize_foldername($RCMAIL->imap->get_mailbox_name());
614 }
615
616
617 /**
618  * Convert the given message part to proper HTML
619  * which can be displayed the message view
620  *
621  * @param object rcube_message_part Message part
622  * @param bool  True if external objects (ie. images ) are allowed
623  * @param bool  True if part should be converted to plaintext
624  * @return string Formatted HTML string
625  */
626 function rcmail_print_body($part, $p = array())
627 {
628   global $REMOTE_OBJECTS;
629   
630   $p += array('safe' => false, 'plain' => false, 'inline_html' => true);
631   
632   // convert html to text/plain
633   if ($part->ctype_secondary == 'html' && $p['plain']) {
634     $txt = new html2text($part->body, false, true);
635     $body = $txt->get_text();
636     $part->ctype_secondary = 'plain';
637   }
638   // text/html
639   else if ($part->ctype_secondary == 'html') {
640     $html = $part->body;
641
642     // special replacements (not properly handled by washtml class)
643     $html_search = array(
644       '/(<\/nobr>)(\s+)(<nobr>)/i',     // space(s) between <NOBR>
645       '/(<[\/]*st1:[^>]+>)/i',          // Microsoft's Smart Tags <ST1>
646       '/<\/?rte_text>/i',               // Rich Text Editor tags (#1485647)
647       '/<title>.*<\/title>/i',          // PHP bug #32547 workaround: remove title tag
648       '/<html[^>]*>/im',                // malformed html: remove html tags (#1485139)
649       '/<\/html>/i',                    // malformed html: remove html tags (#1485139)
650       '/^[\xFE\xFF\xBB\xBF\x00]+((?:<\!doctype|\<html))/im',    // remove byte-order mark (only outlook?)
651     );
652     $html_replace = array(
653       '\\1'.' &nbsp; '.'\\3',
654       '',
655       '',
656       '',
657       '',
658       '',
659       '\\1',
660     );
661     $html = preg_replace($html_search, $html_replace, $html);
662
663     // charset was converted to UTF-8 in rcube_imap::get_message_part() -> change charset specification in HTML accordingly
664     $charset_pattern = '/(\s+content=[\'"]?\w+\/\w+;\s*charset)=([a-z0-9-_]+)/i';
665     if (preg_match($charset_pattern, $html)) {
666       $html = preg_replace($charset_pattern, '\\1='.RCMAIL_CHARSET, $html);
667     }
668     else {
669       // add head for malformed messages, washtml cannot work without that
670       if (!preg_match('/<head[^>]*>(.*)<\/head>/Uims', $html))
671         $html = '<head></head>'. $html;
672       $html = substr_replace($html, '<meta http-equiv="content-type" content="text/html; charset='.RCMAIL_CHARSET.'" />', intval(stripos($html, '<head>')+6), 0);
673     }
674
675     // clean HTML with washhtml by Frederic Motte
676     $wash_opts = array(
677       'show_washed' => false,
678       'allow_remote' => $p['safe'],
679       'blocked_src' => "./program/blocked.gif",
680       'charset' => RCMAIL_CHARSET,
681       'cid_map' => $part->replaces,
682       'html_elements' => array('body'),
683     );
684     
685     if (!$p['inline_html']) {
686       $wash_opts['html_elements'] = array('html','head','title','body');
687     }
688     
689     $washer = new washtml($wash_opts);
690     $washer->add_callback('form', 'rcmail_washtml_callback');
691     
692     if ($p['safe']) {  // allow CSS styles, will be sanitized by rcmail_washtml_callback()
693       $washer->add_callback('style', 'rcmail_washtml_callback');
694     }
695     
696     $body = $washer->wash($html);
697     $REMOTE_OBJECTS = $washer->extlinks;
698
699     return $body;
700   }
701   // text/enriched
702   else if ($part->ctype_secondary=='enriched') {
703     $part->ctype_secondary = 'html';
704     return Q(enriched_to_html($part->body), 'show');
705   }
706   else
707     $body = $part->body;
708
709
710   /**** assert plaintext ****/
711
712   // make links and email-addresses clickable
713   $convert_patterns = $convert_replaces = $replace_strings = array();
714   
715   $url_chars = 'a-z0-9_\-\+\*\$\/&%=@#:;';
716   $url_chars_within = '\?\.~,!';
717
718   $convert_patterns[] = "/([\w]+):\/\/([a-z0-9\-\.]+[a-z]{2,4}([$url_chars$url_chars_within]*[$url_chars])?)/ie";
719   $convert_replaces[] = "rcmail_str_replacement('<a href=\"\\1://\\2\" target=\"_blank\">\\1://\\2</a>', \$replace_strings)";
720
721   $convert_patterns[] = "/([^\/:]|\s)(www\.)([a-z0-9\-]{2,}[a-z]{2,4}([$url_chars$url_chars_within]*[$url_chars])?)/ie";
722   $convert_replaces[] = "rcmail_str_replacement('\\1<a href=\"http://\\2\\3\" target=\"_blank\">\\2\\3</a>', \$replace_strings)";
723   
724   $convert_patterns[] = '/([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9]([a-z0-9\-][.]?)*[a-z0-9]\\.[a-z]{2,5})/ie';
725   $convert_replaces[] = "rcmail_str_replacement('<a href=\"mailto:\\1\" onclick=\"return ".JS_OBJECT_NAME.".command(\'compose\',\'\\1\',this)\">\\1</a>', \$replace_strings)";
726   
727   // search for patterns like links and e-mail addresses
728   $body = preg_replace($convert_patterns, $convert_replaces, $body);
729
730   // split body into single lines
731   $a_lines = preg_split('/\r?\n/', $body);
732   $quote_level = 0;
733
734   // colorize quoted parts
735   for ($n=0; $n < sizeof($a_lines); $n++) {
736     $line = $a_lines[$n];
737     $quotation = '';
738     $q = 0;
739     
740     if (preg_match('/^(>+\s*)+/', $line, $regs)) {
741       $q    = strlen(preg_replace('/\s/', '', $regs[0]));
742       $line = substr($line, strlen($regs[0]));
743
744       if ($q > $quote_level)
745         $quotation = str_repeat('<blockquote>', $q - $quote_level);
746       else if ($q < $quote_level)
747         $quotation = str_repeat("</blockquote>", $quote_level - $q);
748     }
749     else if ($quote_level > 0)
750       $quotation = str_repeat("</blockquote>", $quote_level);
751
752     $quote_level = $q;
753     $a_lines[$n] = $quotation . Q($line, 'replace', false);  // htmlquote plaintext
754   }
755
756   // insert the links for urls and mailtos
757   $body = preg_replace("/##string_replacement\{([0-9]+)\}##/e", "\$replace_strings[\\1]", join("\n", $a_lines));
758
759   return html::tag('pre', array(), $body);
760 }
761
762 /**
763  * add a string to the replacement array and return a replacement string
764  */
765 function rcmail_str_replacement($str, &$rep)
766 {
767   static $count = 0;
768   $rep[$count] = stripslashes($str);
769   return "##string_replacement{".($count++)."}##";
770 }
771
772
773 /**
774  * Callback function for washtml cleaning class
775  */
776 function rcmail_washtml_callback($tagname, $attrib, $content)
777 {
778   switch ($tagname) {
779     case 'form':
780       $out = html::div('form', $content);
781       break;
782       
783     case 'style':
784       // decode all escaped entities and reduce to ascii strings
785       $stripped = preg_replace('/[^a-zA-Z\(:]/', '', rcmail_xss_entitiy_decode($content));
786       
787       // now check for evil strings like expression, behavior or url()
788       if (!preg_match('/expression|behavior|url\(|import/', $stripped)) {
789         $out = html::tag('style', array('type' => 'text/css'), $content);
790         break;
791       }
792     
793     default:
794       $out = '';
795   }
796   
797   return $out;
798 }
799
800
801 /**
802  * return table with message headers
803  */
804 function rcmail_message_headers($attrib, $headers=NULL)
805   {
806   global $IMAP, $OUTPUT, $MESSAGE, $PRINT_MODE, $CONFIG;
807   static $sa_attrib;
808   
809   // keep header table attrib
810   if (is_array($attrib) && !$sa_attrib)
811     $sa_attrib = $attrib;
812   else if (!is_array($attrib) && is_array($sa_attrib))
813     $attrib = $sa_attrib;
814   
815   
816   if (!isset($MESSAGE))
817     return FALSE;
818
819   // get associative array of headers object
820   if (!$headers)
821     $headers = is_object($MESSAGE->headers) ? get_object_vars($MESSAGE->headers) : $MESSAGE->headers;
822     
823   $header_count = 0;
824   
825   // allow the following attributes to be added to the <table> tag
826   $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
827   $out = '<table' . $attrib_str . ">\n";
828
829   // show these headers
830   $standard_headers = array('subject', 'from', 'to', 'cc', 'bcc', 'replyto', 'date');
831
832   foreach ($standard_headers as $hkey)
833     {
834     if (!$headers[$hkey])
835       continue;
836
837     if ($hkey == 'date')
838       {
839       if ($PRINT_MODE)
840         $header_value = format_date($headers[$hkey], $CONFIG['date_long'] ? $CONFIG['date_long'] : 'x');
841       else
842         $header_value = format_date($headers[$hkey]);
843       }
844     else if ($hkey == 'replyto')
845       {
846       if ($headers['replyto'] != $headers['from'])
847         $header_value = Q(rcmail_address_string($headers['replyto'], null, true, $attrib['addicon']), 'show');
848       else
849         continue;
850       }
851     else if (in_array($hkey, array('from', 'to', 'cc', 'bcc')))
852       $header_value = Q(rcmail_address_string($headers[$hkey], null, true, $attrib['addicon']), 'show');
853     else if ($hkey == 'subject' && empty($headers[$hkey]))
854       $header_value = Q(rcube_label('nosubject'));
855     else
856       $header_value = Q(trim($IMAP->decode_header($headers[$hkey])));
857
858     $out .= "\n<tr>\n";
859     $out .= '<td class="header-title">'.Q(rcube_label($hkey)).":&nbsp;</td>\n";
860     $out .= '<td class="'.$hkey.'" width="90%">'.$header_value."</td>\n</tr>";
861     $header_count++;
862     }
863
864   // all headers division
865   $out .= "\n".'<tr><td colspan="2" class="more-headers show-headers"
866         onclick="return '.JS_OBJECT_NAME.'.command(\'load-headers\', \'\', this)"></td></tr>';
867   $out .= "\n".'<tr id="all-headers"><td colspan="2" class="all"><div id="headers-source"></div></td></tr>';
868
869   $OUTPUT->add_gui_object('all_headers_row', 'all-headers');
870   $OUTPUT->add_gui_object('all_headers_box', 'headers-source');
871
872   $out .= "\n</table>\n\n";
873
874   return $header_count ? $out : '';  
875   }
876
877
878 /**
879  * Handler for the 'messagebody' GUI object
880  *
881  * @param array Named parameters
882  * @return string HTML content showing the message body
883  */
884 function rcmail_message_body($attrib)
885   {
886   global $CONFIG, $OUTPUT, $MESSAGE, $IMAP, $REMOTE_OBJECTS;
887
888   if (!is_array($MESSAGE->parts) && empty($MESSAGE->body))
889     return '';
890     
891   if (!$attrib['id'])
892     $attrib['id'] = 'rcmailMsgBody';
893
894   $safe_mode = $MESSAGE->is_safe || intval($_GET['_safe']);
895   $out = '';
896   
897   $header_attrib = array();
898   foreach ($attrib as $attr => $value)
899     if (preg_match('/^headertable([a-z]+)$/i', $attr, $regs))
900       $header_attrib[$regs[1]] = $value;
901
902   if (!empty($MESSAGE->parts))
903     {
904     foreach ($MESSAGE->parts as $i => $part)
905       {
906       if ($part->type == 'headers')
907         $out .= rcmail_message_headers(sizeof($header_attrib) ? $header_attrib : NULL, $part->headers);
908       else if ($part->type == 'content')
909         {
910         if (empty($part->ctype_parameters) || empty($part->ctype_parameters['charset']))
911           $part->ctype_parameters['charset'] = $MESSAGE->headers->charset;
912
913         // fetch part if not available
914         if (!isset($part->body))
915           $part->body = $MESSAGE->get_part_content($part->mime_id);
916
917         $body = rcmail_print_body($part, array('safe' => $safe_mode, 'plain' => !$CONFIG['prefer_html']));
918
919         if ($part->ctype_secondary == 'html')
920           $out .= html::div('message-htmlpart', rcmail_html4inline($body, $attrib['id']));
921         else
922           $out .= html::div('message-part', $body);
923         }
924       }
925     }
926   else
927     $out .= html::div('message-part', html::tag('pre', array(), Q($MESSAGE->body)));
928
929
930   $ctype_primary = strtolower($MESSAGE->structure->ctype_primary);
931   $ctype_secondary = strtolower($MESSAGE->structure->ctype_secondary);
932
933   // list images after mail body
934   if ($CONFIG['inline_images']
935       && $ctype_primary == 'multipart'
936       && !empty($MESSAGE->attachments) 
937       && !strstr($message_body, '<html'))
938     {
939     foreach ($MESSAGE->attachments as $attach_prop) {
940       if (strpos($attach_prop->mimetype, 'image/') === 0) {
941         $out .= html::tag('hr') . html::p(array('align' => "center"),
942           html::img(array(
943             'src' => $MESSAGE->get_part_url($attach_prop->mime_id),
944             'title' => $attach_prop->filename,
945             'alt' => $attach_prop->filename,
946           )));
947         }
948     }
949   }
950   
951   // tell client that there are blocked remote objects
952   if ($REMOTE_OBJECTS && !$safe_mode)
953     $OUTPUT->set_env('blockedobjects', true);
954
955   return html::div($attrib, $out);
956   }
957
958
959
960 /**
961  * modify a HTML message that it can be displayed inside a HTML page
962  */
963 function rcmail_html4inline($body, $container_id)
964   {
965   $base_url = "";
966   $last_style_pos = 0;
967   $body_lc = strtolower($body);
968   
969   // check for <base href>
970   if (preg_match(($base_reg = '/(<base.*href=["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)([^<]*>)/i'), $body, $base_regs))
971     $base_url = $base_regs[2];
972   
973   // find STYLE tags
974   while (($pos = strpos($body_lc, '<style', $last_style_pos)) && ($pos2 = strpos($body_lc, '</style>', $pos)))
975     {
976     $pos = strpos($body_lc, '>', $pos)+1;
977
978     // replace all css definitions with #container [def]
979     $styles = rcmail_mod_css_styles(substr($body, $pos, $pos2-$pos), $container_id, $base_url);
980
981     $body = substr($body, 0, $pos) . $styles . substr($body, $pos2);
982     $body_lc = strtolower($body);
983     $last_style_pos = $pos2;
984     }
985
986   // resolve <base href>
987   if ($base_url)
988     {
989     $body = preg_replace('/(src|background|href)=(["\']?)([\.\/]+[^"\'\s]+)(\2|\s|>)/Uie', "'\\1=\"'.make_absolute_url('\\3', '$base_url').'\"'", $body);
990     $body = preg_replace('/(url\s*\()(["\']?)([\.\/]+[^"\'\)\s]+)(\2)\)/Uie', "'\\1\''.make_absolute_url('\\3', '$base_url').'\')'", $body);
991     $body = preg_replace($base_reg, '', $body);
992     }
993     
994   // modify HTML links to open a new window if clicked
995   $body = preg_replace('/<(a|link)\s+([^>]+)>/Uie', "rcmail_alter_html_link('\\1','\\2', '$container_id');", $body);
996
997   // add comments arround html and other tags
998   $out = preg_replace(array(
999       '/(<!DOCTYPE[^>]*>)/i',
1000       '/(<\?xml[^>]*>)/i',
1001       '/(<\/?html[^>]*>)/i',
1002       '/(<\/?head[^>]*>)/i',
1003       '/(<title[^>]*>.*<\/title>)/Ui',
1004       '/(<\/?meta[^>]*>)/i'),
1005     '<!--\\1-->',
1006     $body);
1007
1008   $out = preg_replace(
1009     array('/<body([^>]*)>/i', '/<\/body>/i'),
1010     array('<div class="rcmBody"\\1>', '</div>'),
1011     $out);
1012
1013   // quote <? of php and xml files that are specified as text/html
1014   $out = preg_replace(array('/<\?/', '/\?>/'), array('&lt;?', '?&gt;'), $out);
1015
1016   return $out;
1017   }
1018
1019
1020 /**
1021  * parse link attributes and set correct target
1022  */
1023 function rcmail_alter_html_link($tag, $attrs, $container_id)
1024 {
1025   $attrib = parse_attrib_string($attrs);
1026   $end = '>';
1027
1028   if ($tag == 'link' && preg_match('/^https?:\/\//i', $attrib['href'])) {
1029     $attrib['href'] = "./bin/modcss.php?u=" . urlencode($attrib['href']) . "&amp;c=" . urlencode($container_id);
1030     $end = ' />';
1031   }
1032   else if (stristr((string)$attrib['href'], 'mailto:')) {
1033     $attrib['onclick'] = sprintf(
1034       "return %s.command('compose','%s',this)",
1035       JS_OBJECT_NAME,
1036       JQ(substr($attrib['href'], 7)));
1037   }
1038   else if (!empty($attrib['href']) && $attrib['href'][0] != '#') {
1039     $attrib['target'] = '_blank';
1040   }
1041
1042   return "<$tag" . html::attrib_string($attrib, array('href','name','target','onclick','id','class','style','title','rel','type','media')) . $end;
1043 }
1044
1045
1046 /**
1047  * decode address string and re-format it as HTML links
1048  */
1049 function rcmail_address_string($input, $max=null, $linked=false, $addicon=null)
1050 {
1051   global $IMAP, $PRINT_MODE, $CONFIG, $OUTPUT, $EMAIL_ADDRESS_PATTERN;
1052
1053   $a_parts = $IMAP->decode_address_list($input);
1054
1055   if (!sizeof($a_parts))
1056     return $input;
1057
1058   $c = count($a_parts);
1059   $j = 0;
1060   $out = '';
1061
1062   foreach ($a_parts as $part) {
1063     $j++;
1064     if ($PRINT_MODE) {
1065       $out .= sprintf('%s &lt;%s&gt;', Q($part['name']), $part['mailto']);
1066     }
1067     else if (preg_match($EMAIL_ADDRESS_PATTERN, $part['mailto'])) {
1068       if ($linked) {
1069         $out .= html::a(array(
1070             'href' => 'mailto:'.$part['mailto'],
1071             'onclick' => sprintf("return %s.command('compose','%s',this)", JS_OBJECT_NAME, JQ($part['mailto'])),
1072             'title' => $part['mailto'],
1073             'class' => "rcmContactAddress",
1074           ),
1075         Q($part['name']));
1076       }
1077       else {
1078         $out .= html::span(array('title' => $part['mailto'], 'class' => "rcmContactAddress"), Q($part['name']));
1079       }
1080
1081       if ($addicon) {
1082         $out .= '&nbsp;' . html::a(array(
1083             'href' => "#add",
1084             'onclick' => sprintf("return %s.command('add-contact','%s',this)", JS_OBJECT_NAME, urlencode($part['string'])),
1085             'title' => rcube_label('addtoaddressbook'),
1086           ),
1087           html::img(array(
1088             'src' => $CONFIG['skin_path'] . $addicon,
1089             'alt' => "Add contact",
1090           )));
1091       }
1092     }
1093     else {
1094       if ($part['name'])
1095         $out .= Q($part['name']);
1096       if ($part['mailto'])
1097         $out .= (strlen($out) ? ' ' : '') . sprintf('&lt;%s&gt;', Q($part['mailto']));
1098     }
1099       
1100     if ($c>$j)
1101       $out .= ','.($max ? '&nbsp;' : ' ');
1102         
1103     if ($max && $j==$max && $c>$j) {
1104       $out .= '...';
1105       break;
1106     }
1107   }
1108     
1109   return $out;
1110 }
1111
1112
1113 /**
1114  * Wrap text to a given number of characters per line
1115  * but respect the mail quotation of replies messages (>)
1116  *
1117  * @param string Text to wrap
1118  * @param int The line width
1119  * @return string The wrapped text
1120  */
1121 function rcmail_wrap_quoted($text, $max = 76)
1122 {
1123   // Rebuild the message body with a maximum of $max chars, while keeping quoted message.
1124   $lines = preg_split('/\r?\n/', trim($text));
1125   $out = '';
1126
1127   foreach ($lines as $line) {
1128     if (strlen($line) > $max) {
1129       if (preg_match('/^([>\s]+)/', $line, $regs)) {
1130         $length = strlen($regs[0]);
1131         $prefix = substr($line, 0, $length);
1132
1133         // Remove '> ' from the line, then wordwrap() the line
1134         $line = wordwrap(substr($line, $length), $max - $length);
1135
1136         // Rebuild the line with '> ' at the beginning of each 'subline'
1137         $newline = '';
1138         foreach (explode("\n", $line) as $l) {
1139           $newline .= $prefix . $l . "\n";
1140         }
1141
1142         // Remove the righest newline char
1143         $line = rtrim($newline);
1144       }
1145       else {
1146         $line = wordwrap($line, $max);
1147       }
1148     }
1149
1150     // Append the line
1151     $out .= $line . "\n";
1152   }
1153   
1154   return $out;
1155 }
1156
1157
1158 function rcmail_message_part_controls()
1159   {
1160   global $MESSAGE;
1161   
1162   $part = asciiwords(get_input_value('_part', RCUBE_INPUT_GPC));
1163   if (!is_object($MESSAGE) || !is_array($MESSAGE->parts) || !($_GET['_uid'] && $_GET['_part']) || !$MESSAGE->mime_parts[$part])
1164     return '';
1165     
1166   $part = $MESSAGE->mime_parts[$part];
1167   $table = new html_table(array('cols' => 3));
1168   
1169   if (!empty($part->filename)) {
1170     $table->add('title', Q(rcube_label('filename')));
1171     $table->add(null, Q($part->filename));
1172     $table->add(null, '[' . html::a('?'.str_replace('_frame=', '_download=', $_SERVER['QUERY_STRING']), Q(rcube_label('download'))) . ']');
1173   }
1174   
1175   if (!empty($part->size)) {
1176     $table->add('title', Q(rcube_label('filesize')));
1177     $table->add(null, Q(show_bytes($part->size)));
1178   }
1179   
1180   return $table->show($attrib);
1181   }
1182
1183
1184
1185 function rcmail_message_part_frame($attrib)
1186   {
1187   global $MESSAGE;
1188   
1189   $part = $MESSAGE->mime_parts[asciiwords(get_input_value('_part', RCUBE_INPUT_GPC))];
1190   $ctype_primary = strtolower($part->ctype_primary);
1191
1192   $attrib['src'] = './?' . str_replace('_frame=', ($ctype_primary=='text' ? '_show=' : '_preload='), $_SERVER['QUERY_STRING']);
1193
1194   return html::iframe($attrib);
1195   }
1196
1197
1198 /**
1199  * clear message composing settings
1200  */
1201 function rcmail_compose_cleanup()
1202   {
1203   if (!isset($_SESSION['compose']))
1204     return;
1205
1206   // remove attachment files from temp dir
1207   if (is_array($_SESSION['compose']['attachments']))
1208     foreach ($_SESSION['compose']['attachments'] as $attachment)
1209       @unlink($attachment['path']);
1210   
1211   unset($_SESSION['compose']);
1212   }
1213   
1214
1215 /**
1216  * Send the given message compose object using the configured method
1217  */
1218 function rcmail_deliver_message(&$message, $from, $mailto)
1219 {
1220   global $CONFIG, $RCMAIL;
1221
1222   $msg_body = $message->get();
1223   $headers = $message->headers();
1224
1225   // send thru SMTP server using custom SMTP library
1226   if ($CONFIG['smtp_server'])
1227     {
1228     // generate list of recipients
1229     $a_recipients = array($mailto);
1230   
1231     if (strlen($headers['Cc']))
1232       $a_recipients[] = $headers['Cc'];
1233     if (strlen($headers['Bcc']))
1234       $a_recipients[] = $headers['Bcc'];
1235   
1236     // clean Bcc from header for recipients
1237     $send_headers = $headers;
1238     unset($send_headers['Bcc']);
1239     // here too, it because txtHeaders() below use $message->_headers not only $send_headers
1240     unset($message->_headers['Bcc']);
1241
1242     // send message
1243     $smtp_response = array();
1244     $sent = smtp_mail($from, $a_recipients, ($foo = $message->txtHeaders($send_headers, true)), $msg_body, $smtp_response);
1245
1246     // log error
1247     if (!$sent)
1248       raise_error(array('code' => 800, 'type' => 'smtp', 'line' => __LINE__, 'file' => __FILE__,
1249                         'message' => "SMTP error: ".join("\n", $smtp_response)), TRUE, FALSE);
1250     }
1251   
1252   // send mail using PHP's mail() function
1253   else
1254     {
1255     // unset some headers because they will be added by the mail() function
1256     $headers_enc = $message->headers($headers);
1257     $headers_php = $message->_headers;
1258     unset($headers_php['To'], $headers_php['Subject']);
1259     
1260     // reset stored headers and overwrite
1261     $message->_headers = array();
1262     $header_str = $message->txtHeaders($headers_php);
1263   
1264     if (ini_get('safe_mode'))
1265       $sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str);
1266     else
1267       $sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str, "-f$from");
1268     }
1269   
1270   if ($sent)
1271   {
1272     // remove MDN headers after sending
1273     unset($headers['Return-Receipt-To'], $headers['Disposition-Notification-To']);
1274     
1275     if ($CONFIG['smtp_log'])
1276       write_log('sendmail', sprintf("User %s [%s]; Message for %s; %s",
1277                 $RCMAIL->user->get_username(),
1278                 $_SERVER['REMOTE_ADDR'],
1279                 $mailto,
1280                 !empty($smtp_response) ? join('; ', $smtp_response) : ''));
1281   }
1282   
1283   $message->_headers = array();
1284   $message->headers($headers);
1285   
1286   return $sent;
1287 }
1288
1289
1290 function rcmail_send_mdn($uid)
1291 {
1292   global $RCMAIL, $IMAP;
1293
1294   $message = new rcube_message($uid);
1295   
1296   if ($message->headers->mdn_to && !$message->headers->mdn_sent && $IMAP->check_permflag('MDNSENT'))
1297   {
1298     $identity = $RCMAIL->user->get_identity();
1299     $sender = format_email_recipient($identity['email'], $identity['name']);
1300     $recipient = array_shift($IMAP->decode_address_list($message->headers->mdn_to));
1301     $mailto = $recipient['mailto'];
1302
1303     $compose = new rcube_mail_mime($RCMAIL->config->header_delimiter());
1304     $compose->setParam(array(
1305       'text_encoding' => 'quoted-printable',
1306       'html_encoding' => 'quoted-printable',
1307       'head_encoding' => 'quoted-printable',
1308       'head_charset'  => RCMAIL_CHARSET,
1309       'html_charset'  => RCMAIL_CHARSET,
1310       'text_charset'  => RCMAIL_CHARSET,
1311     ));
1312     
1313     // compose headers array
1314     $headers = array(
1315       'Date' => date('r'),
1316       'From' => $sender,
1317       'To'   => $message->headers->mdn_to,
1318       'Subject' => rcube_label('receiptread') . ': ' . $message->subject,
1319       'Message-ID' => sprintf('<%s@%s>', md5(uniqid('rcmail'.rand(),true)), $RCMAIL->config->mail_domain($_SESSION['imap_host'])),
1320       'X-Sender' => $identity['email'],
1321       'Content-Type' => 'multipart/report; report-type=disposition-notification',
1322     );
1323     
1324     if ($agent = $RCMAIL->config->get('useragent'))
1325       $headers['User-Agent'] = $agent;
1326
1327     $body = rcube_label("yourmessage") . "\r\n\r\n" .
1328       "\t" . rcube_label("to") . ': ' . rcube_imap::decode_mime_string($message->headers->to, $message->headers->charset) . "\r\n" .
1329       "\t" . rcube_label("subject") . ': ' . $message->subject . "\r\n" .
1330       "\t" . rcube_label("sent") . ': ' . format_date($message->headers->date, $RCMAIL->config->get('date_long')) . "\r\n" .
1331       "\r\n" . rcube_label("receiptnote") . "\r\n";
1332     
1333     $ua = $RCMAIL->config->get('useragent', "RoundCube Webmail (Version ".RCMAIL_VERSION.")");
1334     $report = "Reporting-UA: $ua\r\n";
1335     
1336     if ($message->headers->to)
1337         $report .= "Original-Recipient: {$message->headers->to}\r\n";
1338     
1339     $report .= "Final-Recipient: rfc822; {$identity['email']}\r\n" .
1340                "Original-Message-ID: {$message->headers->messageID}\r\n" .
1341                "Disposition: manual-action/MDN-sent-manually; displayed\r\n";
1342     
1343     $compose->headers($headers);
1344     $compose->setTXTBody(wordwrap($body, 75, "\r\n"));
1345     $compose->addAttachment($report, 'message/disposition-notification', 'MDNPart2.txt', false, '7bit', 'inline');
1346
1347     $sent = rcmail_deliver_message($compose, $identity['email'], $mailto);
1348
1349     if ($sent)
1350     {
1351       $IMAP->set_flag($message->uid, 'MDNSENT');
1352       return true;
1353     }
1354   }
1355   
1356   return false;
1357 }
1358
1359
1360 function rcmail_search_filter($attrib)
1361 {
1362   global $OUTPUT;
1363
1364   if (!strlen($attrib['id']))
1365     $attrib['id'] = 'rcmlistfilter';
1366
1367   $attrib['onchange'] = JS_OBJECT_NAME.'.filter_mailbox(this.value)';
1368   
1369   /*
1370     RFC3501 (6.4.4): 'ALL', 'RECENT', 
1371     'ANSWERED', 'DELETED', 'FLAGGED', 'SEEN',
1372     'UNANSWERED', 'UNDELETED', 'UNFLAGGED', 'UNSEEN',
1373     'NEW', // = (RECENT UNSEEN)
1374     'OLD' // = NOT RECENT
1375   */
1376
1377   $select_filter = new html_select($attrib);
1378   $select_filter->add(rcube_label('all'), 'ALL');
1379   $select_filter->add(rcube_label('unread'), 'UNSEEN');
1380   $select_filter->add(rcube_label('flagged'), 'FLAGGED');
1381   $select_filter->add(rcube_label('unanswered'), 'UNANSWERED');
1382
1383   $out = $select_filter->show($_SESSION['search_filter']);
1384
1385   $OUTPUT->add_gui_object('search_filter', $attrib['id']);
1386
1387   return $out;                                                                          
1388 }
1389
1390 // register UI objects
1391 $OUTPUT->add_handlers(array(
1392   'mailboxlist' => 'rcmail_mailbox_list',
1393   'messages' => 'rcmail_message_list',
1394   'messagecountdisplay' => 'rcmail_messagecount_display',
1395   'quotadisplay' => 'rcmail_quota_display',
1396   'mailboxname' => 'rcmail_mailbox_name_display',
1397   'messageheaders' => 'rcmail_message_headers',
1398   'messagebody' => 'rcmail_message_body',
1399   'messagecontentframe' => 'rcmail_messagecontent_frame',
1400   'messagepartframe' => 'rcmail_message_part_frame',
1401   'messagepartcontrols' => 'rcmail_message_part_controls',
1402   'searchfilter' => 'rcmail_search_filter',
1403   'searchform' => array($OUTPUT, 'search_form'),
1404 ));
1405
1406 ?>