source: github/program/steps/mail/func.inc @ 58687d0

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since 58687d0 was 58687d0, checked in by thomascube <thomas@…>, 4 years ago

Be more tolerant when splitting strings + remove col that we don't have a label for

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