source: github/program/steps/mail/func.inc @ 6d20d01

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since 6d20d01 was 6d20d01, checked in by alecpl <alec@…>, 5 years ago

#1485384: fix quota span tag attribs

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