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

Last change on this file since 2401 was 2401, checked in by thomasb, 4 years ago

Merged branch devel-api (from r2208 to r2387) back into trunk (omitting some sample plugins)

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