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

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