source: github/program/steps/mail/func.inc @ a164a2e6

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