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

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