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

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