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

Last change on this file since 5596 was 5596, checked in by thomasb, 17 months ago

More options for message headers output in templates

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