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

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

Make emtpy/invalid links non-clickable

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 52.8 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    else if ($col_name[0] != '<')
383      $col_name = '<span class="' . $col .'">' . $col_name . '</span>';
384
385    $sort_class = $col == $sort_col ? " sorted$sort_order" : '';
386    $class_name = $col.$sort_class;
387
388    // put it all together
389    $cells[] = array('className' => $class_name, 'id' => "rcm$col", 'html' => $col_name);
390  }
391
392  return $cells;
393}
394
395
396/**
397 * return an HTML iframe for loading mail content
398 */
399function rcmail_messagecontent_frame($attrib)
400{
401  global $OUTPUT, $RCMAIL;
402
403  if (empty($attrib['id']))
404    $attrib['id'] = 'rcmailcontentwindow';
405
406  $attrib['name'] = $attrib['id'];
407
408  if ($RCMAIL->config->get('preview_pane'))
409    $OUTPUT->set_env('contentframe', $attrib['id']);
410  $OUTPUT->set_env('blankpage', $attrib['src'] ? $OUTPUT->abs_url($attrib['src']) : 'program/blank.gif');
411
412  return html::iframe($attrib);
413}
414
415
416function rcmail_messagecount_display($attrib)
417{
418  global $RCMAIL;
419
420  if (!$attrib['id'])
421    $attrib['id'] = 'rcmcountdisplay';
422
423  $RCMAIL->output->add_gui_object('countdisplay', $attrib['id']);
424
425  $content =  $RCMAIL->action != 'show' ? rcmail_get_messagecount_text() : rcube_label('loading');
426
427  return html::span($attrib, $content);
428}
429
430
431function rcmail_get_messagecount_text($count=NULL, $page=NULL)
432{
433  global $RCMAIL;
434
435  if ($page===NULL)
436    $page = $RCMAIL->imap->list_page;
437
438  $start_msg = ($page-1) * $RCMAIL->imap->page_size + 1;
439
440  if ($count!==NULL)
441    $max = $count;
442  else if ($RCMAIL->action)
443    $max = $RCMAIL->imap->messagecount(NULL, $RCMAIL->imap->threading ? 'THREADS' : 'ALL');
444
445  if ($max==0)
446    $out = rcube_label('mailboxempty');
447  else
448    $out = rcube_label(array('name' => $RCMAIL->imap->threading ? 'threadsfromto' : 'messagesfromto',
449            'vars' => array('from'  => $start_msg,
450            'to'    => min($max, $start_msg + $RCMAIL->imap->page_size - 1),
451            'count' => $max)));
452
453  return Q($out);
454}
455
456
457function rcmail_mailbox_name_display($attrib)
458{
459  global $RCMAIL;
460
461  if (!$attrib['id'])
462    $attrib['id'] = 'rcmmailboxname';
463
464  $RCMAIL->output->add_gui_object('mailboxname', $attrib['id']);
465
466  return html::span($attrib, rcmail_get_mailbox_name_text());
467}
468
469
470function rcmail_get_mailbox_name_text()
471{
472  global $RCMAIL;
473  return rcmail_localize_foldername($RCMAIL->imap->get_mailbox_name());
474}
475
476
477function rcmail_send_unread_count($mbox_name, $force=false, $count=null, $mark='')
478{
479  global $RCMAIL;
480
481  $old_unseen = rcmail_get_unseen_count($mbox_name);
482
483  if ($count === null)
484    $unseen = $RCMAIL->imap->messagecount($mbox_name, 'UNSEEN', $force);
485  else
486    $unseen = $count;
487
488  if ($unseen != $old_unseen || ($mbox_name == 'INBOX'))
489    $RCMAIL->output->command('set_unread_count', $mbox_name, $unseen,
490      ($mbox_name == 'INBOX'), $unseen && $mark ? $mark : '');
491
492  rcmail_set_unseen_count($mbox_name, $unseen);
493
494  return $unseen;
495}
496
497
498function rcmail_set_unseen_count($mbox_name, $count)
499{
500  // @TODO: this data is doubled (session and cache tables) if caching is enabled
501
502  // Make sure we have an array here (#1487066)
503  if (!is_array($_SESSION['unseen_count']))
504    $_SESSION['unseen_count'] = array();
505
506  $_SESSION['unseen_count'][$mbox_name] = $count;
507}
508
509
510function rcmail_get_unseen_count($mbox_name)
511{
512  if (is_array($_SESSION['unseen_count']) && array_key_exists($mbox_name, $_SESSION['unseen_count']))
513    return $_SESSION['unseen_count'][$mbox_name];
514  else
515    return null;
516}
517
518
519/**
520 * Sets message is_safe flag according to 'show_images' option value
521 *
522 * @param object rcube_message Message
523 */
524function rcmail_check_safe(&$message)
525{
526  global $RCMAIL;
527
528  $show_images = $RCMAIL->config->get('show_images');
529  if (!$message->is_safe
530    && !empty($show_images)
531    && $message->has_html_part())
532  {
533    switch($show_images) {
534      case '1': // known senders only
535        $CONTACTS = new rcube_contacts($RCMAIL->db, $_SESSION['user_id']);
536        if ($CONTACTS->search('email', $message->sender['mailto'], true, false)->count) {
537          $message->set_safe(true);
538        }
539      break;
540      case '2': // always
541        $message->set_safe(true);
542      break;
543    }
544  }
545}
546
547
548/**
549 * Cleans up the given message HTML Body (for displaying)
550 *
551 * @param string HTML
552 * @param array  Display parameters
553 * @param array  CID map replaces (inline images)
554 * @return string Clean HTML
555 */
556function rcmail_wash_html($html, $p, $cid_replaces)
557{
558  global $REMOTE_OBJECTS;
559
560  $p += array('safe' => false, 'inline_html' => true);
561
562  // special replacements (not properly handled by washtml class)
563  $html_search = array(
564    '/(<\/nobr>)(\s+)(<nobr>)/i',       // space(s) between <NOBR>
565    '/<title[^>]*>[^<]*<\/title>/i',    // PHP bug #32547 workaround: remove title tag
566    '/^(\0\0\xFE\xFF|\xFF\xFE\0\0|\xFE\xFF|\xFF\xFE|\xEF\xBB\xBF)/',    // byte-order mark (only outlook?)
567    '/<html\s[^>]+>/i',                 // washtml/DOMDocument cannot handle xml namespaces
568  );
569  $html_replace = array(
570    '\\1'.' &nbsp; '.'\\3',
571    '',
572    '',
573    '<html>',
574  );
575  $html = preg_replace($html_search, $html_replace, trim($html));
576
577  // PCRE errors handling (#1486856), should we use something like for every preg_* use?
578  if ($html === null && ($preg_error = preg_last_error()) != PREG_NO_ERROR) {
579    $errstr = "Could not clean up HTML message! PCRE Error: $preg_error.";
580
581    if ($preg_error == PREG_BACKTRACK_LIMIT_ERROR)
582      $errstr .= " Consider raising pcre.backtrack_limit!";
583    if ($preg_error == PREG_RECURSION_LIMIT_ERROR)
584      $errstr .= " Consider raising pcre.recursion_limit!";
585
586    raise_error(array('code' => 620, 'type' => 'php',
587        'line' => __LINE__, 'file' => __FILE__,
588        'message' => $errstr), true, false);
589    return '';
590  }
591
592  // fix (unknown/malformed) HTML tags before "wash"
593  $html = preg_replace_callback('/(<[\/]*)([^\s>]+)/', 'rcmail_html_tag_callback', $html);
594
595  // charset was converted to UTF-8 in rcube_imap::get_message_part(),
596  // change/add charset specification in HTML accordingly,
597  // washtml cannot work without that
598  $meta = '<meta http-equiv="Content-Type" content="text/html; charset='.RCMAIL_CHARSET.'" />';
599
600  // remove old meta tag and add the new one, making sure
601  // that it is placed in the head (#1488093)
602  $html = preg_replace('/<meta[^>]+charset=[a-z0-9-_]+[^>]*>/Ui', '', $html);
603  $html = preg_replace('/(<head[^>]*>)/Ui', '\\1'.$meta, $html, -1, $rcount);
604  if (!$rcount) {
605    $html = '<head>' . $meta . '</head>' . $html;
606  }
607
608  // turn relative into absolute urls
609  $html = rcmail_resolve_base($html);
610
611  // clean HTML with washhtml by Frederic Motte
612  $wash_opts = array(
613    'show_washed' => false,
614    'allow_remote' => $p['safe'],
615    'blocked_src' => "./program/blocked.gif",
616    'charset' => RCMAIL_CHARSET,
617    'cid_map' => $cid_replaces,
618    'html_elements' => array('body'),
619  );
620
621  if (!$p['inline_html']) {
622    $wash_opts['html_elements'] = array('html','head','title','body');
623  }
624  if ($p['safe']) {
625    $wash_opts['html_elements'][] = 'link';
626    $wash_opts['html_attribs'] = array('rel','type');
627  }
628
629  // overwrite washer options with options from plugins
630  if (isset($p['html_elements']))
631    $wash_opts['html_elements'] = $p['html_elements'];
632  if (isset($p['html_attribs']))
633    $wash_opts['html_attribs'] = $p['html_attribs'];
634
635  // initialize HTML washer
636  $washer = new washtml($wash_opts);
637
638  if (!$p['skip_washer_form_callback'])
639    $washer->add_callback('form', 'rcmail_washtml_callback');
640
641  // allow CSS styles, will be sanitized by rcmail_washtml_callback()
642  if (!$p['skip_washer_style_callback'])
643    $washer->add_callback('style', 'rcmail_washtml_callback');
644
645  // Remove non-UTF8 characters (#1487813)
646  $html = rc_utf8_clean($html);
647
648  $html = $washer->wash($html);
649  $REMOTE_OBJECTS = $washer->extlinks;
650
651  return $html;
652}
653
654
655/**
656 * Convert the given message part to proper HTML
657 * which can be displayed the message view
658 *
659 * @param object rcube_message_part Message part
660 * @param array  Display parameters array
661 * @return string Formatted HTML string
662 */
663function rcmail_print_body($part, $p = array())
664{
665  global $RCMAIL;
666
667  // trigger plugin hook
668  $data = $RCMAIL->plugins->exec_hook('message_part_before',
669    array('type' => $part->ctype_secondary, 'body' => $part->body, 'id' => $part->mime_id)
670        + $p + array('safe' => false, 'plain' => false, 'inline_html' => true));
671
672  // convert html to text/plain
673  if ($data['type'] == 'html' && $data['plain']) {
674    $txt = new html2text($data['body'], false, true);
675    $body = $txt->get_text();
676    $part->ctype_secondary = 'plain';
677  }
678  // text/html
679  else if ($data['type'] == 'html') {
680    $body = rcmail_wash_html($data['body'], $data, $part->replaces);
681    $part->ctype_secondary = $data['type'];
682  }
683  // text/enriched
684  else if ($data['type'] == 'enriched') {
685    $part->ctype_secondary = 'html';
686    require_once(INSTALL_PATH . 'program/lib/enriched.inc');
687    $body = Q(enriched_to_html($data['body']), 'show');
688  }
689  else {
690    // assert plaintext
691    $body = $part->body;
692    $part->ctype_secondary = $data['type'] = 'plain';
693  }
694
695  // free some memory (hopefully)
696  unset($data['body']);
697
698  // plaintext postprocessing
699  if ($part->ctype_secondary == 'plain')
700    $body = rcmail_plain_body($body, $part->ctype_parameters['format'] == 'flowed');
701
702  // allow post-processing of the message body
703  $data = $RCMAIL->plugins->exec_hook('message_part_after',
704    array('type' => $part->ctype_secondary, 'body' => $body, 'id' => $part->mime_id) + $data);
705
706  return $data['type'] == 'html' ? $data['body'] : html::tag('pre', array(), $data['body']);
707}
708
709
710/**
711 * Handle links and citation marks in plain text message
712 *
713 * @param string  Plain text string
714 * @param boolean Text uses format=flowed
715 *
716 * @return string Formatted HTML string
717 */
718function rcmail_plain_body($body, $flowed=false)
719{
720  global $RCMAIL;
721
722  // make links and email-addresses clickable
723  $replacer = new rcube_string_replacer;
724
725  // search for patterns like links and e-mail addresses
726  $body = preg_replace_callback($replacer->link_pattern, array($replacer, 'link_callback'), $body);
727  $body = preg_replace_callback($replacer->mailto_pattern, array($replacer, 'mailto_callback'), $body);
728
729  // split body into single lines
730  $body = preg_split('/\r?\n/', $body);
731  $quote_level = 0;
732  $last = -1;
733
734  // find/mark quoted lines...
735  for ($n=0, $cnt=count($body); $n < $cnt; $n++) {
736    if ($body[$n][0] == '>' && preg_match('/^(>+\s*)+/', $body[$n], $regs)) {
737      $q = strlen(preg_replace('/\s/', '', $regs[0]));
738      $body[$n] = substr($body[$n], strlen($regs[0]));
739
740      if ($q > $quote_level) {
741        $body[$n] = $replacer->get_replacement($replacer->add(
742          str_repeat('<blockquote>', $q - $quote_level))) . $body[$n];
743      }
744      else if ($q < $quote_level) {
745        $body[$n] = $replacer->get_replacement($replacer->add(
746          str_repeat('</blockquote>', $quote_level - $q))) . $body[$n];
747      }
748      else if ($flowed) {
749        // previous line is flowed
750        if (isset($body[$last]) && $body[$n]
751          && $body[$last][strlen($body[$last])-1] == ' ') {
752          // merge lines
753          $body[$last] .= $body[$n];
754          unset($body[$n]);
755        }
756        else {
757          $last = $n;
758        }
759      }
760    }
761    else {
762      $q = 0;
763      if ($flowed) {
764        // sig separator - line is fixed
765        if ($body[$n] == '-- ') {
766          $last = $last_sig = $n;
767        }
768        else {
769          // remove space-stuffing
770          if ($body[$n][0] == ' ')
771            $body[$n] = substr($body[$n], 1);
772
773          // previous line is flowed?
774          if (isset($body[$last]) && $body[$n]
775            && $last !== $last_sig
776            && $body[$last][strlen($body[$last])-1] == ' '
777          ) {
778            $body[$last] .= $body[$n];
779            unset($body[$n]);
780          }
781          else {
782            $last = $n;
783          }
784        }
785        if ($quote_level > 0)
786          $body[$last] = $replacer->get_replacement($replacer->add(
787            str_repeat('</blockquote>', $quote_level))) . $body[$last];
788      }
789      else if ($quote_level > 0)
790        $body[$n] = $replacer->get_replacement($replacer->add(
791          str_repeat('</blockquote>', $quote_level))) . $body[$n];
792    }
793
794    $quote_level = $q;
795  }
796
797  $body = join("\n", $body);
798
799  // quote plain text (don't use Q() here, to display entities "as is")
800  $table = get_html_translation_table(HTML_SPECIALCHARS);
801  unset($table['?']);
802  $body = strtr($body, $table);
803
804  // colorize signature (up to <sig_max_lines> lines)
805  $len = strlen($body);
806  $sig_max_lines = $RCMAIL->config->get('sig_max_lines', 15);
807  while (($sp = strrpos($body, "-- \n", $sp ? -$len+$sp-1 : 0)) !== false) {
808    if ($sp == 0 || $body[$sp-1] == "\n") {
809      // do not touch blocks with more that X lines
810      if (substr_count($body, "\n", $sp) < $sig_max_lines)
811        $body = substr($body, 0, max(0, $sp))
812          .'<span class="sig">'.substr($body, $sp).'</span>';
813      break;
814    }
815  }
816
817  // insert url/mailto links and citation tags
818  $body = $replacer->resolve($body);
819
820  return $body;
821}
822
823
824/**
825 * Callback function for washtml cleaning class
826 */
827function rcmail_washtml_callback($tagname, $attrib, $content, $washtml)
828{
829  switch ($tagname) {
830    case 'form':
831      $out = html::div('form', $content);
832      break;
833
834    case 'style':
835      // decode all escaped entities and reduce to ascii strings
836      $stripped = preg_replace('/[^a-zA-Z\(:;]/', '', rcmail_xss_entity_decode($content));
837
838      // now check for evil strings like expression, behavior or url()
839      if (!preg_match('/expression|behavior|javascript:|import[^a]/i', $stripped)) {
840        if (!$washtml->get_config('allow_remote') && stripos($stripped, 'url('))
841          $washtml->extlinks = true;
842        else
843          $out = html::tag('style', array('type' => 'text/css'), $content);
844        break;
845      }
846
847    default:
848      $out = '';
849  }
850
851  return $out;
852}
853
854
855/**
856 * Callback function for HTML tags fixing
857 */
858function rcmail_html_tag_callback($matches)
859{
860  $tagname = $matches[2];
861
862  $tagname = preg_replace(array(
863    '/:.*$/',                   // Microsoft's Smart Tags <st1:xxxx>
864    '/[^a-z0-9_\[\]\!-]/i',     // forbidden characters
865    ), '', $tagname);
866
867  return $matches[1].$tagname;
868}
869
870
871/**
872 * return table with message headers
873 */
874function rcmail_message_headers($attrib, $headers=NULL)
875  {
876  global $OUTPUT, $MESSAGE, $PRINT_MODE, $RCMAIL;
877  static $sa_attrib;
878
879  // keep header table attrib
880  if (is_array($attrib) && !$sa_attrib)
881    $sa_attrib = $attrib;
882  else if (!is_array($attrib) && is_array($sa_attrib))
883    $attrib = $sa_attrib;
884
885  if (!isset($MESSAGE))
886    return FALSE;
887
888  // get associative array of headers object
889  if (!$headers)
890    $headers = is_object($MESSAGE->headers) ? get_object_vars($MESSAGE->headers) : $MESSAGE->headers;
891
892  // show these headers
893  $standard_headers = array('subject', 'from', 'to', 'cc', 'bcc', 'replyto',
894    'mail-reply-to', 'mail-followup-to', 'date');
895  $exclude_headers = $attrib['exclude'] ? explode(',', $attrib['exclude']) : array();
896  $output_headers = array();
897
898  foreach ($standard_headers as $hkey) {
899    if ($headers[$hkey])
900      $value = $headers[$hkey];
901    else if ($headers['others'][$hkey])
902      $value = $headers['others'][$hkey];
903    else
904      continue;
905
906    if (in_array($hkey, $exclude_headers))
907      continue;
908
909    if ($hkey == 'date') {
910      if ($PRINT_MODE)
911        $header_value = format_date($value, $RCMAIL->config->get('date_long', 'x'));
912      else
913        $header_value = format_date($value);
914    }
915    else if ($hkey == 'replyto') {
916      if ($headers['replyto'] != $headers['from'])
917        $header_value = rcmail_address_string($value, null, true, $attrib['addicon']);
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']);
926      else
927        continue;
928    }
929    else if ($hkey == 'mail-followup-to') {
930      $header_value = rcmail_address_string($value, null, true, $attrib['addicon']);
931    }
932    else if (in_array($hkey, array('from', 'to', 'cc', 'bcc')))
933      $header_value = rcmail_address_string($value, null, true, $attrib['addicon']);
934    else if ($hkey == 'subject' && empty($value))
935      $header_value = rcube_label('nosubject');
936    else
937      $header_value = trim($RCMAIL->imap->decode_header($value));
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/**
965 * return block to show full message headers
966 */
967function rcmail_message_full_headers($attrib, $headers=NULL)
968{
969  global $OUTPUT;
970
971  $html = html::div(array('class' => "more-headers show-headers", 'onclick' => "return ".JS_OBJECT_NAME.".command('load-headers','',this)"), '');
972  $html .= html::div(array('id' => "all-headers", 'class' => "all", 'style' => 'display:none'), html::div(array('id' => 'headers-source'), ''));
973
974  $OUTPUT->add_gui_object('all_headers_row', 'all-headers');
975  $OUTPUT->add_gui_object('all_headers_box', 'headers-source');
976
977  return html::div($attrib, $html);
978}
979
980
981/**
982 * Handler for the 'messagebody' GUI object
983 *
984 * @param array Named parameters
985 * @return string HTML content showing the message body
986 */
987function rcmail_message_body($attrib)
988{
989  global $CONFIG, $OUTPUT, $MESSAGE, $RCMAIL, $REMOTE_OBJECTS;
990
991  if (!is_array($MESSAGE->parts) && empty($MESSAGE->body))
992    return '';
993
994  if (!$attrib['id'])
995    $attrib['id'] = 'rcmailMsgBody';
996
997  $safe_mode = $MESSAGE->is_safe || intval($_GET['_safe']);
998  $out = '';
999
1000  $header_attrib = array();
1001  foreach ($attrib as $attr => $value)
1002    if (preg_match('/^headertable([a-z]+)$/i', $attr, $regs))
1003      $header_attrib[$regs[1]] = $value;
1004
1005  if (!empty($MESSAGE->parts)) {
1006    foreach ($MESSAGE->parts as $i => $part) {
1007      if ($part->type == 'headers')
1008        $out .= rcmail_message_headers(sizeof($header_attrib) ? $header_attrib : NULL, $part->headers);
1009      else if ($part->type == 'content' && $part->size) {
1010        // Check if we have enough memory to handle the message in it
1011        // #1487424: we need up to 10x more memory than the body
1012        if (!rcmail_mem_check($part->size * 10)) {
1013          $out .= html::span('part-notice', rcube_label('messagetoobig'). ' '
1014            . html::a('?_task=mail&_action=get&_download=1&_uid='.$MESSAGE->uid.'&_part='.$part->mime_id
1015              .'&_mbox='. urlencode($RCMAIL->imap->get_mailbox_name()), rcube_label('download')));
1016          continue;
1017        }
1018
1019        if (empty($part->ctype_parameters) || empty($part->ctype_parameters['charset']))
1020          $part->ctype_parameters['charset'] = $MESSAGE->headers->charset;
1021
1022        // fetch part if not available
1023        if (!isset($part->body))
1024          $part->body = $MESSAGE->get_part_content($part->mime_id);
1025
1026        // message is cached but not exists (#1485443), or other error
1027        if ($part->body === false) {
1028          rcmail_message_error($MESSAGE->uid);
1029        }
1030
1031        $plugin = $RCMAIL->plugins->exec_hook('message_body_prefix', array(
1032          'part' => $part, 'prefix' => ''));
1033
1034        $body = rcmail_print_body($part, array('safe' => $safe_mode, 'plain' => !$CONFIG['prefer_html']));
1035
1036        if ($part->ctype_secondary == 'html') {
1037          $body = rcmail_html4inline($body, $attrib['id'], 'rcmBody', $attrs, $safe_mode);
1038          $div_attr = array('class' => 'message-htmlpart');
1039          $style = array();
1040
1041          if (!empty($attrs)) {
1042            foreach ($attrs as $a_idx => $a_val)
1043              $style[] = $a_idx . ': ' . $a_val;
1044            if (!empty($style))
1045              $div_attr['style'] = implode('; ', $style);
1046          }
1047
1048          $out .= html::div($div_attr, $plugin['prefix'] . $body);
1049        }
1050        else
1051          $out .= html::div('message-part', $plugin['prefix'] . $body);
1052      }
1053    }
1054  }
1055  else {
1056    // Check if we have enough memory to handle the message in it
1057    // #1487424: we need up to 10x more memory than the body
1058    if (!rcmail_mem_check(strlen($MESSAGE->body) * 10)) {
1059      $out .= html::span('part-notice', rcube_label('messagetoobig'). ' '
1060        . html::a('?_task=mail&_action=get&_download=1&_uid='.$MESSAGE->uid.'&_part=0'
1061          .'&_mbox='. urlencode($RCMAIL->imap->get_mailbox_name()), rcube_label('download')));
1062    }
1063    else {
1064      $plugin = $RCMAIL->plugins->exec_hook('message_body_prefix', array(
1065        'part' => $MESSAGE, 'prefix' => ''));
1066
1067      $out .= html::div('message-part', $plugin['prefix'] . html::tag('pre', array(),
1068        rcmail_plain_body(Q($MESSAGE->body, 'strict', false))));
1069    }
1070  }
1071
1072  // list images after mail body
1073  if ($CONFIG['inline_images'] && !empty($MESSAGE->attachments)) {
1074    foreach ($MESSAGE->attachments as $attach_prop) {
1075      // skip inline images
1076      if ($attach_prop->content_id && $attach_prop->disposition == 'inline') {
1077        continue;
1078      }
1079
1080      // Content-Type: image/*...
1081      if (preg_match('/^image\//i', $attach_prop->mimetype) ||
1082        // ...or known file extension: many clients are using application/octet-stream
1083        ($attach_prop->filename &&
1084          preg_match('/^application\/octet-stream$/i', $attach_prop->mimetype) &&
1085          preg_match('/\.(jpg|jpeg|png|gif|bmp)$/i', $attach_prop->filename))
1086      ) {
1087        $out .= html::tag('hr') . html::p(array('align' => "center"),
1088          html::img(array(
1089            'src' => $MESSAGE->get_part_url($attach_prop->mime_id, true),
1090            'title' => $attach_prop->filename,
1091            'alt' => $attach_prop->filename,
1092          )));
1093      }
1094    }
1095  }
1096
1097  // tell client that there are blocked remote objects
1098  if ($REMOTE_OBJECTS && !$safe_mode)
1099    $OUTPUT->set_env('blockedobjects', true);
1100
1101  return html::div($attrib, $out);
1102}
1103
1104
1105/**
1106 * Convert all relative URLs according to a <base> in HTML
1107 */
1108function rcmail_resolve_base($body)
1109{
1110  // check for <base href=...>
1111  if (preg_match('!(<base.*href=["\']?)([hftps]{3,5}://[a-z0-9/.%-]+)!i', $body, $regs)) {
1112    $replacer = new rcube_base_replacer($regs[2]);
1113
1114    // replace all relative paths
1115    $body = preg_replace_callback('/(src|background|href)=(["\']?)([^"\'\s]+)(\2|\s|>)/Ui', array($replacer, 'callback'), $body);
1116    $body = preg_replace_callback('/(url\s*\()(["\']?)([^"\'\)\s]+)(\2)\)/Ui', array($replacer, 'callback'), $body);
1117  }
1118
1119  return $body;
1120}
1121
1122/**
1123 * modify a HTML message that it can be displayed inside a HTML page
1124 */
1125function rcmail_html4inline($body, $container_id, $body_id='', &$attributes=null, $allow_remote=false)
1126{
1127  $last_style_pos = 0;
1128  $cont_id = $container_id.($body_id ? ' div.'.$body_id : '');
1129
1130  // find STYLE tags
1131  while (($pos = stripos($body, '<style', $last_style_pos)) && ($pos2 = stripos($body, '</style>', $pos)))
1132  {
1133    $pos = strpos($body, '>', $pos)+1;
1134
1135    // replace all css definitions with #container [def]
1136    $styles = rcmail_mod_css_styles(
1137      substr($body, $pos, $pos2-$pos), $cont_id, $allow_remote);
1138
1139    $body = substr_replace($body, $styles, $pos, $pos2-$pos);
1140    $last_style_pos = $pos2;
1141  }
1142
1143  // modify HTML links to open a new window if clicked
1144  $GLOBALS['rcmail_html_container_id'] = $container_id;
1145  $body = preg_replace_callback('/<(a|link)\s+([^>]+)>/Ui', 'rcmail_alter_html_link', $body);
1146  unset($GLOBALS['rcmail_html_container_id']);
1147
1148  $body = preg_replace(array(
1149      // add comments arround html and other tags
1150      '/(<!DOCTYPE[^>]*>)/i',
1151      '/(<\?xml[^>]*>)/i',
1152      '/(<\/?html[^>]*>)/i',
1153      '/(<\/?head[^>]*>)/i',
1154      '/(<title[^>]*>.*<\/title>)/Ui',
1155      '/(<\/?meta[^>]*>)/i',
1156      // quote <? of php and xml files that are specified as text/html
1157      '/<\?/',
1158      '/\?>/',
1159      // replace <body> with <div>
1160      '/<body([^>]*)>/i',
1161      '/<\/body>/i',
1162      ),
1163    array(
1164      '<!--\\1-->',
1165      '<!--\\1-->',
1166      '<!--\\1-->',
1167      '<!--\\1-->',
1168      '<!--\\1-->',
1169      '<!--\\1-->',
1170      '&lt;?',
1171      '?&gt;',
1172      '<div class="'.$body_id.'"\\1>',
1173      '</div>',
1174      ),
1175    $body);
1176
1177  $attributes = array();
1178
1179  // Handle body attributes that doesn't play nicely with div elements
1180  $regexp = '/<div class="' . preg_quote($body_id, '/') . '"([^>]*)/';
1181  if (preg_match($regexp, $body, $m)) {
1182    $attrs = $m[0];
1183    // Get bgcolor, we'll set it as background-color of the message container
1184    if ($m[1] && preg_match('/bgcolor=["\']*([a-z0-9#]+)["\']*/', $attrs, $mb)) {
1185      $attributes['background-color'] = $mb[1];
1186      $attrs = preg_replace('/bgcolor=["\']*([a-z0-9#]+)["\']*/', '', $attrs);
1187    }
1188    // Get background, we'll set it as background-image of the message container
1189    if ($m[1] && preg_match('/background=["\']*([^"\'>\s]+)["\']*/', $attrs, $mb)) {
1190      $attributes['background-image'] = 'url('.$mb[1].')';
1191      $attrs = preg_replace('/background=["\']*([^"\'>\s]+)["\']*/', '', $attrs);
1192    }
1193    if (!empty($attributes)) {
1194      $body = preg_replace($regexp, rtrim($attrs), $body, 1);
1195    }
1196
1197    // handle body styles related to background image
1198    if ($attributes['background-image']) {
1199      // get body style
1200      if (preg_match('/#'.preg_quote($cont_id, '/').'\s+\{([^}]+)}/i', $body, $m)) {
1201        // get background related style
1202        if (preg_match_all('/(background-position|background-repeat)\s*:\s*([^;]+);/i', $m[1], $ma, PREG_SET_ORDER)) {
1203          foreach ($ma as $style)
1204            $attributes[$style[1]] = $style[2];
1205        }
1206      }
1207    }
1208  }
1209  // make sure there's 'rcmBody' div, we need it for proper css modification
1210  // its name is hardcoded in rcmail_message_body() also
1211  else {
1212    $body = '<div class="' . $body_id . '">' . $body . '</div>';
1213  }
1214
1215  return $body;
1216}
1217
1218
1219/**
1220 * parse link attributes and set correct target
1221 */
1222function rcmail_alter_html_link($matches)
1223{
1224  global $RCMAIL;
1225
1226  // Support unicode/punycode in top-level domain part
1227  $EMAIL_PATTERN = '([a-z0-9][a-z0-9\-\.\+\_]*@[^&@"\'.][^@&"\']*\\.([^\\x00-\\x40\\x5b-\\x60\\x7b-\\x7f]{2,}|xn--[a-z0-9]{2,}))';
1228
1229  $tag = $matches[1];
1230  $attrib = parse_attrib_string($matches[2]);
1231  $end = '>';
1232
1233  // Remove non-printable characters in URL (#1487805)
1234  if ($attrib['href'])
1235    $attrib['href'] = preg_replace('/[\x00-\x1F]/', '', $attrib['href']);
1236
1237  if ($tag == 'link' && preg_match('/^https?:\/\//i', $attrib['href'])) {
1238    $tempurl = 'tmp-' . md5($attrib['href']) . '.css';
1239    $_SESSION['modcssurls'][$tempurl] = $attrib['href'];
1240    $attrib['href'] = $RCMAIL->url(array('task' => 'utils', 'action' => 'modcss', 'u' => $tempurl, 'c' => $GLOBALS['rcmail_html_container_id']));
1241    $end = ' />';
1242  }
1243  else if (preg_match('/^mailto:'.$EMAIL_PATTERN.'(\?[^"\'>]+)?/i', $attrib['href'], $mailto)) {
1244    $attrib['href'] = $mailto[0];
1245    $attrib['onclick'] = sprintf(
1246      "return %s.command('compose','%s',this)",
1247      JS_OBJECT_NAME,
1248      JQ($mailto[1].$mailto[3]));
1249  }
1250  else if (empty($attrib['href']) && !$attrib['name']) {
1251    $attrib['href'] = './#NOP';
1252    $attrib['onclick'] = 'return false';
1253  }
1254  else if (!empty($attrib['href']) && $attrib['href'][0] != '#') {
1255    $attrib['target'] = '_blank';
1256  }
1257
1258  return "<$tag" . html::attrib_string($attrib, array('href','name','target','onclick','id','class','style','title','rel','type','media')) . $end;
1259}
1260
1261
1262/**
1263 * decode address string and re-format it as HTML links
1264 */
1265function rcmail_address_string($input, $max=null, $linked=false, $addicon=null)
1266{
1267  global $RCMAIL, $PRINT_MODE, $CONFIG;
1268
1269  $a_parts = $RCMAIL->imap->decode_address_list($input);
1270
1271  if (!sizeof($a_parts))
1272    return $input;
1273
1274  $c = count($a_parts);
1275  $j = 0;
1276  $out = '';
1277
1278  if ($addicon && !isset($_SESSION['writeable_abook'])) {
1279    $_SESSION['writeable_abook'] = $RCMAIL->get_address_sources(true) ? true : false;
1280  }
1281
1282  foreach ($a_parts as $part) {
1283    $j++;
1284
1285    $name   = $part['name'];
1286    $mailto = $part['mailto'];
1287    $string = $part['string'];
1288
1289    // IDNA ASCII to Unicode
1290    if ($name == $mailto)
1291      $name = rcube_idn_to_utf8($name);
1292    if ($string == $mailto)
1293      $string = rcube_idn_to_utf8($string);
1294    $mailto = rcube_idn_to_utf8($mailto);
1295
1296    if ($PRINT_MODE) {
1297      $out .= sprintf('%s &lt;%s&gt;', Q($name), $mailto);
1298    }
1299    else if (check_email($part['mailto'], false)) {
1300      if ($linked) {
1301        $address = html::a(array(
1302            'href' => 'mailto:'.$mailto,
1303            'onclick' => sprintf("return %s.command('compose','%s',this)", JS_OBJECT_NAME, JQ($mailto)),
1304            'title' => $mailto,
1305            'class' => "rcmContactAddress",
1306          ),
1307        Q($name ? $name : $mailto));
1308      }
1309      else {
1310        $address = html::span(array('title' => $mailto, 'class' => "rcmContactAddress"),
1311          Q($name ? $name : $mailto));
1312      }
1313
1314      if ($addicon && $_SESSION['writeable_abook']) {
1315        $address = html::span(null, $address . html::a(array(
1316            'href' => "#add",
1317            'onclick' => sprintf("return %s.command('add-contact','%s',this)", JS_OBJECT_NAME, urlencode($string)),
1318            'title' => rcube_label('addtoaddressbook'),
1319            'class' => 'rcmaddcontact',
1320          ),
1321          html::img(array(
1322            'src' => $CONFIG['skin_path'] . $addicon,
1323            'alt' => "Add contact",
1324          ))));
1325      }
1326      $out .= $address;
1327    }
1328    else {
1329      if ($name)
1330        $out .= Q($name);
1331      if ($mailto)
1332        $out .= (strlen($out) ? ' ' : '') . sprintf('&lt;%s&gt;', Q($mailto));
1333    }
1334
1335    if ($c>$j)
1336      $out .= ','.($max ? '&nbsp;' : ' ');
1337
1338    if ($max && $j==$max && $c>$j) {
1339      $out .= '...';
1340      break;
1341    }
1342  }
1343
1344  return $out;
1345}
1346
1347
1348/**
1349 * Wrap text to a given number of characters per line
1350 * but respect the mail quotation of replies messages (>).
1351 * Finally add another quotation level by prpending the lines
1352 * with >
1353 *
1354 * @param string Text to wrap
1355 * @param int The line width
1356 * @return string The wrapped text
1357 */
1358function rcmail_wrap_and_quote($text, $length = 72)
1359{
1360  // Rebuild the message body with a maximum of $max chars, while keeping quoted message.
1361  $max = min(77, $length + 8);
1362  $lines = preg_split('/\r?\n/', trim($text));
1363  $out = '';
1364
1365  foreach ($lines as $line) {
1366    // don't wrap already quoted lines
1367    if ($line[0] == '>')
1368      $line = '>' . rtrim($line);
1369    else if (mb_strlen($line) > $max) {
1370      $newline = '';
1371      foreach(explode("\n", rc_wordwrap($line, $length - 2)) as $l) {
1372        if (strlen($l))
1373          $newline .= '> ' . $l . "\n";
1374        else
1375          $newline .= ">\n";
1376      }
1377      $line = rtrim($newline);
1378    }
1379    else
1380      $line = '> ' . $line;
1381
1382    // Append the line
1383    $out .= $line . "\n";
1384  }
1385
1386  return $out;
1387}
1388
1389
1390function rcmail_draftinfo_encode($p)
1391{
1392  $parts = array();
1393  foreach ($p as $key => $val)
1394    $parts[] = $key . '=' . ($key == 'folder' ? base64_encode($val) : $val);
1395
1396  return join('; ', $parts);
1397}
1398
1399
1400function rcmail_draftinfo_decode($str)
1401{
1402  $info = array();
1403  foreach (preg_split('/;\s+/', $str) as $part) {
1404    list($key, $val) = explode('=', $part, 2);
1405    if ($key == 'folder')
1406      $val = base64_decode($val);
1407    $info[$key] = $val;
1408  }
1409
1410  return $info;
1411}
1412
1413
1414function rcmail_message_part_controls($attrib)
1415{
1416  global $MESSAGE;
1417
1418  $part = asciiwords(get_input_value('_part', RCUBE_INPUT_GPC));
1419  if (!is_object($MESSAGE) || !is_array($MESSAGE->parts) || !($_GET['_uid'] && $_GET['_part']) || !$MESSAGE->mime_parts[$part])
1420    return '';
1421
1422  $part = $MESSAGE->mime_parts[$part];
1423  $table = new html_table(array('cols' => 3));
1424
1425  if (!empty($part->filename)) {
1426    $table->add('title', Q(rcube_label('filename')));
1427    $table->add('header', Q($part->filename));
1428    $table->add('download-link', html::a(array('href' => './?'.str_replace('_frame=', '_download=', $_SERVER['QUERY_STRING'])), Q(rcube_label('download'))));
1429  }
1430
1431  if (!empty($part->size)) {
1432    $table->add('title', Q(rcube_label('filesize')));
1433    $table->add('header', Q(show_bytes($part->size)));
1434  }
1435
1436  return $table->show($attrib);
1437}
1438
1439
1440
1441function rcmail_message_part_frame($attrib)
1442{
1443  global $MESSAGE;
1444
1445  $part = $MESSAGE->mime_parts[asciiwords(get_input_value('_part', RCUBE_INPUT_GPC))];
1446  $ctype_primary = strtolower($part->ctype_primary);
1447
1448  $attrib['src'] = './?' . str_replace('_frame=', ($ctype_primary=='text' ? '_show=' : '_preload='), $_SERVER['QUERY_STRING']);
1449
1450  return html::iframe($attrib);
1451}
1452
1453
1454/**
1455 * clear message composing settings
1456 */
1457function rcmail_compose_cleanup($id)
1458{
1459  if (!isset($_SESSION['compose_data_'.$id]))
1460    return;
1461
1462  $rcmail = rcmail::get_instance();
1463  $rcmail->plugins->exec_hook('attachments_cleanup', array('group' => $id));
1464  $rcmail->session->remove('compose_data_'.$id);
1465}
1466
1467
1468/**
1469 * Send the MDN response
1470 *
1471 * @param mixed $message    Original message object (rcube_message) or UID
1472 * @param array $smtp_error SMTP error array (reference)
1473 *
1474 * @return boolean Send status
1475 */
1476function rcmail_send_mdn($message, &$smtp_error)
1477{
1478  global $RCMAIL;
1479
1480  if (!is_object($message) || !is_a($message, 'rcube_message'))
1481    $message = new rcube_message($message);
1482
1483  if ($message->headers->mdn_to && empty($message->headers->flags['MDNSENT']) &&
1484    ($RCMAIL->imap->check_permflag('MDNSENT') || $RCMAIL->imap->check_permflag('*')))
1485  {
1486    $identity = $RCMAIL->user->get_identity();
1487    $sender = format_email_recipient($identity['email'], $identity['name']);
1488    $recipient = array_shift($RCMAIL->imap->decode_address_list($message->headers->mdn_to));
1489    $mailto = $recipient['mailto'];
1490
1491    $compose = new Mail_mime("\r\n");
1492
1493    $compose->setParam('text_encoding', 'quoted-printable');
1494    $compose->setParam('html_encoding', 'quoted-printable');
1495    $compose->setParam('head_encoding', 'quoted-printable');
1496    $compose->setParam('head_charset', RCMAIL_CHARSET);
1497    $compose->setParam('html_charset', RCMAIL_CHARSET);
1498    $compose->setParam('text_charset', RCMAIL_CHARSET);
1499
1500    // compose headers array
1501    $headers = array(
1502      'Date' => rcmail_user_date(),
1503      'From' => $sender,
1504      'To'   => $message->headers->mdn_to,
1505      'Subject' => rcube_label('receiptread') . ': ' . $message->subject,
1506      'Message-ID' => rcmail_gen_message_id(),
1507      'X-Sender' => $identity['email'],
1508      'References' => trim($message->headers->references . ' ' . $message->headers->messageID),
1509    );
1510
1511    if ($agent = $RCMAIL->config->get('useragent'))
1512      $headers['User-Agent'] = $agent;
1513
1514    $body = rcube_label("yourmessage") . "\r\n\r\n" .
1515      "\t" . rcube_label("to") . ': ' . rcube_imap::decode_mime_string($message->headers->to, $message->headers->charset) . "\r\n" .
1516      "\t" . rcube_label("subject") . ': ' . $message->subject . "\r\n" .
1517      "\t" . rcube_label("sent") . ': ' . format_date($message->headers->date, $RCMAIL->config->get('date_long')) . "\r\n" .
1518      "\r\n" . rcube_label("receiptnote") . "\r\n";
1519
1520    $ua = $RCMAIL->config->get('useragent', "Roundcube Webmail (Version ".RCMAIL_VERSION.")");
1521    $report = "Reporting-UA: $ua\r\n";
1522
1523    if ($message->headers->to)
1524        $report .= "Original-Recipient: {$message->headers->to}\r\n";
1525
1526    $report .= "Final-Recipient: rfc822; {$identity['email']}\r\n" .
1527               "Original-Message-ID: {$message->headers->messageID}\r\n" .
1528               "Disposition: manual-action/MDN-sent-manually; displayed\r\n";
1529
1530    $compose->headers($headers);
1531    $compose->setContentType('multipart/report', array('report-type'=> 'disposition-notification'));
1532    $compose->setTXTBody(rc_wordwrap($body, 75, "\r\n"));
1533    $compose->addAttachment($report, 'message/disposition-notification', 'MDNPart2.txt', false, '7bit', 'inline');
1534
1535    $sent = rcmail_deliver_message($compose, $identity['email'], $mailto, $smtp_error, $body_file);
1536
1537    if ($sent)
1538    {
1539      $RCMAIL->imap->set_flag($message->uid, 'MDNSENT');
1540      return true;
1541    }
1542  }
1543
1544  return false;
1545}
1546
1547
1548// Fixes some content-type names
1549function rcmail_fix_mimetype($name)
1550{
1551  // Some versions of Outlook create garbage Content-Type:
1552  // application/pdf.A520491B_3BF7_494D_8855_7FAC2C6C0608
1553  if (preg_match('/^application\/pdf.+/', $name))
1554    $name = 'application/pdf';
1555
1556  return $name;
1557}
1558
1559function rcmail_search_filter($attrib)
1560{
1561  global $OUTPUT, $CONFIG;
1562
1563  if (!strlen($attrib['id']))
1564    $attrib['id'] = 'rcmlistfilter';
1565
1566  $attrib['onchange'] = JS_OBJECT_NAME.'.filter_mailbox(this.value)';
1567
1568  /*
1569    RFC3501 (6.4.4): 'ALL', 'RECENT',
1570    'ANSWERED', 'DELETED', 'FLAGGED', 'SEEN',
1571    'UNANSWERED', 'UNDELETED', 'UNFLAGGED', 'UNSEEN',
1572    'NEW', // = (RECENT UNSEEN)
1573    'OLD' // = NOT RECENT
1574  */
1575
1576  $select_filter = new html_select($attrib);
1577  $select_filter->add(rcube_label('all'), 'ALL');
1578  $select_filter->add(rcube_label('unread'), 'UNSEEN');
1579  $select_filter->add(rcube_label('flagged'), 'FLAGGED');
1580  $select_filter->add(rcube_label('unanswered'), 'UNANSWERED');
1581  if (!$CONFIG['skip_deleted'])
1582    $select_filter->add(rcube_label('deleted'), 'DELETED');
1583  $select_filter->add(rcube_label('priority').': '.rcube_label('highest'), 'HEADER X-PRIORITY 1');
1584  $select_filter->add(rcube_label('priority').': '.rcube_label('high'), 'HEADER X-PRIORITY 2');
1585  $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');
1586  $select_filter->add(rcube_label('priority').': '.rcube_label('low'), 'HEADER X-PRIORITY 4');
1587  $select_filter->add(rcube_label('priority').': '.rcube_label('lowest'), 'HEADER X-PRIORITY 5');
1588
1589  $out = $select_filter->show($_SESSION['search_filter']);
1590
1591  $OUTPUT->add_gui_object('search_filter', $attrib['id']);
1592
1593  return $out;
1594}
1595
1596function rcmail_message_error($uid=null)
1597{
1598  global $RCMAIL;
1599
1600  // Set env variables for messageerror.html template
1601  if ($RCMAIL->action == 'show') {
1602    $mbox_name = $RCMAIL->imap->get_mailbox_name();
1603    $RCMAIL->output->set_env('mailbox', $mbox_name);
1604    $RCMAIL->output->set_env('uid', null);
1605  }
1606  // display error message
1607  $RCMAIL->output->show_message('messageopenerror', 'error');
1608  // ... display message error page
1609  $RCMAIL->output->send('messageerror');
1610}
1611
1612// register UI objects
1613$OUTPUT->add_handlers(array(
1614  'mailboxlist' => 'rcmail_mailbox_list',
1615  'messages' => 'rcmail_message_list',
1616  'messagecountdisplay' => 'rcmail_messagecount_display',
1617  'quotadisplay' => 'rcmail_quota_display',
1618  'mailboxname' => 'rcmail_mailbox_name_display',
1619  'messageheaders' => 'rcmail_message_headers',
1620  'messagefullheaders' => 'rcmail_message_full_headers',
1621  'messagebody' => 'rcmail_message_body',
1622  'messagecontentframe' => 'rcmail_messagecontent_frame',
1623  'messagepartframe' => 'rcmail_message_part_frame',
1624  'messagepartcontrols' => 'rcmail_message_part_controls',
1625  'searchfilter' => 'rcmail_search_filter',
1626  'searchform' => array($OUTPUT, 'search_form'),
1627));
1628
1629// register action aliases
1630$RCMAIL->register_action_map(array(
1631    'preview' => 'show.inc',
1632    'print'   => 'show.inc',
1633    'moveto'  => 'move_del.inc',
1634    'delete'  => 'move_del.inc',
1635    'send'    => 'sendmail.inc',
1636    'expunge' => 'folders.inc',
1637    'purge'   => 'folders.inc',
1638    'remove-attachment'  => 'attachments.inc',
1639    'display-attachment' => 'attachments.inc',
1640    'upload'             => 'attachments.inc',
1641    'group-expand'       => 'autocomplete.inc',
1642));
Note: See TracBrowser for help on using the repository browser.