source: github/program/steps/mail/func.inc @ 76248c7

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