source: subversion/branches/devel-mcache/roundcubemail/program/steps/mail/func.inc @ 5219

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