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

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