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

Last change on this file since 4024 was 4024, checked in by alec, 3 years ago
  • Fix charset replacement in HTML message bodies (#1487021)
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 56.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-2010, 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
22// setup some global vars used by mail steps
23$SENT_MBOX = $RCMAIL->config->get('sent_mbox');
24$DRAFTS_MBOX = $RCMAIL->config->get('drafts_mbox');
25$SEARCH_MODS_DEFAULT = array('*' => array('subject'=>1, 'from'=>1), $SENT_MBOX => array('subject'=>1, 'to'=>1), $DRAFTS_MBOX => array('subject'=>1, 'to'=>1));
26
27// Simplified for IDN in Unicode
28//$EMAIL_ADDRESS_PATTERN = '([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9][a-z0-9\-\.]*\\.[a-z]{2,5})';
29$EMAIL_ADDRESS_PATTERN = '([a-z0-9][a-z0-9\-\.\+\_]*@[^&@"\'.][^@&"\']*\\.[a-z]{2,5})';
30
31// actions that do not require imap connection here
32$NOIMAP_ACTIONS = array('addcontact', 'autocomplete', 'upload', 'display-attachment', 'remove-attachment', 'get');
33
34// always instantiate imap object (but not yet connect to server)
35$RCMAIL->imap_init();
36
37// log in to imap server
38if (!in_array($RCMAIL->action, $NOIMAP_ACTIONS) && !$RCMAIL->imap_connect()) {
39  $RCMAIL->kill_session();
40
41  if ($OUTPUT->ajax_call)
42    $OUTPUT->redirect(array(), 2000);
43
44  $OUTPUT->set_env('task', 'login');
45  $OUTPUT->send('login');
46}
47
48// set imap properties and session vars
49if ($mbox = get_input_value('_mbox', RCUBE_INPUT_GPC))
50  $IMAP->set_mailbox(($_SESSION['mbox'] = $mbox));
51else if ($IMAP)
52  $_SESSION['mbox'] = $IMAP->get_mailbox_name();
53
54if (!empty($_GET['_page']))
55  $IMAP->set_page(($_SESSION['page'] = intval($_GET['_page'])));
56
57// set default sort col/order to session
58if (!isset($_SESSION['sort_col']))
59  $_SESSION['sort_col'] = $CONFIG['message_sort_col'];
60if (!isset($_SESSION['sort_order']))
61  $_SESSION['sort_order'] = $CONFIG['message_sort_order'];
62
63// set threads mode
64$a_threading = $RCMAIL->config->get('message_threading', array());
65if (isset($_GET['_threads'])) {
66  if ($_GET['_threads'])
67    $a_threading[$_SESSION['mbox']] = true;
68  else
69    unset($a_threading[$_SESSION['mbox']]);
70  $RCMAIL->user->save_prefs(array('message_threading' => $a_threading));
71}
72$IMAP->set_threading($a_threading[$_SESSION['mbox']]);
73
74// set message set for search result
75if (!empty($_REQUEST['_search']) && isset($_SESSION['search'][$_REQUEST['_search']]))
76  {
77  $IMAP->set_search_set($_SESSION['search'][$_REQUEST['_search']]);
78  $OUTPUT->set_env('search_request', $_REQUEST['_search']);
79  $OUTPUT->set_env('search_text', $_SESSION['last_text_search']);
80  }
81
82// set main env variables, labels and page title
83if (empty($RCMAIL->action) || $RCMAIL->action == 'list')
84  {
85  $mbox_name = $IMAP->get_mailbox_name();
86
87  if (empty($RCMAIL->action))
88    {
89    // initialize searching result if search_filter is used
90    if ($_SESSION['search_filter'] && $_SESSION['search_filter'] != 'ALL')
91      {
92      $search_request = md5($mbox_name.$_SESSION['search_filter']);
93
94      $IMAP->search($mbox_name, $_SESSION['search_filter'], RCMAIL_CHARSET, $_SESSION['sort_col']);
95      $_SESSION['search'][$search_request] = $IMAP->get_search_set();
96      $OUTPUT->set_env('search_request', $search_request);
97      }
98
99      $search_mods = $RCMAIL->config->get('search_mods', $SEARCH_MODS_DEFAULT);
100      $OUTPUT->set_env('search_mods', $search_mods);
101    }
102
103  // set current mailbox and some other vars in client environment
104  $OUTPUT->set_env('mailbox', $mbox_name);
105  $OUTPUT->set_env('pagesize', $IMAP->page_size);
106  $OUTPUT->set_env('quota', $IMAP->get_capability('quota'));
107  $OUTPUT->set_env('delimiter', $IMAP->get_hierarchy_delimiter());
108  $OUTPUT->set_env('threading', (bool) $IMAP->threading);
109  $OUTPUT->set_env('threads', $IMAP->threading
110        || $IMAP->get_capability('thread=references')
111        || $IMAP->get_capability('thread=orderedsubject')
112        || $IMAP->get_capability('thread=refs') 
113  );
114
115  if ($CONFIG['flag_for_deletion'])
116    $OUTPUT->set_env('flag_for_deletion', true);
117  if ($CONFIG['read_when_deleted'])
118    $OUTPUT->set_env('read_when_deleted', true);
119  if ($CONFIG['skip_deleted'])
120    $OUTPUT->set_env('skip_deleted', true);
121  if ($CONFIG['display_next'])
122    $OUTPUT->set_env('display_next', true);
123
124  $OUTPUT->set_env('preview_pane_mark_read', $RCMAIL->config->get('preview_pane_mark_read', 0));
125
126  if ($CONFIG['trash_mbox'])
127    $OUTPUT->set_env('trash_mailbox', $CONFIG['trash_mbox']);
128  if ($CONFIG['drafts_mbox'])
129    $OUTPUT->set_env('drafts_mailbox', $CONFIG['drafts_mbox']);
130  if ($CONFIG['junk_mbox'])
131    $OUTPUT->set_env('junk_mailbox', $CONFIG['junk_mbox']);
132
133  if (!$OUTPUT->ajax_call)
134    $OUTPUT->add_label('checkingmail', 'deletemessage', 'movemessagetotrash',
135      'movingmessage', 'copyingmessage', 'copy', 'move', 'quota');
136
137  $OUTPUT->set_pagetitle(rcmail_localize_foldername($mbox_name));
138  }
139
140
141/**
142 * return the message list as HTML table
143 */
144function rcmail_message_list($attrib)
145{
146  global $IMAP, $CONFIG, $OUTPUT;
147
148  // add some labels to client
149  $OUTPUT->add_label('from', 'to');
150
151  // add id to message list table if not specified
152  if (!strlen($attrib['id']))
153    $attrib['id'] = 'rcubemessagelist';
154
155  // define list of cols to be displayed based on parameter or config
156  if (empty($attrib['columns'])) {
157    $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
158    $OUTPUT->set_env('col_movable', !in_array('list_cols', (array)$CONFIG['dont_override']));
159  }
160  else {
161    $a_show_cols = preg_split('/[\s,;]+/', strip_quotes($attrib['columns']));
162    $attrib['columns'] = $a_show_cols;
163  }
164
165  // save some variables for use in ajax list
166  $_SESSION['list_attrib'] = $attrib;
167
168  $mbox = $IMAP->get_mailbox_name();
169  $delim = $IMAP->get_hierarchy_delimiter();
170
171  // show 'to' instead of 'from' in sent/draft messages
172  if ((strpos($mbox.$delim, $CONFIG['sent_mbox'].$delim)===0 || strpos($mbox.$delim, $CONFIG['drafts_mbox'].$delim)===0)
173      && (($f = array_search('from', $a_show_cols)) !== false) && array_search('to', $a_show_cols) === false)
174    $a_show_cols[$f] = 'to';
175
176  // make sure 'threads' and 'subject' columns are present
177  if (!in_array('subject', $a_show_cols))
178    array_unshift($a_show_cols, 'subject');
179  if (!in_array('threads', $a_show_cols))
180    array_unshift($a_show_cols, 'threads');
181
182  $skin_path = $_SESSION['skin_path'] = $CONFIG['skin_path'];
183
184  // set client env
185  $OUTPUT->add_gui_object('messagelist', $attrib['id']);
186  $OUTPUT->set_env('autoexpand_threads', intval($CONFIG['autoexpand_threads']));
187  $OUTPUT->set_env('sort_col', $_SESSION['sort_col']);
188  $OUTPUT->set_env('sort_order', $_SESSION['sort_order']);
189
190  if ($attrib['messageicon'])
191    $OUTPUT->set_env('messageicon', $skin_path . $attrib['messageicon']);
192  if ($attrib['deletedicon'])
193    $OUTPUT->set_env('deletedicon', $skin_path . $attrib['deletedicon']);
194  if ($attrib['unreadicon'])
195    $OUTPUT->set_env('unreadicon', $skin_path . $attrib['unreadicon']);
196  if ($attrib['repliedicon'])
197    $OUTPUT->set_env('repliedicon', $skin_path . $attrib['repliedicon']);
198  if ($attrib['forwardedicon'])
199    $OUTPUT->set_env('forwardedicon', $skin_path . $attrib['forwardedicon']);
200  if ($attrib['forwardedrepliedicon'])
201    $OUTPUT->set_env('forwardedrepliedicon', $skin_path . $attrib['forwardedrepliedicon']);
202  if ($attrib['attachmenticon'])
203    $OUTPUT->set_env('attachmenticon', $skin_path . $attrib['attachmenticon']);
204  if ($attrib['flaggedicon'])
205    $OUTPUT->set_env('flaggedicon', $skin_path . $attrib['flaggedicon']);
206  if ($attrib['unflaggedicon'])
207    $OUTPUT->set_env('unflaggedicon', $skin_path . $attrib['unflaggedicon']);
208  if ($attrib['unreadchildrenicon'])
209    $OUTPUT->set_env('unreadchildrenicon', $skin_path . $attrib['unreadchildrenicon']);
210
211  $OUTPUT->set_env('messages', array());
212  $OUTPUT->set_env('coltypes', $a_show_cols);
213
214  $OUTPUT->include_script('list.js');
215
216  $thead = '';
217  foreach (rcmail_message_list_head($attrib, $a_show_cols) as $cell)
218    $thead .= html::tag('td', array('class' => $cell['className'], 'id' => $cell['id']), $cell['html']);
219
220  return html::tag('table',
221    $attrib,
222    html::tag('thead', null, html::tag('tr', null, $thead)) .
223      html::tag('tbody', null, ''),
224        array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
225}
226
227
228/**
229 * return javascript commands to add rows to the message list
230 */
231function rcmail_js_message_list($a_headers, $insert_top=FALSE, $a_show_cols=null)
232{
233  global $CONFIG, $IMAP, $RCMAIL, $OUTPUT;
234
235  if (empty($a_show_cols)) {
236    if (!empty($_SESSION['list_attrib']['columns']))
237      $a_show_cols = $_SESSION['list_attrib']['columns'];
238    else
239      $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
240  }
241  else {
242    if (!is_array($a_show_cols))
243      $a_show_cols = preg_split('/[\s,;]+/', strip_quotes($a_show_cols));
244    $head_replace = true;
245  }
246
247  $mbox = $IMAP->get_mailbox_name();
248  $delim = $IMAP->get_hierarchy_delimiter();
249
250  // make sure 'threads' and 'subject' columns are present
251  if (!in_array('subject', $a_show_cols))
252    array_unshift($a_show_cols, 'subject');
253  if (!in_array('threads', $a_show_cols))
254    array_unshift($a_show_cols, 'threads');
255
256  $_SESSION['list_attrib']['columns'] = $a_show_cols;
257
258  // show 'to' instead of 'from' in sent/draft messages
259  if ((strpos($mbox.$delim, $CONFIG['sent_mbox'].$delim)===0 || strpos($mbox.$delim, $CONFIG['drafts_mbox'].$delim)===0)
260      && (($f = array_search('from', $a_show_cols)) !== false) && array_search('to', $a_show_cols) === false)
261    $a_show_cols[$f] = 'to';
262
263  // Make sure there are no duplicated columns (#1486999)
264  $a_show_cols = array_unique($a_show_cols);
265
266  // Plugins may set header's list_cols/list_flags and other rcube_mail_header variables
267  // and list columns
268  $plugin = $RCMAIL->plugins->exec_hook('messages_list',
269    array('messages' => $a_headers, 'cols' => $a_show_cols));
270
271  $a_show_cols = $plugin['cols'];
272  $a_headers   = $plugin['messages'];
273
274  $thead = $head_replace ? rcmail_message_list_head($_SESSION['list_attrib'], $a_show_cols) : NULL;
275
276  $OUTPUT->command('set_message_coltypes', $a_show_cols, $thead);
277
278  if (empty($a_headers))
279    return;
280
281  // remove 'threads', 'attachment', 'flag' columns, we don't need them here
282  if (($key = array_search('attachment', $a_show_cols)) !== FALSE)
283    unset($a_show_cols[$key]);
284  if (($key = array_search('flag', $a_show_cols)) !== FALSE)
285    unset($a_show_cols[$key]);
286  if (($key = array_search('threads', $a_show_cols)) !== FALSE)
287    unset($a_show_cols[$key]);
288  // loop through message headers
289
290  foreach ($a_headers as $n => $header)
291    {
292    if (empty($header))
293      continue;
294
295    $a_msg_cols = array();
296    $a_msg_flags = array();
297
298    $IMAP->set_charset(!empty($header->charset) ? $header->charset : $CONFIG['default_charset']);
299
300    // format each col; similar as in rcmail_message_list()
301    foreach ($a_show_cols as $col)
302      {
303      if (in_array($col, array('from', 'to', 'cc', 'replyto')))
304        $cont = Q(rcmail_address_string($header->$col, 3), 'show');
305      else if ($col=='subject')
306        {
307        $cont = abbreviate_string(trim($IMAP->decode_header($header->$col)), 160);
308        if (!$cont) $cont = rcube_label('nosubject');
309        $cont = Q($cont);
310        }
311      else if ($col=='size')
312        $cont = show_bytes($header->$col);
313      else if ($col=='date')
314        $cont = format_date($header->date);
315      else
316        $cont = Q($header->$col);
317
318      $a_msg_cols[$col] = $cont;
319      }
320
321    if ($header->depth)
322      $a_msg_flags['depth'] = $header->depth;
323    else if ($header->has_children)
324      $roots[] = $header->uid;
325    if ($header->parent_uid)
326      $a_msg_flags['parent_uid'] = $header->parent_uid;
327    if ($header->has_children)
328      $a_msg_flags['has_children'] = $header->has_children;
329    if ($header->unread_children)
330      $a_msg_flags['unread_children'] = $header->unread_children;
331    if ($header->deleted)
332      $a_msg_flags['deleted'] = 1;
333    if (!$header->seen)
334      $a_msg_flags['unread'] = 1;
335    if ($header->answered)
336      $a_msg_flags['replied'] = 1;
337    if ($header->forwarded)
338      $a_msg_flags['forwarded'] = 1;
339    if ($header->flagged)
340      $a_msg_flags['flagged'] = 1;
341    if (preg_match("/(application\/|multipart\/m)/i", $header->ctype))
342      $a_msg_flags['attachment'] = 1;
343    $a_msg_flags['mbox'] = $mbox;
344
345    // merge with plugin result
346    if (!empty($header->list_flags) && is_array($header->list_flags))
347      $a_msg_flags = array_merge($a_msg_flags, $header->list_flags);
348    if (!empty($header->list_cols) && is_array($header->list_cols))
349      $a_msg_cols = array_merge($a_msg_cols, $header->list_cols);
350
351    $OUTPUT->command('add_message_row',
352      $header->uid,
353      $a_msg_cols,
354      $a_msg_flags,
355      $insert_top);
356    }
357
358    if ($IMAP->threading) {
359      $OUTPUT->command('init_threads', (array) $roots);
360    }
361}
362
363
364/*
365 * Creates <THEAD> for message list table
366 */
367function rcmail_message_list_head($attrib, $a_show_cols)
368{
369  global $CONFIG;
370
371  $skin_path = $_SESSION['skin_path'];
372  $image_tag = html::img(array('src' => "%s%s", 'alt' => "%s"));
373
374  // check to see if we have some settings for sorting
375  $sort_col   = $_SESSION['sort_col'];
376  $sort_order = $_SESSION['sort_order'];
377
378  // define sortable columns
379  $a_sort_cols = array('subject', 'date', 'from', 'to', 'size', 'cc');
380
381  if (!empty($attrib['optionsmenuicon']))
382    $list_menu = html::a(
383      array('href' => '#', 'onclick' => 'return '.JS_OBJECT_NAME.".command('menu-open', 'messagelistmenu')"),
384      html::img(array('src' => $skin_path . $attrib['optionsmenuicon'], 'id' => 'listmenulink', 'title' => rcube_label('listoptions')))
385    );
386  else
387    $list_menu = '';
388
389  $cells = array();
390
391  foreach ($a_show_cols as $col) {
392    // get column name
393    switch ($col) {
394      case 'flag':
395        $col_name = sprintf($image_tag, $skin_path, $attrib['unflaggedicon'], '');
396        break;
397      case 'attachment':
398        $col_name = sprintf($image_tag, $skin_path, $attrib['attachmenticon'], '');
399        break;
400      case 'threads':
401        $col_name = $list_menu;
402        break;
403      default:
404        $col_name = Q(rcube_label($col));
405    }
406
407    // make sort links
408    if (in_array($col, $a_sort_cols))
409      $col_name = html::a(array('href'=>"./#sort", 'onclick' => 'return '.JS_OBJECT_NAME.".command('sort','".$col."',this)", 'title' => rcube_label('sortby')), $col_name);
410
411    $sort_class = $col == $sort_col ? " sorted$sort_order" : '';
412    $class_name = $col == 'attachment' ? 'icon' : $col.$sort_class;
413
414    // put it all together
415    $cells[] = array('className' => $class_name, 'id' => "rcm$col", 'html' => $col_name);
416  }
417
418  return $cells;
419}
420
421
422/**
423 * return an HTML iframe for loading mail content
424 */
425function rcmail_messagecontent_frame($attrib)
426  {
427  global $OUTPUT, $RCMAIL;
428
429  if (empty($attrib['id']))
430    $attrib['id'] = 'rcmailcontentwindow';
431
432  $attrib['name'] = $attrib['id'];
433
434  if ($RCMAIL->config->get('preview_pane'))
435    $OUTPUT->set_env('contentframe', $attrib['id']);
436  $OUTPUT->set_env('blankpage', $attrib['src'] ? $OUTPUT->abs_url($attrib['src']) : 'program/blank.gif');
437
438  return html::iframe($attrib);
439  }
440
441
442function rcmail_messagecount_display($attrib)
443  {
444  global $IMAP, $OUTPUT;
445
446  if (!$attrib['id'])
447    $attrib['id'] = 'rcmcountdisplay';
448
449  $OUTPUT->add_gui_object('countdisplay', $attrib['id']);
450
451  return html::span($attrib, rcmail_get_messagecount_text());
452  }
453
454
455function rcmail_quota_display($attrib)
456  {
457  global $OUTPUT;
458
459  if (!$attrib['id'])
460    $attrib['id'] = 'rcmquotadisplay';
461
462  if(isset($attrib['display']))
463    $_SESSION['quota_display'] = $attrib['display'];
464
465  $OUTPUT->add_gui_object('quotadisplay', $attrib['id']);
466
467  $quota = rcmail_quota_content($attrib);
468
469  $OUTPUT->add_script('$(document).ready(function(){
470        rcmail.set_quota('.json_serialize($quota).')});', 'foot');
471
472  return html::span($attrib, '');
473  }
474
475
476function rcmail_quota_content($attrib=NULL)
477  {
478  global $COMM_PATH, $RCMAIL;
479
480  $quota = $RCMAIL->imap->get_quota();
481  $quota = $RCMAIL->plugins->exec_hook('quota', $quota);
482
483  $quota_result = (array) $quota;
484  $quota_result['type'] = isset($_SESSION['quota_display']) ? $_SESSION['quota_display'] : '';
485
486  if (!$quota['total'] && $RCMAIL->config->get('quota_zero_as_unlimited')) {
487    $quota_result['title'] = rcube_label('unlimited');
488    $quota_result['percent'] = 0;
489    }
490  else if ($quota['total']) {
491    if (!isset($quota['percent']))
492      $quota_result['percent'] = min(100, round(($quota['used']/max(1,$quota['total']))*100));
493
494    $title = sprintf('%s / %s (%.0f%%)',
495        show_bytes($quota['used'] * 1024), show_bytes($quota['total'] * 1024),
496        $quota_result['percent']);
497
498    $quota_result['title'] = $title;
499
500    if ($attrib['width'])
501      $quota_result['width'] = $attrib['width'];
502    if ($attrib['height'])
503      $quota_result['height']   = $attrib['height'];
504    }
505  else {
506    $quota_result['title'] = rcube_label('unknown');
507    $quota_result['percent'] = 0;
508    }
509
510  return $quota_result;
511  }
512
513
514function rcmail_get_messagecount_text($count=NULL, $page=NULL)
515  {
516  global $RCMAIL, $IMAP, $MESSAGE;
517
518  if (isset($MESSAGE->index))
519    {
520    return rcube_label(array('name' => 'messagenrof',
521        'vars' => array('nr'  => $MESSAGE->index+1,
522        'count' => $count!==NULL ? $count : $IMAP->messagecount(NULL, 'ALL')))); // Only messages, no threads here
523    }
524
525  if ($page===NULL)
526    $page = $IMAP->list_page;
527
528  $start_msg = ($page-1) * $IMAP->page_size + 1;
529
530  if ($count!==NULL)
531    $max = $count;
532  else if ($RCMAIL->action)
533    $max = $IMAP->messagecount(NULL, $IMAP->threading ? 'THREADS' : 'ALL');
534
535  if ($max==0)
536    $out = rcube_label('mailboxempty');
537  else
538    $out = rcube_label(array('name' => $IMAP->threading ? 'threadsfromto' : 'messagesfromto',
539            'vars' => array('from'  => $start_msg,
540            'to'    => min($max, $start_msg + $IMAP->page_size - 1),
541            'count' => $max)));
542
543  return Q($out);
544  }
545
546
547function rcmail_mailbox_name_display($attrib)
548{
549  global $RCMAIL;
550
551  if (!$attrib['id'])
552    $attrib['id'] = 'rcmmailboxname';
553
554  $RCMAIL->output->add_gui_object('mailboxname', $attrib['id']);
555
556  return html::span($attrib, rcmail_get_mailbox_name_text());
557}
558
559
560function rcmail_get_mailbox_name_text()
561{
562  global $RCMAIL;
563  return rcmail_localize_foldername($RCMAIL->imap->get_mailbox_name());
564}
565
566
567function rcmail_send_unread_count($mbox_name, $force=false, $count=null)
568{
569  global $RCMAIL;
570
571  $old_unseen = $_SESSION['unseen_count'][$mbox_name];
572
573  if ($count === null)
574    $unseen = $RCMAIL->imap->messagecount($mbox_name, 'UNSEEN', $force);
575  else
576    $unseen = $count;
577
578  if ($unseen != $old_unseen || ($mbox_name == 'INBOX'))
579    $RCMAIL->output->command('set_unread_count', $mbox_name, $unseen, ($mbox_name == 'INBOX'));
580
581  // @TODO: this data is doubled (session and cache tables) if caching is enabled
582  $_SESSION['unseen_count'][$mbox_name] = $unseen;
583
584  return $unseen;
585}
586
587
588/**
589 * Sets message is_safe flag according to 'show_images' option value
590 *
591 * @param object rcube_message Message
592 */
593function rcmail_check_safe(&$message)
594{
595  global $RCMAIL;
596
597  $show_images = $RCMAIL->config->get('show_images');
598  if (!$message->is_safe
599    && !empty($show_images)
600    && $message->has_html_part())
601  {
602    switch($show_images) {
603      case '1': // known senders only
604        $CONTACTS = new rcube_contacts($RCMAIL->db, $_SESSION['user_id']);
605        if ($CONTACTS->search('email', $message->sender['mailto'], true, false)->count) {
606          $message->set_safe(true);
607        }
608      break;
609      case '2': // always
610        $message->set_safe(true);
611      break;
612    }
613  }
614}
615
616
617/**
618 * Cleans up the given message HTML Body (for displaying)
619 *
620 * @param string HTML
621 * @param array  Display parameters
622 * @param array  CID map replaces (inline images)
623 * @return string Clean HTML
624 */
625function rcmail_wash_html($html, $p = array(), $cid_replaces)
626{
627  global $REMOTE_OBJECTS;
628
629  $p += array('safe' => false, 'inline_html' => true);
630
631  // special replacements (not properly handled by washtml class)
632  $html_search = array(
633    '/(<\/nobr>)(\s+)(<nobr>)/i',       // space(s) between <NOBR>
634    '/<title[^>]*>.*<\/title>/i',       // PHP bug #32547 workaround: remove title tag
635    '/^(\0\0\xFE\xFF|\xFF\xFE\0\0|\xFE\xFF|\xFF\xFE|\xEF\xBB\xBF)/',    // byte-order mark (only outlook?)
636    '/<html\s[^>]+>/i',                 // washtml/DOMDocument cannot handle xml namespaces
637  );
638  $html_replace = array(
639    '\\1'.' &nbsp; '.'\\3',
640    '',
641    '',
642    '<html>',
643  );
644  $html = preg_replace($html_search, $html_replace, $html);
645
646  // PCRE errors handling (#1486856), should we use something like for every preg_* use?
647  if ($html === null && ($preg_error = preg_last_error()) != PREG_NO_ERROR) {
648    $errstr = "Could not clean up HTML message! PCRE Error: $preg_error.";
649
650    if ($preg_error == PREG_BACKTRACK_LIMIT_ERROR)
651      $errstr .= " Consider raising pcre.backtrack_limit!";
652    if ($preg_error == PREG_RECURSION_LIMIT_ERROR)
653      $errstr .= " Consider raising pcre.recursion_limit!";
654
655    raise_error(array('code' => 600, 'type' => 'php',
656        'line' => __LINE__, 'file' => __FILE__,
657        'message' => $errstr), true, false);
658    return '';
659  }
660
661  // fix (unknown/malformed) HTML tags before "wash"
662  $html = preg_replace_callback('/(<[\/]*)([^\s>]+)/', 'rcmail_html_tag_callback', $html);
663
664  // charset was converted to UTF-8 in rcube_imap::get_message_part(),
665  // -> change charset specification in HTML accordingly
666  $charset_pattern = '(<meta\s+[^>]*content=)[\'"]?(\w+\/\w+;\s*charset=)([a-z0-9-_]+[\'"]?)';
667  if (preg_match("/$charset_pattern/Ui", $html)) {
668    $html = preg_replace("/$charset_pattern/i", '\\1"\\2'.RCMAIL_CHARSET.'"', $html);
669  }
670  else {
671    // add meta content-type to malformed messages, washtml cannot work without that
672    if (!preg_match('/<head[^>]*>(.*)<\/head>/Uims', $html))
673      $html = '<head></head>'. $html;
674    $html = substr_replace($html, '<meta http-equiv="Content-Type" content="text/html; charset='.RCMAIL_CHARSET.'" />', intval(stripos($html, '<head>')+6), 0);
675  }
676  // turn relative into absolute urls
677  $html = rcmail_resolve_base($html);
678
679  // clean HTML with washhtml by Frederic Motte
680  $wash_opts = array(
681    'show_washed' => false,
682    'allow_remote' => $p['safe'],
683    'blocked_src' => "./program/blocked.gif",
684    'charset' => RCMAIL_CHARSET,
685    'cid_map' => $cid_replaces,
686    'html_elements' => array('body'),
687  );
688
689  if (!$p['inline_html']) {
690    $wash_opts['html_elements'] = array('html','head','title','body');
691  }
692  if ($p['safe']) {
693    $wash_opts['html_elements'][] = 'link';
694    $wash_opts['html_attribs'] = array('rel','type');
695  }
696
697  // overwrite washer options with options from plugins
698  if (isset($p['html_elements']))
699    $wash_opts['html_elements'] = $p['html_elements'];
700  if (isset($p['html_attribs']))
701    $wash_opts['html_attribs'] = $p['html_attribs'];
702
703  // initialize HTML washer
704  $washer = new washtml($wash_opts);
705
706  if (!$p['skip_washer_form_callback'])
707    $washer->add_callback('form', 'rcmail_washtml_callback');
708
709  // allow CSS styles, will be sanitized by rcmail_washtml_callback()
710  if (!$p['skip_washer_style_callback'])
711    $washer->add_callback('style', 'rcmail_washtml_callback');
712
713  $html = $washer->wash($html);
714  $REMOTE_OBJECTS = $washer->extlinks;
715
716  return $html;
717}
718
719
720/**
721 * Convert the given message part to proper HTML
722 * which can be displayed the message view
723 *
724 * @param object rcube_message_part Message part
725 * @param array  Display parameters array
726 * @return string Formatted HTML string
727 */
728function rcmail_print_body($part, $p = array())
729{
730  global $RCMAIL;
731
732  // trigger plugin hook
733  $data = $RCMAIL->plugins->exec_hook('message_part_before',
734    array('type' => $part->ctype_secondary, 'body' => $part->body) + $p + array('safe' => false, 'plain' => false, 'inline_html' => true));
735
736  // convert html to text/plain
737  if ($data['type'] == 'html' && $data['plain']) {
738    $txt = new html2text($data['body'], false, true);
739    $body = $txt->get_text();
740    $part->ctype_secondary = 'plain';
741  }
742  // text/html
743  else if ($data['type'] == 'html') {
744    $body = rcmail_wash_html($data['body'], $data, $part->replaces);
745    $part->ctype_secondary = $data['type'];
746  }
747  // text/enriched
748  else if ($data['type'] == 'enriched') {
749    $part->ctype_secondary = 'html';
750    require_once('lib/enriched.inc');
751    $body = Q(enriched_to_html($data['body']), 'show');
752  }
753  else {
754    // assert plaintext
755    $body = $part->body;
756    $part->ctype_secondary = $data['type'] = 'plain';
757  }
758
759  // free some memory (hopefully)
760  unset($data['body']);
761
762  // plaintext postprocessing
763  if ($part->ctype_secondary == 'plain')
764    $body = rcmail_plain_body($body, $part->ctype_parameters['format'] == 'flowed');
765
766  // allow post-processing of the message body
767  $data = $RCMAIL->plugins->exec_hook('message_part_after', array('type' => $part->ctype_secondary, 'body' => $body) + $data);
768
769  return $data['type'] == 'html' ? $data['body'] : html::tag('pre', array(), $data['body']);
770}
771
772
773/**
774 * Handle links and citation marks in plain text message
775 *
776 * @param string  Plain text string
777 * @param boolean Text uses format=flowed
778 *
779 * @return string Formatted HTML string
780 */
781function rcmail_plain_body($body, $flowed=false)
782{
783  global $RCMAIL;
784
785  // make links and email-addresses clickable
786  $replacer = new rcube_string_replacer;
787
788  // search for patterns like links and e-mail addresses
789  $body = preg_replace_callback($replacer->link_pattern, array($replacer, 'link_callback'), $body);
790  $body = preg_replace_callback($replacer->mailto_pattern, array($replacer, 'mailto_callback'), $body);
791
792  // split body into single lines
793  $a_lines = preg_split('/\r?\n/', $body);
794  $quote_level = 0;
795  $last = -1;
796
797  // find/mark quoted lines...
798  for ($n=0, $cnt=count($a_lines); $n < $cnt; $n++) {
799    if ($a_lines[$n][0] == '>' && preg_match('/^(>+\s*)+/', $a_lines[$n], $regs)) {
800      $q = strlen(preg_replace('/\s/', '', $regs[0]));
801      $a_lines[$n] = substr($a_lines[$n], strlen($regs[0]));
802
803      if ($q > $quote_level)
804        $a_lines[$n] = $replacer->get_replacement($replacer->add(
805          str_repeat('<blockquote>', $q - $quote_level))) . $a_lines[$n];
806      else if ($q < $quote_level)
807        $a_lines[$n] = $replacer->get_replacement($replacer->add(
808          str_repeat('</blockquote>', $quote_level - $q))) . $a_lines[$n];
809      else if ($flowed) {
810        // previous line is flowed
811        if (isset($a_lines[$last]) && $a_lines[$n]
812          && $a_lines[$last][strlen($a_lines[$last])-1] == ' ') {
813          // merge lines
814          $a_lines[$last] .= $a_lines[$n];
815          unset($a_lines[$n]);
816        }
817        else
818          $last = $n;
819      }
820    }
821    else {
822      $q = 0;
823      if ($flowed) {
824        // sig separator - line is fixed
825        if ($a_lines[$n] == '-- ') {
826          $last = $n;
827        }
828        else {
829          // remove space-stuffing
830          if ($a_lines[$n][0] == ' ')
831            $a_lines[$n] = substr($a_lines[$n], 1);
832
833          // previous line is flowed?
834          if (isset($a_lines[$last]) && $a_lines[$n]
835            && $a_lines[$last] != '-- '
836            && $a_lines[$last][strlen($a_lines[$last])-1] == ' '
837          ) {
838            $a_lines[$last] .= $a_lines[$n];
839            unset($a_lines[$n]);
840          }
841          else {
842            $last = $n;
843          }
844        }
845        if ($quote_level > 0)
846          $a_lines[$last] = $replacer->get_replacement($replacer->add(
847            str_repeat('</blockquote>', $quote_level))) . $a_lines[$last];
848      }
849      else if ($quote_level > 0)
850        $a_lines[$n] = $replacer->get_replacement($replacer->add(
851          str_repeat('</blockquote>', $quote_level))) . $a_lines[$n];
852    }
853
854    $quote_level = $q;
855  }
856
857  // quote plain text
858  $body = Q(join("\n", $a_lines), 'dummy', false);
859
860  // colorize signature
861  $len = strlen($body);
862  while (($sp = strrpos($body, "-- \n", $sp ? -$len+$sp-1 : 0)) !== false) {
863    if ($sp == 0 || $body[$sp-1] == "\n") {
864      // do not touch blocks with more that X lines
865      if (substr_count($body, "\n", $sp) < $RCMAIL->config->get('sig_max_lines', 15))
866        $body = substr($body, 0, max(0, $sp))
867          .'<span class="sig">'.substr($body, $sp).'</span>';
868      break;
869    }
870  }
871
872  // insert url/mailto links and citation tags
873  $body = $replacer->resolve($body);
874
875  return $body;
876}
877
878
879/**
880 * Callback function for washtml cleaning class
881 */
882function rcmail_washtml_callback($tagname, $attrib, $content)
883{
884  switch ($tagname) {
885    case 'form':
886      $out = html::div('form', $content);
887      break;
888
889    case 'style':
890      // decode all escaped entities and reduce to ascii strings
891      $stripped = preg_replace('/[^a-zA-Z\(:]/', '', rcmail_xss_entity_decode($content));
892
893      // now check for evil strings like expression, behavior or url()
894      if (!preg_match('/expression|behavior|url\(|import/', $stripped)) {
895        $out = html::tag('style', array('type' => 'text/css'), $content);
896        break;
897      }
898
899    default:
900      $out = '';
901  }
902
903  return $out;
904}
905
906
907/**
908 * Callback function for HTML tags fixing
909 */
910function rcmail_html_tag_callback($matches)
911{
912  $tagname = $matches[2];
913
914  $tagname = preg_replace(array(
915    '/:.*$/',                   // Microsoft's Smart Tags <st1:xxxx>
916    '/[^a-z0-9_\[\]\!-]/i',     // forbidden characters
917    ), '', $tagname);
918
919  return $matches[1].$tagname;
920}
921
922
923/**
924 * return table with message headers
925 */
926function rcmail_message_headers($attrib, $headers=NULL)
927  {
928  global $IMAP, $OUTPUT, $MESSAGE, $PRINT_MODE, $RCMAIL;
929  static $sa_attrib;
930
931  // keep header table attrib
932  if (is_array($attrib) && !$sa_attrib)
933    $sa_attrib = $attrib;
934  else if (!is_array($attrib) && is_array($sa_attrib))
935    $attrib = $sa_attrib;
936
937  if (!isset($MESSAGE))
938    return FALSE;
939
940  // get associative array of headers object
941  if (!$headers)
942    $headers = is_object($MESSAGE->headers) ? get_object_vars($MESSAGE->headers) : $MESSAGE->headers;
943
944  // show these headers
945  $standard_headers = array('subject', 'from', 'to', 'cc', 'bcc', 'replyto', 'date');
946  $output_headers = array();
947
948  foreach ($standard_headers as $hkey) {
949    if (!$headers[$hkey])
950      continue;
951
952    if ($hkey == 'date') {
953      if ($PRINT_MODE)
954        $header_value = format_date($headers[$hkey], $RCMAIL->config->get('date_long', 'x'));
955      else
956        $header_value = format_date($headers[$hkey]);
957    }
958    else if ($hkey == 'replyto') {
959      if ($headers['replyto'] != $headers['from'])
960        $header_value = rcmail_address_string($headers['replyto'], null, true, $attrib['addicon']);
961      else
962        continue;
963    }
964    else if (in_array($hkey, array('from', 'to', 'cc', 'bcc')))
965      $header_value = rcmail_address_string($headers[$hkey], null, true, $attrib['addicon']);
966    else if ($hkey == 'subject' && empty($headers[$hkey]))
967      $header_value = rcube_label('nosubject');
968    else
969      $header_value = trim($IMAP->decode_header($headers[$hkey]));
970
971    $output_headers[$hkey] = array('title' => rcube_label($hkey), 'value' => $header_value, 'raw' => $headers[$hkey]);
972  }
973
974  $plugin = $RCMAIL->plugins->exec_hook('message_headers_output', array('output' => $output_headers, 'headers' => $MESSAGE->headers));
975
976  // compose html table
977  $table = new html_table(array('cols' => 2));
978
979  foreach ($plugin['output'] as $hkey => $row) {
980    $table->add(array('class' => 'header-title'), Q($row['title']));
981    $table->add(array('class' => $hkey, 'width' => "90%"), Q($row['value'], ($hkey == 'subject' ? 'strict' : 'show')));
982  }
983
984  // all headers division
985  $table->add(array('colspan' => 2, 'class' => "more-headers show-headers", 'onclick' => "return ".JS_OBJECT_NAME.".command('load-headers','',this)"), '');
986  $table->add_row(array('id' => "all-headers"));
987  $table->add(array('colspan' => 2, 'class' => "all"), html::div(array('id' => 'headers-source'), ''));
988 
989  $OUTPUT->add_gui_object('all_headers_row', 'all-headers');
990  $OUTPUT->add_gui_object('all_headers_box', 'headers-source');
991
992  return $table->show($attrib);
993  }
994
995
996/**
997 * Handler for the 'messagebody' GUI object
998 *
999 * @param array Named parameters
1000 * @return string HTML content showing the message body
1001 */
1002function rcmail_message_body($attrib)
1003  {
1004  global $CONFIG, $OUTPUT, $MESSAGE, $IMAP, $RCMAIL, $REMOTE_OBJECTS;
1005
1006  if (!is_array($MESSAGE->parts) && empty($MESSAGE->body))
1007    return '';
1008
1009  if (!$attrib['id'])
1010    $attrib['id'] = 'rcmailMsgBody';
1011
1012  $safe_mode = $MESSAGE->is_safe || intval($_GET['_safe']);
1013  $out = '';
1014
1015  $header_attrib = array();
1016  foreach ($attrib as $attr => $value)
1017    if (preg_match('/^headertable([a-z]+)$/i', $attr, $regs))
1018      $header_attrib[$regs[1]] = $value;
1019
1020  if (!empty($MESSAGE->parts))
1021    {
1022    foreach ($MESSAGE->parts as $i => $part)
1023      {
1024      if ($part->type == 'headers')
1025        $out .= rcmail_message_headers(sizeof($header_attrib) ? $header_attrib : NULL, $part->headers);
1026      else if ($part->type == 'content' && $part->size)
1027        {
1028        if (empty($part->ctype_parameters) || empty($part->ctype_parameters['charset']))
1029          $part->ctype_parameters['charset'] = $MESSAGE->headers->charset;
1030
1031        // fetch part if not available
1032        if (!isset($part->body))
1033          $part->body = $MESSAGE->get_part_content($part->mime_id);
1034
1035        // message is cached but not exists (#1485443), or other error
1036        if ($part->body === false) {
1037          rcmail_message_error($MESSAGE->uid);
1038        }
1039
1040        $plugin = $RCMAIL->plugins->exec_hook('message_body_prefix', array(
1041          'part' => $part, 'prefix' => ''));
1042
1043        $body = rcmail_print_body($part, array('safe' => $safe_mode, 'plain' => !$CONFIG['prefer_html']));
1044
1045        if ($part->ctype_secondary == 'html') {
1046          $body = rcmail_html4inline($body, $attrib['id'], 'rcmBody', $attrs);
1047          $div_attr = array('class' => 'message-htmlpart');
1048          $style = array();
1049
1050          if (!empty($attrs)) {
1051            foreach ($attrs as $a_idx => $a_val)
1052              $style[] = $a_idx . ': ' . $a_val;
1053            if (!empty($style))
1054              $div_attr['style'] = implode('; ', $style);
1055          }
1056
1057          $out .= html::div($div_attr, $plugin['prefix'] . $body);
1058        }
1059        else
1060          $out .= html::div('message-part', $plugin['prefix'] . $body);
1061        }
1062      }
1063    }
1064  else {
1065    $plugin = $RCMAIL->plugins->exec_hook('message_body_prefix', array(
1066      'part' => $MESSAGE, 'prefix' => ''));
1067
1068    $out .= html::div('message-part', $plugin['prefix'] . html::tag('pre', array(),
1069      rcmail_plain_body(Q($MESSAGE->body, 'strict', false))));
1070    }
1071
1072  $ctype_primary = strtolower($MESSAGE->structure->ctype_primary);
1073  $ctype_secondary = strtolower($MESSAGE->structure->ctype_secondary);
1074
1075  // list images after mail body
1076  if ($CONFIG['inline_images']
1077      && $ctype_primary == 'multipart'
1078      && !empty($MESSAGE->attachments))
1079    {
1080    foreach ($MESSAGE->attachments as $attach_prop) {
1081      // Content-Type: image/*...
1082      if (preg_match('/^image\//i', $attach_prop->mimetype) ||
1083        // ...or known file extension: many clients are using application/octet-stream
1084        ($attach_prop->filename &&
1085          preg_match('/^application\/octet-stream$/i', $attach_prop->mimetype) &&
1086          preg_match('/\.(jpg|jpeg|png|gif|bmp)$/i', $attach_prop->filename))
1087      ) {
1088        $out .= html::tag('hr') . html::p(array('align' => "center"),
1089          html::img(array(
1090            'src' => $MESSAGE->get_part_url($attach_prop->mime_id),
1091            'title' => $attach_prop->filename,
1092            'alt' => $attach_prop->filename,
1093          )));
1094        }
1095    }
1096  }
1097
1098  // tell client that there are blocked remote objects
1099  if ($REMOTE_OBJECTS && !$safe_mode)
1100    $OUTPUT->set_env('blockedobjects', true);
1101
1102  return html::div($attrib, $out);
1103  }
1104
1105
1106/**
1107 * Convert all relative URLs according to a <base> in HTML
1108 */
1109function rcmail_resolve_base($body)
1110{
1111  // check for <base href=...>
1112  if (preg_match('!(<base.*href=["\']?)([hftps]{3,5}://[a-z0-9/.%-]+)!i', $body, $regs)) {
1113    $replacer = new rcube_base_replacer($regs[2]);
1114
1115    // replace all relative paths
1116    $body = preg_replace_callback('/(src|background|href)=(["\']?)([\.\/]+[^"\'\s]+)(\2|\s|>)/Ui', array($replacer, 'callback'), $body);
1117    $body = preg_replace_callback('/(url\s*\()(["\']?)([\.\/]+[^"\'\)\s]+)(\2)\)/Ui', array($replacer, 'callback'), $body);
1118  }
1119
1120  return $body;
1121}
1122
1123/**
1124 * modify a HTML message that it can be displayed inside a HTML page
1125 */
1126function rcmail_html4inline($body, $container_id, $body_id='', &$attributes=null)
1127{
1128  $last_style_pos = 0;
1129  $body_lc = strtolower($body);
1130  $cont_id = $container_id.($body_id ? ' div.'.$body_id : '');
1131
1132  // find STYLE tags
1133  while (($pos = strpos($body_lc, '<style', $last_style_pos)) && ($pos2 = strpos($body_lc, '</style>', $pos)))
1134  {
1135    $pos = strpos($body_lc, '>', $pos)+1;
1136
1137    // replace all css definitions with #container [def]
1138    $styles = rcmail_mod_css_styles(
1139      substr($body, $pos, $pos2-$pos), $cont_id);
1140
1141    $body = substr($body, 0, $pos) . $styles . substr($body, $pos2);
1142    $body_lc = strtolower($body);
1143    $last_style_pos = $pos2;
1144  }
1145
1146  // modify HTML links to open a new window if clicked
1147  $GLOBALS['rcmail_html_container_id'] = $container_id;
1148  $body = preg_replace_callback('/<(a|link)\s+([^>]+)>/Ui', 'rcmail_alter_html_link', $body);
1149  unset($GLOBALS['rcmail_html_container_id']);
1150
1151  $body = preg_replace(array(
1152      // add comments arround html and other tags
1153      '/(<!DOCTYPE[^>]*>)/i',
1154      '/(<\?xml[^>]*>)/i',
1155      '/(<\/?html[^>]*>)/i',
1156      '/(<\/?head[^>]*>)/i',
1157      '/(<title[^>]*>.*<\/title>)/Ui',
1158      '/(<\/?meta[^>]*>)/i',
1159      // quote <? of php and xml files that are specified as text/html
1160      '/<\?/',
1161      '/\?>/',
1162      // replace <body> with <div>
1163      '/<body([^>]*)>/i',
1164      '/<\/body>/i',
1165      ),
1166    array(
1167      '<!--\\1-->',
1168      '<!--\\1-->',
1169      '<!--\\1-->',
1170      '<!--\\1-->',
1171      '<!--\\1-->',
1172      '<!--\\1-->',
1173      '&lt;?',
1174      '?&gt;',
1175      '<div class="'.$body_id.'"\\1>',
1176      '</div>',
1177      ),
1178    $body);
1179
1180  $attributes = array();
1181
1182  // Handle body attributes that doesn't play nicely with div elements
1183  if (preg_match('/<div class="' . preg_quote($body_id, '/') . '" ([^>]+)/', $body, $m)) {
1184    $attrs = $m[0];
1185    // Get bgcolor, we'll set it as background-color of the message container
1186    if (preg_match('/bgcolor=["\']*([a-z0-9#]+)["\']*/', $attrs, $mb)) {
1187      $attributes['background-color'] = $mb[1];
1188      $attrs = preg_replace('/bgcolor=["\']*([a-z0-9#]+)["\']*/', '', $attrs);
1189    }
1190    // Get background, we'll set it as background-image of the message container
1191    if (preg_match('/background=["\']*([^"\'>\s]+)["\']*/', $attrs, $mb)) {
1192      $attributes['background-image'] = 'url('.$mb[1].')';
1193      $attrs = preg_replace('/background=["\']*([^"\'>\s]+)["\']*/', '', $attrs);
1194    }
1195    if (!empty($attributes))
1196      $body = preg_replace('/<div class="' . preg_quote($body_id, '/') . '" [^>]+/', rtrim($attrs), $body, 1);
1197
1198    // handle body styles related to background image
1199    if ($attributes['background-image']) {
1200      // get body style
1201      if (preg_match('/#'.preg_quote($cont_id, '/').'\s+\{([^}]+)}/i', $body, $m)) {
1202        // get background related style
1203        if (preg_match_all('/(background-position|background-repeat)\s*:\s*([^;]+);/i', $m[1], $ma, PREG_SET_ORDER)) {
1204          foreach ($ma as $style)
1205            $attributes[$style[1]] = $style[2];
1206        }
1207      }
1208    }
1209  }
1210  // make sure there's 'rcmBody' div, we need it for proper css modification
1211  // its name is hardcoded in rcmail_message_body() also
1212  else
1213    $body = '<div class="' . $body_id . '">' . $body . '</div>';
1214
1215  return $body;
1216}
1217
1218
1219/**
1220 * parse link attributes and set correct target
1221 */
1222function rcmail_alter_html_link($matches)
1223{
1224  global $EMAIL_ADDRESS_PATTERN;
1225
1226  $tag = $matches[1];
1227  $attrib = parse_attrib_string($matches[2]);
1228  $end = '>';
1229
1230  if ($tag == 'link' && preg_match('/^https?:\/\//i', $attrib['href'])) {
1231    $attrib['href'] = "?_task=utils&amp;_action=modcss&amp;u=" . urlencode($attrib['href'])
1232        . "&amp;c=" . urlencode($GLOBALS['rcmail_html_container_id']);
1233    $end = ' />';
1234  }
1235  else if (preg_match('/^mailto:'.$EMAIL_ADDRESS_PATTERN.'(\?[^"\'>]+)?/i', $attrib['href'], $mailto)) {
1236    $attrib['href'] = $mailto[0];
1237    $attrib['onclick'] = sprintf(
1238      "return %s.command('compose','%s',this)",
1239      JS_OBJECT_NAME,
1240      JQ($mailto[1].$mailto[2]));
1241  }
1242  else if (!empty($attrib['href']) && $attrib['href'][0] != '#') {
1243    $attrib['target'] = '_blank';
1244  }
1245
1246  return "<$tag" . html::attrib_string($attrib, array('href','name','target','onclick','id','class','style','title','rel','type','media')) . $end;
1247}
1248
1249
1250/**
1251 * decode address string and re-format it as HTML links
1252 */
1253function rcmail_address_string($input, $max=null, $linked=false, $addicon=null)
1254{
1255  global $IMAP, $RCMAIL, $PRINT_MODE, $CONFIG;
1256  static $got_writable_abook = null;
1257
1258  $a_parts = $IMAP->decode_address_list($input);
1259
1260  if (!sizeof($a_parts))
1261    return $input;
1262
1263  $c = count($a_parts);
1264  $j = 0;
1265  $out = '';
1266
1267  if ($got_writable_abook === null && $books = $RCMAIL->get_address_sources(true)) {
1268    $got_writable_abook = true;
1269  }
1270
1271  foreach ($a_parts as $part) {
1272    $j++;
1273
1274    $name   = $part['name'];
1275    $mailto = $part['mailto'];
1276    $string = $part['string'];
1277
1278    // IDNA ASCII to Unicode
1279    if ($name == $mailto)
1280      $name = idn_to_utf8($name);
1281    if ($string == $mailto)
1282      $string = idn_to_utf8($string);
1283    $mailto = idn_to_utf8($mailto);
1284
1285    if ($PRINT_MODE) {
1286      $out .= sprintf('%s &lt;%s&gt;', Q($name), $mailto);
1287    }
1288    else if (check_email($part['mailto'], false)) {
1289      if ($linked) {
1290        $out .= html::a(array(
1291            'href' => 'mailto:'.$mailto,
1292            'onclick' => sprintf("return %s.command('compose','%s',this)", JS_OBJECT_NAME, JQ($mailto)),
1293            'title' => $mailto,
1294            'class' => "rcmContactAddress",
1295          ),
1296        Q($name ? $name : $mailto));
1297      }
1298      else {
1299        $out .= html::span(array('title' => $mailto, 'class' => "rcmContactAddress"),
1300          Q($name ? $name : $mailto));
1301      }
1302
1303      if ($addicon && $got_writable_abook) {
1304        $out .= '&nbsp;' . html::a(array(
1305            'href' => "#add",
1306            'onclick' => sprintf("return %s.command('add-contact','%s',this)", JS_OBJECT_NAME, urlencode($string)),
1307            'title' => rcube_label('addtoaddressbook'),
1308          ),
1309          html::img(array(
1310            'src' => $CONFIG['skin_path'] . $addicon,
1311            'alt' => "Add contact",
1312          )));
1313      }
1314    }
1315    else {
1316      if ($name)
1317        $out .= Q($name);
1318      if ($mailto)
1319        $out .= (strlen($out) ? ' ' : '') . sprintf('&lt;%s&gt;', Q($mailto));
1320    }
1321
1322    if ($c>$j)
1323      $out .= ','.($max ? '&nbsp;' : ' ');
1324
1325    if ($max && $j==$max && $c>$j) {
1326      $out .= '...';
1327      break;
1328    }
1329  }
1330
1331  return $out;
1332}
1333
1334
1335/**
1336 * Wrap text to a given number of characters per line
1337 * but respect the mail quotation of replies messages (>).
1338 * Finally add another quotation level by prpending the lines
1339 * with >
1340 *
1341 * @param string Text to wrap
1342 * @param int The line width
1343 * @return string The wrapped text
1344 */
1345function rcmail_wrap_and_quote($text, $length = 72)
1346{
1347  // Rebuild the message body with a maximum of $max chars, while keeping quoted message.
1348  $max = min(77, $length + 8);
1349  $lines = preg_split('/\r?\n/', trim($text));
1350  $out = '';
1351
1352  foreach ($lines as $line) {
1353    // don't wrap already quoted lines
1354    if ($line[0] == '>')
1355      $line = '>' . rtrim($line);
1356    else if (mb_strlen($line) > $max) {
1357      $newline = '';
1358      foreach(explode("\n", rc_wordwrap($line, $length - 2)) as $l) {
1359        if (strlen($l))
1360          $newline .= '> ' . $l . "\n";
1361        else
1362          $newline .= ">\n";
1363      }
1364      $line = rtrim($newline);
1365    }
1366    else
1367      $line = '> ' . $line;
1368
1369    // Append the line
1370    $out .= $line . "\n";
1371  }
1372
1373  return $out;
1374}
1375
1376
1377function rcmail_draftinfo_encode($p)
1378{
1379  $parts = array();
1380  foreach ($p as $key => $val)
1381    $parts[] = $key . '=' . ($key == 'folder' ? base64_encode($val) : $val);
1382
1383  return join('; ', $parts);
1384}
1385
1386
1387function rcmail_draftinfo_decode($str)
1388{
1389  $info = array();
1390  foreach (preg_split('/;\s+/', $str) as $part) {
1391    list($key, $val) = explode('=', $part, 2);
1392    if ($key == 'folder')
1393      $val = base64_decode($val);
1394    $info[$key] = $val;
1395  }
1396
1397  return $info;
1398}
1399
1400
1401function rcmail_message_part_controls()
1402{
1403  global $MESSAGE;
1404
1405  $part = asciiwords(get_input_value('_part', RCUBE_INPUT_GPC));
1406  if (!is_object($MESSAGE) || !is_array($MESSAGE->parts) || !($_GET['_uid'] && $_GET['_part']) || !$MESSAGE->mime_parts[$part])
1407    return '';
1408
1409  $part = $MESSAGE->mime_parts[$part];
1410  $table = new html_table(array('cols' => 3));
1411
1412  if (!empty($part->filename)) {
1413    $table->add('title', Q(rcube_label('filename')));
1414    $table->add(null, Q($part->filename));
1415    $table->add(null, '[' . html::a('?'.str_replace('_frame=', '_download=', $_SERVER['QUERY_STRING']), Q(rcube_label('download'))) . ']');
1416  }
1417
1418  if (!empty($part->size)) {
1419    $table->add('title', Q(rcube_label('filesize')));
1420    $table->add(null, Q(show_bytes($part->size)));
1421  }
1422
1423  return $table->show($attrib);
1424}
1425
1426
1427
1428function rcmail_message_part_frame($attrib)
1429{
1430  global $MESSAGE;
1431
1432  $part = $MESSAGE->mime_parts[asciiwords(get_input_value('_part', RCUBE_INPUT_GPC))];
1433  $ctype_primary = strtolower($part->ctype_primary);
1434
1435  $attrib['src'] = './?' . str_replace('_frame=', ($ctype_primary=='text' ? '_show=' : '_preload='), $_SERVER['QUERY_STRING']);
1436
1437  return html::iframe($attrib);
1438}
1439
1440
1441/**
1442 * clear message composing settings
1443 */
1444function rcmail_compose_cleanup()
1445{
1446  if (!isset($_SESSION['compose']))
1447    return;
1448
1449  $rcmail = rcmail::get_instance();
1450  $rcmail->plugins->exec_hook('attachments_cleanup', array());
1451  $rcmail->session->remove('compose');
1452}
1453
1454
1455/**
1456 * Send the given message using the configured method
1457 *
1458 * @param object $message    Reference to Mail_MIME object
1459 * @param string $from       Sender address string
1460 * @param array  $mailto     Array of recipient address strings
1461 * @param array  $smtp_error SMTP error array (reference)
1462 * @param string $body_file  Location of file with saved message body (reference)
1463 *
1464 * @return boolean Send status.
1465 */
1466function rcmail_deliver_message(&$message, $from, $mailto, &$smtp_error, &$body_file)
1467{
1468  global $CONFIG, $RCMAIL;
1469
1470  $headers = $message->headers();
1471
1472  // send thru SMTP server using custom SMTP library
1473  if ($CONFIG['smtp_server']) {
1474    // generate list of recipients
1475    $a_recipients = array($mailto);
1476
1477    if (strlen($headers['Cc']))
1478      $a_recipients[] = $headers['Cc'];
1479    if (strlen($headers['Bcc']))
1480      $a_recipients[] = $headers['Bcc'];
1481
1482    // clean Bcc from header for recipients
1483    $send_headers = $headers;
1484    unset($send_headers['Bcc']);
1485    // here too, it because txtHeaders() below use $message->_headers not only $send_headers
1486    unset($message->_headers['Bcc']);
1487
1488    $smtp_headers = $message->txtHeaders($send_headers, true);
1489
1490    if ($message->getParam('delay_file_io')) {
1491      // use common temp dir
1492      $temp_dir = $RCMAIL->config->get('temp_dir');
1493      $body_file = tempnam($temp_dir, 'rcmMsg');
1494      if (PEAR::isError($mime_result = $message->saveMessageBody($body_file))) {
1495        raise_error(array('code' => 600, 'type' => 'php',
1496            'file' => __FILE__, 'line' => __LINE__,
1497            'message' => "Could not create message: ".$mime_result->getMessage()),
1498            TRUE, FALSE);
1499        return false;
1500      }
1501      $msg_body = fopen($body_file, 'r');
1502    } else {
1503      $msg_body = $message->get();
1504    }
1505
1506    // send message
1507    if (!is_object($RCMAIL->smtp))
1508      $RCMAIL->smtp_init(true);
1509
1510    $sent = $RCMAIL->smtp->send_mail($from, $a_recipients, $smtp_headers, $msg_body);
1511    $smtp_response = $RCMAIL->smtp->get_response();
1512    $smtp_error = $RCMAIL->smtp->get_error();
1513
1514    // log error
1515    if (!$sent)
1516      raise_error(array('code' => 800, 'type' => 'smtp', 'line' => __LINE__, 'file' => __FILE__,
1517                        'message' => "SMTP error: ".join("\n", $smtp_response)), TRUE, FALSE);
1518  }
1519  // send mail using PHP's mail() function
1520  else {
1521    // unset some headers because they will be added by the mail() function
1522    $headers_enc = $message->headers($headers);
1523    $headers_php = $message->_headers;
1524    unset($headers_php['To'], $headers_php['Subject']);
1525
1526    // reset stored headers and overwrite
1527    $message->_headers = array();
1528    $header_str = $message->txtHeaders($headers_php);
1529
1530    // #1485779
1531    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1532      if (preg_match_all('/<([^@]+@[^>]+)>/', $headers_enc['To'], $m)) {
1533        $headers_enc['To'] = implode(', ', $m[1]);
1534      }
1535    }
1536
1537    $msg_body = $message->get();
1538
1539    if (PEAR::isError($msg_body))
1540      raise_error(array('code' => 600, 'type' => 'php',
1541            'file' => __FILE__, 'line' => __LINE__,
1542            'message' => "Could not create message: ".$msg_body->getMessage()),
1543            TRUE, FALSE);
1544    else {
1545      $delim   = $RCMAIL->config->header_delimiter();
1546      $to      = $headers_enc['To'];
1547      $subject = $headers_enc['Subject'];
1548
1549      if ($delim != "\r\n") {
1550        $header_str = str_replace("\r\n", $delim, $header_str);
1551        $msg_body   = str_replace("\r\n", $delim, $msg_body);
1552        $to         = str_replace("\r\n", $delim, $to);
1553        $subject    = str_replace("\r\n", $delim, $subject);
1554      }
1555
1556      if (ini_get('safe_mode'))
1557        $sent = mail($to, $subject, $msg_body, $header_str);
1558      else
1559        $sent = mail($to, $subject, $msg_body, $header_str, "-f$from");
1560    }
1561  }
1562
1563  if ($sent) {
1564    $RCMAIL->plugins->exec_hook('message_sent', array('headers' => $headers, 'body' => $msg_body));
1565
1566    // remove MDN headers after sending
1567    unset($headers['Return-Receipt-To'], $headers['Disposition-Notification-To']);
1568
1569    // get all recipients
1570    if ($headers['Cc'])
1571      $mailto .= $headers['Cc'];
1572    if ($headers['Bcc'])
1573      $mailto .= $headers['Bcc'];
1574    if (preg_match_all('/<([^@]+@[^>]+)>/', $mailto, $m))
1575      $mailto = implode(', ', array_unique($m[1]));
1576
1577    if ($CONFIG['smtp_log']) {
1578      write_log('sendmail', sprintf("User %s [%s]; Message for %s; %s",
1579        $RCMAIL->user->get_username(),
1580        $_SERVER['REMOTE_ADDR'],
1581        $mailto,
1582        !empty($smtp_response) ? join('; ', $smtp_response) : ''));
1583    }
1584  }
1585
1586  if (is_resource($msg_body)) {
1587    fclose($msg_body);
1588  }
1589
1590  $message->_headers = array();
1591  $message->headers($headers);
1592
1593  return $sent;
1594}
1595
1596/**
1597 * Send the MDN response
1598 *
1599 * @param mixed $message    Original message object (rcube_message) or UID
1600 * @param array $smtp_error SMTP error array (reference)
1601 *
1602 * @return boolean Send status
1603 */
1604function rcmail_send_mdn($message, &$smtp_error)
1605{
1606  global $RCMAIL, $IMAP;
1607
1608  if (!is_a($message, rcube_message))
1609    $message = new rcube_message($message);
1610
1611  if ($message->headers->mdn_to && !$message->headers->mdn_sent &&
1612    ($IMAP->check_permflag('MDNSENT') || $IMAP->check_permflag('*')))
1613  {
1614    $identity = $RCMAIL->user->get_identity();
1615    $sender = format_email_recipient($identity['email'], $identity['name']);
1616    $recipient = array_shift($IMAP->decode_address_list($message->headers->mdn_to));
1617    $mailto = $recipient['mailto'];
1618
1619    $compose = new Mail_mime("\r\n");
1620
1621    $compose->setParam('text_encoding', 'quoted-printable');
1622    $compose->setParam('html_encoding', 'quoted-printable');
1623    $compose->setParam('head_encoding', 'quoted-printable');
1624    $compose->setParam('head_charset', RCMAIL_CHARSET);
1625    $compose->setParam('html_charset', RCMAIL_CHARSET);
1626    $compose->setParam('text_charset', RCMAIL_CHARSET);
1627
1628    // compose headers array
1629    $headers = array(
1630      'Date' => rcmail_user_date(),
1631      'From' => $sender,
1632      'To'   => $message->headers->mdn_to,
1633      'Subject' => rcube_label('receiptread') . ': ' . $message->subject,
1634      'Message-ID' => rcmail_gen_message_id(),
1635      'X-Sender' => $identity['email'],
1636      'References' => trim($message->headers->references . ' ' . $message->headers->messageID),
1637    );
1638
1639    if ($agent = $RCMAIL->config->get('useragent'))
1640      $headers['User-Agent'] = $agent;
1641
1642    $body = rcube_label("yourmessage") . "\r\n\r\n" .
1643      "\t" . rcube_label("to") . ': ' . rcube_imap::decode_mime_string($message->headers->to, $message->headers->charset) . "\r\n" .
1644      "\t" . rcube_label("subject") . ': ' . $message->subject . "\r\n" .
1645      "\t" . rcube_label("sent") . ': ' . format_date($message->headers->date, $RCMAIL->config->get('date_long')) . "\r\n" .
1646      "\r\n" . rcube_label("receiptnote") . "\r\n";
1647
1648    $ua = $RCMAIL->config->get('useragent', "Roundcube Webmail (Version ".RCMAIL_VERSION.")");
1649    $report = "Reporting-UA: $ua\r\n";
1650
1651    if ($message->headers->to)
1652        $report .= "Original-Recipient: {$message->headers->to}\r\n";
1653
1654    $report .= "Final-Recipient: rfc822; {$identity['email']}\r\n" .
1655               "Original-Message-ID: {$message->headers->messageID}\r\n" .
1656               "Disposition: manual-action/MDN-sent-manually; displayed\r\n";
1657
1658    $compose->headers($headers);
1659    $compose->setContentType('multipart/report', array('report-type'=> 'disposition-notification'));
1660    $compose->setTXTBody(rc_wordwrap($body, 75, "\r\n"));
1661    $compose->addAttachment($report, 'message/disposition-notification', 'MDNPart2.txt', false, '7bit', 'inline');
1662
1663    $sent = rcmail_deliver_message($compose, $identity['email'], $mailto, $smtp_error, $body_file);
1664
1665    if ($sent)
1666    {
1667      $IMAP->set_flag($message->uid, 'MDNSENT');
1668      return true;
1669    }
1670  }
1671
1672  return false;
1673}
1674
1675// Returns unique Message-ID
1676function rcmail_gen_message_id()
1677{
1678  global $RCMAIL;
1679
1680  $local_part  = md5(uniqid('rcmail'.mt_rand(),true));
1681  $domain_part = $RCMAIL->user->get_username('domain');
1682
1683  // Try to find FQDN, some spamfilters doesn't like 'localhost' (#1486924)
1684  if (!preg_match('/\.[a-z]+$/i', $domain_part)) {
1685    if (($host = preg_replace('/:[0-9]+$/', '', $_SERVER['HTTP_HOST']))
1686      && preg_match('/\.[a-z]+$/i', $host)) {
1687        $domain_part = $host;
1688    }
1689    else if (($host = preg_replace('/:[0-9]+$/', '', $_SERVER['SERVER_NAME']))
1690      && preg_match('/\.[a-z]+$/i', $host)) {
1691        $domain_part = $host;
1692    }
1693  }
1694
1695  return sprintf('<%s@%s>', $local_part, $domain_part);
1696}
1697
1698// Returns RFC2822 formatted current date in user's timezone
1699function rcmail_user_date()
1700{
1701  global $CONFIG;
1702
1703  // get user's timezone
1704  if ($CONFIG['timezone'] === 'auto') {
1705    $tz = isset($_SESSION['timezone']) ? $_SESSION['timezone'] : date('Z')/3600;
1706  }
1707  else {
1708    $tz = $CONFIG['timezone'];
1709    if ($CONFIG['dst_active'])
1710      $tz++;
1711  }
1712
1713  $date = time() + $tz * 60 * 60;
1714  $date = gmdate('r', $date);
1715  $tz   = sprintf('%+05d', intval($tz) * 100 + ($tz - intval($tz)) * 60);
1716  $date = preg_replace('/[+-][0-9]{4}$/', $tz, $date);
1717
1718  return $date;
1719}
1720
1721
1722function rcmail_search_filter($attrib)
1723{
1724  global $OUTPUT, $CONFIG;
1725
1726  if (!strlen($attrib['id']))
1727    $attrib['id'] = 'rcmlistfilter';
1728
1729  $attrib['onchange'] = JS_OBJECT_NAME.'.filter_mailbox(this.value)';
1730
1731  /*
1732    RFC3501 (6.4.4): 'ALL', 'RECENT',
1733    'ANSWERED', 'DELETED', 'FLAGGED', 'SEEN',
1734    'UNANSWERED', 'UNDELETED', 'UNFLAGGED', 'UNSEEN',
1735    'NEW', // = (RECENT UNSEEN)
1736    'OLD' // = NOT RECENT
1737  */
1738
1739  $select_filter = new html_select($attrib);
1740  $select_filter->add(rcube_label('all'), 'ALL');
1741  $select_filter->add(rcube_label('unread'), 'UNSEEN');
1742  $select_filter->add(rcube_label('flagged'), 'FLAGGED');
1743  $select_filter->add(rcube_label('unanswered'), 'UNANSWERED');
1744  if (!$CONFIG['skip_deleted'])
1745    $select_filter->add(rcube_label('deleted'), 'DELETED');
1746
1747  $out = $select_filter->show($_SESSION['search_filter']);
1748
1749  $OUTPUT->add_gui_object('search_filter', $attrib['id']);
1750
1751  return $out;
1752}
1753
1754function rcmail_message_error($uid=null)
1755{
1756  global $RCMAIL;
1757
1758  // Set env variables for messageerror.html template
1759  if ($RCMAIL->action == 'show') {
1760    $mbox_name = $RCMAIL->imap->get_mailbox_name();
1761    $RCMAIL->output->set_env('mailbox', $mbox_name);
1762    $RCMAIL->output->set_env('uid', null);
1763  }
1764  // display error message
1765  $RCMAIL->output->show_message('messageopenerror', 'error');
1766  // ... display message error page
1767  $RCMAIL->output->send('messageerror');
1768}
1769
1770// register UI objects
1771$OUTPUT->add_handlers(array(
1772  'mailboxlist' => 'rcmail_mailbox_list',
1773  'messages' => 'rcmail_message_list',
1774  'messagecountdisplay' => 'rcmail_messagecount_display',
1775  'quotadisplay' => 'rcmail_quota_display',
1776  'mailboxname' => 'rcmail_mailbox_name_display',
1777  'messageheaders' => 'rcmail_message_headers',
1778  'messagebody' => 'rcmail_message_body',
1779  'messagecontentframe' => 'rcmail_messagecontent_frame',
1780  'messagepartframe' => 'rcmail_message_part_frame',
1781  'messagepartcontrols' => 'rcmail_message_part_controls',
1782  'searchfilter' => 'rcmail_search_filter',
1783  'searchform' => array($OUTPUT, 'search_form'),
1784));
1785
1786
Note: See TracBrowser for help on using the repository browser.