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

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