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

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