source: subversion/trunk/roundcubemail/program/steps/mail/func.inc @ 2064

Last change on this file since 2064 was 2064, checked in by thomasb, 5 years ago

Remove BOM in html message body + don't require quotes in meta tag specifying charset

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