source: github/program/steps/mail/func.inc @ 6925adb

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since 6925adb was 6925adb, checked in by thomascube <thomas@…>, 5 years ago

Fix empty subject header display (#1485383) + improve safari CSS hacks

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