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

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since a862043 was a862043, checked in by svncommit <devs@…>, 5 years ago

restore some script environment variables removed in r1918 but needed in "show" action

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