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

Last change on this file since 5781 was 5781, checked in by thomasb, 16 months ago

Merged devel-framework branch (r5746:5779) back into trunk

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