source: github/program/steps/mail/func.inc @ 19cc5b9

HEADdev-browser-capabilitiespdo
Last change on this file since 19cc5b9 was 19cc5b9, checked in by Aleksander Machniak <alec@…>, 12 months ago

Display Tiff as Jpeg in browsers without Tiff support (#1488452)

  • Property mode set to 100644
File size: 54.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
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(
26    '*'         => array('subject'=>1, 'from'=>1),
27    $SENT_MBOX  => array('subject'=>1, 'to'=>1),
28    $DRAFTS_MBOX => array('subject'=>1, 'to'=>1)
29);
30
31// always instantiate storage object (but not connect to server yet)
32$RCMAIL->storage_init();
33
34// set imap properties and session vars
35if (strlen(trim($mbox = get_input_value('_mbox', RCUBE_INPUT_GPC, true))))
36  $RCMAIL->storage->set_folder(($_SESSION['mbox'] = $mbox));
37else if ($RCMAIL->storage)
38  $_SESSION['mbox'] = $RCMAIL->storage->get_folder();
39
40if (!empty($_GET['_page']))
41  $RCMAIL->storage->set_page(($_SESSION['page'] = intval($_GET['_page'])));
42
43// set default sort col/order to session
44if (!isset($_SESSION['sort_col']))
45  $_SESSION['sort_col'] = !empty($CONFIG['message_sort_col']) ? $CONFIG['message_sort_col'] : '';
46if (!isset($_SESSION['sort_order']))
47  $_SESSION['sort_order'] = strtoupper($CONFIG['message_sort_order']) == 'ASC' ? 'ASC' : 'DESC';
48
49// set threads mode
50$a_threading = $RCMAIL->config->get('message_threading', array());
51if (isset($_GET['_threads'])) {
52  if ($_GET['_threads'])
53    $a_threading[$_SESSION['mbox']] = true;
54  else
55    unset($a_threading[$_SESSION['mbox']]);
56  $RCMAIL->user->save_prefs(array('message_threading' => $a_threading));
57}
58$RCMAIL->storage->set_threading($a_threading[$_SESSION['mbox']]);
59
60// set message set for search result
61if (!empty($_REQUEST['_search']) && isset($_SESSION['search'])
62    && $_SESSION['search_request'] == $_REQUEST['_search']
63) {
64  $RCMAIL->storage->set_search_set($_SESSION['search']);
65  $OUTPUT->set_env('search_request', $_REQUEST['_search']);
66  $OUTPUT->set_env('search_text', $_SESSION['last_text_search']);
67}
68
69// set main env variables, labels and page title
70if (empty($RCMAIL->action) || $RCMAIL->action == 'list') {
71  $mbox_name = $RCMAIL->storage->get_folder();
72
73  if (empty($RCMAIL->action)) {
74    // initialize searching result if search_filter is used
75    if ($_SESSION['search_filter'] && $_SESSION['search_filter'] != 'ALL') {
76      $search_request = md5($mbox_name.$_SESSION['search_filter']);
77
78      $RCMAIL->storage->search($mbox_name, $_SESSION['search_filter'], RCMAIL_CHARSET, $_SESSION['sort_col']);
79      $_SESSION['search'] = $RCMAIL->storage->get_search_set();
80      $_SESSION['search_request'] = $search_request;
81      $OUTPUT->set_env('search_request', $search_request);
82    }
83
84    $search_mods = $RCMAIL->config->get('search_mods', $SEARCH_MODS_DEFAULT);
85    $OUTPUT->set_env('search_mods', $search_mods);
86  }
87
88  $threading = (bool) $RCMAIL->storage->get_threading();
89
90  // set current mailbox and some other vars in client environment
91  $OUTPUT->set_env('mailbox', $mbox_name);
92  $OUTPUT->set_env('pagesize', $RCMAIL->storage->get_pagesize());
93  $OUTPUT->set_env('quota', $RCMAIL->storage->get_capability('QUOTA'));
94  $OUTPUT->set_env('delimiter', $RCMAIL->storage->get_hierarchy_delimiter());
95  $OUTPUT->set_env('threading', $threading);
96  $OUTPUT->set_env('threads', $threading || $RCMAIL->storage->get_capability('THREAD'));
97  $OUTPUT->set_env('preview_pane_mark_read', $RCMAIL->config->get('preview_pane_mark_read', 0));
98
99  if ($CONFIG['delete_junk'])
100    $OUTPUT->set_env('delete_junk', true);
101  if ($CONFIG['flag_for_deletion'])
102    $OUTPUT->set_env('flag_for_deletion', true);
103  if ($CONFIG['read_when_deleted'])
104    $OUTPUT->set_env('read_when_deleted', true);
105  if ($CONFIG['skip_deleted'])
106    $OUTPUT->set_env('skip_deleted', true);
107  if ($CONFIG['display_next'])
108    $OUTPUT->set_env('display_next', true);
109  if ($CONFIG['forward_attachment'])
110    $OUTPUT->set_env('forward_attachment', true);
111  if ($CONFIG['trash_mbox'])
112    $OUTPUT->set_env('trash_mailbox', $CONFIG['trash_mbox']);
113  if ($CONFIG['drafts_mbox'])
114    $OUTPUT->set_env('drafts_mailbox', $CONFIG['drafts_mbox']);
115  if ($CONFIG['junk_mbox'])
116    $OUTPUT->set_env('junk_mailbox', $CONFIG['junk_mbox']);
117
118  if (!empty($_SESSION['browser_caps']))
119    $OUTPUT->set_env('browser_capabilities', $_SESSION['browser_caps']);
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 (rcmail_part_image_type($attach_prop)) {
1110        $out .= html::tag('hr') . html::p(array('align' => "center"),
1111          html::img(array(
1112            'src' => $MESSAGE->get_part_url($attach_prop->mime_id, true),
1113            'title' => $attach_prop->filename,
1114            'alt' => $attach_prop->filename,
1115          )));
1116      }
1117    }
1118  }
1119
1120  // tell client that there are blocked remote objects
1121  if ($REMOTE_OBJECTS && !$safe_mode)
1122    $OUTPUT->set_env('blockedobjects', true);
1123
1124  return html::div($attrib, $out);
1125}
1126
1127function rcmail_part_image_type($part)
1128{
1129  $rcmail = rcmail::get_instance();
1130
1131  // Skip TIFF images if browser doesn't support this format...
1132  $tiff_support = !empty($_SESSION['browser_caps']) && !empty($_SESSION['browser_caps']['tif']);
1133  // until we can convert them to JPEG
1134  $tiff_support = $tiff_support || $rcmail->config->get('im_convert_path');
1135
1136  // Content-type regexp
1137  $mime_regex = $tiff_support ? '/^image\//i' : '/^image\/(?!tif)/i';
1138
1139  // Content-Type: image/*...
1140  if (preg_match($mime_regex, $part->mimetype)) {
1141    return $part->mimetype;
1142  }
1143
1144  // Many clients use application/octet-stream, we'll detect mimetype
1145  // by checking filename extension
1146
1147  // Supported image filename extensions to image type map
1148  $types = array(
1149    'jpg'  => 'image/jpeg',
1150    'jpeg' => 'image/jpeg',
1151    'png'  => 'image/png',
1152    'gif'  => 'image/gif',
1153    'bmp'  => 'image/bmp',
1154  );
1155  if ($tiff_support) {
1156    $types['tif']  = 'image/tiff';
1157    $types['tiff'] = 'image/tiff';
1158  }
1159
1160  if ($part->filename
1161    && preg_match('/^application\/octet-stream$/i', $part->mimetype)
1162    && preg_match('/\.([^.])$/i', $part->filename, $m)
1163    && ($extension = strtolower($m[1]))
1164    && isset($types[$extension])
1165  ) {
1166    return $types[$extension];
1167  }
1168}
1169
1170/**
1171 * Convert all relative URLs according to a <base> in HTML
1172 */
1173function rcmail_resolve_base($body)
1174{
1175  // check for <base href=...>
1176  if (preg_match('!(<base.*href=["\']?)([hftps]{3,5}://[a-z0-9/.%-]+)!i', $body, $regs)) {
1177    $replacer = new rcube_base_replacer($regs[2]);
1178    $body     = $replacer->replace($body);
1179  }
1180
1181  return $body;
1182}
1183
1184
1185/**
1186 * modify a HTML message that it can be displayed inside a HTML page
1187 */
1188function rcmail_html4inline($body, $container_id, $body_id='', &$attributes=null, $allow_remote=false)
1189{
1190  $last_style_pos = 0;
1191  $cont_id = $container_id.($body_id ? ' div.'.$body_id : '');
1192
1193  // find STYLE tags
1194  while (($pos = stripos($body, '<style', $last_style_pos)) && ($pos2 = stripos($body, '</style>', $pos)))
1195  {
1196    $pos = strpos($body, '>', $pos)+1;
1197
1198    // replace all css definitions with #container [def]
1199    $styles = rcmail_mod_css_styles(
1200      substr($body, $pos, $pos2-$pos), $cont_id, $allow_remote);
1201
1202    $body = substr_replace($body, $styles, $pos, $pos2-$pos);
1203    $last_style_pos = $pos2;
1204  }
1205
1206  // modify HTML links to open a new window if clicked
1207  $GLOBALS['rcmail_html_container_id'] = $container_id;
1208  $body = preg_replace_callback('/<(a|link)\s+([^>]+)>/Ui', 'rcmail_alter_html_link', $body);
1209  unset($GLOBALS['rcmail_html_container_id']);
1210
1211  $body = preg_replace(array(
1212      // add comments arround html and other tags
1213      '/(<!DOCTYPE[^>]*>)/i',
1214      '/(<\?xml[^>]*>)/i',
1215      '/(<\/?html[^>]*>)/i',
1216      '/(<\/?head[^>]*>)/i',
1217      '/(<title[^>]*>.*<\/title>)/Ui',
1218      '/(<\/?meta[^>]*>)/i',
1219      // quote <? of php and xml files that are specified as text/html
1220      '/<\?/',
1221      '/\?>/',
1222      // replace <body> with <div>
1223      '/<body([^>]*)>/i',
1224      '/<\/body>/i',
1225      ),
1226    array(
1227      '<!--\\1-->',
1228      '<!--\\1-->',
1229      '<!--\\1-->',
1230      '<!--\\1-->',
1231      '<!--\\1-->',
1232      '<!--\\1-->',
1233      '&lt;?',
1234      '?&gt;',
1235      '<div class="'.$body_id.'"\\1>',
1236      '</div>',
1237      ),
1238    $body);
1239
1240  $attributes = array();
1241
1242  // Handle body attributes that doesn't play nicely with div elements
1243  $regexp = '/<div class="' . preg_quote($body_id, '/') . '"([^>]*)/';
1244  if (preg_match($regexp, $body, $m)) {
1245    $attrs = $m[0];
1246    // Get bgcolor, we'll set it as background-color of the message container
1247    if ($m[1] && preg_match('/bgcolor=["\']*([a-z0-9#]+)["\']*/', $attrs, $mb)) {
1248      $attributes['background-color'] = $mb[1];
1249      $attrs = preg_replace('/bgcolor=["\']*([a-z0-9#]+)["\']*/', '', $attrs);
1250    }
1251    // Get background, we'll set it as background-image of the message container
1252    if ($m[1] && preg_match('/background=["\']*([^"\'>\s]+)["\']*/', $attrs, $mb)) {
1253      $attributes['background-image'] = 'url('.$mb[1].')';
1254      $attrs = preg_replace('/background=["\']*([^"\'>\s]+)["\']*/', '', $attrs);
1255    }
1256    if (!empty($attributes)) {
1257      $body = preg_replace($regexp, rtrim($attrs), $body, 1);
1258    }
1259
1260    // handle body styles related to background image
1261    if ($attributes['background-image']) {
1262      // get body style
1263      if (preg_match('/#'.preg_quote($cont_id, '/').'\s+\{([^}]+)}/i', $body, $m)) {
1264        // get background related style
1265        if (preg_match_all('/(background-position|background-repeat)\s*:\s*([^;]+);/i', $m[1], $ma, PREG_SET_ORDER)) {
1266          foreach ($ma as $style)
1267            $attributes[$style[1]] = $style[2];
1268        }
1269      }
1270    }
1271  }
1272  // make sure there's 'rcmBody' div, we need it for proper css modification
1273  // its name is hardcoded in rcmail_message_body() also
1274  else {
1275    $body = '<div class="' . $body_id . '">' . $body . '</div>';
1276  }
1277
1278  return $body;
1279}
1280
1281
1282/**
1283 * parse link attributes and set correct target
1284 */
1285function rcmail_alter_html_link($matches)
1286{
1287  global $RCMAIL;
1288
1289  // Support unicode/punycode in top-level domain part
1290  $EMAIL_PATTERN = '([a-z0-9][a-z0-9\-\.\+\_]*@[^&@"\'.][^@&"\']*\\.([^\\x00-\\x40\\x5b-\\x60\\x7b-\\x7f]{2,}|xn--[a-z0-9]{2,}))';
1291
1292  $tag = $matches[1];
1293  $attrib = parse_attrib_string($matches[2]);
1294  $end = '>';
1295
1296  // Remove non-printable characters in URL (#1487805)
1297  if ($attrib['href'])
1298    $attrib['href'] = preg_replace('/[\x00-\x1F]/', '', $attrib['href']);
1299
1300  if ($tag == 'link' && preg_match('/^https?:\/\//i', $attrib['href'])) {
1301    $tempurl = 'tmp-' . md5($attrib['href']) . '.css';
1302    $_SESSION['modcssurls'][$tempurl] = $attrib['href'];
1303    $attrib['href'] = $RCMAIL->url(array('task' => 'utils', 'action' => 'modcss', 'u' => $tempurl, 'c' => $GLOBALS['rcmail_html_container_id']));
1304    $end = ' />';
1305  }
1306  else if (preg_match('/^mailto:'.$EMAIL_PATTERN.'(\?[^"\'>]+)?/i', $attrib['href'], $mailto)) {
1307    $attrib['href'] = $mailto[0];
1308    $attrib['onclick'] = sprintf(
1309      "return %s.command('compose','%s',this)",
1310      JS_OBJECT_NAME,
1311      JQ($mailto[1].$mailto[3]));
1312  }
1313  else if (empty($attrib['href']) && !$attrib['name']) {
1314    $attrib['href'] = './#NOP';
1315    $attrib['onclick'] = 'return false';
1316  }
1317  else if (!empty($attrib['href']) && $attrib['href'][0] != '#') {
1318    $attrib['target'] = '_blank';
1319  }
1320
1321  return "<$tag" . html::attrib_string($attrib, array('href','name','target','onclick','id','class','style','title','rel','type','media')) . $end;
1322}
1323
1324
1325/**
1326 * decode address string and re-format it as HTML links
1327 */
1328function rcmail_address_string($input, $max=null, $linked=false, $addicon=null, $default_charset=null)
1329{
1330  global $RCMAIL, $PRINT_MODE, $CONFIG;
1331
1332  $a_parts = rcube_mime::decode_address_list($input, null, true, $default_charset);
1333
1334  if (!sizeof($a_parts))
1335    return $input;
1336
1337  $c = count($a_parts);
1338  $j = 0;
1339  $out = '';
1340
1341  if ($addicon && !isset($_SESSION['writeable_abook'])) {
1342    $_SESSION['writeable_abook'] = $RCMAIL->get_address_sources(true) ? true : false;
1343  }
1344
1345  foreach ($a_parts as $part) {
1346    $j++;
1347
1348    $name   = $part['name'];
1349    $mailto = $part['mailto'];
1350    $string = $part['string'];
1351
1352    // IDNA ASCII to Unicode
1353    if ($name == $mailto)
1354      $name = rcube_idn_to_utf8($name);
1355    if ($string == $mailto)
1356      $string = rcube_idn_to_utf8($string);
1357    $mailto = rcube_idn_to_utf8($mailto);
1358
1359    if ($PRINT_MODE) {
1360      $out .= sprintf('%s &lt;%s&gt;', Q($name), $mailto);
1361    }
1362    else if (check_email($part['mailto'], false)) {
1363      if ($linked) {
1364        $address = html::a(array(
1365            'href' => 'mailto:'.$mailto,
1366            'onclick' => sprintf("return %s.command('compose','%s',this)", JS_OBJECT_NAME, JQ($mailto)),
1367            'title' => $mailto,
1368            'class' => "rcmContactAddress",
1369          ),
1370        Q($name ? $name : $mailto));
1371      }
1372      else {
1373        $address = html::span(array('title' => $mailto, 'class' => "rcmContactAddress"),
1374          Q($name ? $name : $mailto));
1375      }
1376
1377      if ($addicon && $_SESSION['writeable_abook']) {
1378        $address = html::span(null, $address . html::a(array(
1379            'href' => "#add",
1380            'onclick' => sprintf("return %s.command('add-contact','%s',this)", JS_OBJECT_NAME, $string),
1381            'title' => rcube_label('addtoaddressbook'),
1382            'class' => 'rcmaddcontact',
1383          ),
1384          html::img(array(
1385            'src' => $CONFIG['skin_path'] . $addicon,
1386            'alt' => "Add contact",
1387          ))));
1388      }
1389      $out .= $address;
1390    }
1391    else {
1392      if ($name)
1393        $out .= Q($name);
1394      if ($mailto)
1395        $out .= (strlen($out) ? ' ' : '') . sprintf('&lt;%s&gt;', Q($mailto));
1396    }
1397
1398    if ($c>$j)
1399      $out .= ','.($max ? '&nbsp;' : ' ');
1400
1401    if ($max && $j==$max && $c>$j) {
1402      $out .= '...';
1403      break;
1404    }
1405  }
1406
1407  return $out;
1408}
1409
1410
1411/**
1412 * Wrap text to a given number of characters per line
1413 * but respect the mail quotation of replies messages (>).
1414 * Finally add another quotation level by prpending the lines
1415 * with >
1416 *
1417 * @param string Text to wrap
1418 * @param int The line width
1419 * @return string The wrapped text
1420 */
1421function rcmail_wrap_and_quote($text, $length = 72)
1422{
1423  // Rebuild the message body with a maximum of $max chars, while keeping quoted message.
1424  $max = min(77, $length + 8);
1425  $lines = preg_split('/\r?\n/', trim($text));
1426  $out = '';
1427
1428  foreach ($lines as $line) {
1429    // don't wrap already quoted lines
1430    if ($line[0] == '>')
1431      $line = '>' . rtrim($line);
1432    else if (mb_strlen($line) > $max) {
1433      $newline = '';
1434      foreach(explode("\n", rc_wordwrap($line, $length - 2)) as $l) {
1435        if (strlen($l))
1436          $newline .= '> ' . $l . "\n";
1437        else
1438          $newline .= ">\n";
1439      }
1440      $line = rtrim($newline);
1441    }
1442    else
1443      $line = '> ' . $line;
1444
1445    // Append the line
1446    $out .= $line . "\n";
1447  }
1448
1449  return $out;
1450}
1451
1452
1453function rcmail_draftinfo_encode($p)
1454{
1455  $parts = array();
1456  foreach ($p as $key => $val)
1457    $parts[] = $key . '=' . ($key == 'folder' ? base64_encode($val) : $val);
1458
1459  return join('; ', $parts);
1460}
1461
1462
1463function rcmail_draftinfo_decode($str)
1464{
1465  $info = array();
1466  foreach (preg_split('/;\s+/', $str) as $part) {
1467    list($key, $val) = explode('=', $part, 2);
1468    if ($key == 'folder')
1469      $val = base64_decode($val);
1470    $info[$key] = $val;
1471  }
1472
1473  return $info;
1474}
1475
1476
1477function rcmail_message_part_controls($attrib)
1478{
1479  global $MESSAGE;
1480
1481  $part = asciiwords(get_input_value('_part', RCUBE_INPUT_GPC));
1482  if (!is_object($MESSAGE) || !is_array($MESSAGE->parts) || !($_GET['_uid'] && $_GET['_part']) || !$MESSAGE->mime_parts[$part])
1483    return '';
1484
1485  $part = $MESSAGE->mime_parts[$part];
1486  $table = new html_table(array('cols' => 3));
1487
1488  $filename = $part->filename;
1489  if (empty($filename) && $attach_prop->mimetype == 'text/html') {
1490    $filename = rcube_label('htmlmessage');
1491  }
1492
1493  if (!empty($filename)) {
1494    $table->add('title', Q(rcube_label('filename')));
1495    $table->add('header', Q($filename));
1496    $table->add('download-link', html::a(array('href' => './?'.str_replace('_frame=', '_download=', $_SERVER['QUERY_STRING'])), Q(rcube_label('download'))));
1497  }
1498
1499  if (!empty($part->size)) {
1500    $table->add('title', Q(rcube_label('filesize')));
1501    $table->add('header', Q(show_bytes($part->size)));
1502  }
1503
1504  return $table->show($attrib);
1505}
1506
1507
1508
1509function rcmail_message_part_frame($attrib)
1510{
1511  global $MESSAGE;
1512
1513  $part = $MESSAGE->mime_parts[asciiwords(get_input_value('_part', RCUBE_INPUT_GPC))];
1514  $ctype_primary = strtolower($part->ctype_primary);
1515
1516  $attrib['src'] = './?' . str_replace('_frame=', ($ctype_primary=='text' ? '_show=' : '_preload='), $_SERVER['QUERY_STRING']);
1517
1518  return html::iframe($attrib);
1519}
1520
1521
1522/**
1523 * clear message composing settings
1524 */
1525function rcmail_compose_cleanup($id)
1526{
1527  if (!isset($_SESSION['compose_data_'.$id]))
1528    return;
1529
1530  $rcmail = rcmail::get_instance();
1531  $rcmail->plugins->exec_hook('attachments_cleanup', array('group' => $id));
1532  $rcmail->session->remove('compose_data_'.$id);
1533}
1534
1535
1536/**
1537 * Send the MDN response
1538 *
1539 * @param mixed $message    Original message object (rcube_message) or UID
1540 * @param array $smtp_error SMTP error array (reference)
1541 *
1542 * @return boolean Send status
1543 */
1544function rcmail_send_mdn($message, &$smtp_error)
1545{
1546  global $RCMAIL;
1547
1548  if (!is_object($message) || !is_a($message, 'rcube_message'))
1549    $message = new rcube_message($message);
1550
1551  if ($message->headers->mdn_to && empty($message->headers->flags['MDNSENT']) &&
1552    ($RCMAIL->storage->check_permflag('MDNSENT') || $RCMAIL->storage->check_permflag('*')))
1553  {
1554    $identity = $RCMAIL->user->get_identity();
1555    $sender = format_email_recipient($identity['email'], $identity['name']);
1556    $recipient = array_shift(rcube_mime::decode_address_list(
1557      $message->headers->mdn_to, 1, true, $message->headers->charset));
1558    $mailto = $recipient['mailto'];
1559
1560    $compose = new Mail_mime("\r\n");
1561
1562    $compose->setParam('text_encoding', 'quoted-printable');
1563    $compose->setParam('html_encoding', 'quoted-printable');
1564    $compose->setParam('head_encoding', 'quoted-printable');
1565    $compose->setParam('head_charset', RCMAIL_CHARSET);
1566    $compose->setParam('html_charset', RCMAIL_CHARSET);
1567    $compose->setParam('text_charset', RCMAIL_CHARSET);
1568
1569    // compose headers array
1570    $headers = array(
1571      'Date' => rcmail_user_date(),
1572      'From' => $sender,
1573      'To'   => $message->headers->mdn_to,
1574      'Subject' => rcube_label('receiptread') . ': ' . $message->subject,
1575      'Message-ID' => rcmail_gen_message_id(),
1576      'X-Sender' => $identity['email'],
1577      'References' => trim($message->headers->references . ' ' . $message->headers->messageID),
1578    );
1579
1580    if ($agent = $RCMAIL->config->get('useragent'))
1581      $headers['User-Agent'] = $agent;
1582
1583    $body = rcube_label("yourmessage") . "\r\n\r\n" .
1584      "\t" . rcube_label("to") . ': ' . rcube_mime::decode_mime_string($message->headers->to, $message->headers->charset) . "\r\n" .
1585      "\t" . rcube_label("subject") . ': ' . $message->subject . "\r\n" .
1586      "\t" . rcube_label("sent") . ': ' . format_date($message->headers->date, $RCMAIL->config->get('date_long')) . "\r\n" .
1587      "\r\n" . rcube_label("receiptnote") . "\r\n";
1588
1589    $ua = $RCMAIL->config->get('useragent', "Roundcube Webmail (Version ".RCMAIL_VERSION.")");
1590    $report = "Reporting-UA: $ua\r\n";
1591
1592    if ($message->headers->to)
1593        $report .= "Original-Recipient: {$message->headers->to}\r\n";
1594
1595    $report .= "Final-Recipient: rfc822; {$identity['email']}\r\n" .
1596               "Original-Message-ID: {$message->headers->messageID}\r\n" .
1597               "Disposition: manual-action/MDN-sent-manually; displayed\r\n";
1598
1599    $compose->headers($headers);
1600    $compose->setContentType('multipart/report', array('report-type'=> 'disposition-notification'));
1601    $compose->setTXTBody(rc_wordwrap($body, 75, "\r\n"));
1602    $compose->addAttachment($report, 'message/disposition-notification', 'MDNPart2.txt', false, '7bit', 'inline');
1603
1604    $sent = rcmail_deliver_message($compose, $identity['email'], $mailto, $smtp_error, $body_file);
1605
1606    if ($sent)
1607    {
1608      $RCMAIL->storage->set_flag($message->uid, 'MDNSENT');
1609      return true;
1610    }
1611  }
1612
1613  return false;
1614}
1615
1616
1617// Fixes some content-type names
1618function rcmail_fix_mimetype($name)
1619{
1620  // Some versions of Outlook create garbage Content-Type:
1621  // application/pdf.A520491B_3BF7_494D_8855_7FAC2C6C0608
1622  if (preg_match('/^application\/pdf.+/', $name))
1623    $name = 'application/pdf';
1624
1625  return $name;
1626}
1627
1628function rcmail_search_filter($attrib)
1629{
1630  global $OUTPUT, $CONFIG;
1631
1632  if (!strlen($attrib['id']))
1633    $attrib['id'] = 'rcmlistfilter';
1634
1635  $attrib['onchange'] = JS_OBJECT_NAME.'.filter_mailbox(this.value)';
1636
1637  /*
1638    RFC3501 (6.4.4): 'ALL', 'RECENT',
1639    'ANSWERED', 'DELETED', 'FLAGGED', 'SEEN',
1640    'UNANSWERED', 'UNDELETED', 'UNFLAGGED', 'UNSEEN',
1641    'NEW', // = (RECENT UNSEEN)
1642    'OLD' // = NOT RECENT
1643  */
1644
1645  $select_filter = new html_select($attrib);
1646  $select_filter->add(rcube_label('all'), 'ALL');
1647  $select_filter->add(rcube_label('unread'), 'UNSEEN');
1648  $select_filter->add(rcube_label('flagged'), 'FLAGGED');
1649  $select_filter->add(rcube_label('unanswered'), 'UNANSWERED');
1650  if (!$CONFIG['skip_deleted'])
1651    $select_filter->add(rcube_label('deleted'), 'DELETED');
1652  $select_filter->add(rcube_label('priority').': '.rcube_label('highest'), 'HEADER X-PRIORITY 1');
1653  $select_filter->add(rcube_label('priority').': '.rcube_label('high'), 'HEADER X-PRIORITY 2');
1654  $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');
1655  $select_filter->add(rcube_label('priority').': '.rcube_label('low'), 'HEADER X-PRIORITY 4');
1656  $select_filter->add(rcube_label('priority').': '.rcube_label('lowest'), 'HEADER X-PRIORITY 5');
1657
1658  $out = $select_filter->show($_SESSION['search_filter']);
1659
1660  $OUTPUT->add_gui_object('search_filter', $attrib['id']);
1661
1662  return $out;
1663}
1664
1665function rcmail_message_error($uid=null)
1666{
1667  global $RCMAIL;
1668
1669  // Set env variables for messageerror.html template
1670  if ($RCMAIL->action == 'show') {
1671    $mbox_name = $RCMAIL->storage->get_folder();
1672    $RCMAIL->output->set_env('mailbox', $mbox_name);
1673    $RCMAIL->output->set_env('uid', null);
1674  }
1675  // display error message
1676  $RCMAIL->output->show_message('messageopenerror', 'error');
1677  // ... display message error page
1678  $RCMAIL->output->send('messageerror');
1679}
1680
1681// register UI objects
1682$OUTPUT->add_handlers(array(
1683  'mailboxlist' => 'rcmail_mailbox_list',
1684  'messages' => 'rcmail_message_list',
1685  'messagecountdisplay' => 'rcmail_messagecount_display',
1686  'quotadisplay' => 'rcmail_quota_display',
1687  'mailboxname' => 'rcmail_mailbox_name_display',
1688  'messageheaders' => 'rcmail_message_headers',
1689  'messagefullheaders' => 'rcmail_message_full_headers',
1690  'messagebody' => 'rcmail_message_body',
1691  'messagecontentframe' => 'rcmail_messagecontent_frame',
1692  'messagepartframe' => 'rcmail_message_part_frame',
1693  'messagepartcontrols' => 'rcmail_message_part_controls',
1694  'searchfilter' => 'rcmail_search_filter',
1695  'searchform' => array($OUTPUT, 'search_form'),
1696));
1697
1698// register action aliases
1699$RCMAIL->register_action_map(array(
1700    'preview' => 'show.inc',
1701    'print'   => 'show.inc',
1702    'moveto'  => 'move_del.inc',
1703    'delete'  => 'move_del.inc',
1704    'send'    => 'sendmail.inc',
1705    'expunge' => 'folders.inc',
1706    'purge'   => 'folders.inc',
1707    'remove-attachment'  => 'attachments.inc',
1708    'display-attachment' => 'attachments.inc',
1709    'upload'             => 'attachments.inc',
1710    'group-expand'       => 'autocomplete.inc',
1711));
Note: See TracBrowser for help on using the repository browser.