4 +-----------------------------------------------------------------------+
5 | program/steps/mail/func.inc |
7 | This file is part of the Roundcube Webmail client |
8 | Copyright (C) 2005-2010, Roundcube Dev. - Switzerland |
9 | Licensed under the GNU GPL |
12 | Provide webmail functionality and GUI objects |
14 +-----------------------------------------------------------------------+
15 | Author: Thomas Bruederli <roundcube@gmail.com> |
16 +-----------------------------------------------------------------------+
18 $Id: func.inc 4830 2011-06-02 12:36:32Z alec $
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(
26 '*' => array('subject'=>1, 'from'=>1),
27 $SENT_MBOX => array('subject'=>1, 'to'=>1),
28 $DRAFTS_MBOX => array('subject'=>1, 'to'=>1)
31 // actions that do not require imap connection here
32 $NOIMAP_ACTIONS = array('addcontact', 'autocomplete', 'upload', 'display-attachment', 'remove-attachment', 'get');
34 // always instantiate imap object (but not yet connect to server)
37 // log in to imap server
38 if (!in_array($RCMAIL->action, $NOIMAP_ACTIONS) && !$RCMAIL->imap_connect()) {
39 $RCMAIL->kill_session();
41 if ($OUTPUT->ajax_call)
42 $OUTPUT->redirect(array(), 2000);
44 $OUTPUT->set_env('task', 'login');
45 $OUTPUT->send('login');
48 // set imap properties and session vars
49 if (strlen(trim($mbox = get_input_value('_mbox', RCUBE_INPUT_GPC, true))))
50 $IMAP->set_mailbox(($_SESSION['mbox'] = $mbox));
52 $_SESSION['mbox'] = $IMAP->get_mailbox_name();
54 if (!empty($_GET['_page']))
55 $IMAP->set_page(($_SESSION['page'] = intval($_GET['_page'])));
57 // set default sort col/order to session
58 if (!isset($_SESSION['sort_col']))
59 $_SESSION['sort_col'] = !empty($CONFIG['message_sort_col']) ? $CONFIG['message_sort_col'] : '';
60 if (!isset($_SESSION['sort_order']))
61 $_SESSION['sort_order'] = strtoupper($CONFIG['message_sort_order']) == 'ASC' ? 'ASC' : 'DESC';
64 $a_threading = $RCMAIL->config->get('message_threading', array());
65 if (isset($_GET['_threads'])) {
66 if ($_GET['_threads'])
67 $a_threading[$_SESSION['mbox']] = true;
69 unset($a_threading[$_SESSION['mbox']]);
70 $RCMAIL->user->save_prefs(array('message_threading' => $a_threading));
72 $IMAP->set_threading($a_threading[$_SESSION['mbox']]);
74 // set message set for search result
75 if (!empty($_REQUEST['_search']) && isset($_SESSION['search'])
76 && $_SESSION['search_request'] == $_REQUEST['_search']
78 $IMAP->set_search_set($_SESSION['search']);
79 $OUTPUT->set_env('search_request', $_REQUEST['_search']);
80 $OUTPUT->set_env('search_text', $_SESSION['last_text_search']);
83 // set main env variables, labels and page title
84 if (empty($RCMAIL->action) || $RCMAIL->action == 'list') {
85 $mbox_name = $IMAP->get_mailbox_name();
87 if (empty($RCMAIL->action)) {
88 // initialize searching result if search_filter is used
89 if ($_SESSION['search_filter'] && $_SESSION['search_filter'] != 'ALL') {
90 $search_request = md5($mbox_name.$_SESSION['search_filter']);
92 $IMAP->search($mbox_name, $_SESSION['search_filter'], RCMAIL_CHARSET, $_SESSION['sort_col']);
93 $_SESSION['search'] = $IMAP->get_search_set();
94 $_SESSION['search_request'] = $search_request;
95 $OUTPUT->set_env('search_request', $search_request);
98 $search_mods = $RCMAIL->config->get('search_mods', $SEARCH_MODS_DEFAULT);
99 $OUTPUT->set_env('search_mods', $search_mods);
102 // set current mailbox and some other vars in client environment
103 $OUTPUT->set_env('mailbox', $mbox_name);
104 $OUTPUT->set_env('pagesize', $IMAP->page_size);
105 $OUTPUT->set_env('quota', $IMAP->get_capability('QUOTA'));
106 $OUTPUT->set_env('delimiter', $IMAP->get_hierarchy_delimiter());
107 $OUTPUT->set_env('threading', (bool) $IMAP->threading);
108 $OUTPUT->set_env('threads', $IMAP->threading || $IMAP->get_capability('THREAD'));
110 if ($CONFIG['flag_for_deletion'])
111 $OUTPUT->set_env('flag_for_deletion', true);
112 if ($CONFIG['read_when_deleted'])
113 $OUTPUT->set_env('read_when_deleted', true);
114 if ($CONFIG['skip_deleted'])
115 $OUTPUT->set_env('skip_deleted', true);
116 if ($CONFIG['display_next'])
117 $OUTPUT->set_env('display_next', true);
119 $OUTPUT->set_env('preview_pane_mark_read', $RCMAIL->config->get('preview_pane_mark_read', 0));
121 if ($CONFIG['trash_mbox'])
122 $OUTPUT->set_env('trash_mailbox', $CONFIG['trash_mbox']);
123 if ($CONFIG['drafts_mbox'])
124 $OUTPUT->set_env('drafts_mailbox', $CONFIG['drafts_mbox']);
125 if ($CONFIG['junk_mbox'])
126 $OUTPUT->set_env('junk_mailbox', $CONFIG['junk_mbox']);
128 if (!$OUTPUT->ajax_call)
129 $OUTPUT->add_label('checkingmail', 'deletemessage', 'movemessagetotrash',
130 'movingmessage', 'copyingmessage', 'deletingmessage', 'markingmessage',
131 'copy', 'move', 'quota');
133 $OUTPUT->set_pagetitle(rcmail_localize_foldername($mbox_name));
138 * return the message list as HTML table
140 function rcmail_message_list($attrib)
142 global $IMAP, $CONFIG, $OUTPUT;
144 // add some labels to client
145 $OUTPUT->add_label('from', 'to');
147 // add id to message list table if not specified
148 if (!strlen($attrib['id']))
149 $attrib['id'] = 'rcubemessagelist';
151 // define list of cols to be displayed based on parameter or config
152 if (empty($attrib['columns'])) {
153 $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
154 $OUTPUT->set_env('col_movable', !in_array('list_cols', (array)$CONFIG['dont_override']));
157 $a_show_cols = preg_split('/[\s,;]+/', strip_quotes($attrib['columns']));
158 $attrib['columns'] = $a_show_cols;
161 // save some variables for use in ajax list
162 $_SESSION['list_attrib'] = $attrib;
164 $mbox = $IMAP->get_mailbox_name();
165 $delim = $IMAP->get_hierarchy_delimiter();
167 // show 'to' instead of 'from' in sent/draft messages
168 if ((strpos($mbox.$delim, $CONFIG['sent_mbox'].$delim)===0 || strpos($mbox.$delim, $CONFIG['drafts_mbox'].$delim)===0)
169 && (($f = array_search('from', $a_show_cols)) !== false) && array_search('to', $a_show_cols) === false)
170 $a_show_cols[$f] = 'to';
172 // make sure 'threads' and 'subject' columns are present
173 if (!in_array('subject', $a_show_cols))
174 array_unshift($a_show_cols, 'subject');
175 if (!in_array('threads', $a_show_cols))
176 array_unshift($a_show_cols, 'threads');
178 $skin_path = $_SESSION['skin_path'] = $CONFIG['skin_path'];
181 $OUTPUT->add_gui_object('messagelist', $attrib['id']);
182 $OUTPUT->set_env('autoexpand_threads', intval($CONFIG['autoexpand_threads']));
183 $OUTPUT->set_env('sort_col', $_SESSION['sort_col']);
184 $OUTPUT->set_env('sort_order', $_SESSION['sort_order']);
185 $OUTPUT->set_env('messages', array());
186 $OUTPUT->set_env('coltypes', $a_show_cols);
188 $OUTPUT->include_script('list.js');
191 foreach (rcmail_message_list_head($attrib, $a_show_cols) as $cell)
192 $thead .= html::tag('td', array('class' => $cell['className'], 'id' => $cell['id']), $cell['html']);
194 return html::tag('table',
196 html::tag('thead', null, html::tag('tr', null, $thead)) .
197 html::tag('tbody', null, ''),
198 array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
203 * return javascript commands to add rows to the message list
205 function rcmail_js_message_list($a_headers, $insert_top=FALSE, $a_show_cols=null)
207 global $CONFIG, $IMAP, $RCMAIL, $OUTPUT;
209 if (empty($a_show_cols)) {
210 if (!empty($_SESSION['list_attrib']['columns']))
211 $a_show_cols = $_SESSION['list_attrib']['columns'];
213 $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
216 if (!is_array($a_show_cols))
217 $a_show_cols = preg_split('/[\s,;]+/', strip_quotes($a_show_cols));
218 $head_replace = true;
221 $mbox = $IMAP->get_mailbox_name();
222 $delim = $IMAP->get_hierarchy_delimiter();
224 // make sure 'threads' and 'subject' columns are present
225 if (!in_array('subject', $a_show_cols))
226 array_unshift($a_show_cols, 'subject');
227 if (!in_array('threads', $a_show_cols))
228 array_unshift($a_show_cols, 'threads');
230 $_SESSION['list_attrib']['columns'] = $a_show_cols;
232 // show 'to' instead of 'from' in sent/draft messages
233 if ((strpos($mbox.$delim, $CONFIG['sent_mbox'].$delim)===0 || strpos($mbox.$delim, $CONFIG['drafts_mbox'].$delim)===0)
234 && (($f = array_search('from', $a_show_cols)) !== false) && array_search('to', $a_show_cols) === false)
235 $a_show_cols[$f] = 'to';
237 // Make sure there are no duplicated columns (#1486999)
238 $a_show_cols = array_unique($a_show_cols);
240 // Plugins may set header's list_cols/list_flags and other rcube_mail_header variables
242 $plugin = $RCMAIL->plugins->exec_hook('messages_list',
243 array('messages' => $a_headers, 'cols' => $a_show_cols));
245 $a_show_cols = $plugin['cols'];
246 $a_headers = $plugin['messages'];
248 $thead = $head_replace ? rcmail_message_list_head($_SESSION['list_attrib'], $a_show_cols) : NULL;
250 $OUTPUT->command('set_message_coltypes', $a_show_cols, $thead);
252 if (empty($a_headers))
255 // remove 'threads', 'attachment', 'flag', 'status' columns, we don't need them here
256 foreach (array('threads', 'attachment', 'flag', 'status') as $col) {
257 if (($key = array_search($col, $a_show_cols)) !== FALSE)
258 unset($a_show_cols[$key]);
261 // loop through message headers
262 foreach ($a_headers as $n => $header) {
266 $a_msg_cols = array();
267 $a_msg_flags = array();
269 $IMAP->set_charset(!empty($header->charset) ? $header->charset : $CONFIG['default_charset']);
271 // format each col; similar as in rcmail_message_list()
272 foreach ($a_show_cols as $col) {
273 if (in_array($col, array('from', 'to', 'cc', 'replyto')))
274 $cont = Q(rcmail_address_string($header->$col, 3), 'show');
275 else if ($col=='subject') {
276 $cont = trim($IMAP->decode_header($header->$col));
277 if (!$cont) $cont = rcube_label('nosubject');
280 else if ($col=='size')
281 $cont = show_bytes($header->$col);
282 else if ($col=='date')
283 $cont = format_date($header->date);
285 $cont = Q($header->$col);
287 $a_msg_cols[$col] = $cont;
291 $a_msg_flags['depth'] = $header->depth;
292 else if ($header->has_children)
293 $roots[] = $header->uid;
294 if ($header->parent_uid)
295 $a_msg_flags['parent_uid'] = $header->parent_uid;
296 if ($header->has_children)
297 $a_msg_flags['has_children'] = $header->has_children;
298 if ($header->unread_children)
299 $a_msg_flags['unread_children'] = $header->unread_children;
300 if ($header->deleted)
301 $a_msg_flags['deleted'] = 1;
303 $a_msg_flags['unread'] = 1;
304 if ($header->answered)
305 $a_msg_flags['replied'] = 1;
306 if ($header->forwarded)
307 $a_msg_flags['forwarded'] = 1;
308 if ($header->flagged)
309 $a_msg_flags['flagged'] = 1;
310 if ($header->others['list-post'])
311 $a_msg_flags['ml'] = 1;
313 $a_msg_flags['ctype'] = Q($header->ctype);
314 $a_msg_flags['mbox'] = $mbox;
316 // merge with plugin result
317 if (!empty($header->list_flags) && is_array($header->list_flags))
318 $a_msg_flags = array_merge($a_msg_flags, $header->list_flags);
319 if (!empty($header->list_cols) && is_array($header->list_cols))
320 $a_msg_cols = array_merge($a_msg_cols, $header->list_cols);
322 $OUTPUT->command('add_message_row',
329 if ($IMAP->threading) {
330 $OUTPUT->command('init_threads', (array) $roots);
336 * Creates <THEAD> for message list table
338 function rcmail_message_list_head($attrib, $a_show_cols)
342 $skin_path = $_SESSION['skin_path'];
343 $image_tag = html::img(array('src' => "%s%s", 'alt' => "%s"));
345 // check to see if we have some settings for sorting
346 $sort_col = $_SESSION['sort_col'];
347 $sort_order = $_SESSION['sort_order'];
349 // define sortable columns
350 $a_sort_cols = array('subject', 'date', 'from', 'to', 'size', 'cc');
352 if (!empty($attrib['optionsmenuicon'])) {
353 $onclick = 'return ' . JS_OBJECT_NAME . ".command('menu-open', 'messagelistmenu')";
354 if ($attrib['optionsmenuicon'] === true || $attrib['optionsmenuicon'] == 'true')
355 $list_menu = html::div(array('onclick' => $onclick, 'class' => 'listmenu',
356 'id' => 'listmenulink', 'title' => rcube_label('listoptions')));
358 $list_menu = html::a(array('href' => '#', 'onclick' => $onclick),
359 html::img(array('src' => $skin_path . $attrib['optionsmenuicon'],
360 'id' => 'listmenulink', 'title' => rcube_label('listoptions')))
368 foreach ($a_show_cols as $col) {
372 $col_name = '<span class="flagged"> </span>';
376 $col_name = '<span class="' . $col .'"> </span>';
379 $col_name = $list_menu;
382 $col_name = Q(rcube_label($col));
386 if (in_array($col, $a_sort_cols))
387 $col_name = html::a(array('href'=>"./#sort", 'onclick' => 'return '.JS_OBJECT_NAME.".command('sort','".$col."',this)", 'title' => rcube_label('sortby')), $col_name);
389 $sort_class = $col == $sort_col ? " sorted$sort_order" : '';
390 $class_name = $col.$sort_class;
392 // put it all together
393 $cells[] = array('className' => $class_name, 'id' => "rcm$col", 'html' => $col_name);
401 * return an HTML iframe for loading mail content
403 function rcmail_messagecontent_frame($attrib)
405 global $OUTPUT, $RCMAIL;
407 if (empty($attrib['id']))
408 $attrib['id'] = 'rcmailcontentwindow';
410 $attrib['name'] = $attrib['id'];
412 if ($RCMAIL->config->get('preview_pane'))
413 $OUTPUT->set_env('contentframe', $attrib['id']);
414 $OUTPUT->set_env('blankpage', $attrib['src'] ? $OUTPUT->abs_url($attrib['src']) : 'program/blank.gif');
416 return html::iframe($attrib);
420 function rcmail_messagecount_display($attrib)
425 $attrib['id'] = 'rcmcountdisplay';
427 $RCMAIL->output->add_gui_object('countdisplay', $attrib['id']);
429 $content = $RCMAIL->action != 'show' ? rcmail_get_messagecount_text() : rcube_label('loading');
431 return html::span($attrib, $content);
435 function rcmail_get_messagecount_text($count=NULL, $page=NULL)
437 global $RCMAIL, $IMAP;
440 $page = $IMAP->list_page;
442 $start_msg = ($page-1) * $IMAP->page_size + 1;
446 else if ($RCMAIL->action)
447 $max = $IMAP->messagecount(NULL, $IMAP->threading ? 'THREADS' : 'ALL');
450 $out = rcube_label('mailboxempty');
452 $out = rcube_label(array('name' => $IMAP->threading ? 'threadsfromto' : 'messagesfromto',
453 'vars' => array('from' => $start_msg,
454 'to' => min($max, $start_msg + $IMAP->page_size - 1),
461 function rcmail_mailbox_name_display($attrib)
466 $attrib['id'] = 'rcmmailboxname';
468 $RCMAIL->output->add_gui_object('mailboxname', $attrib['id']);
470 return html::span($attrib, rcmail_get_mailbox_name_text());
474 function rcmail_get_mailbox_name_text()
477 return rcmail_localize_foldername($RCMAIL->imap->get_mailbox_name());
481 function rcmail_send_unread_count($mbox_name, $force=false, $count=null)
485 $old_unseen = rcmail_get_unseen_count($mbox_name);
488 $unseen = $RCMAIL->imap->messagecount($mbox_name, 'UNSEEN', $force);
492 if ($unseen != $old_unseen || ($mbox_name == 'INBOX'))
493 $RCMAIL->output->command('set_unread_count', $mbox_name, $unseen, ($mbox_name == 'INBOX'));
495 rcmail_set_unseen_count($mbox_name, $unseen);
501 function rcmail_set_unseen_count($mbox_name, $count)
503 // @TODO: this data is doubled (session and cache tables) if caching is enabled
505 // Make sure we have an array here (#1487066)
506 if (!is_array($_SESSION['unseen_count']))
507 $_SESSION['unseen_count'] = array();
509 $_SESSION['unseen_count'][$mbox_name] = $count;
513 function rcmail_get_unseen_count($mbox_name)
515 if (is_array($_SESSION['unseen_count']) && array_key_exists($mbox_name, $_SESSION['unseen_count']))
516 return $_SESSION['unseen_count'][$mbox_name];
523 * Sets message is_safe flag according to 'show_images' option value
525 * @param object rcube_message Message
527 function rcmail_check_safe(&$message)
531 $show_images = $RCMAIL->config->get('show_images');
532 if (!$message->is_safe
533 && !empty($show_images)
534 && $message->has_html_part())
536 switch($show_images) {
537 case '1': // known senders only
538 $CONTACTS = new rcube_contacts($RCMAIL->db, $_SESSION['user_id']);
539 if ($CONTACTS->search('email', $message->sender['mailto'], true, false)->count) {
540 $message->set_safe(true);
544 $message->set_safe(true);
552 * Cleans up the given message HTML Body (for displaying)
555 * @param array Display parameters
556 * @param array CID map replaces (inline images)
557 * @return string Clean HTML
559 function rcmail_wash_html($html, $p = array(), $cid_replaces)
561 global $REMOTE_OBJECTS;
563 $p += array('safe' => false, 'inline_html' => true);
565 // special replacements (not properly handled by washtml class)
566 $html_search = array(
567 '/(<\/nobr>)(\s+)(<nobr>)/i', // space(s) between <NOBR>
568 '/<title[^>]*>.*<\/title>/i', // PHP bug #32547 workaround: remove title tag
569 '/^(\0\0\xFE\xFF|\xFF\xFE\0\0|\xFE\xFF|\xFF\xFE|\xEF\xBB\xBF)/', // byte-order mark (only outlook?)
570 '/<html\s[^>]+>/i', // washtml/DOMDocument cannot handle xml namespaces
572 $html_replace = array(
573 '\\1'.' '.'\\3',
578 $html = preg_replace($html_search, $html_replace, trim($html));
580 // PCRE errors handling (#1486856), should we use something like for every preg_* use?
581 if ($html === null && ($preg_error = preg_last_error()) != PREG_NO_ERROR) {
582 $errstr = "Could not clean up HTML message! PCRE Error: $preg_error.";
584 if ($preg_error == PREG_BACKTRACK_LIMIT_ERROR)
585 $errstr .= " Consider raising pcre.backtrack_limit!";
586 if ($preg_error == PREG_RECURSION_LIMIT_ERROR)
587 $errstr .= " Consider raising pcre.recursion_limit!";
589 raise_error(array('code' => 600, 'type' => 'php',
590 'line' => __LINE__, 'file' => __FILE__,
591 'message' => $errstr), true, false);
595 // fix (unknown/malformed) HTML tags before "wash"
596 $html = preg_replace_callback('/(<[\/]*)([^\s>]+)/', 'rcmail_html_tag_callback', $html);
598 // charset was converted to UTF-8 in rcube_imap::get_message_part(),
599 // -> change charset specification in HTML accordingly
600 $charset_pattern = '(<meta\s+[^>]*content=)[\'"]?(\w+\/\w+;\s*charset=)([a-z0-9-_]+[\'"]?)';
601 if (preg_match("/$charset_pattern/Ui", $html)) {
602 $html = preg_replace("/$charset_pattern/i", '\\1"\\2'.RCMAIL_CHARSET.'"', $html);
605 // add meta content-type to malformed messages, washtml cannot work without that
606 if (!preg_match('/<head[^>]*>(.*)<\/head>/Uims', $html))
607 $html = '<head></head>'. $html;
608 $html = substr_replace($html, '<meta http-equiv="Content-Type" content="text/html; charset='.RCMAIL_CHARSET.'" />', intval(stripos($html, '<head>')+6), 0);
611 // turn relative into absolute urls
612 $html = rcmail_resolve_base($html);
614 // clean HTML with washhtml by Frederic Motte
616 'show_washed' => false,
617 'allow_remote' => $p['safe'],
618 'blocked_src' => "./program/blocked.gif",
619 'charset' => RCMAIL_CHARSET,
620 'cid_map' => $cid_replaces,
621 'html_elements' => array('body'),
624 if (!$p['inline_html']) {
625 $wash_opts['html_elements'] = array('html','head','title','body');
628 $wash_opts['html_elements'][] = 'link';
629 $wash_opts['html_attribs'] = array('rel','type');
632 // overwrite washer options with options from plugins
633 if (isset($p['html_elements']))
634 $wash_opts['html_elements'] = $p['html_elements'];
635 if (isset($p['html_attribs']))
636 $wash_opts['html_attribs'] = $p['html_attribs'];
638 // initialize HTML washer
639 $washer = new washtml($wash_opts);
641 if (!$p['skip_washer_form_callback'])
642 $washer->add_callback('form', 'rcmail_washtml_callback');
644 // allow CSS styles, will be sanitized by rcmail_washtml_callback()
645 if (!$p['skip_washer_style_callback'])
646 $washer->add_callback('style', 'rcmail_washtml_callback');
648 $html = $washer->wash($html);
649 $REMOTE_OBJECTS = $washer->extlinks;
656 * Convert the given message part to proper HTML
657 * which can be displayed the message view
659 * @param object rcube_message_part Message part
660 * @param array Display parameters array
661 * @return string Formatted HTML string
663 function rcmail_print_body($part, $p = array())
667 // trigger plugin hook
668 $data = $RCMAIL->plugins->exec_hook('message_part_before',
669 array('type' => $part->ctype_secondary, 'body' => $part->body, 'id' => $part->mime_id)
670 + $p + array('safe' => false, 'plain' => false, 'inline_html' => true));
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';
679 else if ($data['type'] == 'html') {
680 $body = rcmail_wash_html($data['body'], $data, $part->replaces);
681 $part->ctype_secondary = $data['type'];
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');
692 $part->ctype_secondary = $data['type'] = 'plain';
695 // free some memory (hopefully)
696 unset($data['body']);
698 // plaintext postprocessing
699 if ($part->ctype_secondary == 'plain')
700 $body = rcmail_plain_body($body, $part->ctype_parameters['format'] == 'flowed');
702 // allow post-processing of the message body
703 $data = $RCMAIL->plugins->exec_hook('message_part_after',
704 array('type' => $part->ctype_secondary, 'body' => $body, 'id' => $part->mime_id) + $data);
706 return $data['type'] == 'html' ? $data['body'] : html::tag('pre', array(), $data['body']);
711 * Handle links and citation marks in plain text message
713 * @param string Plain text string
714 * @param boolean Text uses format=flowed
716 * @return string Formatted HTML string
718 function rcmail_plain_body($body, $flowed=false)
722 // make links and email-addresses clickable
723 $replacer = new rcube_string_replacer;
725 // search for patterns like links and e-mail addresses
726 $body = preg_replace_callback($replacer->link_pattern, array($replacer, 'link_callback'), $body);
727 $body = preg_replace_callback($replacer->mailto_pattern, array($replacer, 'mailto_callback'), $body);
729 // split body into single lines
730 $body = preg_split('/\r?\n/', $body);
734 // find/mark quoted lines...
735 for ($n=0, $cnt=count($body); $n < $cnt; $n++) {
736 if ($body[$n][0] == '>' && preg_match('/^(>+\s*)+/', $body[$n], $regs)) {
737 $q = strlen(preg_replace('/\s/', '', $regs[0]));
738 $body[$n] = substr($body[$n], strlen($regs[0]));
740 if ($q > $quote_level) {
741 $body[$n] = $replacer->get_replacement($replacer->add(
742 str_repeat('<blockquote>', $q - $quote_level))) . $body[$n];
744 else if ($q < $quote_level) {
745 $body[$n] = $replacer->get_replacement($replacer->add(
746 str_repeat('</blockquote>', $quote_level - $q))) . $body[$n];
749 // previous line is flowed
750 if (isset($body[$last]) && $body[$n]
751 && $body[$last][strlen($body[$last])-1] == ' ') {
753 $body[$last] .= $body[$n];
764 // sig separator - line is fixed
765 if ($body[$n] == '-- ') {
766 $last = $last_sig = $n;
769 // remove space-stuffing
770 if ($body[$n][0] == ' ')
771 $body[$n] = substr($body[$n], 1);
773 // previous line is flowed?
774 if (isset($body[$last]) && $body[$n]
775 && $last != $last_sig
776 && $body[$last][strlen($body[$last])-1] == ' '
778 $body[$last] .= $body[$n];
785 if ($quote_level > 0)
786 $body[$last] = $replacer->get_replacement($replacer->add(
787 str_repeat('</blockquote>', $quote_level))) . $body[$last];
789 else if ($quote_level > 0)
790 $body[$n] = $replacer->get_replacement($replacer->add(
791 str_repeat('</blockquote>', $quote_level))) . $body[$n];
797 $body = join("\n", $body);
799 // quote plain text (don't use Q() here, to display entities "as is")
800 $table = get_html_translation_table(HTML_SPECIALCHARS);
802 $body = strtr($body, $table);
804 // colorize signature (up to <sig_max_lines> lines)
805 $len = strlen($body);
806 $sig_max_lines = $RCMAIL->config->get('sig_max_lines', 15);
807 while (($sp = strrpos($body, "-- \n", $sp ? -$len+$sp-1 : 0)) !== false) {
808 if ($sp == 0 || $body[$sp-1] == "\n") {
809 // do not touch blocks with more that X lines
810 if (substr_count($body, "\n", $sp) < $sig_max_lines)
811 $body = substr($body, 0, max(0, $sp))
812 .'<span class="sig">'.substr($body, $sp).'</span>';
817 // insert url/mailto links and citation tags
818 $body = $replacer->resolve($body);
825 * Callback function for washtml cleaning class
827 function rcmail_washtml_callback($tagname, $attrib, $content)
831 $out = html::div('form', $content);
835 // decode all escaped entities and reduce to ascii strings
836 $stripped = preg_replace('/[^a-zA-Z\(:;]/', '', rcmail_xss_entity_decode($content));
838 // now check for evil strings like expression, behavior or url()
839 if (!preg_match('/expression|behavior|url\(|import[^a]/', $stripped)) {
840 $out = html::tag('style', array('type' => 'text/css'), $content);
853 * Callback function for HTML tags fixing
855 function rcmail_html_tag_callback($matches)
857 $tagname = $matches[2];
859 $tagname = preg_replace(array(
860 '/:.*$/', // Microsoft's Smart Tags <st1:xxxx>
861 '/[^a-z0-9_\[\]\!-]/i', // forbidden characters
864 return $matches[1].$tagname;
869 * return table with message headers
871 function rcmail_message_headers($attrib, $headers=NULL)
873 global $IMAP, $OUTPUT, $MESSAGE, $PRINT_MODE, $RCMAIL;
876 // keep header table attrib
877 if (is_array($attrib) && !$sa_attrib)
878 $sa_attrib = $attrib;
879 else if (!is_array($attrib) && is_array($sa_attrib))
880 $attrib = $sa_attrib;
882 if (!isset($MESSAGE))
885 // get associative array of headers object
887 $headers = is_object($MESSAGE->headers) ? get_object_vars($MESSAGE->headers) : $MESSAGE->headers;
889 // show these headers
890 $standard_headers = array('subject', 'from', 'to', 'cc', 'bcc', 'replyto',
891 'mail-reply-to', 'mail-followup-to', 'date');
892 $output_headers = array();
894 foreach ($standard_headers as $hkey) {
896 $value = $headers[$hkey];
897 else if ($headers['others'][$hkey])
898 $value = $headers['others'][$hkey];
902 if ($hkey == 'date') {
904 $header_value = format_date($value, $RCMAIL->config->get('date_long', 'x'));
906 $header_value = format_date($value);
908 else if ($hkey == 'replyto') {
909 if ($headers['replyto'] != $headers['from'])
910 $header_value = rcmail_address_string($value, null, true, $attrib['addicon']);
914 else if ($hkey == 'mail-reply-to') {
915 if ($headers['mail-replyto'] != $headers['reply-to']
916 && $headers['reply-to'] != $headers['from']
918 $header_value = rcmail_address_string($value, null, true, $attrib['addicon']);
922 else if ($hkey == 'mail-followup-to') {
923 $header_value = rcmail_address_string($value, null, true, $attrib['addicon']);
925 else if (in_array($hkey, array('from', 'to', 'cc', 'bcc')))
926 $header_value = rcmail_address_string($value, null, true, $attrib['addicon']);
927 else if ($hkey == 'subject' && empty($value))
928 $header_value = rcube_label('nosubject');
930 $header_value = trim($IMAP->decode_header($value));
932 $output_headers[$hkey] = array(
933 'title' => rcube_label(preg_replace('/(^mail-|-)/', '', $hkey)),
934 'value' => $header_value, 'raw' => $value
938 $plugin = $RCMAIL->plugins->exec_hook('message_headers_output',
939 array('output' => $output_headers, 'headers' => $MESSAGE->headers));
941 // compose html table
942 $table = new html_table(array('cols' => 2));
944 foreach ($plugin['output'] as $hkey => $row) {
945 $table->add(array('class' => 'header-title'), Q($row['title']));
946 $table->add(array('class' => 'header '.$hkey), Q($row['value'], ($hkey == 'subject' ? 'strict' : 'show')));
949 return $table->show($attrib);
954 * return block to show full message headers
956 function rcmail_message_full_headers($attrib, $headers=NULL)
960 $html = html::div(array('class' => "more-headers show-headers", 'onclick' => "return ".JS_OBJECT_NAME.".command('load-headers','',this)"), '');
961 $html .= html::div(array('id' => "all-headers", 'class' => "all", 'style' => 'display:none'), html::div(array('id' => 'headers-source'), ''));
963 $OUTPUT->add_gui_object('all_headers_row', 'all-headers');
964 $OUTPUT->add_gui_object('all_headers_box', 'headers-source');
966 return html::div($attrib, $html);
971 * Handler for the 'messagebody' GUI object
973 * @param array Named parameters
974 * @return string HTML content showing the message body
976 function rcmail_message_body($attrib)
978 global $CONFIG, $OUTPUT, $MESSAGE, $IMAP, $RCMAIL, $REMOTE_OBJECTS;
980 if (!is_array($MESSAGE->parts) && empty($MESSAGE->body))
984 $attrib['id'] = 'rcmailMsgBody';
986 $safe_mode = $MESSAGE->is_safe || intval($_GET['_safe']);
989 $header_attrib = array();
990 foreach ($attrib as $attr => $value)
991 if (preg_match('/^headertable([a-z]+)$/i', $attr, $regs))
992 $header_attrib[$regs[1]] = $value;
994 if (!empty($MESSAGE->parts))
996 foreach ($MESSAGE->parts as $i => $part)
998 if ($part->type == 'headers')
999 $out .= rcmail_message_headers(sizeof($header_attrib) ? $header_attrib : NULL, $part->headers);
1000 else if ($part->type == 'content' && $part->size)
1002 if (empty($part->ctype_parameters) || empty($part->ctype_parameters['charset']))
1003 $part->ctype_parameters['charset'] = $MESSAGE->headers->charset;
1005 // fetch part if not available
1006 if (!isset($part->body))
1007 $part->body = $MESSAGE->get_part_content($part->mime_id);
1009 // message is cached but not exists (#1485443), or other error
1010 if ($part->body === false) {
1011 rcmail_message_error($MESSAGE->uid);
1014 $plugin = $RCMAIL->plugins->exec_hook('message_body_prefix', array(
1015 'part' => $part, 'prefix' => ''));
1017 $body = rcmail_print_body($part, array('safe' => $safe_mode, 'plain' => !$CONFIG['prefer_html']));
1019 if ($part->ctype_secondary == 'html') {
1020 $body = rcmail_html4inline($body, $attrib['id'], 'rcmBody', $attrs);
1021 $div_attr = array('class' => 'message-htmlpart');
1024 if (!empty($attrs)) {
1025 foreach ($attrs as $a_idx => $a_val)
1026 $style[] = $a_idx . ': ' . $a_val;
1028 $div_attr['style'] = implode('; ', $style);
1031 $out .= html::div($div_attr, $plugin['prefix'] . $body);
1034 $out .= html::div('message-part', $plugin['prefix'] . $body);
1039 $plugin = $RCMAIL->plugins->exec_hook('message_body_prefix', array(
1040 'part' => $MESSAGE, 'prefix' => ''));
1042 $out .= html::div('message-part', $plugin['prefix'] . html::tag('pre', array(),
1043 rcmail_plain_body(Q($MESSAGE->body, 'strict', false))));
1046 $ctype_primary = strtolower($MESSAGE->structure->ctype_primary);
1047 $ctype_secondary = strtolower($MESSAGE->structure->ctype_secondary);
1049 // list images after mail body
1050 if ($CONFIG['inline_images']
1051 && $ctype_primary == 'multipart'
1052 && !empty($MESSAGE->attachments))
1054 foreach ($MESSAGE->attachments as $attach_prop) {
1055 // Content-Type: image/*...
1056 if (preg_match('/^image\//i', $attach_prop->mimetype) ||
1057 // ...or known file extension: many clients are using application/octet-stream
1058 ($attach_prop->filename &&
1059 preg_match('/^application\/octet-stream$/i', $attach_prop->mimetype) &&
1060 preg_match('/\.(jpg|jpeg|png|gif|bmp)$/i', $attach_prop->filename))
1062 $out .= html::tag('hr') . html::p(array('align' => "center"),
1064 'src' => $MESSAGE->get_part_url($attach_prop->mime_id),
1065 'title' => $attach_prop->filename,
1066 'alt' => $attach_prop->filename,
1072 // tell client that there are blocked remote objects
1073 if ($REMOTE_OBJECTS && !$safe_mode)
1074 $OUTPUT->set_env('blockedobjects', true);
1076 return html::div($attrib, $out);
1081 * Convert all relative URLs according to a <base> in HTML
1083 function rcmail_resolve_base($body)
1085 // check for <base href=...>
1086 if (preg_match('!(<base.*href=["\']?)([hftps]{3,5}://[a-z0-9/.%-]+)!i', $body, $regs)) {
1087 $replacer = new rcube_base_replacer($regs[2]);
1089 // replace all relative paths
1090 $body = preg_replace_callback('/(src|background|href)=(["\']?)([^"\'\s]+)(\2|\s|>)/Ui', array($replacer, 'callback'), $body);
1091 $body = preg_replace_callback('/(url\s*\()(["\']?)([^"\'\)\s]+)(\2)\)/Ui', array($replacer, 'callback'), $body);
1098 * modify a HTML message that it can be displayed inside a HTML page
1100 function rcmail_html4inline($body, $container_id, $body_id='', &$attributes=null)
1102 $last_style_pos = 0;
1103 $body_lc = strtolower($body);
1104 $cont_id = $container_id.($body_id ? ' div.'.$body_id : '');
1107 while (($pos = strpos($body_lc, '<style', $last_style_pos)) && ($pos2 = strpos($body_lc, '</style>', $pos)))
1109 $pos = strpos($body_lc, '>', $pos)+1;
1111 // replace all css definitions with #container [def]
1112 $styles = rcmail_mod_css_styles(
1113 substr($body, $pos, $pos2-$pos), $cont_id);
1115 $body = substr($body, 0, $pos) . $styles . substr($body, $pos2);
1116 $body_lc = strtolower($body);
1117 $last_style_pos = $pos2;
1120 // modify HTML links to open a new window if clicked
1121 $GLOBALS['rcmail_html_container_id'] = $container_id;
1122 $body = preg_replace_callback('/<(a|link)\s+([^>]+)>/Ui', 'rcmail_alter_html_link', $body);
1123 unset($GLOBALS['rcmail_html_container_id']);
1125 $body = preg_replace(array(
1126 // add comments arround html and other tags
1127 '/(<!DOCTYPE[^>]*>)/i',
1128 '/(<\?xml[^>]*>)/i',
1129 '/(<\/?html[^>]*>)/i',
1130 '/(<\/?head[^>]*>)/i',
1131 '/(<title[^>]*>.*<\/title>)/Ui',
1132 '/(<\/?meta[^>]*>)/i',
1133 // quote <? of php and xml files that are specified as text/html
1136 // replace <body> with <div>
1149 '<div class="'.$body_id.'"\\1>',
1154 $attributes = array();
1156 // Handle body attributes that doesn't play nicely with div elements
1157 $regexp = '/<div class="' . preg_quote($body_id, '/') . '"([^>]*)/';
1158 if (preg_match($regexp, $body, $m)) {
1160 // Get bgcolor, we'll set it as background-color of the message container
1161 if ($m[1] && preg_match('/bgcolor=["\']*([a-z0-9#]+)["\']*/', $attrs, $mb)) {
1162 $attributes['background-color'] = $mb[1];
1163 $attrs = preg_replace('/bgcolor=["\']*([a-z0-9#]+)["\']*/', '', $attrs);
1165 // Get background, we'll set it as background-image of the message container
1166 if ($m[1] && preg_match('/background=["\']*([^"\'>\s]+)["\']*/', $attrs, $mb)) {
1167 $attributes['background-image'] = 'url('.$mb[1].')';
1168 $attrs = preg_replace('/background=["\']*([^"\'>\s]+)["\']*/', '', $attrs);
1170 if (!empty($attributes)) {
1171 $body = preg_replace($regexp, rtrim($attrs), $body, 1);
1174 // handle body styles related to background image
1175 if ($attributes['background-image']) {
1177 if (preg_match('/#'.preg_quote($cont_id, '/').'\s+\{([^}]+)}/i', $body, $m)) {
1178 // get background related style
1179 if (preg_match_all('/(background-position|background-repeat)\s*:\s*([^;]+);/i', $m[1], $ma, PREG_SET_ORDER)) {
1180 foreach ($ma as $style)
1181 $attributes[$style[1]] = $style[2];
1186 // make sure there's 'rcmBody' div, we need it for proper css modification
1187 // its name is hardcoded in rcmail_message_body() also
1189 $body = '<div class="' . $body_id . '">' . $body . '</div>';
1197 * parse link attributes and set correct target
1199 function rcmail_alter_html_link($matches)
1203 // Support unicode/punycode in top-level domain part
1204 $EMAIL_PATTERN = '([a-z0-9][a-z0-9\-\.\+\_]*@[^&@"\'.][^@&"\']*\\.([^\\x00-\\x40\\x5b-\\x60\\x7b-\\x7f]{2,}|xn--[a-z0-9]{2,}))';
1207 $attrib = parse_attrib_string($matches[2]);
1210 // Remove non-printable characters in URL (#1487805)
1211 $attrib['href'] = preg_replace('/[\x00-\x1F]/', '', $attrib['href']);
1213 if ($tag == 'link' && preg_match('/^https?:\/\//i', $attrib['href'])) {
1214 $tempurl = 'tmp-' . md5($attrib['href']) . '.css';
1215 $_SESSION['modcssurls'][$tempurl] = $attrib['href'];
1216 $attrib['href'] = $RCMAIL->url(array('task' => 'utils', 'action' => 'modcss', 'u' => $tempurl, 'c' => $GLOBALS['rcmail_html_container_id']));
1219 else if (preg_match('/^mailto:'.$EMAIL_PATTERN.'(\?[^"\'>]+)?/i', $attrib['href'], $mailto)) {
1220 $attrib['href'] = $mailto[0];
1221 $attrib['onclick'] = sprintf(
1222 "return %s.command('compose','%s',this)",
1224 JQ($mailto[1].$mailto[3]));
1226 else if (!empty($attrib['href']) && $attrib['href'][0] != '#') {
1227 $attrib['target'] = '_blank';
1230 return "<$tag" . html::attrib_string($attrib, array('href','name','target','onclick','id','class','style','title','rel','type','media')) . $end;
1235 * decode address string and re-format it as HTML links
1237 function rcmail_address_string($input, $max=null, $linked=false, $addicon=null)
1239 global $IMAP, $RCMAIL, $PRINT_MODE, $CONFIG;
1240 static $got_writable_abook = null;
1242 $a_parts = $IMAP->decode_address_list($input);
1244 if (!sizeof($a_parts))
1247 $c = count($a_parts);
1251 if ($got_writable_abook === null && $books = $RCMAIL->get_address_sources(true)) {
1252 $got_writable_abook = true;
1255 foreach ($a_parts as $part) {
1258 $name = $part['name'];
1259 $mailto = $part['mailto'];
1260 $string = $part['string'];
1262 // IDNA ASCII to Unicode
1263 if ($name == $mailto)
1264 $name = rcube_idn_to_utf8($name);
1265 if ($string == $mailto)
1266 $string = rcube_idn_to_utf8($string);
1267 $mailto = rcube_idn_to_utf8($mailto);
1270 $out .= sprintf('%s <%s>', Q($name), $mailto);
1272 else if (check_email($part['mailto'], false)) {
1274 $out .= html::a(array(
1275 'href' => 'mailto:'.$mailto,
1276 'onclick' => sprintf("return %s.command('compose','%s',this)", JS_OBJECT_NAME, JQ($mailto)),
1278 'class' => "rcmContactAddress",
1280 Q($name ? $name : $mailto));
1283 $out .= html::span(array('title' => $mailto, 'class' => "rcmContactAddress"),
1284 Q($name ? $name : $mailto));
1287 if ($addicon && $got_writable_abook) {
1288 $out .= ' ' . html::a(array(
1290 'onclick' => sprintf("return %s.command('add-contact','%s',this)", JS_OBJECT_NAME, urlencode($string)),
1291 'title' => rcube_label('addtoaddressbook'),
1294 'src' => $CONFIG['skin_path'] . $addicon,
1295 'alt' => "Add contact",
1303 $out .= (strlen($out) ? ' ' : '') . sprintf('<%s>', Q($mailto));
1307 $out .= ','.($max ? ' ' : ' ');
1309 if ($max && $j==$max && $c>$j) {
1320 * Wrap text to a given number of characters per line
1321 * but respect the mail quotation of replies messages (>).
1322 * Finally add another quotation level by prpending the lines
1325 * @param string Text to wrap
1326 * @param int The line width
1327 * @return string The wrapped text
1329 function rcmail_wrap_and_quote($text, $length = 72)
1331 // Rebuild the message body with a maximum of $max chars, while keeping quoted message.
1332 $max = min(77, $length + 8);
1333 $lines = preg_split('/\r?\n/', trim($text));
1336 foreach ($lines as $line) {
1337 // don't wrap already quoted lines
1338 if ($line[0] == '>')
1339 $line = '>' . rtrim($line);
1340 else if (mb_strlen($line) > $max) {
1342 foreach(explode("\n", rc_wordwrap($line, $length - 2)) as $l) {
1344 $newline .= '> ' . $l . "\n";
1348 $line = rtrim($newline);
1351 $line = '> ' . $line;
1354 $out .= $line . "\n";
1361 function rcmail_draftinfo_encode($p)
1364 foreach ($p as $key => $val)
1365 $parts[] = $key . '=' . ($key == 'folder' ? base64_encode($val) : $val);
1367 return join('; ', $parts);
1371 function rcmail_draftinfo_decode($str)
1374 foreach (preg_split('/;\s+/', $str) as $part) {
1375 list($key, $val) = explode('=', $part, 2);
1376 if ($key == 'folder')
1377 $val = base64_decode($val);
1385 function rcmail_message_part_controls()
1389 $part = asciiwords(get_input_value('_part', RCUBE_INPUT_GPC));
1390 if (!is_object($MESSAGE) || !is_array($MESSAGE->parts) || !($_GET['_uid'] && $_GET['_part']) || !$MESSAGE->mime_parts[$part])
1393 $part = $MESSAGE->mime_parts[$part];
1394 $table = new html_table(array('cols' => 3));
1396 if (!empty($part->filename)) {
1397 $table->add('title', Q(rcube_label('filename')));
1398 $table->add(null, Q($part->filename));
1399 $table->add(null, '[' . html::a('?'.str_replace('_frame=', '_download=', $_SERVER['QUERY_STRING']), Q(rcube_label('download'))) . ']');
1402 if (!empty($part->size)) {
1403 $table->add('title', Q(rcube_label('filesize')));
1404 $table->add(null, Q(show_bytes($part->size)));
1407 return $table->show($attrib);
1412 function rcmail_message_part_frame($attrib)
1416 $part = $MESSAGE->mime_parts[asciiwords(get_input_value('_part', RCUBE_INPUT_GPC))];
1417 $ctype_primary = strtolower($part->ctype_primary);
1419 $attrib['src'] = './?' . str_replace('_frame=', ($ctype_primary=='text' ? '_show=' : '_preload='), $_SERVER['QUERY_STRING']);
1421 return html::iframe($attrib);
1426 * clear message composing settings
1428 function rcmail_compose_cleanup()
1430 if (!isset($_SESSION['compose']))
1433 $rcmail = rcmail::get_instance();
1434 $rcmail->plugins->exec_hook('attachments_cleanup', array());
1435 $rcmail->session->remove('compose');
1440 * Send the given message using the configured method
1442 * @param object $message Reference to Mail_MIME object
1443 * @param string $from Sender address string
1444 * @param array $mailto Array of recipient address strings
1445 * @param array $smtp_error SMTP error array (reference)
1446 * @param string $body_file Location of file with saved message body (reference)
1447 * @param array $smtp_opts SMTP options (e.g. DSN request)
1449 * @return boolean Send status.
1451 function rcmail_deliver_message(&$message, $from, $mailto, &$smtp_error, &$body_file, $smtp_opts=null)
1453 global $CONFIG, $RCMAIL;
1455 $headers = $message->headers();
1457 // send thru SMTP server using custom SMTP library
1458 if ($CONFIG['smtp_server']) {
1459 // generate list of recipients
1460 $a_recipients = array($mailto);
1462 if (strlen($headers['Cc']))
1463 $a_recipients[] = $headers['Cc'];
1464 if (strlen($headers['Bcc']))
1465 $a_recipients[] = $headers['Bcc'];
1467 // clean Bcc from header for recipients
1468 $send_headers = $headers;
1469 unset($send_headers['Bcc']);
1470 // here too, it because txtHeaders() below use $message->_headers not only $send_headers
1471 unset($message->_headers['Bcc']);
1473 $smtp_headers = $message->txtHeaders($send_headers, true);
1475 if ($message->getParam('delay_file_io')) {
1476 // use common temp dir
1477 $temp_dir = $RCMAIL->config->get('temp_dir');
1478 $body_file = tempnam($temp_dir, 'rcmMsg');
1479 if (PEAR::isError($mime_result = $message->saveMessageBody($body_file))) {
1480 raise_error(array('code' => 600, 'type' => 'php',
1481 'file' => __FILE__, 'line' => __LINE__,
1482 'message' => "Could not create message: ".$mime_result->getMessage()),
1486 $msg_body = fopen($body_file, 'r');
1488 $msg_body = $message->get();
1492 if (!is_object($RCMAIL->smtp))
1493 $RCMAIL->smtp_init(true);
1495 $sent = $RCMAIL->smtp->send_mail($from, $a_recipients, $smtp_headers, $msg_body, $smtp_opts);
1496 $smtp_response = $RCMAIL->smtp->get_response();
1497 $smtp_error = $RCMAIL->smtp->get_error();
1501 raise_error(array('code' => 800, 'type' => 'smtp', 'line' => __LINE__, 'file' => __FILE__,
1502 'message' => "SMTP error: ".join("\n", $smtp_response)), TRUE, FALSE);
1504 // send mail using PHP's mail() function
1506 // unset some headers because they will be added by the mail() function
1507 $headers_enc = $message->headers($headers);
1508 $headers_php = $message->_headers;
1509 unset($headers_php['To'], $headers_php['Subject']);
1511 // reset stored headers and overwrite
1512 $message->_headers = array();
1513 $header_str = $message->txtHeaders($headers_php);
1516 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1517 if (preg_match_all('/<([^@]+@[^>]+)>/', $headers_enc['To'], $m)) {
1518 $headers_enc['To'] = implode(', ', $m[1]);
1522 $msg_body = $message->get();
1524 if (PEAR::isError($msg_body))
1525 raise_error(array('code' => 600, 'type' => 'php',
1526 'file' => __FILE__, 'line' => __LINE__,
1527 'message' => "Could not create message: ".$msg_body->getMessage()),
1530 $delim = $RCMAIL->config->header_delimiter();
1531 $to = $headers_enc['To'];
1532 $subject = $headers_enc['Subject'];
1533 $header_str = rtrim($header_str);
1535 if ($delim != "\r\n") {
1536 $header_str = str_replace("\r\n", $delim, $header_str);
1537 $msg_body = str_replace("\r\n", $delim, $msg_body);
1538 $to = str_replace("\r\n", $delim, $to);
1539 $subject = str_replace("\r\n", $delim, $subject);
1542 if (ini_get('safe_mode'))
1543 $sent = mail($to, $subject, $msg_body, $header_str);
1545 $sent = mail($to, $subject, $msg_body, $header_str, "-f$from");
1550 $RCMAIL->plugins->exec_hook('message_sent', array('headers' => $headers, 'body' => $msg_body));
1552 // remove MDN headers after sending
1553 unset($headers['Return-Receipt-To'], $headers['Disposition-Notification-To']);
1555 // get all recipients
1557 $mailto .= $headers['Cc'];
1558 if ($headers['Bcc'])
1559 $mailto .= $headers['Bcc'];
1560 if (preg_match_all('/<([^@]+@[^>]+)>/', $mailto, $m))
1561 $mailto = implode(', ', array_unique($m[1]));
1563 if ($CONFIG['smtp_log']) {
1564 write_log('sendmail', sprintf("User %s [%s]; Message for %s; %s",
1565 $RCMAIL->user->get_username(),
1566 $_SERVER['REMOTE_ADDR'],
1568 !empty($smtp_response) ? join('; ', $smtp_response) : ''));
1572 if (is_resource($msg_body)) {
1576 $message->_headers = array();
1577 $message->headers($headers);
1583 * Send the MDN response
1585 * @param mixed $message Original message object (rcube_message) or UID
1586 * @param array $smtp_error SMTP error array (reference)
1588 * @return boolean Send status
1590 function rcmail_send_mdn($message, &$smtp_error)
1592 global $RCMAIL, $IMAP;
1594 if (!is_a($message, rcube_message))
1595 $message = new rcube_message($message);
1597 if ($message->headers->mdn_to && !$message->headers->mdn_sent &&
1598 ($IMAP->check_permflag('MDNSENT') || $IMAP->check_permflag('*')))
1600 $identity = $RCMAIL->user->get_identity();
1601 $sender = format_email_recipient($identity['email'], $identity['name']);
1602 $recipient = array_shift($IMAP->decode_address_list($message->headers->mdn_to));
1603 $mailto = $recipient['mailto'];
1605 $compose = new Mail_mime("\r\n");
1607 $compose->setParam('text_encoding', 'quoted-printable');
1608 $compose->setParam('html_encoding', 'quoted-printable');
1609 $compose->setParam('head_encoding', 'quoted-printable');
1610 $compose->setParam('head_charset', RCMAIL_CHARSET);
1611 $compose->setParam('html_charset', RCMAIL_CHARSET);
1612 $compose->setParam('text_charset', RCMAIL_CHARSET);
1614 // compose headers array
1616 'Date' => rcmail_user_date(),
1618 'To' => $message->headers->mdn_to,
1619 'Subject' => rcube_label('receiptread') . ': ' . $message->subject,
1620 'Message-ID' => rcmail_gen_message_id(),
1621 'X-Sender' => $identity['email'],
1622 'References' => trim($message->headers->references . ' ' . $message->headers->messageID),
1625 if ($agent = $RCMAIL->config->get('useragent'))
1626 $headers['User-Agent'] = $agent;
1628 $body = rcube_label("yourmessage") . "\r\n\r\n" .
1629 "\t" . rcube_label("to") . ': ' . rcube_imap::decode_mime_string($message->headers->to, $message->headers->charset) . "\r\n" .
1630 "\t" . rcube_label("subject") . ': ' . $message->subject . "\r\n" .
1631 "\t" . rcube_label("sent") . ': ' . format_date($message->headers->date, $RCMAIL->config->get('date_long')) . "\r\n" .
1632 "\r\n" . rcube_label("receiptnote") . "\r\n";
1634 $ua = $RCMAIL->config->get('useragent', "Roundcube Webmail (Version ".RCMAIL_VERSION.")");
1635 $report = "Reporting-UA: $ua\r\n";
1637 if ($message->headers->to)
1638 $report .= "Original-Recipient: {$message->headers->to}\r\n";
1640 $report .= "Final-Recipient: rfc822; {$identity['email']}\r\n" .
1641 "Original-Message-ID: {$message->headers->messageID}\r\n" .
1642 "Disposition: manual-action/MDN-sent-manually; displayed\r\n";
1644 $compose->headers($headers);
1645 $compose->setContentType('multipart/report', array('report-type'=> 'disposition-notification'));
1646 $compose->setTXTBody(rc_wordwrap($body, 75, "\r\n"));
1647 $compose->addAttachment($report, 'message/disposition-notification', 'MDNPart2.txt', false, '7bit', 'inline');
1649 $sent = rcmail_deliver_message($compose, $identity['email'], $mailto, $smtp_error, $body_file);
1653 $IMAP->set_flag($message->uid, 'MDNSENT');
1661 // Returns unique Message-ID
1662 function rcmail_gen_message_id()
1666 $local_part = md5(uniqid('rcmail'.mt_rand(),true));
1667 $domain_part = $RCMAIL->user->get_username('domain');
1669 // Try to find FQDN, some spamfilters doesn't like 'localhost' (#1486924)
1670 if (!preg_match('/\.[a-z]+$/i', $domain_part)) {
1671 if (($host = preg_replace('/:[0-9]+$/', '', $_SERVER['HTTP_HOST']))
1672 && preg_match('/\.[a-z]+$/i', $host)) {
1673 $domain_part = $host;
1675 else if (($host = preg_replace('/:[0-9]+$/', '', $_SERVER['SERVER_NAME']))
1676 && preg_match('/\.[a-z]+$/i', $host)) {
1677 $domain_part = $host;
1681 return sprintf('<%s@%s>', $local_part, $domain_part);
1684 // Returns RFC2822 formatted current date in user's timezone
1685 function rcmail_user_date()
1689 // get user's timezone
1690 if ($CONFIG['timezone'] === 'auto') {
1691 $tz = isset($_SESSION['timezone']) ? $_SESSION['timezone'] : date('Z')/3600;
1694 $tz = $CONFIG['timezone'];
1695 if ($CONFIG['dst_active'])
1699 $date = time() + $tz * 60 * 60;
1700 $date = gmdate('r', $date);
1701 $tz = sprintf('%+05d', intval($tz) * 100 + ($tz - intval($tz)) * 60);
1702 $date = preg_replace('/[+-][0-9]{4}$/', $tz, $date);
1707 // Fixes some content-type names
1708 function rcmail_fix_mimetype($name)
1710 // Some versions of Outlook create garbage Content-Type:
1711 // application/pdf.A520491B_3BF7_494D_8855_7FAC2C6C0608
1712 if (preg_match('/^application\/pdf.+/', $name))
1713 $name = 'application/pdf';
1718 function rcmail_search_filter($attrib)
1720 global $OUTPUT, $CONFIG;
1722 if (!strlen($attrib['id']))
1723 $attrib['id'] = 'rcmlistfilter';
1725 $attrib['onchange'] = JS_OBJECT_NAME.'.filter_mailbox(this.value)';
1728 RFC3501 (6.4.4): 'ALL', 'RECENT',
1729 'ANSWERED', 'DELETED', 'FLAGGED', 'SEEN',
1730 'UNANSWERED', 'UNDELETED', 'UNFLAGGED', 'UNSEEN',
1731 'NEW', // = (RECENT UNSEEN)
1732 'OLD' // = NOT RECENT
1735 $select_filter = new html_select($attrib);
1736 $select_filter->add(rcube_label('all'), 'ALL');
1737 $select_filter->add(rcube_label('unread'), 'UNSEEN');
1738 $select_filter->add(rcube_label('flagged'), 'FLAGGED');
1739 $select_filter->add(rcube_label('unanswered'), 'UNANSWERED');
1740 if (!$CONFIG['skip_deleted'])
1741 $select_filter->add(rcube_label('deleted'), 'DELETED');
1743 $out = $select_filter->show($_SESSION['search_filter']);
1745 $OUTPUT->add_gui_object('search_filter', $attrib['id']);
1750 function rcmail_message_error($uid=null)
1754 // Set env variables for messageerror.html template
1755 if ($RCMAIL->action == 'show') {
1756 $mbox_name = $RCMAIL->imap->get_mailbox_name();
1757 $RCMAIL->output->set_env('mailbox', $mbox_name);
1758 $RCMAIL->output->set_env('uid', null);
1760 // display error message
1761 $RCMAIL->output->show_message('messageopenerror', 'error');
1762 // ... display message error page
1763 $RCMAIL->output->send('messageerror');
1766 // register UI objects
1767 $OUTPUT->add_handlers(array(
1768 'mailboxlist' => 'rcmail_mailbox_list',
1769 'messages' => 'rcmail_message_list',
1770 'messagecountdisplay' => 'rcmail_messagecount_display',
1771 'quotadisplay' => 'rcmail_quota_display',
1772 'mailboxname' => 'rcmail_mailbox_name_display',
1773 'messageheaders' => 'rcmail_message_headers',
1774 'messagefullheaders' => 'rcmail_message_full_headers',
1775 'messagebody' => 'rcmail_message_body',
1776 'messagecontentframe' => 'rcmail_messagecontent_frame',
1777 'messagepartframe' => 'rcmail_message_part_frame',
1778 'messagepartcontrols' => 'rcmail_message_part_controls',
1779 'searchfilter' => 'rcmail_search_filter',
1780 'searchform' => array($OUTPUT, 'search_form'),