source: github/program/steps/mail/func.inc @ e2f30659

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