source: github/program/steps/mail/func.inc @ 6b49292

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since 6b49292 was 6b49292, checked in by alecpl <alec@…>, 3 years ago
  • Add message content-type to the message flags in add_message_row(), can be used e.g. to set message row style/icon according to message type
  • Property mode set to 100644
File size: 56.1 KB
Line 
1<?php
2
3/*
4 +-----------------------------------------------------------------------+
5 | program/steps/mail/func.inc                                           |
6 |                                                                       |
7 | This file is part of the Roundcube Webmail client                     |
8 | Copyright (C) 2005-2010, 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'][$_REQUEST['_search']]))
76  {
77  $IMAP->set_search_set($_SESSION['search'][$_REQUEST['_search']]);
78  $OUTPUT->set_env('search_request', $_REQUEST['_search']);
79  $OUTPUT->set_env('search_text', $_SESSION['last_text_search']);
80  }
81
82// set main env variables, labels and page title
83if (empty($RCMAIL->action) || $RCMAIL->action == 'list')
84  {
85  $mbox_name = $IMAP->get_mailbox_name();
86
87  if (empty($RCMAIL->action))
88    {
89    // initialize searching result if search_filter is used
90    if ($_SESSION['search_filter'] && $_SESSION['search_filter'] != 'ALL')
91      {
92      $search_request = md5($mbox_name.$_SESSION['search_filter']);
93
94      $IMAP->search($mbox_name, $_SESSION['search_filter'], RCMAIL_CHARSET, $_SESSION['sort_col']);
95      $_SESSION['search'][$search_request] = $IMAP->get_search_set();
96      $OUTPUT->set_env('search_request', $search_request);
97      }
98
99      $search_mods = $RCMAIL->config->get('search_mods', $SEARCH_MODS_DEFAULT);
100      $OUTPUT->set_env('search_mods', $search_mods);
101    }
102
103  // set current mailbox and some other vars in client environment
104  $OUTPUT->set_env('mailbox', $mbox_name);
105  $OUTPUT->set_env('pagesize', $IMAP->page_size);
106  $OUTPUT->set_env('quota', $IMAP->get_capability('quota'));
107  $OUTPUT->set_env('delimiter', $IMAP->get_hierarchy_delimiter());
108  $OUTPUT->set_env('threading', (bool) $IMAP->threading);
109  $OUTPUT->set_env('threads', $IMAP->threading
110        || $IMAP->get_capability('thread=references')
111        || $IMAP->get_capability('thread=orderedsubject')
112        || $IMAP->get_capability('thread=refs') 
113  );
114
115  if ($CONFIG['flag_for_deletion'])
116    $OUTPUT->set_env('flag_for_deletion', true);
117  if ($CONFIG['read_when_deleted'])
118    $OUTPUT->set_env('read_when_deleted', true);
119  if ($CONFIG['skip_deleted'])
120    $OUTPUT->set_env('skip_deleted', true);
121  if ($CONFIG['display_next'])
122    $OUTPUT->set_env('display_next', true);
123
124  $OUTPUT->set_env('preview_pane_mark_read', $RCMAIL->config->get('preview_pane_mark_read', 0));
125
126  if ($CONFIG['trash_mbox'])
127    $OUTPUT->set_env('trash_mailbox', $CONFIG['trash_mbox']);
128  if ($CONFIG['drafts_mbox'])
129    $OUTPUT->set_env('drafts_mailbox', $CONFIG['drafts_mbox']);
130  if ($CONFIG['junk_mbox'])
131    $OUTPUT->set_env('junk_mailbox', $CONFIG['junk_mbox']);
132
133  if (!$OUTPUT->ajax_call)
134    $OUTPUT->add_label('checkingmail', 'deletemessage', 'movemessagetotrash',
135      'movingmessage', 'copyingmessage', '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' columns, we don't need them here
260  if (($key = array_search('attachment', $a_show_cols)) !== FALSE)
261    unset($a_show_cols[$key]);
262  if (($key = array_search('flag', $a_show_cols)) !== FALSE)
263    unset($a_show_cols[$key]);
264  if (($key = array_search('threads', $a_show_cols)) !== FALSE)
265    unset($a_show_cols[$key]);
266  // loop through message headers
267
268  foreach ($a_headers as $n => $header)
269    {
270    if (empty($header))
271      continue;
272
273    $a_msg_cols = array();
274    $a_msg_flags = array();
275
276    $IMAP->set_charset(!empty($header->charset) ? $header->charset : $CONFIG['default_charset']);
277
278    // format each col; similar as in rcmail_message_list()
279    foreach ($a_show_cols as $col)
280      {
281      if (in_array($col, array('from', 'to', 'cc', 'replyto')))
282        $cont = Q(rcmail_address_string($header->$col, 3), 'show');
283      else if ($col=='subject')
284        {
285        $cont = abbreviate_string(trim($IMAP->decode_header($header->$col)), 160);
286        if (!$cont) $cont = rcube_label('nosubject');
287        $cont = Q($cont);
288        }
289      else if ($col=='size')
290        $cont = show_bytes($header->$col);
291      else if ($col=='date')
292        $cont = format_date($header->date);
293      else
294        $cont = Q($header->$col);
295
296      $a_msg_cols[$col] = $cont;
297      }
298
299    if ($header->depth)
300      $a_msg_flags['depth'] = $header->depth;
301    else if ($header->has_children)
302      $roots[] = $header->uid;
303    if ($header->parent_uid)
304      $a_msg_flags['parent_uid'] = $header->parent_uid;
305    if ($header->has_children)
306      $a_msg_flags['has_children'] = $header->has_children;
307    if ($header->unread_children)
308      $a_msg_flags['unread_children'] = $header->unread_children;
309    if ($header->deleted)
310      $a_msg_flags['deleted'] = 1;
311    if (!$header->seen)
312      $a_msg_flags['unread'] = 1;
313    if ($header->answered)
314      $a_msg_flags['replied'] = 1;
315    if ($header->forwarded)
316      $a_msg_flags['forwarded'] = 1;
317    if ($header->flagged)
318      $a_msg_flags['flagged'] = 1;
319    if ($header->others['list-post'])
320      $a_msg_flags['ml'] = 1;
321
322    $a_msg_flags['ctype'] = Q($header->ctype);
323    $a_msg_flags['mbox'] = $mbox;
324
325    // merge with plugin result
326    if (!empty($header->list_flags) && is_array($header->list_flags))
327      $a_msg_flags = array_merge($a_msg_flags, $header->list_flags);
328    if (!empty($header->list_cols) && is_array($header->list_cols))
329      $a_msg_cols = array_merge($a_msg_cols, $header->list_cols);
330
331    $OUTPUT->command('add_message_row',
332      $header->uid,
333      $a_msg_cols,
334      $a_msg_flags,
335      $insert_top);
336    }
337
338    if ($IMAP->threading) {
339      $OUTPUT->command('init_threads', (array) $roots);
340    }
341}
342
343
344/*
345 * Creates <THEAD> for message list table
346 */
347function rcmail_message_list_head($attrib, $a_show_cols)
348{
349  global $CONFIG;
350
351  $skin_path = $_SESSION['skin_path'];
352  $image_tag = html::img(array('src' => "%s%s", 'alt' => "%s"));
353
354  // check to see if we have some settings for sorting
355  $sort_col   = $_SESSION['sort_col'];
356  $sort_order = $_SESSION['sort_order'];
357
358  // define sortable columns
359  $a_sort_cols = array('subject', 'date', 'from', 'to', 'size', 'cc');
360
361  if (!empty($attrib['optionsmenuicon'])) {
362    $onclick = 'return ' . JS_OBJECT_NAME . ".command('menu-open', 'messagelistmenu')";
363    if ($attrib['optionsmenuicon'] === true || $attrib['optionsmenuicon'] == 'true')
364      $list_menu = html::div(array('onclick' => $onclick, 'class' => 'listmenu',
365        'id' => 'listmenulink', 'title' => rcube_label('listoptions')));
366    else
367      $list_menu = html::a(array('href' => '#', 'onclick' => $onclick),
368        html::img(array('src' => $skin_path . $attrib['optionsmenuicon'],
369          'id' => 'listmenulink', 'title' => rcube_label('listoptions')))
370      );
371  }
372  else
373    $list_menu = '';
374
375  $cells = array();
376
377  foreach ($a_show_cols as $col) {
378    // get column name
379    switch ($col) {
380      case 'flag':
381        $col_name = '<span class="flagged">&nbsp;</span>';
382        break;
383      case 'attachment':
384        $col_name = '<span class="attachment">&nbsp;</span>';
385        break;
386      case 'threads':
387        $col_name = $list_menu;
388        break;
389      default:
390        $col_name = Q(rcube_label($col));
391    }
392
393    // make sort links
394    if (in_array($col, $a_sort_cols))
395      $col_name = html::a(array('href'=>"./#sort", 'onclick' => 'return '.JS_OBJECT_NAME.".command('sort','".$col."',this)", 'title' => rcube_label('sortby')), $col_name);
396
397    $sort_class = $col == $sort_col ? " sorted$sort_order" : '';
398    $class_name = $col.$sort_class;
399
400    // put it all together
401    $cells[] = array('className' => $class_name, 'id' => "rcm$col", 'html' => $col_name);
402  }
403
404  return $cells;
405}
406
407
408/**
409 * return an HTML iframe for loading mail content
410 */
411function rcmail_messagecontent_frame($attrib)
412  {
413  global $OUTPUT, $RCMAIL;
414
415  if (empty($attrib['id']))
416    $attrib['id'] = 'rcmailcontentwindow';
417
418  $attrib['name'] = $attrib['id'];
419
420  if ($RCMAIL->config->get('preview_pane'))
421    $OUTPUT->set_env('contentframe', $attrib['id']);
422  $OUTPUT->set_env('blankpage', $attrib['src'] ? $OUTPUT->abs_url($attrib['src']) : 'program/blank.gif');
423
424  return html::iframe($attrib);
425  }
426
427
428function rcmail_messagecount_display($attrib)
429  {
430  global $IMAP, $OUTPUT;
431
432  if (!$attrib['id'])
433    $attrib['id'] = 'rcmcountdisplay';
434
435  $OUTPUT->add_gui_object('countdisplay', $attrib['id']);
436
437  return html::span($attrib, rcmail_get_messagecount_text());
438  }
439
440
441function rcmail_quota_display($attrib)
442  {
443  global $OUTPUT;
444
445  if (!$attrib['id'])
446    $attrib['id'] = 'rcmquotadisplay';
447
448  if(isset($attrib['display']))
449    $_SESSION['quota_display'] = $attrib['display'];
450
451  $OUTPUT->add_gui_object('quotadisplay', $attrib['id']);
452
453  $quota = rcmail_quota_content($attrib);
454
455  $OUTPUT->add_script('$(document).ready(function(){
456        rcmail.set_quota('.json_serialize($quota).')});', 'foot');
457
458  return html::span($attrib, '');
459  }
460
461
462function rcmail_quota_content($attrib=NULL)
463  {
464  global $COMM_PATH, $RCMAIL;
465
466  $quota = $RCMAIL->imap->get_quota();
467  $quota = $RCMAIL->plugins->exec_hook('quota', $quota);
468
469  $quota_result = (array) $quota;
470  $quota_result['type'] = isset($_SESSION['quota_display']) ? $_SESSION['quota_display'] : '';
471
472  if (!$quota['total'] && $RCMAIL->config->get('quota_zero_as_unlimited')) {
473    $quota_result['title'] = rcube_label('unlimited');
474    $quota_result['percent'] = 0;
475    }
476  else if ($quota['total']) {
477    if (!isset($quota['percent']))
478      $quota_result['percent'] = min(100, round(($quota['used']/max(1,$quota['total']))*100));
479
480    $title = sprintf('%s / %s (%.0f%%)',
481        show_bytes($quota['used'] * 1024), show_bytes($quota['total'] * 1024),
482        $quota_result['percent']);
483
484    $quota_result['title'] = $title;
485
486    if ($attrib['width'])
487      $quota_result['width'] = $attrib['width'];
488    if ($attrib['height'])
489      $quota_result['height']   = $attrib['height'];
490    }
491  else {
492    $quota_result['title'] = rcube_label('unknown');
493    $quota_result['percent'] = 0;
494    }
495
496  return $quota_result;
497  }
498
499
500function rcmail_get_messagecount_text($count=NULL, $page=NULL)
501  {
502  global $RCMAIL, $IMAP, $MESSAGE;
503
504  if (isset($MESSAGE->index))
505    {
506    return rcube_label(array('name' => 'messagenrof',
507        'vars' => array('nr'  => $MESSAGE->index+1,
508        'count' => $count!==NULL ? $count : $IMAP->messagecount(NULL, 'ALL')))); // Only messages, no threads here
509    }
510
511  if ($page===NULL)
512    $page = $IMAP->list_page;
513
514  $start_msg = ($page-1) * $IMAP->page_size + 1;
515
516  if ($count!==NULL)
517    $max = $count;
518  else if ($RCMAIL->action)
519    $max = $IMAP->messagecount(NULL, $IMAP->threading ? 'THREADS' : 'ALL');
520
521  if ($max==0)
522    $out = rcube_label('mailboxempty');
523  else
524    $out = rcube_label(array('name' => $IMAP->threading ? 'threadsfromto' : 'messagesfromto',
525            'vars' => array('from'  => $start_msg,
526            'to'    => min($max, $start_msg + $IMAP->page_size - 1),
527            'count' => $max)));
528
529  return Q($out);
530  }
531
532
533function rcmail_mailbox_name_display($attrib)
534{
535  global $RCMAIL;
536
537  if (!$attrib['id'])
538    $attrib['id'] = 'rcmmailboxname';
539
540  $RCMAIL->output->add_gui_object('mailboxname', $attrib['id']);
541
542  return html::span($attrib, rcmail_get_mailbox_name_text());
543}
544
545
546function rcmail_get_mailbox_name_text()
547{
548  global $RCMAIL;
549  return rcmail_localize_foldername($RCMAIL->imap->get_mailbox_name());
550}
551
552
553function rcmail_send_unread_count($mbox_name, $force=false, $count=null)
554{
555  global $RCMAIL;
556
557  $old_unseen = $_SESSION['unseen_count'][$mbox_name];
558
559  if ($count === null)
560    $unseen = $RCMAIL->imap->messagecount($mbox_name, 'UNSEEN', $force);
561  else
562    $unseen = $count;
563
564  if ($unseen != $old_unseen || ($mbox_name == 'INBOX'))
565    $RCMAIL->output->command('set_unread_count', $mbox_name, $unseen, ($mbox_name == 'INBOX'));
566
567  // @TODO: this data is doubled (session and cache tables) if caching is enabled
568  $_SESSION['unseen_count'][$mbox_name] = $unseen;
569
570  return $unseen;
571}
572
573
574/**
575 * Sets message is_safe flag according to 'show_images' option value
576 *
577 * @param object rcube_message Message
578 */
579function rcmail_check_safe(&$message)
580{
581  global $RCMAIL;
582
583  $show_images = $RCMAIL->config->get('show_images');
584  if (!$message->is_safe
585    && !empty($show_images)
586    && $message->has_html_part())
587  {
588    switch($show_images) {
589      case '1': // known senders only
590        $CONTACTS = new rcube_contacts($RCMAIL->db, $_SESSION['user_id']);
591        if ($CONTACTS->search('email', $message->sender['mailto'], true, false)->count) {
592          $message->set_safe(true);
593        }
594      break;
595      case '2': // always
596        $message->set_safe(true);
597      break;
598    }
599  }
600}
601
602
603/**
604 * Cleans up the given message HTML Body (for displaying)
605 *
606 * @param string HTML
607 * @param array  Display parameters
608 * @param array  CID map replaces (inline images)
609 * @return string Clean HTML
610 */
611function rcmail_wash_html($html, $p = array(), $cid_replaces)
612{
613  global $REMOTE_OBJECTS;
614
615  $p += array('safe' => false, 'inline_html' => true);
616
617  // special replacements (not properly handled by washtml class)
618  $html_search = array(
619    '/(<\/nobr>)(\s+)(<nobr>)/i',       // space(s) between <NOBR>
620    '/<title[^>]*>.*<\/title>/i',       // PHP bug #32547 workaround: remove title tag
621    '/^(\0\0\xFE\xFF|\xFF\xFE\0\0|\xFE\xFF|\xFF\xFE|\xEF\xBB\xBF)/',    // byte-order mark (only outlook?)
622    '/<html\s[^>]+>/i',                 // washtml/DOMDocument cannot handle xml namespaces
623  );
624  $html_replace = array(
625    '\\1'.' &nbsp; '.'\\3',
626    '',
627    '',
628    '<html>',
629  );
630  $html = preg_replace($html_search, $html_replace, $html);
631
632  // PCRE errors handling (#1486856), should we use something like for every preg_* use?
633  if ($html === null && ($preg_error = preg_last_error()) != PREG_NO_ERROR) {
634    $errstr = "Could not clean up HTML message! PCRE Error: $preg_error.";
635
636    if ($preg_error == PREG_BACKTRACK_LIMIT_ERROR)
637      $errstr .= " Consider raising pcre.backtrack_limit!";
638    if ($preg_error == PREG_RECURSION_LIMIT_ERROR)
639      $errstr .= " Consider raising pcre.recursion_limit!";
640
641    raise_error(array('code' => 600, 'type' => 'php',
642        'line' => __LINE__, 'file' => __FILE__,
643        'message' => $errstr), true, false);
644    return '';
645  }
646
647  // fix (unknown/malformed) HTML tags before "wash"
648  $html = preg_replace_callback('/(<[\/]*)([^\s>]+)/', 'rcmail_html_tag_callback', $html);
649
650  // charset was converted to UTF-8 in rcube_imap::get_message_part(),
651  // -> change charset specification in HTML accordingly
652  $charset_pattern = '(<meta\s+[^>]*content=)[\'"]?(\w+\/\w+;\s*charset=)([a-z0-9-_]+[\'"]?)';
653  if (preg_match("/$charset_pattern/Ui", $html)) {
654    $html = preg_replace("/$charset_pattern/i", '\\1"\\2'.RCMAIL_CHARSET.'"', $html);
655  }
656  else {
657    // add meta content-type to malformed messages, washtml cannot work without that
658    if (!preg_match('/<head[^>]*>(.*)<\/head>/Uims', $html))
659      $html = '<head></head>'. $html;
660    $html = substr_replace($html, '<meta http-equiv="Content-Type" content="text/html; charset='.RCMAIL_CHARSET.'" />', intval(stripos($html, '<head>')+6), 0);
661  }
662  // turn relative into absolute urls
663  $html = rcmail_resolve_base($html);
664
665  // clean HTML with washhtml by Frederic Motte
666  $wash_opts = array(
667    'show_washed' => false,
668    'allow_remote' => $p['safe'],
669    'blocked_src' => "./program/blocked.gif",
670    'charset' => RCMAIL_CHARSET,
671    'cid_map' => $cid_replaces,
672    'html_elements' => array('body'),
673  );
674
675  if (!$p['inline_html']) {
676    $wash_opts['html_elements'] = array('html','head','title','body');
677  }
678  if ($p['safe']) {
679    $wash_opts['html_elements'][] = 'link';
680    $wash_opts['html_attribs'] = array('rel','type');
681  }
682
683  // overwrite washer options with options from plugins
684  if (isset($p['html_elements']))
685    $wash_opts['html_elements'] = $p['html_elements'];
686  if (isset($p['html_attribs']))
687    $wash_opts['html_attribs'] = $p['html_attribs'];
688
689  // initialize HTML washer
690  $washer = new washtml($wash_opts);
691
692  if (!$p['skip_washer_form_callback'])
693    $washer->add_callback('form', 'rcmail_washtml_callback');
694
695  // allow CSS styles, will be sanitized by rcmail_washtml_callback()
696  if (!$p['skip_washer_style_callback'])
697    $washer->add_callback('style', 'rcmail_washtml_callback');
698
699  $html = $washer->wash($html);
700  $REMOTE_OBJECTS = $washer->extlinks;
701
702  return $html;
703}
704
705
706/**
707 * Convert the given message part to proper HTML
708 * which can be displayed the message view
709 *
710 * @param object rcube_message_part Message part
711 * @param array  Display parameters array
712 * @return string Formatted HTML string
713 */
714function rcmail_print_body($part, $p = array())
715{
716  global $RCMAIL;
717
718  // trigger plugin hook
719  $data = $RCMAIL->plugins->exec_hook('message_part_before',
720    array('type' => $part->ctype_secondary, 'body' => $part->body) + $p + array('safe' => false, 'plain' => false, 'inline_html' => true));
721
722  // convert html to text/plain
723  if ($data['type'] == 'html' && $data['plain']) {
724    $txt = new html2text($data['body'], false, true);
725    $body = $txt->get_text();
726    $part->ctype_secondary = 'plain';
727  }
728  // text/html
729  else if ($data['type'] == 'html') {
730    $body = rcmail_wash_html($data['body'], $data, $part->replaces);
731    $part->ctype_secondary = $data['type'];
732  }
733  // text/enriched
734  else if ($data['type'] == 'enriched') {
735    $part->ctype_secondary = 'html';
736    require_once('lib/enriched.inc');
737    $body = Q(enriched_to_html($data['body']), 'show');
738  }
739  else {
740    // assert plaintext
741    $body = $part->body;
742    $part->ctype_secondary = $data['type'] = 'plain';
743  }
744
745  // free some memory (hopefully)
746  unset($data['body']);
747
748  // plaintext postprocessing
749  if ($part->ctype_secondary == 'plain')
750    $body = rcmail_plain_body($body, $part->ctype_parameters['format'] == 'flowed');
751
752  // allow post-processing of the message body
753  $data = $RCMAIL->plugins->exec_hook('message_part_after', array('type' => $part->ctype_secondary, 'body' => $body) + $data);
754
755  return $data['type'] == 'html' ? $data['body'] : html::tag('pre', array(), $data['body']);
756}
757
758
759/**
760 * Handle links and citation marks in plain text message
761 *
762 * @param string  Plain text string
763 * @param boolean Text uses format=flowed
764 *
765 * @return string Formatted HTML string
766 */
767function rcmail_plain_body($body, $flowed=false)
768{
769  global $RCMAIL;
770
771  // make links and email-addresses clickable
772  $replacer = new rcube_string_replacer;
773
774  // search for patterns like links and e-mail addresses
775  $body = preg_replace_callback($replacer->link_pattern, array($replacer, 'link_callback'), $body);
776  $body = preg_replace_callback($replacer->mailto_pattern, array($replacer, 'mailto_callback'), $body);
777
778  // split body into single lines
779  $a_lines = preg_split('/\r?\n/', $body);
780  $quote_level = 0;
781  $last = -1;
782
783  // find/mark quoted lines...
784  for ($n=0, $cnt=count($a_lines); $n < $cnt; $n++) {
785    if ($a_lines[$n][0] == '>' && preg_match('/^(>+\s*)+/', $a_lines[$n], $regs)) {
786      $q = strlen(preg_replace('/\s/', '', $regs[0]));
787      $a_lines[$n] = substr($a_lines[$n], strlen($regs[0]));
788
789      if ($q > $quote_level)
790        $a_lines[$n] = $replacer->get_replacement($replacer->add(
791          str_repeat('<blockquote>', $q - $quote_level))) . $a_lines[$n];
792      else if ($q < $quote_level)
793        $a_lines[$n] = $replacer->get_replacement($replacer->add(
794          str_repeat('</blockquote>', $quote_level - $q))) . $a_lines[$n];
795      else if ($flowed) {
796        // previous line is flowed
797        if (isset($a_lines[$last]) && $a_lines[$n]
798          && $a_lines[$last][strlen($a_lines[$last])-1] == ' ') {
799          // merge lines
800          $a_lines[$last] .= $a_lines[$n];
801          unset($a_lines[$n]);
802        }
803        else
804          $last = $n;
805      }
806    }
807    else {
808      $q = 0;
809      if ($flowed) {
810        // sig separator - line is fixed
811        if ($a_lines[$n] == '-- ') {
812          $last = $n;
813        }
814        else {
815          // remove space-stuffing
816          if ($a_lines[$n][0] == ' ')
817            $a_lines[$n] = substr($a_lines[$n], 1);
818
819          // previous line is flowed?
820          if (isset($a_lines[$last]) && $a_lines[$n]
821            && $a_lines[$last] != '-- '
822            && $a_lines[$last][strlen($a_lines[$last])-1] == ' '
823          ) {
824            $a_lines[$last] .= $a_lines[$n];
825            unset($a_lines[$n]);
826          }
827          else {
828            $last = $n;
829          }
830        }
831        if ($quote_level > 0)
832          $a_lines[$last] = $replacer->get_replacement($replacer->add(
833            str_repeat('</blockquote>', $quote_level))) . $a_lines[$last];
834      }
835      else if ($quote_level > 0)
836        $a_lines[$n] = $replacer->get_replacement($replacer->add(
837          str_repeat('</blockquote>', $quote_level))) . $a_lines[$n];
838    }
839
840    $quote_level = $q;
841  }
842
843  // quote plain text
844  $body = Q(join("\n", $a_lines), 'dummy', false);
845
846  // colorize signature
847  $len = strlen($body);
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) < $RCMAIL->config->get('sig_max_lines', 15))
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.