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

Last change on this file since 3479 was 3479, checked in by thomasb, 3 years ago

Option not to mark messages as read when viewed in preview pane (#1485012)

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 48.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$EMAIL_ADDRESS_PATTERN = '([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9][a-z0-9\-\.]*\\.[a-z]{2,5})';
28
29// actions that do not require imap connection
30$NOIMAP_ACTIONS = array('spell', 'addcontact', 'autocomplete', 'upload', 'display-attachment', 'remove-attachment');
31
32// always instantiate imap object (but not yet connect to server)
33$RCMAIL->imap_init();
34
35// log in to imap server
36if (!in_array($RCMAIL->action, $NOIMAP_ACTIONS) && !$RCMAIL->imap_connect()) {
37  $RCMAIL->kill_session();
38
39  if ($OUTPUT->ajax_call)
40    $OUTPUT->redirect(array(), 2000);
41
42  $OUTPUT->set_env('task', 'login');
43  $OUTPUT->send('login');
44}
45
46// set imap properties and session vars
47if ($mbox = get_input_value('_mbox', RCUBE_INPUT_GPC))
48  $IMAP->set_mailbox(($_SESSION['mbox'] = $mbox));
49else if ($IMAP)
50  $_SESSION['mbox'] = $IMAP->get_mailbox_name();
51
52if (!empty($_GET['_page']))
53  $IMAP->set_page(($_SESSION['page'] = intval($_GET['_page'])));
54
55// set default sort col/order to session
56if (!isset($_SESSION['sort_col']))
57  $_SESSION['sort_col'] = $CONFIG['message_sort_col'];
58if (!isset($_SESSION['sort_order']))
59  $_SESSION['sort_order'] = $CONFIG['message_sort_order'];
60
61// set threads mode
62$a_threading = $RCMAIL->config->get('message_threading', array());
63if (isset($_GET['_threads'])) {
64  if ($_GET['_threads'])
65    $a_threading[$_SESSION['mbox']] = true;
66  else
67    unset($a_threading[$_SESSION['mbox']]);
68  $RCMAIL->user->save_prefs(array('message_threading' => $a_threading));
69}
70$IMAP->set_threading($a_threading[$_SESSION['mbox']]);
71
72// set message set for search result
73if (!empty($_REQUEST['_search']) && isset($_SESSION['search'][$_REQUEST['_search']]))
74  {
75  $IMAP->set_search_set($_SESSION['search'][$_REQUEST['_search']]);
76  $OUTPUT->set_env('search_request', $_REQUEST['_search']);
77  $OUTPUT->set_env('search_text', $_SESSION['last_text_search']);
78  }
79
80// set main env variables, labels and page title
81if (empty($RCMAIL->action) || $RCMAIL->action == 'list')
82  {
83  $mbox_name = $IMAP->get_mailbox_name();
84
85  if (empty($RCMAIL->action))
86    {
87    // initialize searching result if search_filter is used
88    if ($_SESSION['search_filter'] && $_SESSION['search_filter'] != 'ALL')
89      {
90      $search_request = md5($mbox_name.$_SESSION['search_filter']);
91 
92      $IMAP->search($mbox_name, $_SESSION['search_filter'], RCMAIL_CHARSET, $_SESSION['sort_col']);
93      $_SESSION['search'][$search_request] = $IMAP->get_search_set();
94      $OUTPUT->set_env('search_request', $search_request);
95      }
96   
97      $search_mods = $RCMAIL->config->get('search_mods', $SEARCH_MODS_DEFAULT);
98      $OUTPUT->set_env('search_mods', $search_mods);
99     
100      // make sure the message count is refreshed (for default view)
101      $IMAP->messagecount($mbox_name, $IMAP->threading ? 'THREADS' : 'ALL', true);
102    }
103       
104  // set current mailbox and some other vars in client environment
105  $OUTPUT->set_env('mailbox', $mbox_name);
106  $OUTPUT->set_env('pagesize', $IMAP->page_size);
107  $OUTPUT->set_env('quota', $IMAP->get_capability('quota'));
108  $OUTPUT->set_env('delimiter', $IMAP->get_hierarchy_delimiter());
109  $OUTPUT->set_env('threading', (bool) $IMAP->threading);
110  $OUTPUT->set_env('threads', $IMAP->threading
111        || $IMAP->get_capability('thread=references')
112        || $IMAP->get_capability('thread=orderedsubject')
113        || $IMAP->get_capability('thread=refs') 
114  );
115
116  if ($CONFIG['flag_for_deletion'])
117    $OUTPUT->set_env('flag_for_deletion', true);
118  if ($CONFIG['read_when_deleted'])
119    $OUTPUT->set_env('read_when_deleted', true);
120  if ($CONFIG['skip_deleted'])
121    $OUTPUT->set_env('skip_deleted', true);
122  if ($CONFIG['display_next'])
123    $OUTPUT->set_env('display_next', true);
124
125  $OUTPUT->set_env('preview_pane_mark_read', $RCMAIL->config->get('preview_pane_mark_read', 0));
126
127  if ($CONFIG['trash_mbox'])
128    $OUTPUT->set_env('trash_mailbox', $CONFIG['trash_mbox']);
129  if ($CONFIG['drafts_mbox'])
130    $OUTPUT->set_env('drafts_mailbox', $CONFIG['drafts_mbox']);
131  if ($CONFIG['junk_mbox'])
132    $OUTPUT->set_env('junk_mailbox', $CONFIG['junk_mbox']);
133
134  if (!$OUTPUT->ajax_call)
135    $OUTPUT->add_label('checkingmail', 'deletemessage', 'movemessagetotrash',
136      'movingmessage', 'copyingmessage', 'copy', 'move');
137
138  $OUTPUT->set_pagetitle(rcmail_localize_foldername($mbox_name));
139  }
140
141
142/**
143 * return the message list as HTML table
144 */
145function rcmail_message_list($attrib)
146{
147  global $IMAP, $CONFIG, $OUTPUT;
148
149  // add some labels to client
150  $OUTPUT->add_label('from', 'to');
151
152  // add id to message list table if not specified
153  if (!strlen($attrib['id']))
154    $attrib['id'] = 'rcubemessagelist';
155
156  // define list of cols to be displayed based on parameter or config
157  if (empty($attrib['columns']))
158      $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
159  else
160      $a_show_cols = preg_split('/[\s,;]+/', strip_quotes($attrib['columns']));
161
162  // save some variables for use in ajax list
163  $_SESSION['list_columns'] = $a_show_cols;
164  $_SESSION['list_attrib'] = $attrib;
165 
166  $mbox = $IMAP->get_mailbox_name();
167  $delim = $IMAP->get_hierarchy_delimiter();
168
169  // show 'to' instead of 'from' in sent/draft messages
170  if ((strpos($mbox.$delim, $CONFIG['sent_mbox'].$delim)===0 || strpos($mbox.$delim, $CONFIG['drafts_mbox'].$delim)===0)
171      && (($f = array_search('from', $a_show_cols)) !== false) && array_search('to', $a_show_cols) === false)
172    $a_show_cols[$f] = 'to';
173
174  $skin_path = $_SESSION['skin_path'] = $CONFIG['skin_path'];
175  $message_count = $IMAP->messagecount(NULL, $IMAP->threading ? 'THREADS' : 'ALL');
176 
177  // set client env
178  $OUTPUT->add_gui_object('mailcontframe', 'mailcontframe');
179  $OUTPUT->add_gui_object('messagelist', $attrib['id']);
180  $OUTPUT->set_env('autoexpand_threads', intval($CONFIG['autoexpand_threads']));
181  $OUTPUT->set_env('messagecount', $message_count);
182  $OUTPUT->set_env('current_page', $IMAP->list_page);
183  $OUTPUT->set_env('pagecount', ceil($message_count/$IMAP->page_size));
184  $OUTPUT->set_env('sort_col', $_SESSION['sort_col']);
185  $OUTPUT->set_env('sort_order', $_SESSION['sort_order']);
186 
187  if ($attrib['messageicon'])
188    $OUTPUT->set_env('messageicon', $skin_path . $attrib['messageicon']);
189  if ($attrib['deletedicon'])
190    $OUTPUT->set_env('deletedicon', $skin_path . $attrib['deletedicon']);
191  if ($attrib['unreadicon'])
192    $OUTPUT->set_env('unreadicon', $skin_path . $attrib['unreadicon']);
193  if ($attrib['repliedicon'])
194    $OUTPUT->set_env('repliedicon', $skin_path . $attrib['repliedicon']);
195  if ($attrib['forwardedicon'])
196    $OUTPUT->set_env('forwardedicon', $skin_path . $attrib['forwardedicon']);
197  if ($attrib['forwardedrepliedicon'])
198    $OUTPUT->set_env('forwardedrepliedicon', $skin_path . $attrib['forwardedrepliedicon']);
199  if ($attrib['attachmenticon'])
200    $OUTPUT->set_env('attachmenticon', $skin_path . $attrib['attachmenticon']);
201  if ($attrib['flaggedicon'])
202    $OUTPUT->set_env('flaggedicon', $skin_path . $attrib['flaggedicon']);
203  if ($attrib['unflaggedicon'])
204    $OUTPUT->set_env('unflaggedicon', $skin_path . $attrib['unflaggedicon']);
205  if ($attrib['unreadchildrenicon'])
206    $OUTPUT->set_env('unreadchildrenicon', $skin_path . $attrib['unreadchildrenicon']);
207 
208  $OUTPUT->set_env('messages', array());
209  $OUTPUT->set_env('coltypes', $a_show_cols);
210 
211  if (!$message_count)
212    $OUTPUT->show_message('nomessagesfound', 'notice');
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 * or to replace the whole list (IE only)
231 */
232function rcmail_js_message_list($a_headers, $insert_top=FALSE, $replace=TRUE, $head_replace=FALSE)
233{
234  global $CONFIG, $IMAP, $OUTPUT;
235
236  if (empty($_SESSION['list_columns']))
237    $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
238  else
239    $a_show_cols = $_SESSION['list_columns'];
240
241  $mbox = $IMAP->get_mailbox_name();
242  $delim = $IMAP->get_hierarchy_delimiter();
243 
244  // show 'to' instead of 'from' in sent/draft messages
245  if ((strpos($mbox.$delim, $CONFIG['sent_mbox'].$delim)===0 || strpos($mbox.$delim, $CONFIG['drafts_mbox'].$delim)===0)
246      && (($f = array_search('from', $a_show_cols)) !== false) && array_search('to', $a_show_cols) === false)
247    $a_show_cols[$f] = 'to';
248
249  $thead = $head_replace ? rcmail_message_list_head($_SESSION['list_attrib'], $a_show_cols) : NULL;
250 
251  $OUTPUT->command('set_message_coltypes', $a_show_cols, $thead);
252
253  if (empty($a_headers))
254    return;
255
256  // remove 'attachment' and 'flag' columns, we don't need them here
257  if(($key = array_search('attachment', $a_show_cols)) !== FALSE)
258    unset($a_show_cols[$key]);
259  if(($key = array_search('flag', $a_show_cols)) !== FALSE)
260    unset($a_show_cols[$key]);
261
262  if ($OUTPUT->browser->ie && $replace)
263    $OUTPUT->command('offline_message_list', true);
264
265  // loop through message headers
266  foreach ($a_headers as $n => $header)
267    {
268    $a_msg_cols = array();
269    $a_msg_flags = array();
270   
271    if (empty($header))
272      continue;
273
274    $IMAP->set_charset(!empty($header->charset) ? $header->charset : $CONFIG['default_charset']);
275
276    // format each col; similar as in rcmail_message_list()
277    foreach ($a_show_cols as $col)
278      {
279      if (in_array($col, array('from', 'to', 'cc', 'replyto')))
280        $cont = Q(rcmail_address_string($header->$col, 3), 'show');
281      else if ($col=='subject')
282        {
283        $cont = abbreviate_string(trim($IMAP->decode_header($header->$col)), 160);
284        if (!$cont) $cont = rcube_label('nosubject');
285        $cont = Q($cont);
286        }
287      else if ($col=='size')
288        $cont = show_bytes($header->$col);
289      else if ($col=='date')
290        $cont = format_date($header->date);
291      else
292        $cont = Q($header->$col);
293         
294      $a_msg_cols[$col] = $cont;
295      }
296
297    if ($header->depth)
298      $a_msg_flags['depth'] = $header->depth;
299    if ($header->parent_uid)
300      $a_msg_flags['parent_uid'] = $header->parent_uid;
301    if ($header->has_children)
302      $a_msg_flags['has_children'] = $header->has_children;
303    if ($header->unread_children)
304      $a_msg_flags['unread_children'] = $header->unread_children;
305    if ($header->deleted)
306      $a_msg_flags['deleted'] = 1;
307    if (!$header->seen)
308      $a_msg_flags['unread'] = 1;
309    if ($header->answered)
310      $a_msg_flags['replied'] = 1;
311    if ($header->forwarded)
312      $a_msg_flags['forwarded'] = 1;
313    if ($header->flagged)
314      $a_msg_flags['flagged'] = 1;
315    if(preg_match("/multipart\/m/i", $header->ctype))
316      $a_msg_flags['attachment'] = 1;
317    $a_msg_flags['mbox'] = $mbox;
318
319    $OUTPUT->command('add_message_row',
320      $header->uid,
321      $a_msg_cols,
322      $a_msg_flags,
323      $insert_top);
324    }
325
326  if ($browser->ie && $replace)
327    $OUTPUT->command('offline_message_list', false);
328  }
329
330
331/*
332 * Creates <THEAD> for message list table
333 */
334function rcmail_message_list_head($attrib, $a_show_cols)
335{
336  global $CONFIG;
337
338  $skin_path = $_SESSION['skin_path'];
339  $image_tag = html::img(array('src' => "%s%s", 'alt' => "%s"));
340
341  // check to see if we have some settings for sorting
342  $sort_col   = $_SESSION['sort_col'];
343  $sort_order = $_SESSION['sort_order'];
344
345  // define sortable columns
346  $a_sort_cols = array('subject', 'date', 'from', 'to', 'size', 'cc');
347 
348  if (!empty($attrib['optionsmenuicon']))
349    $list_menu = html::a(
350      array('href' => '#', 'onclick' => 'return '.JS_OBJECT_NAME.".command('menu-open', 'messagelistmenu')"),
351      html::img(array('src' => $skin_path . $attrib['optionsmenuicon'], 'id' => 'listmenulink', 'title' => rcube_label('listoptions')))
352    );
353  else
354    $list_menu = '';
355
356  $cells = array(array('className' => 'threads', 'html' => $list_menu));
357
358  foreach ($a_show_cols as $col) {
359    // get column name
360    switch ($col) {
361      case 'flag':
362        $col_name = sprintf($image_tag, $skin_path, $attrib['unflaggedicon'], '');
363        break;
364      case 'attachment':
365        $col_name = sprintf($image_tag, $skin_path, $attrib['attachmenticon'], '');
366        break;
367      default:
368        $col_name = Q(rcube_label($col));
369    }
370
371    // make sort links
372    if (in_array($col, $a_sort_cols))
373      $col_name = html::a(array('href'=>"./#sort", 'onclick' => 'return '.JS_OBJECT_NAME.".command('sort','".$col."',this)", 'title' => rcube_label('sortby')), $col_name);
374
375    $sort_class = $col == $sort_col ? " sorted$sort_order" : '';
376    $class_name = $col == 'attachment' ? 'icon' : $col.$sort_class;
377
378    // put it all together
379    $cells[] = array('className' => $class_name, 'id' => "rcm$col", 'html' => $col_name);
380  }
381
382  return $cells;
383}
384
385
386/**
387 * return an HTML iframe for loading mail content
388 */
389function rcmail_messagecontent_frame($attrib)
390  {
391  global $OUTPUT;
392 
393  if (empty($attrib['id']))
394    $attrib['id'] = 'rcmailcontentwindow';
395
396  $attrib['name'] = $attrib['id'];
397
398  $OUTPUT->set_env('contentframe', $attrib['id']);
399  $OUTPUT->set_env('blankpage', $attrib['src'] ? $OUTPUT->abs_url($attrib['src']) : 'program/blank.gif');
400
401  return html::iframe($attrib);
402  }
403
404
405function rcmail_messagecount_display($attrib)
406  {
407  global $IMAP, $OUTPUT;
408 
409  if (!$attrib['id'])
410    $attrib['id'] = 'rcmcountdisplay';
411
412  $OUTPUT->add_gui_object('countdisplay', $attrib['id']);
413
414  return html::span($attrib, rcmail_get_messagecount_text());
415  }
416
417
418function rcmail_quota_display($attrib)
419  {
420  global $OUTPUT;
421
422  if (!$attrib['id'])
423    $attrib['id'] = 'rcmquotadisplay';
424
425  if(isset($attrib['display']))
426    $_SESSION['quota_display'] = $attrib['display'];
427
428  $OUTPUT->add_gui_object('quotadisplay', $attrib['id']);
429 
430  $quota = rcmail_quota_content($attrib);
431 
432  if (is_array($quota)) {
433    $OUTPUT->add_script('$(document).ready(function(){
434        rcmail.set_quota('.json_serialize($quota).')});', 'foot');
435    $quota = '';
436    }
437 
438  return html::span($attrib, $quota);
439  }
440
441
442function rcmail_quota_content($attrib=NULL)
443  {
444  global $COMM_PATH, $RCMAIL;
445
446  $display = isset($_SESSION['quota_display']) ? $_SESSION['quota_display'] : '';
447
448  $quota = $RCMAIL->imap->get_quota();
449  $quota = $RCMAIL->plugins->exec_hook('quota', $quota);
450
451  if (!isset($quota['used']) || !isset($quota['total']))
452    return rcube_label('unknown');
453
454  if (!($quota['total']==0 && $RCMAIL->config->get('quota_zero_as_unlimited')))
455    {
456    if (!isset($quota['percent']))
457      $quota['percent'] = min(100, round(($quota['used']/max(1,$quota['total']))*100));
458   
459    $quota_result = sprintf('%s / %s (%.0f%%)',
460        show_bytes($quota['used'] * 1024), show_bytes($quota['total'] * 1024),
461        $quota['percent']);
462
463    if ($display == 'image') {
464      $quota_result = array(
465        'percent'       => $quota['percent'],
466        'title'         => $quota_result,
467        );
468
469      if ($attrib['width'])
470        $quota_result['width'] = $attrib['width'];
471      if ($attrib['height'])
472        $quota_result['height'] = $attrib['height'];
473      }
474    }
475  else
476    return rcube_label('unlimited');
477
478  return $quota_result;
479  }
480
481
482function rcmail_get_messagecount_text($count=NULL, $page=NULL)
483  {
484  global $IMAP, $MESSAGE;
485 
486  if (isset($MESSAGE->index))
487    {
488    return rcube_label(array('name' => 'messagenrof',
489        'vars' => array('nr'  => $MESSAGE->index+1,
490        'count' => $count!==NULL ? $count : $IMAP->messagecount(NULL, 'ALL')))); // Only messages, no threads here
491    }
492
493  if ($page===NULL)
494    $page = $IMAP->list_page;
495   
496  $start_msg = ($page-1) * $IMAP->page_size + 1;
497  $max = $count!==NULL ? $count : $IMAP->messagecount(NULL, $IMAP->threading ? 'THREADS' : 'ALL');
498
499  if ($max==0)
500    $out = rcube_label('mailboxempty');
501  else
502    $out = rcube_label(array('name' => $IMAP->threading ? 'threadsfromto' : 'messagesfromto',
503            'vars' => array('from'  => $start_msg,
504            'to'    => min($max, $start_msg + $IMAP->page_size - 1),
505            'count' => $max)));
506
507  return Q($out);
508  }
509
510
511function rcmail_mailbox_name_display($attrib)
512{
513  global $RCMAIL;
514
515  if (!$attrib['id'])
516    $attrib['id'] = 'rcmmailboxname';
517
518  $RCMAIL->output->add_gui_object('mailboxname', $attrib['id']);
519
520  return html::span($attrib, rcmail_get_mailbox_name_text());
521}
522
523
524function rcmail_get_mailbox_name_text()
525{
526  global $RCMAIL;
527  return rcmail_localize_foldername($RCMAIL->imap->get_mailbox_name());
528}
529
530
531function rcmail_send_unread_count($mbox_name, $force=false)
532{
533  global $RCMAIL;
534   
535  $old_unseen = $_SESSION['unseen_count'][$mbox_name];
536  $unseen = $RCMAIL->imap->messagecount($mbox_name, 'UNSEEN', $force);
537
538  if ($unseen != $old_unseen || ($mbox_name == 'INBOX'))
539    $RCMAIL->output->command('set_unread_count', $mbox_name, $unseen, ($mbox_name == 'INBOX'));
540
541  // @TODO: this data is doubled (session and cache tables) if caching is enabled
542  $_SESSION['unseen_count'][$mbox_name] = $unseen;
543   
544  return $unseen;
545}
546
547
548/**
549 * Sets message is_safe flag according to 'show_images' option value
550 *
551 * @param object rcube_message Message
552 */
553function rcmail_check_safe(&$message)
554{
555  global $RCMAIL;
556
557  $show_images = $RCMAIL->config->get('show_images');
558  if (!$message->is_safe
559    && !empty($show_images)
560    && $message->has_html_part())
561  {
562    switch($show_images) {
563      case '1': // known senders only
564        $CONTACTS = new rcube_contacts($RCMAIL->db, $_SESSION['user_id']);
565        if ($CONTACTS->search('email', $message->sender['mailto'], true, false)->count) {
566          $message->set_safe(true);
567        }
568      break;
569      case '2': // always
570        $message->set_safe(true);
571      break;
572    }
573  }
574}
575
576
577/**
578 * Cleans up the given message HTML Body (for displaying)
579 *
580 * @param string HTML
581 * @param array  Display parameters
582 * @param array  CID map replaces (inline images)
583 * @return string Clean HTML
584 */
585function rcmail_wash_html($html, $p = array(), $cid_replaces)
586{
587  global $REMOTE_OBJECTS;
588
589  $p += array('safe' => false, 'inline_html' => true);
590
591  // special replacements (not properly handled by washtml class)
592  $html_search = array(
593    '/(<\/nobr>)(\s+)(<nobr>)/i',       // space(s) between <NOBR>
594    '/<title[^>]*>.*<\/title>/i',       // PHP bug #32547 workaround: remove title tag
595    '/^(\0\0\xFE\xFF|\xFF\xFE\0\0|\xFE\xFF|\xFF\xFE|\xEF\xBB\xBF)/',    // byte-order mark (only outlook?)
596    '/<html\s[^>]+>/i',                 // washtml/DOMDocument cannot handle xml namespaces
597  );
598  $html_replace = array(
599    '\\1'.' &nbsp; '.'\\3',
600    '',
601    '',
602    '<html>',
603  );
604  $html = preg_replace($html_search, $html_replace, $html);
605
606  // fix (unknown/malformed) HTML tags before "wash"
607  $html = preg_replace_callback('/(<[\/]*)([^\s>]+)/', 'rcmail_html_tag_callback', $html);
608
609  // charset was converted to UTF-8 in rcube_imap::get_message_part(),
610  // -> change charset specification in HTML accordingly
611  $charset_pattern = '(<meta\s+[^>]* content=)[\'"]?(\w+\/\w+;\s*charset=)([a-z0-9-_]+[\'"]?)';
612  if (preg_match("/$charset_pattern/Ui", $html)) {
613    $html = preg_replace("/$charset_pattern/i", '\\1"\\2'.RCMAIL_CHARSET.'"', $html);
614  }
615  else {
616    // add meta content-type to malformed messages, washtml cannot work without that
617    if (!preg_match('/<head[^>]*>(.*)<\/head>/Uims', $html))
618      $html = '<head></head>'. $html;
619    $html = substr_replace($html, '<meta http-equiv="Content-Type" content="text/html; charset='.RCMAIL_CHARSET.'" />', intval(stripos($html, '<head>')+6), 0);
620  }
621
622  // turn relative into absolute urls
623  $html = rcmail_resolve_base($html);
624
625  // clean HTML with washhtml by Frederic Motte
626  $wash_opts = array(
627    'show_washed' => false,
628    'allow_remote' => $p['safe'],
629    'blocked_src' => "./program/blocked.gif",
630    'charset' => RCMAIL_CHARSET,
631    'cid_map' => $cid_replaces,
632    'html_elements' => array('body'),
633  );
634
635  if (!$p['inline_html']) {
636    $wash_opts['html_elements'] = array('html','head','title','body');
637  }
638  if ($p['safe']) {
639    $wash_opts['html_elements'][] = 'link';
640    $wash_opts['html_attribs'] = array('rel','type');
641  }
642   
643  $washer = new washtml($wash_opts);
644  $washer->add_callback('form', 'rcmail_washtml_callback');
645
646  // allow CSS styles, will be sanitized by rcmail_washtml_callback()
647  $washer->add_callback('style', 'rcmail_washtml_callback');
648
649  $html = $washer->wash($html);
650  $REMOTE_OBJECTS = $washer->extlinks;
651
652  return $html;
653}
654
655
656/**
657 * Convert the given message part to proper HTML
658 * which can be displayed the message view
659 *
660 * @param object rcube_message_part Message part
661 * @param array  Display parameters array
662 * @return string Formatted HTML string
663 */
664function rcmail_print_body($part, $p = array())
665{
666  global $RCMAIL;
667 
668  // trigger plugin hook
669  $data = $RCMAIL->plugins->exec_hook('message_part_before',
670    array('type' => $part->ctype_secondary, 'body' => $part->body) + $p + array('safe' => false, 'plain' => false, 'inline_html' => true));
671
672  // convert html to text/plain
673  if ($data['type'] == 'html' && $data['plain']) {
674    $txt = new html2text($data['body'], false, true);
675    $body = $txt->get_text();
676    $part->ctype_secondary = 'plain';
677  }
678  // text/html
679  else if ($data['type'] == 'html') {
680    $body = rcmail_wash_html($data['body'], $data, $part->replaces);
681    $part->ctype_secondary = $data['type'];
682  }
683  // text/enriched
684  else if ($data['type'] == 'enriched') {
685    $part->ctype_secondary = 'html';
686    require_once('lib/enriched.inc');
687    $body = Q(enriched_to_html($data['body']), 'show');
688  }
689  else {
690    // assert plaintext
691    $body = $part->body;
692    $part->ctype_secondary = $data['type'] = 'plain';
693  }
694 
695  // free some memory (hopefully)
696  unset($data['body']);
697
698  // plaintext postprocessing
699  if ($part->ctype_secondary == 'plain')
700    $body = rcmail_plain_body($body);
701
702  // allow post-processing of the message body
703  $data = $RCMAIL->plugins->exec_hook('message_part_after', array('type' => $part->ctype_secondary, 'body' => $body) + $data);
704
705  return $data['type'] == 'html' ? $data['body'] : html::tag('pre', array(), $data['body']);
706}
707
708
709/**
710 * Handle links and citation marks in plain text message
711 *
712 * @param string  Plain text string
713 * @return string Formatted HTML string
714 */
715function rcmail_plain_body($body)
716{
717  // make links and email-addresses clickable
718  $replacements = new rcube_string_replacer;
719   
720  // search for patterns like links and e-mail addresses
721  $body = preg_replace_callback($replacements->link_pattern, array($replacements, 'link_callback'), $body);
722  $body = preg_replace_callback($replacements->mailto_pattern, array($replacements, 'mailto_callback'), $body);
723
724  // split body into single lines
725  $a_lines = preg_split('/\r?\n/', $body);
726  $q_lines = array();
727  $quote_level = 0;
728
729  // find/mark quoted lines...
730  for ($n=0, $cnt=count($a_lines); $n < $cnt; $n++) {
731    $q = 0;
732
733    if ($a_lines[$n][0] == '>' && preg_match('/^(>+\s*)+/', $a_lines[$n], $regs)) {
734      $q = strlen(preg_replace('/\s/', '', $regs[0]));
735        $a_lines[$n] = substr($a_lines[$n], strlen($regs[0]));
736
737      if ($q > $quote_level)
738        $q_lines[$n]['quote'] = $q - $quote_level;
739      else if ($q < $quote_level)
740        $q_lines[$n]['endquote'] = $quote_level - $q;
741    }
742    else if ($quote_level > 0)
743      $q_lines[$n]['endquote'] = $quote_level;
744
745    $quote_level = $q;
746  }
747
748  // quote plain text
749  $body = Q(join("\n", $a_lines), 'replace', false);
750
751  // colorize signature
752  if (($sp = strrpos($body, '-- ')) !== false)
753    if (($sp == 0 || $body[$sp-1] == "\n") && $body[$sp+3] == "\n") {
754      $body = substr($body, 0, max(0, $sp))
755        .'<span class="sig">'.substr($body, $sp).'</span>';
756    }
757
758  // colorize quoted lines
759  $a_lines = preg_split('/\n/', $body);
760  foreach ($q_lines as $i => $q)
761    if ($q['quote'])
762      $a_lines[$i] = str_repeat('<blockquote>', $q['quote']) . $a_lines[$i];
763    else if ($q['endquote'])
764      $a_lines[$i] = str_repeat('</blockquote>', $q['endquote']) . $a_lines[$i];
765
766  // insert the links for urls and mailtos
767  $body = $replacements->resolve(join("\n", $a_lines));
768   
769  return $body;
770}
771
772
773/**
774 * add a string to the replacement array and return a replacement string
775 */
776function rcmail_str_replacement($str, &$rep)
777{
778  static $count = 0;
779  $rep[$count] = stripslashes($str);
780  return "##string_replacement{".($count++)."}##";
781}
782
783
784/**
785 * Callback function for washtml cleaning class
786 */
787function rcmail_washtml_callback($tagname, $attrib, $content)
788{
789  switch ($tagname) {
790    case 'form':
791      $out = html::div('form', $content);
792      break;
793     
794    case 'style':
795      // decode all escaped entities and reduce to ascii strings
796      $stripped = preg_replace('/[^a-zA-Z\(:]/', '', rcmail_xss_entity_decode($content));
797     
798      // now check for evil strings like expression, behavior or url()
799      if (!preg_match('/expression|behavior|url\(|import/', $stripped)) {
800        $out = html::tag('style', array('type' => 'text/css'), $content);
801        break;
802      }
803   
804    default:
805      $out = '';
806  }
807 
808  return $out;
809}
810
811
812/**
813 * Callback function for HTML tags fixing
814 */
815function rcmail_html_tag_callback($matches)
816{
817  $tagname = $matches[2];
818
819  $tagname = preg_replace(array(
820    '/:.*$/',                   // Microsoft's Smart Tags <st1:xxxx>
821    '/[^a-z0-9_\[\]\!-]/i',     // forbidden characters
822    ), '', $tagname);
823
824  return $matches[1].$tagname;
825}
826
827
828/**
829 * return table with message headers
830 */
831function rcmail_message_headers($attrib, $headers=NULL)
832  {
833  global $IMAP, $OUTPUT, $MESSAGE, $PRINT_MODE, $RCMAIL;
834  static $sa_attrib;
835 
836  // keep header table attrib
837  if (is_array($attrib) && !$sa_attrib)
838    $sa_attrib = $attrib;
839  else if (!is_array($attrib) && is_array($sa_attrib))
840    $attrib = $sa_attrib;
841 
842  if (!isset($MESSAGE))
843    return FALSE;
844
845  // get associative array of headers object
846  if (!$headers)
847    $headers = is_object($MESSAGE->headers) ? get_object_vars($MESSAGE->headers) : $MESSAGE->headers;
848
849  // show these headers
850  $standard_headers = array('subject', 'from', 'to', 'cc', 'bcc', 'replyto', 'date');
851  $output_headers = array();
852
853  foreach ($standard_headers as $hkey) {
854    if (!$headers[$hkey])
855      continue;
856
857    if ($hkey == 'date') {
858      if ($PRINT_MODE)
859        $header_value = format_date($headers[$hkey], $RCMAIL->config->get('date_long', 'x'));
860      else
861        $header_value = format_date($headers[$hkey]);
862    }
863    else if ($hkey == 'replyto') {
864      if ($headers['replyto'] != $headers['from'])
865        $header_value = rcmail_address_string($headers['replyto'], null, true, $attrib['addicon']);
866      else
867        continue;
868    }
869    else if (in_array($hkey, array('from', 'to', 'cc', 'bcc')))
870      $header_value = rcmail_address_string($headers[$hkey], null, true, $attrib['addicon']);
871    else if ($hkey == 'subject' && empty($headers[$hkey]))
872      $header_value = rcube_label('nosubject');
873    else
874      $header_value = trim($IMAP->decode_header($headers[$hkey]));
875     
876    $output_headers[$hkey] = array('title' => rcube_label($hkey), 'value' => $header_value, 'raw' => $headers[$hkey]);
877  }
878   
879  $plugin = $RCMAIL->plugins->exec_hook('message_headers_output', array('output' => $output_headers, 'headers' => $MESSAGE->headers));
880 
881  // compose html table
882  $table = new html_table(array('cols' => 2));
883 
884  foreach ($plugin['output'] as $hkey => $row) {
885    $table->add(array('class' => 'header-title'), Q($row['title']));
886    $table->add(array('class' => $hkey, 'width' => "90%"), Q($row['value'], ($hkey == 'subject' ? 'strict' : 'show')));
887  }
888
889  // all headers division
890  $table->add(array('colspan' => 2, 'class' => "more-headers show-headers", 'onclick' => "return ".JS_OBJECT_NAME.".command('load-headers','',this)"), '');
891  $table->add_row(array('id' => "all-headers"));
892  $table->add(array('colspan' => 2, 'class' => "all"), html::div(array('id' => 'headers-source'), ''));
893 
894  $OUTPUT->add_gui_object('all_headers_row', 'all-headers');
895  $OUTPUT->add_gui_object('all_headers_box', 'headers-source');
896
897  return $table->show($attrib);
898  }
899
900
901/**
902 * Handler for the 'messagebody' GUI object
903 *
904 * @param array Named parameters
905 * @return string HTML content showing the message body
906 */
907function rcmail_message_body($attrib)
908  {
909  global $CONFIG, $OUTPUT, $MESSAGE, $IMAP, $REMOTE_OBJECTS;
910
911  if (!is_array($MESSAGE->parts) && empty($MESSAGE->body))
912    return '';
913   
914  if (!$attrib['id'])
915    $attrib['id'] = 'rcmailMsgBody';
916
917  $safe_mode = $MESSAGE->is_safe || intval($_GET['_safe']);
918  $out = '';
919 
920  $header_attrib = array();
921  foreach ($attrib as $attr => $value)
922    if (preg_match('/^headertable([a-z]+)$/i', $attr, $regs))
923      $header_attrib[$regs[1]] = $value;
924
925  if (!empty($MESSAGE->parts))
926    {
927    foreach ($MESSAGE->parts as $i => $part)
928      {
929      if ($part->type == 'headers')
930        $out .= rcmail_message_headers(sizeof($header_attrib) ? $header_attrib : NULL, $part->headers);
931      else if ($part->type == 'content' && $part->size)
932        {
933        if (empty($part->ctype_parameters) || empty($part->ctype_parameters['charset']))
934          $part->ctype_parameters['charset'] = $MESSAGE->headers->charset;
935
936        // fetch part if not available
937        if (!isset($part->body))
938          $part->body = $MESSAGE->get_part_content($part->mime_id);
939
940        $body = rcmail_print_body($part, array('safe' => $safe_mode, 'plain' => !$CONFIG['prefer_html']));
941
942        if ($part->ctype_secondary == 'html')
943          $out .= html::div('message-htmlpart', rcmail_html4inline($body, $attrib['id'], 'div.rcmBody'));
944        else
945          $out .= html::div('message-part', $body);
946        }
947      }
948    }
949  else
950    $out .= html::div('message-part', html::tag('pre', array(),
951      rcmail_plain_body(Q($MESSAGE->body, 'strict', false))));
952
953  $ctype_primary = strtolower($MESSAGE->structure->ctype_primary);
954  $ctype_secondary = strtolower($MESSAGE->structure->ctype_secondary);
955
956  // list images after mail body
957  if ($CONFIG['inline_images']
958      && $ctype_primary == 'multipart'
959      && !empty($MESSAGE->attachments)
960      && !strstr($message_body, '<html'))
961    {
962    foreach ($MESSAGE->attachments as $attach_prop) {
963      if (strpos($attach_prop->mimetype, 'image/') === 0) {
964        $out .= html::tag('hr') . html::p(array('align' => "center"),
965          html::img(array(
966            'src' => $MESSAGE->get_part_url($attach_prop->mime_id),
967            'title' => $attach_prop->filename,
968            'alt' => $attach_prop->filename,
969          )));
970        }
971    }
972  }
973 
974  // tell client that there are blocked remote objects
975  if ($REMOTE_OBJECTS && !$safe_mode)
976    $OUTPUT->set_env('blockedobjects', true);
977
978  return html::div($attrib, $out);
979  }
980
981
982/**
983 * Convert all relative URLs according to a <base> in HTML
984 */
985function rcmail_resolve_base($body)
986{
987  // check for <base href=...>
988  if (preg_match('!(<base.*href=["\']?)([hftps]{3,5}://[a-z0-9/.%-]+)!i', $body, $regs)) {
989    $replacer = new rcube_base_replacer($regs[2]);
990
991    // replace all relative paths
992    $body = preg_replace_callback('/(src|background|href)=(["\']?)([\.\/]+[^"\'\s]+)(\2|\s|>)/Ui', array($replacer, 'callback'), $body);
993    $body = preg_replace_callback('/(url\s*\()(["\']?)([\.\/]+[^"\'\)\s]+)(\2)\)/Ui', array($replacer, 'callback'), $body);
994  }
995
996  return $body;
997}
998
999/**
1000 * modify a HTML message that it can be displayed inside a HTML page
1001 */
1002function rcmail_html4inline($body, $container_id, $body_id='')
1003  {
1004  $last_style_pos = 0;
1005  $body_lc = strtolower($body);
1006 
1007  // find STYLE tags
1008  while (($pos = strpos($body_lc, '<style', $last_style_pos)) && ($pos2 = strpos($body_lc, '</style>', $pos)))
1009    {
1010    $pos = strpos($body_lc, '>', $pos)+1;
1011
1012    // replace all css definitions with #container [def]
1013    $styles = rcmail_mod_css_styles(substr($body, $pos, $pos2-$pos), $container_id.($body_id ? ' '.$body_id : ''));
1014
1015    $body = substr($body, 0, $pos) . $styles . substr($body, $pos2);
1016    $body_lc = strtolower($body);
1017    $last_style_pos = $pos2;
1018    }
1019
1020  // modify HTML links to open a new window if clicked
1021  $GLOBALS['rcmail_html_container_id'] = $container_id;
1022  $body = preg_replace_callback('/<(a|link)\s+([^>]+)>/Ui', 'rcmail_alter_html_link', $body);
1023  unset($GLOBALS['rcmail_html_container_id']);
1024
1025  $out = preg_replace(array(
1026      // add comments arround html and other tags
1027      '/(<!DOCTYPE[^>]*>)/i',
1028      '/(<\?xml[^>]*>)/i',
1029      '/(<\/?html[^>]*>)/i',
1030      '/(<\/?head[^>]*>)/i',
1031      '/(<title[^>]*>.*<\/title>)/Ui',
1032      '/(<\/?meta[^>]*>)/i',
1033      // quote <? of php and xml files that are specified as text/html
1034      '/<\?/',
1035      '/\?>/',
1036      // replace <body> with <div>
1037      '/<body([^>]*)>/i',
1038      '/<\/body>/i',
1039      ),
1040    array(
1041      '<!--\\1-->',
1042      '<!--\\1-->',
1043      '<!--\\1-->',
1044      '<!--\\1-->',
1045      '<!--\\1-->',
1046      '<!--\\1-->',
1047      '&lt;?',
1048      '?&gt;',
1049      '<div class="rcmBody"\\1>',
1050      '</div>',
1051      ),
1052    $body);
1053
1054  // make sure there's 'rcmBody' div, we need it for proper css modification
1055  // its name is hardcoded in rcmail_message_body() also
1056  if (!preg_match('/<div class="rcmBody"/', $out))
1057    $out = '<div class="rcmBody">' . $out . '</div>';
1058
1059  return $out;
1060  }
1061
1062
1063/**
1064 * parse link attributes and set correct target
1065 */
1066function rcmail_alter_html_link($matches)
1067{
1068  global $EMAIL_ADDRESS_PATTERN;
1069 
1070  $tag = $matches[1];
1071  $attrib = parse_attrib_string($matches[2]);
1072  $end = '>';
1073
1074  if ($tag == 'link' && preg_match('/^https?:\/\//i', $attrib['href'])) {
1075    $attrib['href'] = "./bin/modcss.php?u=" . urlencode($attrib['href']) . "&amp;c=" . urlencode($GLOBALS['rcmail_html_container_id']);
1076    $end = ' />';
1077  }
1078  else if (preg_match('/^mailto:'.$EMAIL_ADDRESS_PATTERN.'(\?[^"\'>]+)?/i', $attrib['href'], $mailto)) {
1079    $attrib['href'] = $mailto[0];
1080    $attrib['onclick'] = sprintf(
1081      "return %s.command('compose','%s',this)",
1082      JS_OBJECT_NAME,
1083      JQ($mailto[1].$mailto[2]));
1084  }
1085  else if (!empty($attrib['href']) && $attrib['href'][0] != '#') {
1086    $attrib['target'] = '_blank';
1087  }
1088
1089  return "<$tag" . html::attrib_string($attrib, array('href','name','target','onclick','id','class','style','title','rel','type','media')) . $end;
1090}
1091
1092
1093/**
1094 * decode address string and re-format it as HTML links
1095 */
1096function rcmail_address_string($input, $max=null, $linked=false, $addicon=null)
1097{
1098  global $IMAP, $RCMAIL, $PRINT_MODE, $CONFIG, $OUTPUT, $EMAIL_ADDRESS_PATTERN;
1099  static $got_writable_abook = null;
1100
1101  $a_parts = $IMAP->decode_address_list($input);
1102
1103  if (!sizeof($a_parts))
1104    return $input;
1105
1106  $c = count($a_parts);
1107  $j = 0;
1108  $out = '';
1109
1110  if ($got_writable_abook === null && $books = $RCMAIL->get_address_sources(true)) {
1111    $got_writable_abook = true;
1112  }
1113
1114  foreach ($a_parts as $part) {
1115    $j++;
1116    if ($PRINT_MODE) {
1117      $out .= sprintf('%s &lt;%s&gt;', Q($part['name']), $part['mailto']);
1118    }
1119    else if (check_email($part['mailto'], false)) {
1120      if ($linked) {
1121        $out .= html::a(array(
1122            'href' => 'mailto:'.$part['mailto'],
1123            'onclick' => sprintf("return %s.command('compose','%s',this)", JS_OBJECT_NAME, JQ($part['mailto'])),
1124            'title' => $part['mailto'],
1125            'class' => "rcmContactAddress",
1126          ),
1127        Q($part['name']));
1128      }
1129      else {
1130        $out .= html::span(array('title' => $part['mailto'], 'class' => "rcmContactAddress"), Q($part['name']));
1131      }
1132
1133      if ($addicon && $got_writable_abook) {
1134        $out .= '&nbsp;' . html::a(array(
1135            'href' => "#add",
1136            'onclick' => sprintf("return %s.command('add-contact','%s',this)", JS_OBJECT_NAME, urlencode($part['string'])),
1137            'title' => rcube_label('addtoaddressbook'),
1138          ),
1139          html::img(array(
1140            'src' => $CONFIG['skin_path'] . $addicon,
1141            'alt' => "Add contact",
1142          )));
1143      }
1144    }
1145    else {
1146      if ($part['name'])
1147        $out .= Q($part['name']);
1148      if ($part['mailto'])
1149        $out .= (strlen($out) ? ' ' : '') . sprintf('&lt;%s&gt;', Q($part['mailto']));
1150    }
1151     
1152    if ($c>$j)
1153      $out .= ','.($max ? '&nbsp;' : ' ');
1154       
1155    if ($max && $j==$max && $c>$j) {
1156      $out .= '...';
1157      break;
1158    }
1159  }
1160   
1161  return $out;
1162}
1163
1164
1165/**
1166 * Wrap text to a given number of characters per line
1167 * but respect the mail quotation of replies messages (>)
1168 *
1169 * @param string Text to wrap
1170 * @param int The line width
1171 * @return string The wrapped text
1172 */
1173function rcmail_wrap_quoted($text, $max = 76)
1174{
1175  // Rebuild the message body with a maximum of $max chars, while keeping quoted message.
1176  $lines = preg_split('/\r?\n/', trim($text));
1177  $out = '';
1178
1179  foreach ($lines as $line) {
1180    if (strlen($line) > $max) {
1181      if (preg_match('/^([>\s]+)/', $line, $regs)) {
1182        $length = strlen($regs[0]);
1183        $prefix = substr($line, 0, $length);
1184
1185        // Remove '> ' from the line, then wordwrap() the line
1186        $line = rc_wordwrap(substr($line, $length), $max - $length);
1187
1188        // Rebuild the line with '> ' at the beginning of each 'subline'
1189        $newline = '';
1190        foreach (explode("\n", $line) as $l) {
1191          $newline .= $prefix . $l . "\n";
1192        }
1193
1194        // Remove the righest newline char
1195        $line = rtrim($newline);
1196      }
1197      else {
1198        $line = rc_wordwrap($line, $max);
1199      }
1200    }
1201
1202    // Append the line
1203    $out .= $line . "\n";
1204  }
1205 
1206  return $out;
1207}
1208
1209
1210function rcmail_draftinfo_encode($p)
1211{
1212  $parts = array();
1213  foreach ($p as $key => $val)
1214    $parts[] = $key . '=' . ($key == 'folder' ? base64_encode($val) : $val);
1215 
1216  return join('; ', $parts);
1217}
1218
1219
1220function rcmail_draftinfo_decode($str)
1221{
1222  $info = array();
1223  foreach (preg_split('/;\s+/', $str) as $part) {
1224    list($key, $val) = explode('=', $part, 2);
1225    if ($key == 'folder')
1226      $val = base64_decode($val);
1227    $info[$key] = $val;
1228  }
1229 
1230  return $info;
1231}
1232
1233
1234function rcmail_message_part_controls()
1235  {
1236  global $MESSAGE;
1237 
1238  $part = asciiwords(get_input_value('_part', RCUBE_INPUT_GPC));
1239  if (!is_object($MESSAGE) || !is_array($MESSAGE->parts) || !($_GET['_uid'] && $_GET['_part']) || !$MESSAGE->mime_parts[$part])
1240    return '';
1241   
1242  $part = $MESSAGE->mime_parts[$part];
1243  $table = new html_table(array('cols' => 3));
1244 
1245  if (!empty($part->filename)) {
1246    $table->add('title', Q(rcube_label('filename')));
1247    $table->add(null, Q($part->filename));
1248    $table->add(null, '[' . html::a('?'.str_replace('_frame=', '_download=', $_SERVER['QUERY_STRING']), Q(rcube_label('download'))) . ']');
1249  }
1250 
1251  if (!empty($part->size)) {
1252    $table->add('title', Q(rcube_label('filesize')));
1253    $table->add(null, Q(show_bytes($part->size)));
1254  }
1255 
1256  return $table->show($attrib);
1257  }
1258
1259
1260
1261function rcmail_message_part_frame($attrib)
1262  {
1263  global $MESSAGE;
1264 
1265  $part = $MESSAGE->mime_parts[asciiwords(get_input_value('_part', RCUBE_INPUT_GPC))];
1266  $ctype_primary = strtolower($part->ctype_primary);
1267
1268  $attrib['src'] = './?' . str_replace('_frame=', ($ctype_primary=='text' ? '_show=' : '_preload='), $_SERVER['QUERY_STRING']);
1269
1270  return html::iframe($attrib);
1271  }
1272
1273
1274/**
1275 * clear message composing settings
1276 */
1277function rcmail_compose_cleanup()
1278  {
1279  if (!isset($_SESSION['compose']))
1280    return;
1281
1282  $rcmail = rcmail::get_instance();
1283  $rcmail->plugins->exec_hook('cleanup_attachments',array());
1284  $rcmail->session->remove('compose');
1285  }
1286 
1287
1288/**
1289 * Send the given message using the configured method
1290 *
1291 * @param object $message    Reference to Mail_MIME object
1292 * @param string $from       Sender address string
1293 * @param array  $mailto     Array of recipient address strings
1294 * @param array  $smtp_error SMTP error array (reference)
1295 * @param string $body_file  Location of file with saved message body (reference)
1296 *
1297 * @return boolean Send status.
1298 */
1299function rcmail_deliver_message(&$message, $from, $mailto, &$smtp_error, &$body_file)
1300{
1301  global $CONFIG, $RCMAIL;
1302
1303  $headers = $message->headers();
1304
1305  // send thru SMTP server using custom SMTP library
1306  if ($CONFIG['smtp_server']) {
1307    // generate list of recipients
1308    $a_recipients = array($mailto);
1309 
1310    if (strlen($headers['Cc']))
1311      $a_recipients[] = $headers['Cc'];
1312    if (strlen($headers['Bcc']))
1313      $a_recipients[] = $headers['Bcc'];
1314 
1315    // clean Bcc from header for recipients
1316    $send_headers = $headers;
1317    unset($send_headers['Bcc']);
1318    // here too, it because txtHeaders() below use $message->_headers not only $send_headers
1319    unset($message->_headers['Bcc']);
1320
1321    $smtp_headers = $message->txtHeaders($send_headers, true);
1322
1323    if ($message->getParam('delay_file_io')) {
1324      // use common temp dir
1325      $temp_dir = $RCMAIL->config->get('temp_dir');
1326      $body_file = tempnam($temp_dir, 'rcmMsg');
1327      if (PEAR::isError($mime_result = $message->saveMessageBody($body_file))) {
1328        raise_error(array('code' => 600, 'type' => 'php',
1329            'file' => __FILE__, 'line' => __LINE__,
1330            'message' => "Could not create message: ".$mime_result->getMessage()),
1331            TRUE, FALSE);
1332        return false;
1333      }
1334      $msg_body = fopen($body_file, 'r');
1335    } else {
1336      $msg_body = $message->get();
1337    }
1338
1339    // send message
1340    if (!is_object($RCMAIL->smtp))
1341      $RCMAIL->smtp_init(true);
1342     
1343    $sent = $RCMAIL->smtp->send_mail($from, $a_recipients, $smtp_headers, $msg_body);
1344    $smtp_response = $RCMAIL->smtp->get_response();
1345    $smtp_error = $RCMAIL->smtp->get_error();
1346
1347    if (is_resource($msg_body)) {
1348      fclose($msg_body);
1349    }
1350
1351    // log error
1352    if (!$sent)
1353      raise_error(array('code' => 800, 'type' => 'smtp', 'line' => __LINE__, 'file' => __FILE__,
1354                        'message' => "SMTP error: ".join("\n", $smtp_response)), TRUE, FALSE);
1355  }
1356  // send mail using PHP's mail() function
1357  else {
1358    // unset some headers because they will be added by the mail() function
1359    $headers_enc = $message->headers($headers);
1360    $headers_php = $message->_headers;
1361    unset($headers_php['To'], $headers_php['Subject']);
1362   
1363    // reset stored headers and overwrite
1364    $message->_headers = array();
1365    $header_str = $message->txtHeaders($headers_php);
1366   
1367    // #1485779
1368    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1369      if (preg_match_all('/<([^@]+@[^>]+)>/', $headers_enc['To'], $m)) {
1370        $headers_enc['To'] = implode(', ', $m[1]);
1371        }
1372      }
1373   
1374    $msg_body = $message->get();
1375
1376    if (PEAR::isError($msg_body))
1377      raise_error(array('code' => 600, 'type' => 'php',
1378            'file' => __FILE__, 'line' => __LINE__,
1379            'message' => "Could not create message: ".$msg_body->getMessage()),
1380            TRUE, FALSE);
1381    else if (ini_get('safe_mode'))
1382      $sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str);
1383    else
1384      $sent = mail($headers_enc['To'], $headers_enc['Subject'], $msg_body, $header_str, "-f$from");
1385  }
1386 
1387  if ($sent) {
1388    $RCMAIL->plugins->exec_hook('message_sent', array('headers' => $headers, 'body' => $msg_body));
1389   
1390    // remove MDN headers after sending
1391    unset($headers['Return-Receipt-To'], $headers['Disposition-Notification-To']);
1392   
1393    if ($CONFIG['smtp_log']) {
1394      write_log('sendmail', sprintf("User %s [%s]; Message for %s; %s",
1395        $RCMAIL->user->get_username(),
1396        $_SERVER['REMOTE_ADDR'],
1397        $mailto,
1398        !empty($smtp_response) ? join('; ', $smtp_response) : ''));
1399    }
1400  }
1401
1402  $message->_headers = array();
1403  $message->headers($headers);
1404 
1405  return $sent;
1406}
1407
1408
1409function rcmail_send_mdn($uid, &$smtp_error)
1410{
1411  global $RCMAIL, $IMAP;
1412
1413  $message = new rcube_message($uid);
1414 
1415  if ($message->headers->mdn_to && !$message->headers->mdn_sent &&
1416    ($IMAP->check_permflag('MDNSENT') || $IMAP->check_permflag('*')))
1417  {
1418    $identity = $RCMAIL->user->get_identity();
1419    $sender = format_email_recipient($identity['email'], $identity['name']);
1420    $recipient = array_shift($IMAP->decode_address_list($message->headers->mdn_to));
1421    $mailto = $recipient['mailto'];
1422
1423    $compose = new Mail_mime($RCMAIL->config->header_delimiter());
1424
1425    $compose->setParam('text_encoding', 'quoted-printable');
1426    $compose->setParam('html_encoding', 'quoted-printable');
1427    $compose->setParam('head_encoding', 'quoted-printable');
1428    $compose->setParam('head_charset', RCMAIL_CHARSET);
1429    $compose->setParam('html_charset', RCMAIL_CHARSET);
1430    $compose->setParam('text_charset', RCMAIL_CHARSET);
1431   
1432    // compose headers array
1433    $headers = array(
1434      'Date' => date('r'),
1435      'From' => $sender,
1436      'To'   => $message->headers->mdn_to,
1437      'Subject' => rcube_label('receiptread') . ': ' . $message->subject,
1438      'Message-ID' => sprintf('<%s@%s>', md5(uniqid('rcmail'.mt_rand(),true)), $RCMAIL->config->mail_domain($_SESSION['imap_host'])),
1439      'X-Sender' => $identity['email'],
1440      'Content-Type' => 'multipart/report; report-type=disposition-notification',
1441    );
1442   
1443    if ($agent = $RCMAIL->config->get('useragent'))
1444      $headers['User-Agent'] = $agent;
1445
1446    $body = rcube_label("yourmessage") . "\r\n\r\n" .
1447      "\t" . rcube_label("to") . ': ' . rcube_imap::decode_mime_string($message->headers->to, $message->headers->charset) . "\r\n" .
1448      "\t" . rcube_label("subject") . ': ' . $message->subject . "\r\n" .
1449      "\t" . rcube_label("sent") . ': ' . format_date($message->headers->date, $RCMAIL->config->get('date_long')) . "\r\n" .
1450      "\r\n" . rcube_label("receiptnote") . "\r\n";
1451   
1452    $ua = $RCMAIL->config->get('useragent', "RoundCube Webmail (Version ".RCMAIL_VERSION.")");
1453    $report = "Reporting-UA: $ua\r\n";
1454   
1455    if ($message->headers->to)
1456        $report .= "Original-Recipient: {$message->headers->to}\r\n";
1457   
1458    $report .= "Final-Recipient: rfc822; {$identity['email']}\r\n" .
1459               "Original-Message-ID: {$message->headers->messageID}\r\n" .
1460               "Disposition: manual-action/MDN-sent-manually; displayed\r\n";
1461   
1462    $compose->headers($headers);
1463    $compose->setTXTBody(rc_wordwrap($body, 75, "\r\n"));
1464    $compose->addAttachment($report, 'message/disposition-notification', 'MDNPart2.txt', false, '7bit', 'inline');
1465
1466    $sent = rcmail_deliver_message($compose, $identity['email'], $mailto, $smtp_error, $body_file);
1467
1468    if ($sent)
1469    {
1470      $IMAP->set_flag($message->uid, 'MDNSENT');
1471      return true;
1472    }
1473  }
1474 
1475  return false;
1476}
1477
1478function rcmail_search_filter($attrib)
1479{
1480  global $OUTPUT, $CONFIG;
1481
1482  if (!strlen($attrib['id']))
1483    $attrib['id'] = 'rcmlistfilter';
1484
1485  $attrib['onchange'] = JS_OBJECT_NAME.'.filter_mailbox(this.value)';
1486 
1487  /*
1488    RFC3501 (6.4.4): 'ALL', 'RECENT',
1489    'ANSWERED', 'DELETED', 'FLAGGED', 'SEEN',
1490    'UNANSWERED', 'UNDELETED', 'UNFLAGGED', 'UNSEEN',
1491    'NEW', // = (RECENT UNSEEN)
1492    'OLD' // = NOT RECENT
1493  */
1494
1495  $select_filter = new html_select($attrib);
1496  $select_filter->add(rcube_label('all'), 'ALL');
1497  $select_filter->add(rcube_label('unread'), 'UNSEEN');
1498  $select_filter->add(rcube_label('flagged'), 'FLAGGED');
1499  $select_filter->add(rcube_label('unanswered'), 'UNANSWERED');
1500  if (!$CONFIG['skip_deleted'])
1501    $select_filter->add(rcube_label('deleted'), 'DELETED');
1502
1503  $out = $select_filter->show($_SESSION['search_filter']);
1504
1505  $OUTPUT->add_gui_object('search_filter', $attrib['id']);
1506
1507  return $out;                                                                         
1508}
1509
1510
1511// register UI objects
1512$OUTPUT->add_handlers(array(
1513  'mailboxlist' => 'rcmail_mailbox_list',
1514  'messages' => 'rcmail_message_list',
1515  'messagecountdisplay' => 'rcmail_messagecount_display',
1516  'quotadisplay' => 'rcmail_quota_display',
1517  'mailboxname' => 'rcmail_mailbox_name_display',
1518  'messageheaders' => 'rcmail_message_headers',
1519  'messagebody' => 'rcmail_message_body',
1520  'messagecontentframe' => 'rcmail_messagecontent_frame',
1521  'messagepartframe' => 'rcmail_message_part_frame',
1522  'messagepartcontrols' => 'rcmail_message_part_controls',
1523  'searchfilter' => 'rcmail_search_filter',
1524  'searchform' => array($OUTPUT, 'search_form'),
1525));
1526
1527?>
Note: See TracBrowser for help on using the repository browser.