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

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