comparison program/steps/mail/func.inc @ 0:4681f974d28b

vanilla 1.3.3 distro, I hope
author Charlie Root
date Thu, 04 Jan 2018 15:52:31 -0500
parents
children 0cac1d1e799f
comparison
equal deleted inserted replaced
-1:000000000000 0:4681f974d28b
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-2014, The Roundcube Dev Team |
9 | |
10 | Licensed under the GNU General Public License version 3 or |
11 | any later version with exceptions for skins & plugins. |
12 | See the README file for a full license statement. |
13 | |
14 | PURPOSE: |
15 | Provide webmail functionality and GUI objects |
16 | |
17 +-----------------------------------------------------------------------+
18 | Author: Thomas Bruederli <roundcube@gmail.com> |
19 | Author: Aleksander Machniak <alec@alec.pl> |
20 +-----------------------------------------------------------------------+
21 */
22
23 // always instantiate storage object (but not connect to server yet)
24 $RCMAIL->storage_init();
25
26 // init environment - set current folder, page, list mode
27 rcmail_init_env();
28
29 // set message set for search result
30 if (!empty($_REQUEST['_search']) && isset($_SESSION['search'])
31 && $_SESSION['search_request'] == $_REQUEST['_search']
32 ) {
33 $RCMAIL->storage->set_search_set($_SESSION['search']);
34
35 $OUTPUT->set_env('search_request', $_REQUEST['_search']);
36 $OUTPUT->set_env('search_text', $_SESSION['last_text_search']);
37 }
38
39 // remove mbox part from _uid
40 if (($_uid = rcube_utils::get_input_value('_uid', rcube_utils::INPUT_GPC)) && !is_array($_uid) && preg_match('/^\d+-.+/', $_uid)) {
41 list($_uid, $mbox) = explode('-', $_uid, 2);
42 if (isset($_GET['_uid'])) $_GET['_uid'] = $_uid;
43 if (isset($_POST['_uid'])) $_POST['_uid'] = $_uid;
44 $_REQUEST['_uid'] = $_uid;
45 unset($_uid);
46
47 // override mbox
48 if (!empty($mbox)) {
49 $_GET['_mbox'] = $mbox;
50 $_POST['_mbox'] = $mbox;
51 $RCMAIL->storage->set_folder(($_SESSION['mbox'] = $mbox));
52 }
53 }
54
55 if (!empty($_SESSION['browser_caps']) && !$OUTPUT->ajax_call) {
56 $OUTPUT->set_env('browser_capabilities', $_SESSION['browser_caps']);
57 }
58
59 // set main env variables, labels and page title
60 if (empty($RCMAIL->action) || $RCMAIL->action == 'list') {
61 // connect to storage server and trigger error on failure
62 $RCMAIL->storage_connect();
63
64 $mbox_name = $RCMAIL->storage->get_folder();
65
66 if (empty($RCMAIL->action)) {
67 $OUTPUT->set_env('search_mods', rcmail_search_mods());
68
69 if (!empty($_SESSION['search_scope']))
70 $OUTPUT->set_env('search_scope', $_SESSION['search_scope']);
71
72 rcmail_list_pagetitle();
73 }
74
75 $threading = (bool) $RCMAIL->storage->get_threading();
76 $delimiter = $RCMAIL->storage->get_hierarchy_delimiter();
77
78 // set current mailbox and some other vars in client environment
79 $OUTPUT->set_env('mailbox', $mbox_name);
80 $OUTPUT->set_env('pagesize', $RCMAIL->storage->get_pagesize());
81 $OUTPUT->set_env('current_page', max(1, $_SESSION['page']));
82 $OUTPUT->set_env('delimiter', $delimiter);
83 $OUTPUT->set_env('threading', $threading);
84 $OUTPUT->set_env('threads', $threading || $RCMAIL->storage->get_capability('THREAD'));
85 $OUTPUT->set_env('reply_all_mode', (int) $RCMAIL->config->get('reply_all_mode'));
86 $OUTPUT->set_env('layout', $RCMAIL->config->get('layout') ?: 'widescreen');
87
88 if ($RCMAIL->storage->get_capability('QUOTA')) {
89 $OUTPUT->set_env('quota', true);
90 }
91
92 // set special folders
93 foreach (array('drafts', 'trash', 'junk') as $mbox) {
94 if ($folder = $RCMAIL->config->get($mbox . '_mbox')) {
95 $OUTPUT->set_env($mbox . '_mailbox', $folder);
96 }
97 }
98
99 if (!empty($_GET['_uid'])) {
100 $OUTPUT->set_env('list_uid', $_GET['_uid']);
101 }
102
103 // set configuration
104 $RCMAIL->set_env_config(array('delete_junk', 'flag_for_deletion', 'read_when_deleted',
105 'skip_deleted', 'display_next', 'message_extwin', 'forward_attachment'));
106
107 if (!$OUTPUT->ajax_call) {
108 $OUTPUT->add_label('checkingmail', 'deletemessage', 'movemessagetotrash',
109 'movingmessage', 'copyingmessage', 'deletingmessage', 'markingmessage',
110 'copy', 'move', 'quota', 'replyall', 'replylist', 'stillsearching',
111 'flagged', 'unflagged', 'unread', 'deleted', 'replied', 'forwarded',
112 'priority', 'withattachment', 'fileuploaderror', 'mark', 'markallread',
113 'folders-cur', 'folders-sub', 'folders-all', 'cancel');
114 }
115 }
116
117 // register UI objects
118 $OUTPUT->add_handlers(array(
119 'mailboxlist' => array($RCMAIL, 'folder_list'),
120 'quotadisplay' => array($RCMAIL, 'quota_display'),
121 'messages' => 'rcmail_message_list',
122 'messagecountdisplay' => 'rcmail_messagecount_display',
123 'listmenulink' => 'rcmail_options_menu_link',
124 'mailboxname' => 'rcmail_mailbox_name_display',
125 'messageheaders' => 'rcmail_message_headers',
126 'messagefullheaders' => 'rcmail_message_full_headers',
127 'messagebody' => 'rcmail_message_body',
128 'messagecontentframe' => 'rcmail_messagecontent_frame',
129 'messageimportform' => 'rcmail_message_import_form',
130 'searchfilter' => 'rcmail_search_filter',
131 'searchinterval' => 'rcmail_search_interval',
132 'searchform' => array($OUTPUT, 'search_form'),
133 ));
134
135 // register action aliases
136 $RCMAIL->register_action_map(array(
137 'refresh' => 'check_recent.inc',
138 'preview' => 'show.inc',
139 'print' => 'show.inc',
140 'move' => 'move_del.inc',
141 'delete' => 'move_del.inc',
142 'send' => 'sendmail.inc',
143 'expunge' => 'folders.inc',
144 'purge' => 'folders.inc',
145 'remove-attachment' => 'attachments.inc',
146 'rename-attachment' => 'attachments.inc',
147 'display-attachment' => 'attachments.inc',
148 'upload' => 'attachments.inc',
149 'group-expand' => 'autocomplete.inc',
150 ));
151
152
153 /**
154 * Sets storage properties and session
155 */
156 function rcmail_init_env()
157 {
158 global $RCMAIL;
159
160 $default_threading = $RCMAIL->config->get('default_list_mode', 'list') == 'threads';
161 $a_threading = $RCMAIL->config->get('message_threading', array());
162 $message_sort_col = $RCMAIL->config->get('message_sort_col');
163 $message_sort_order = $RCMAIL->config->get('message_sort_order');
164
165 // set imap properties and session vars
166 if (!strlen($mbox = rcube_utils::get_input_value('_mbox', rcube_utils::INPUT_GPC, true))) {
167 $mbox = strlen($_SESSION['mbox']) ? $_SESSION['mbox'] : 'INBOX';
168 }
169
170 // we handle 'page' argument on 'list' and 'getunread' to prevent from
171 // race condition and unintentional page overwrite in session
172 if ($RCMAIL->action == 'list' || $RCMAIL->action == 'getunread') {
173 if (!($page = intval($_GET['_page']))) {
174 $page = $_SESSION['page'] ?: 1;
175 }
176
177 $_SESSION['page'] = $page;
178 }
179
180 $RCMAIL->storage->set_folder($_SESSION['mbox'] = $mbox);
181 $RCMAIL->storage->set_page($_SESSION['page']);
182
183 // set default sort col/order to session
184 if (!isset($_SESSION['sort_col'])) {
185 $_SESSION['sort_col'] = $message_sort_col ?: '';
186 }
187 if (!isset($_SESSION['sort_order'])) {
188 $_SESSION['sort_order'] = strtoupper($message_sort_order) == 'ASC' ? 'ASC' : 'DESC';
189 }
190
191 // set threads mode
192 if (isset($_GET['_threads'])) {
193 if ($_GET['_threads']) {
194 // re-set current page number when listing mode changes
195 if (!$a_threading[$_SESSION['mbox']]) {
196 $RCMAIL->storage->set_page($_SESSION['page'] = 1);
197 }
198
199 $a_threading[$_SESSION['mbox']] = true;
200 }
201 else {
202 // re-set current page number when listing mode changes
203 if ($a_threading[$_SESSION['mbox']]) {
204 $RCMAIL->storage->set_page($_SESSION['page'] = 1);
205 }
206
207 $a_threading[$_SESSION['mbox']] = false;
208 }
209
210 $RCMAIL->user->save_prefs(array('message_threading' => $a_threading));
211 }
212
213 $threading = isset($a_threading[$_SESSION['mbox']]) ? $a_threading[$_SESSION['mbox']] : $default_threading;
214
215 $RCMAIL->storage->set_threading($threading);
216 }
217
218 /**
219 * Sets page title
220 */
221 function rcmail_list_pagetitle()
222 {
223 global $RCMAIL;
224
225 if ($RCMAIL->output->get_env('search_request')) {
226 $pagetitle = $RCMAIL->gettext('searchresult');
227 }
228 else {
229 $mbox_name = $RCMAIL->output->get_env('mailbox') ?: $RCMAIL->storage->get_folder();
230 $delimiter = $RCMAIL->storage->get_hierarchy_delimiter();
231 $pagetitle = $RCMAIL->localize_foldername($mbox_name, true);
232 $pagetitle = str_replace($delimiter, " \xC2\xBB ", $pagetitle);
233 }
234
235 $RCMAIL->output->set_pagetitle($pagetitle);
236 }
237
238 /**
239 * Returns default search mods
240 */
241 function rcmail_search_mods()
242 {
243 global $RCMAIL;
244
245 $mods = $RCMAIL->config->get('search_mods');
246
247 if (empty($mods)) {
248 $mods = array('*' => array('subject' => 1, 'from' => 1));
249
250 foreach (array('sent', 'drafts') as $mbox) {
251 if ($mbox = $RCMAIL->config->get($mbox . '_mbox')) {
252 $mods[$mbox] = array('subject' => 1, 'to' => 1);
253 }
254 }
255 }
256
257 return $mods;
258 }
259
260 /**
261 * Returns 'to' if current folder is configured Sent or Drafts
262 * or their subfolders, otherwise returns 'from'.
263 *
264 * @return string Column name
265 */
266 function rcmail_message_list_smart_column_name()
267 {
268 global $RCMAIL;
269
270 $delim = $RCMAIL->storage->get_hierarchy_delimiter();
271 $mbox = $RCMAIL->output->get_env('mailbox') ?: $RCMAIL->storage->get_folder();
272 $sent_mbox = $RCMAIL->config->get('sent_mbox');
273 $drafts_mbox = $RCMAIL->config->get('drafts_mbox');
274
275 if ((strpos($mbox.$delim, $sent_mbox.$delim) === 0 || strpos($mbox.$delim, $drafts_mbox.$delim) === 0)
276 && strtoupper($mbox) != 'INBOX'
277 ) {
278 return 'to';
279 }
280
281 return 'from';
282 }
283
284 /**
285 * Returns configured messages list sorting column name
286 * The name is context-sensitive, which means if sorting is set to 'fromto'
287 * it will return 'from' or 'to' according to current folder type.
288 *
289 * @return string Column name
290 */
291 function rcmail_sort_column()
292 {
293 global $RCMAIL;
294
295 if (isset($_SESSION['sort_col'])) {
296 $column = $_SESSION['sort_col'];
297 }
298 else {
299 $column = $RCMAIL->config->get('message_sort_col');
300 }
301
302 // get name of smart From/To column in folder context
303 if ($column == 'fromto') {
304 $column = rcmail_message_list_smart_column_name();
305 }
306
307 return $column;
308 }
309
310 /**
311 * Returns configured message list sorting order
312 *
313 * @return string Sorting order (ASC|DESC)
314 */
315 function rcmail_sort_order()
316 {
317 global $RCMAIL;
318
319 if (isset($_SESSION['sort_order'])) {
320 return $_SESSION['sort_order'];
321 }
322
323 return $RCMAIL->config->get('message_sort_order');
324 }
325
326 /**
327 * return the message list as HTML table
328 */
329 function rcmail_message_list($attrib)
330 {
331 global $RCMAIL, $OUTPUT;
332
333 // add some labels to client
334 $OUTPUT->add_label('from', 'to');
335
336 // add id to message list table if not specified
337 if (!strlen($attrib['id'])) {
338 $attrib['id'] = 'rcubemessagelist';
339 }
340
341 // define list of cols to be displayed based on parameter or config
342 if (empty($attrib['columns'])) {
343 $list_cols = $RCMAIL->config->get('list_cols');
344 $a_show_cols = !empty($list_cols) && is_array($list_cols) ? $list_cols : array('subject');
345
346 $OUTPUT->set_env('col_movable', !in_array('list_cols', (array)$RCMAIL->config->get('dont_override')));
347 }
348 else {
349 $a_show_cols = preg_split('/[\s,;]+/', str_replace(array("'", '"'), '', $attrib['columns']));
350 $attrib['columns'] = $a_show_cols;
351 }
352
353 // save some variables for use in ajax list
354 $_SESSION['list_attrib'] = $attrib;
355
356 // make sure 'threads' and 'subject' columns are present
357 if (!in_array('subject', $a_show_cols))
358 array_unshift($a_show_cols, 'subject');
359 if (!in_array('threads', $a_show_cols))
360 array_unshift($a_show_cols, 'threads');
361
362 $listcols = $a_show_cols;
363
364 // Widescreen layout uses hardcoded list of columns
365 if ($RCMAIL->config->get('layout', 'widescreen') == 'widescreen') {
366 $a_show_cols = array('threads', 'subject', 'fromto', 'date', 'flag', 'attachment');
367 $listcols = $a_show_cols;
368 array_shift($listcols);
369 }
370
371 // set client env
372 $OUTPUT->add_gui_object('messagelist', $attrib['id']);
373 $OUTPUT->set_env('autoexpand_threads', intval($RCMAIL->config->get('autoexpand_threads')));
374 $OUTPUT->set_env('sort_col', $_SESSION['sort_col']);
375 $OUTPUT->set_env('sort_order', $_SESSION['sort_order']);
376 $OUTPUT->set_env('messages', array());
377 $OUTPUT->set_env('listcols', $listcols);
378
379 $OUTPUT->include_script('list.js');
380
381 $table = new html_table($attrib);
382
383 if (!$attrib['noheader']) {
384 foreach (rcmail_message_list_head($attrib, $a_show_cols) as $cell)
385 $table->add_header(array('class' => $cell['className'], 'id' => $cell['id']), $cell['html']);
386 }
387
388 return $table->show();
389 }
390
391 /**
392 * return javascript commands to add rows to the message list
393 */
394 function rcmail_js_message_list($a_headers, $insert_top=false, $a_show_cols=null)
395 {
396 global $RCMAIL, $OUTPUT;
397
398 if (empty($a_show_cols)) {
399 if (!empty($_SESSION['list_attrib']['columns']))
400 $a_show_cols = $_SESSION['list_attrib']['columns'];
401 else {
402 $list_cols = $RCMAIL->config->get('list_cols');
403 $a_show_cols = !empty($list_cols) && is_array($list_cols) ? $list_cols : array('subject');
404 }
405 }
406 else {
407 if (!is_array($a_show_cols)) {
408 $a_show_cols = preg_split('/[\s,;]+/', str_replace(array("'", '"'), '', $a_show_cols));
409 }
410 $head_replace = true;
411 }
412
413 $delimiter = $RCMAIL->storage->get_hierarchy_delimiter();
414 $search_set = $RCMAIL->storage->get_search_set();
415 $multifolder = $search_set && $search_set[1]->multi;
416
417 // add/remove 'folder' column to the list on multi-folder searches
418 if ($multifolder && !in_array('folder', $a_show_cols)) {
419 $a_show_cols[] = 'folder';
420 $head_replace = true;
421 }
422 else if (!$multifolder && ($found = array_search('folder', $a_show_cols)) !== false) {
423 unset($a_show_cols[$found]);
424 $head_replace = true;
425 }
426
427 $mbox = $RCMAIL->output->get_env('mailbox') ?: $RCMAIL->storage->get_folder();
428
429 // make sure 'threads' and 'subject' columns are present
430 if (!in_array('subject', $a_show_cols))
431 array_unshift($a_show_cols, 'subject');
432 if (!in_array('threads', $a_show_cols))
433 array_unshift($a_show_cols, 'threads');
434
435 // Make sure there are no duplicated columns (#1486999)
436 $a_show_cols = array_unique($a_show_cols);
437 $_SESSION['list_attrib']['columns'] = $a_show_cols;
438
439 // Widescreen layout uses hardcoded list of columns
440 if ($RCMAIL->config->get('layout', 'widescreen') == 'widescreen') {
441 $a_show_cols = array('threads', 'subject', 'fromto', 'date', 'flag', 'attachment');
442 }
443
444 // Plugins may set header's list_cols/list_flags and other rcube_message_header variables
445 // and list columns
446 $plugin = $RCMAIL->plugins->exec_hook('messages_list',
447 array('messages' => $a_headers, 'cols' => $a_show_cols));
448
449 $a_show_cols = $plugin['cols'];
450 $a_headers = $plugin['messages'];
451
452 if ($RCMAIL->config->get('layout', 'widescreen') == 'widescreen') {
453 if (!$RCMAIL->storage->get_threading()) {
454 if (($idx = array_search('threads', $a_show_cols)) !== false) {
455 unset($a_show_cols[$idx]);
456 }
457 }
458 }
459
460 $thead = $head_replace ? rcmail_message_list_head($_SESSION['list_attrib'], $a_show_cols) : NULL;
461
462 // get name of smart From/To column in folder context
463 if (array_search('fromto', $a_show_cols) !== false) {
464 $smart_col = rcmail_message_list_smart_column_name();
465 }
466
467 $OUTPUT->command('set_message_coltypes', array_values($a_show_cols), $thead, $smart_col);
468
469 if ($multifolder && $_SESSION['search_scope'] == 'all') {
470 $OUTPUT->command('select_folder', '');
471 }
472
473 $OUTPUT->set_env('multifolder_listing', $multifolder);
474
475 if (empty($a_headers)) {
476 return;
477 }
478
479 // remove 'threads', 'attachment', 'flag', 'status' columns, we don't need them here
480 foreach (array('threads', 'attachment', 'flag', 'status', 'priority') as $col) {
481 if (($key = array_search($col, $a_show_cols)) !== FALSE) {
482 unset($a_show_cols[$key]);
483 }
484 }
485
486 $sort_col = $_SESSION['sort_col'];
487
488 // loop through message headers
489 foreach ($a_headers as $header) {
490 if (empty($header) || !$header->size) {
491 continue;
492 }
493
494 // make message UIDs unique by appending the folder name
495 if ($multifolder) {
496 $header->uid .= '-'.$header->folder;
497 $header->flags['skip_mbox_check'] = true;
498 if ($header->parent_uid)
499 $header->parent_uid .= '-'.$header->folder;
500 }
501
502 $a_msg_cols = array();
503 $a_msg_flags = array();
504
505 // format each col; similar as in rcmail_message_list()
506 foreach ($a_show_cols as $col) {
507 $col_name = $col == 'fromto' ? $smart_col : $col;
508
509 if (in_array($col_name, array('from', 'to', 'cc', 'replyto'))) {
510 $cont = rcmail_address_string($header->$col_name, 3, false, null, $header->charset);
511 if (empty($cont)) $cont = '&nbsp;'; // for widescreen mode
512 }
513 else if ($col == 'subject') {
514 $cont = trim(rcube_mime::decode_header($header->$col, $header->charset));
515 if (!$cont) $cont = $RCMAIL->gettext('nosubject');
516 $cont = rcube::Q($cont);
517 }
518 else if ($col == 'size')
519 $cont = $RCMAIL->show_bytes($header->$col);
520 else if ($col == 'date')
521 $cont = $RCMAIL->format_date($sort_col == 'arrival' ? $header->internaldate : $header->date);
522 else if ($col == 'folder') {
523 if ($last_folder !== $header->folder) {
524 $last_folder = $header->folder;
525 $last_folder_name = $RCMAIL->localize_foldername($last_folder, true);
526 $last_folder_name = str_replace($delimiter, " \xC2\xBB ", $last_folder_name);
527 }
528
529 $cont = rcube::Q($last_folder_name);
530 }
531 else
532 $cont = rcube::Q($header->$col);
533
534 $a_msg_cols[$col] = $cont;
535 }
536
537 $a_msg_flags = array_change_key_case(array_map('intval', (array) $header->flags));
538 if ($header->depth)
539 $a_msg_flags['depth'] = $header->depth;
540 else if ($header->has_children)
541 $roots[] = $header->uid;
542 if ($header->parent_uid)
543 $a_msg_flags['parent_uid'] = $header->parent_uid;
544 if ($header->has_children)
545 $a_msg_flags['has_children'] = $header->has_children;
546 if ($header->unread_children)
547 $a_msg_flags['unread_children'] = $header->unread_children;
548 if ($header->flagged_children)
549 $a_msg_flags['flagged_children'] = $header->flagged_children;
550 if ($header->others['list-post'])
551 $a_msg_flags['ml'] = 1;
552 if ($header->priority)
553 $a_msg_flags['prio'] = (int) $header->priority;
554
555 $a_msg_flags['ctype'] = rcube::Q($header->ctype);
556 $a_msg_flags['mbox'] = $header->folder;
557
558 // merge with plugin result (Deprecated, use $header->flags)
559 if (!empty($header->list_flags) && is_array($header->list_flags))
560 $a_msg_flags = array_merge($a_msg_flags, $header->list_flags);
561 if (!empty($header->list_cols) && is_array($header->list_cols))
562 $a_msg_cols = array_merge($a_msg_cols, $header->list_cols);
563
564 $OUTPUT->command('add_message_row', $header->uid, $a_msg_cols, $a_msg_flags, $insert_top);
565 }
566
567 if ($RCMAIL->storage->get_threading()) {
568 $OUTPUT->command('init_threads', (array) $roots, $mbox);
569 }
570 }
571
572 /*
573 * Creates <THEAD> for message list table
574 */
575 function rcmail_message_list_head($attrib, $a_show_cols)
576 {
577 global $RCMAIL;
578
579 // check to see if we have some settings for sorting
580 $sort_col = $_SESSION['sort_col'];
581 $sort_order = $_SESSION['sort_order'];
582
583 $dont_override = (array) $RCMAIL->config->get('dont_override');
584 $disabled_sort = in_array('message_sort_col', $dont_override);
585 $disabled_order = in_array('message_sort_order', $dont_override);
586
587 $RCMAIL->output->set_env('disabled_sort_col', $disabled_sort);
588 $RCMAIL->output->set_env('disabled_sort_order', $disabled_order);
589
590 // define sortable columns
591 if ($disabled_sort)
592 $a_sort_cols = $sort_col && !$disabled_order ? array($sort_col) : array();
593 else
594 $a_sort_cols = array('subject', 'date', 'from', 'to', 'fromto', 'size', 'cc');
595
596 if (!empty($attrib['optionsmenuicon'])) {
597 $list_menu = rcmail_options_menu_link($attrib);
598 }
599
600 $cells = $coltypes = array();
601
602 // get name of smart From/To column in folder context
603 if (array_search('fromto', $a_show_cols) !== false) {
604 $smart_col = rcmail_message_list_smart_column_name();
605 }
606
607 foreach ($a_show_cols as $col) {
608 $label = '';
609 $sortable = false;
610 $rel_col = $col == 'date' && $sort_col == 'arrival' ? 'arrival' : $col;
611
612 // get column name
613 switch ($col) {
614 case 'flag':
615 $col_name = html::span('flagged', $RCMAIL->gettext('flagged'));
616 break;
617 case 'attachment':
618 case 'priority':
619 $col_name = html::span($col, $RCMAIL->gettext($col));
620 break;
621 case 'status':
622 $col_name = html::span($col, $RCMAIL->gettext('readstatus'));
623 break;
624 case 'threads':
625 $col_name = (string) $list_menu;
626 break;
627 case 'fromto':
628 $label = $RCMAIL->gettext($smart_col);
629 $col_name = rcube::Q($label);
630 break;
631 default:
632 $label = $RCMAIL->gettext($col);
633 $col_name = rcube::Q($label);
634 }
635
636 // make sort links
637 if (in_array($col, $a_sort_cols)) {
638 $sortable = true;
639 $col_name = html::a(array(
640 'href' => "./#sort",
641 'class' => 'sortcol',
642 'rel' => $rel_col,
643 'title' => $RCMAIL->gettext('sortby')
644 ), $col_name);
645 }
646 else if ($col_name[0] != '<') {
647 $col_name = '<span class="' . $col .'">' . $col_name . '</span>';
648 }
649
650 $sort_class = $rel_col == $sort_col && !$disabled_order ? " sorted$sort_order" : '';
651 $class_name = $col.$sort_class;
652
653 // put it all together
654 $cells[] = array('className' => $class_name, 'id' => "rcm$col", 'html' => $col_name);
655 $coltypes[$col] = array('className' => $class_name, 'id' => "rcm$col", 'label' => $label, 'sortable' => $sortable);
656 }
657
658 $RCMAIL->output->set_env('coltypes', $coltypes);
659 return $cells;
660 }
661
662 function rcmail_options_menu_link($attrib)
663 {
664 global $RCMAIL;
665
666 $onclick = 'return ' . rcmail_output::JS_OBJECT_NAME . ".command('menu-open', 'messagelistmenu', this, event)";
667 $inner = $title = $RCMAIL->gettext('listoptions');
668
669 if (is_string($attrib['optionsmenuicon']) && $attrib['optionsmenuicon'] != 'true') {
670 $inner = html::img(array('src' => $RCMAIL->output->abs_url($attrib['optionsmenuicon'], true), 'alt' => $title));
671 }
672
673 return html::a(array(
674 'href' => '#list-options',
675 'onclick' => $onclick,
676 'class' => 'listmenu',
677 'id' => 'listmenulink',
678 'title' => $title,
679 'tabindex' => '0',
680 ), $inner);
681 }
682
683 /**
684 * Return an HTML iframe for loading mail content
685 */
686 function rcmail_messagecontent_frame($attrib)
687 {
688 global $OUTPUT;
689
690 if (empty($attrib['id'])) {
691 $attrib['id'] = 'rcmailcontentwindow';
692 }
693
694 return $OUTPUT->frame($attrib, true);
695 }
696
697 function rcmail_messagecount_display($attrib)
698 {
699 global $RCMAIL;
700
701 if (!$attrib['id']) {
702 $attrib['id'] = 'rcmcountdisplay';
703 }
704
705 $RCMAIL->output->add_gui_object('countdisplay', $attrib['id']);
706
707 $content = $RCMAIL->action != 'show' ? rcmail_get_messagecount_text() : $RCMAIL->gettext('loading');
708
709 return html::span($attrib, $content);
710 }
711
712 function rcmail_get_messagecount_text($count = null, $page = null)
713 {
714 global $RCMAIL;
715
716 if ($page === null) {
717 $page = $RCMAIL->storage->get_page();
718 }
719
720 $page_size = $RCMAIL->storage->get_pagesize();
721 $start_msg = ($page-1) * $page_size + 1;
722 $max = $count;
723
724 if ($max === null && $RCMAIL->action) {
725 $max = $RCMAIL->storage->count(null, $RCMAIL->storage->get_threading() ? 'THREADS' : 'ALL');
726 }
727
728 if (!$max) {
729 $out = $RCMAIL->storage->get_search_set() ? $RCMAIL->gettext('nomessages') : $RCMAIL->gettext('mailboxempty');
730 }
731 else {
732 $out = $RCMAIL->gettext(array('name' => $RCMAIL->storage->get_threading() ? 'threadsfromto' : 'messagesfromto',
733 'vars' => array('from' => $start_msg,
734 'to' => min($max, $start_msg + $page_size - 1),
735 'count' => $max)));
736 }
737
738 return rcube::Q($out);
739 }
740
741 function rcmail_mailbox_name_display($attrib)
742 {
743 global $RCMAIL;
744
745 if (!$attrib['id']) {
746 $attrib['id'] = 'rcmmailboxname';
747 }
748
749 $RCMAIL->output->add_gui_object('mailboxname', $attrib['id']);
750
751 return html::span($attrib, rcmail_get_mailbox_name_text());
752 }
753
754 function rcmail_get_mailbox_name_text()
755 {
756 global $RCMAIL;
757 return $RCMAIL->localize_foldername($RCMAIL->output->get_env('mailbox') ?: $RCMAIL->storage->get_folder());
758 }
759
760 function rcmail_send_unread_count($mbox_name, $force=false, $count=null, $mark='')
761 {
762 global $RCMAIL;
763
764 $old_unseen = rcmail_get_unseen_count($mbox_name);
765 $unseen = $count;
766
767 if ($unseen === null) {
768 $unseen = $RCMAIL->storage->count($mbox_name, 'UNSEEN', $force);
769 }
770
771 if ($unseen != $old_unseen || ($mbox_name == 'INBOX')) {
772 $RCMAIL->output->command('set_unread_count', $mbox_name, $unseen,
773 ($mbox_name == 'INBOX'), $unseen && $mark ? $mark : '');
774 }
775
776 rcmail_set_unseen_count($mbox_name, $unseen);
777
778 return $unseen;
779 }
780
781 function rcmail_set_unseen_count($mbox_name, $count)
782 {
783 // @TODO: this data is doubled (session and cache tables) if caching is enabled
784
785 // Make sure we have an array here (#1487066)
786 if (!is_array($_SESSION['unseen_count'])) {
787 $_SESSION['unseen_count'] = array();
788 }
789
790 $_SESSION['unseen_count'][$mbox_name] = $count;
791 }
792
793 function rcmail_get_unseen_count($mbox_name)
794 {
795 if (is_array($_SESSION['unseen_count']) && array_key_exists($mbox_name, $_SESSION['unseen_count'])) {
796 return $_SESSION['unseen_count'][$mbox_name];
797 }
798 }
799
800 /**
801 * Sets message is_safe flag according to 'show_images' option value
802 *
803 * @param object rcube_message Message
804 */
805 function rcmail_check_safe($message)
806 {
807 global $RCMAIL;
808
809 if (!$message->is_safe
810 && ($show_images = $RCMAIL->config->get('show_images'))
811 && $message->has_html_part()
812 ) {
813 switch ($show_images) {
814 case 1: // known senders only
815 // get default addressbook, like in addcontact.inc
816 $CONTACTS = $RCMAIL->get_address_book(-1, true);
817
818 if ($CONTACTS && $message->sender['mailto']) {
819 $result = $CONTACTS->search('email', $message->sender['mailto'], 1, false);
820 if ($result->count) {
821 $message->set_safe(true);
822 }
823 }
824
825 $RCMAIL->plugins->exec_hook('message_check_safe', array('message' => $message));
826 break;
827
828 case 2: // always
829 $message->set_safe(true);
830 break;
831 }
832 }
833
834 return !empty($message->is_safe);
835 }
836
837 /**
838 * Cleans up the given message HTML Body (for displaying)
839 *
840 * @param string HTML
841 * @param array Display parameters
842 * @param array CID map replaces (inline images)
843 * @return string Clean HTML
844 */
845 function rcmail_wash_html($html, $p, $cid_replaces = array())
846 {
847 global $REMOTE_OBJECTS;
848
849 $p += array('safe' => false, 'inline_html' => true);
850
851 // charset was converted to UTF-8 in rcube_storage::get_message_part(),
852 // change/add charset specification in HTML accordingly,
853 // washtml cannot work without that
854 $meta = '<meta http-equiv="Content-Type" content="text/html; charset='.RCUBE_CHARSET.'" />';
855
856 // remove old meta tag and add the new one, making sure
857 // that it is placed in the head (#1488093)
858 $html = preg_replace('/<meta[^>]+charset=[a-z0-9-_]+[^>]*>/Ui', '', $html);
859 $html = preg_replace('/(<head[^>]*>)/Ui', '\\1'.$meta, $html, -1, $rcount);
860 if (!$rcount) {
861 $html = '<head>' . $meta . '</head>' . $html;
862 }
863
864 // clean HTML with washhtml by Frederic Motte
865 $wash_opts = array(
866 'show_washed' => false,
867 'allow_remote' => $p['safe'],
868 'blocked_src' => 'program/resources/blocked.gif',
869 'charset' => RCUBE_CHARSET,
870 'cid_map' => $cid_replaces,
871 'html_elements' => array('body'),
872 );
873
874 if (!$p['inline_html']) {
875 $wash_opts['html_elements'] = array('html','head','title','body');
876 }
877 if ($p['safe']) {
878 $wash_opts['html_elements'][] = 'link';
879 $wash_opts['html_attribs'] = array('rel','type');
880 }
881
882 // overwrite washer options with options from plugins
883 if (isset($p['html_elements']))
884 $wash_opts['html_elements'] = $p['html_elements'];
885 if (isset($p['html_attribs']))
886 $wash_opts['html_attribs'] = $p['html_attribs'];
887
888 // initialize HTML washer
889 $washer = new rcube_washtml($wash_opts);
890
891 if (!$p['skip_washer_form_callback']) {
892 $washer->add_callback('form', 'rcmail_washtml_callback');
893 }
894
895 // allow CSS styles, will be sanitized by rcmail_washtml_callback()
896 if (!$p['skip_washer_style_callback']) {
897 $washer->add_callback('style', 'rcmail_washtml_callback');
898 }
899
900 // modify HTML links to open a new window if clicked
901 if (!$p['skip_washer_link_callback']) {
902 $washer->add_callback('a', 'rcmail_washtml_link_callback');
903 $washer->add_callback('area', 'rcmail_washtml_link_callback');
904
905 if ($p['safe'])
906 $washer->add_callback('link', 'rcmail_washtml_link_callback');
907 }
908
909 // Remove non-UTF8 characters (#1487813)
910 $html = rcube_charset::clean($html);
911
912 $html = $washer->wash($html);
913 $REMOTE_OBJECTS = $washer->extlinks;
914
915 return $html;
916 }
917
918 /**
919 * Convert the given message part to proper HTML
920 * which can be displayed the message view
921 *
922 * @param string Message part body
923 * @param rcube_message_part Message part
924 * @param array Display parameters array
925 *
926 * @return string Formatted HTML string
927 */
928 function rcmail_print_body($body, $part, $p = array())
929 {
930 global $RCMAIL;
931
932 // trigger plugin hook
933 $data = $RCMAIL->plugins->exec_hook('message_part_before',
934 array('type' => $part->ctype_secondary, 'body' => $body, 'id' => $part->mime_id)
935 + $p + array('safe' => false, 'plain' => false, 'inline_html' => true));
936
937 // convert html to text/plain
938 if ($data['plain'] && ($data['type'] == 'html' || $data['type'] == 'enriched')) {
939 if ($data['type'] == 'enriched') {
940 $data['body'] = rcube_enriched::to_html($data['body']);
941 }
942
943 $body = $RCMAIL->html2text($data['body']);
944 $part->ctype_secondary = 'plain';
945 }
946 // text/html
947 else if ($data['type'] == 'html') {
948 $body = rcmail_wash_html($data['body'], $data, $part->replaces);
949 $part->ctype_secondary = $data['type'];
950 }
951 // text/enriched
952 else if ($data['type'] == 'enriched') {
953 $body = rcube_enriched::to_html($data['body']);
954 $body = rcmail_wash_html($body, $data, $part->replaces);
955 $part->ctype_secondary = 'html';
956 }
957 else {
958 // assert plaintext
959 $body = $data['body'];
960 $part->ctype_secondary = $data['type'] = 'plain';
961 }
962
963 // free some memory (hopefully)
964 unset($data['body']);
965
966 // plaintext postprocessing
967 if ($part->ctype_secondary == 'plain') {
968 $flowed = $part->ctype_parameters['format'] == 'flowed';
969 $delsp = $part->ctype_parameters['delsp'] == 'yes';
970 $body = rcmail_plain_body($body, $flowed, $delsp);
971 }
972
973 // allow post-processing of the message body
974 $data = $RCMAIL->plugins->exec_hook('message_part_after',
975 array('type' => $part->ctype_secondary, 'body' => $body, 'id' => $part->mime_id) + $data);
976
977 return $data['body'];
978 }
979
980 /**
981 * Handle links and citation marks in plain text message
982 *
983 * @param string Plain text string
984 * @param boolean Set to True if the source text is in format=flowed
985 *
986 * @return string Formatted HTML string
987 */
988 function rcmail_plain_body($body, $flowed = false, $delsp = false)
989 {
990 $options = array('flowed' => $flowed, 'wrap' => !$flowed, 'replacer' => 'rcmail_string_replacer',
991 'delsp' => $delsp);
992 $text2html = new rcube_text2html($body, false, $options);
993 $body = $text2html->get_html();
994
995 return $body;
996 }
997
998 /**
999 * Callback function for washtml cleaning class
1000 */
1001 function rcmail_washtml_callback($tagname, $attrib, $content, $washtml)
1002 {
1003 switch ($tagname) {
1004 case 'form':
1005 $out = html::div('form', $content);
1006 break;
1007
1008 case 'style':
1009 // Crazy big styles may freeze the browser (#1490539)
1010 // remove content with more than 5k lines
1011 if (substr_count($content, "\n") > 5000) {
1012 $out = '';
1013 break;
1014 }
1015
1016 // decode all escaped entities and reduce to ascii strings
1017 $stripped = preg_replace('/[^a-zA-Z\(:;]/', '', rcube_utils::xss_entity_decode($content));
1018
1019 // now check for evil strings like expression, behavior or url()
1020 if (!preg_match('/expression|behavior|javascript:|import[^a]/i', $stripped)) {
1021 if (!$washtml->get_config('allow_remote') && preg_match('/url\((?!data:image)/', $stripped)) {
1022 $washtml->extlinks = true;
1023 }
1024 else {
1025 $out = html::tag('style', array('type' => 'text/css'), $content);
1026 }
1027 break;
1028 }
1029
1030 default:
1031 $out = '';
1032 }
1033
1034 return $out;
1035 }
1036
1037 /**
1038 * return table with message headers
1039 */
1040 function rcmail_message_headers($attrib, $headers=null)
1041 {
1042 global $MESSAGE, $PRINT_MODE, $RCMAIL;
1043 static $sa_attrib;
1044
1045 // keep header table attrib
1046 if (is_array($attrib) && !$sa_attrib && !$attrib['valueof']) {
1047 $sa_attrib = $attrib;
1048 }
1049 else if (!is_array($attrib) && is_array($sa_attrib)) {
1050 $attrib = $sa_attrib;
1051 }
1052
1053 if (!isset($MESSAGE)) {
1054 return false;
1055 }
1056
1057 // get associative array of headers object
1058 if (!$headers) {
1059 $headers_obj = $MESSAGE->headers;
1060 $headers = get_object_vars($MESSAGE->headers);
1061 }
1062 else if (is_object($headers)) {
1063 $headers_obj = $headers;
1064 $headers = get_object_vars($headers_obj);
1065 }
1066 else {
1067 $headers_obj = rcube_message_header::from_array($headers);
1068 }
1069
1070 // show these headers
1071 $standard_headers = array('subject', 'from', 'sender', 'to', 'cc', 'bcc', 'replyto',
1072 'mail-reply-to', 'mail-followup-to', 'date', 'priority');
1073 $exclude_headers = $attrib['exclude'] ? explode(',', $attrib['exclude']) : array();
1074 $output_headers = array();
1075
1076 foreach ($standard_headers as $hkey) {
1077 if ($headers[$hkey])
1078 $value = $headers[$hkey];
1079 else if ($headers['others'][$hkey])
1080 $value = $headers['others'][$hkey];
1081 else if (!$attrib['valueof'])
1082 continue;
1083
1084 if (in_array($hkey, $exclude_headers))
1085 continue;
1086
1087 $ishtml = false;
1088 $header_title = $RCMAIL->gettext(preg_replace('/(^mail-|-)/', '', $hkey));
1089
1090 if ($hkey == 'date') {
1091 if ($PRINT_MODE)
1092 $header_value = $RCMAIL->format_date($value, $RCMAIL->config->get('date_long', 'x'));
1093 else
1094 $header_value = $RCMAIL->format_date($value);
1095 }
1096 else if ($hkey == 'priority') {
1097 if ($value) {
1098 $header_value = html::span('prio' . $value, rcube::Q(rcmail_localized_priority($value)));
1099 $ishtml = true;
1100 }
1101 else {
1102 continue;
1103 }
1104 }
1105 else if ($hkey == 'replyto') {
1106 if ($headers['replyto'] != $headers['from']) {
1107 $header_value = rcmail_address_string($value, $attrib['max'], true,
1108 $attrib['addicon'], $headers['charset'], $header_title);
1109 $ishtml = true;
1110 }
1111 else {
1112 continue;
1113 }
1114 }
1115 else if ($hkey == 'mail-reply-to') {
1116 if ($headers['mail-replyto'] != $headers['replyto']
1117 && $headers['replyto'] != $headers['from']
1118 ) {
1119 $header_value = rcmail_address_string($value, $attrib['max'], true,
1120 $attrib['addicon'], $headers['charset'], $header_title);
1121 $ishtml = true;
1122 }
1123 else {
1124 continue;
1125 }
1126 }
1127 else if ($hkey == 'sender') {
1128 if ($headers['sender'] != $headers['from']) {
1129 $header_value = rcmail_address_string($value, $attrib['max'], true,
1130 $attrib['addicon'], $headers['charset'], $header_title);
1131 $ishtml = true;
1132 }
1133 else {
1134 continue;
1135 }
1136 }
1137 else if ($hkey == 'mail-followup-to') {
1138 $header_value = rcmail_address_string($value, $attrib['max'], true,
1139 $attrib['addicon'], $headers['charset'], $header_title);
1140 $ishtml = true;
1141 }
1142 else if (in_array($hkey, array('from', 'to', 'cc', 'bcc'))) {
1143 $header_value = rcmail_address_string($value, $attrib['max'], true,
1144 $attrib['addicon'], $headers['charset'], $header_title);
1145 $ishtml = true;
1146 }
1147 else if ($hkey == 'subject' && empty($value)) {
1148 $header_value = $RCMAIL->gettext('nosubject');
1149 }
1150 else {
1151 $value = is_array($value) ? implode(' ', $value) : $value;
1152 $header_value = trim(rcube_mime::decode_header($value, $headers['charset']));
1153 }
1154
1155 $output_headers[$hkey] = array(
1156 'title' => $header_title,
1157 'value' => $header_value,
1158 'raw' => $value,
1159 'html' => $ishtml,
1160 );
1161 }
1162
1163 $plugin = $RCMAIL->plugins->exec_hook('message_headers_output', array(
1164 'output' => $output_headers,
1165 'headers' => $headers_obj,
1166 'exclude' => $exclude_headers, // readonly
1167 'folder' => $MESSAGE->folder, // readonly
1168 'uid' => $MESSAGE->uid, // readonly
1169 ));
1170
1171 // single header value is requested
1172 if (!empty($attrib['valueof'])) {
1173 $row = $plugin['output'][$attrib['valueof']];
1174 return $row['html'] ? $row['value'] : rcube::Q($row['value']);
1175 }
1176
1177 // compose html table
1178 $table = new html_table(array('cols' => 2));
1179
1180 foreach ($plugin['output'] as $hkey => $row) {
1181 $val = $row['html'] ? $row['value'] : rcube::Q($row['value']);
1182
1183 $table->add(array('class' => 'header-title'), rcube::Q($row['title']));
1184 $table->add(array('class' => 'header '.$hkey), $val);
1185 }
1186
1187 return $table->show($attrib);
1188 }
1189
1190 /**
1191 * Convert Priority header value into a localized string
1192 */
1193 function rcmail_localized_priority($value)
1194 {
1195 global $RCMAIL;
1196
1197 $labels_map = array(
1198 '1' => 'highest',
1199 '2' => 'high',
1200 '3' => 'normal',
1201 '4' => 'low',
1202 '5' => 'lowest',
1203 );
1204
1205 if ($value && $labels_map[$value]) {
1206 return $RCMAIL->gettext($labels_map[$value]);
1207 }
1208
1209 return '';
1210 }
1211
1212 /**
1213 * return block to show full message headers
1214 */
1215 function rcmail_message_full_headers($attrib)
1216 {
1217 global $OUTPUT, $RCMAIL;
1218
1219 $html = html::div(array('id' => "all-headers", 'class' => "all", 'style' => 'display:none'), html::div(array('id' => 'headers-source'), ''));
1220 $html .= html::div(array(
1221 'class' => "more-headers show-headers",
1222 'onclick' => "return ".rcmail_output::JS_OBJECT_NAME.".command('show-headers','',this)",
1223 'title' => $RCMAIL->gettext('togglefullheaders')
1224 ), '');
1225
1226 $OUTPUT->add_gui_object('all_headers_row', 'all-headers');
1227 $OUTPUT->add_gui_object('all_headers_box', 'headers-source');
1228
1229 return html::div($attrib, $html);
1230 }
1231
1232 /**
1233 * Handler for the 'messagebody' GUI object
1234 *
1235 * @param array Named parameters
1236 * @return string HTML content showing the message body
1237 */
1238 function rcmail_message_body($attrib)
1239 {
1240 global $OUTPUT, $MESSAGE, $RCMAIL, $REMOTE_OBJECTS;
1241
1242 if (!is_array($MESSAGE->parts) && empty($MESSAGE->body)) {
1243 return '';
1244 }
1245
1246 if (!$attrib['id'])
1247 $attrib['id'] = 'rcmailMsgBody';
1248
1249 $safe_mode = $MESSAGE->is_safe || intval($_GET['_safe']);
1250 $out = '';
1251 $part_no = 0;
1252
1253 $header_attrib = array();
1254 foreach ($attrib as $attr => $value) {
1255 if (preg_match('/^headertable([a-z]+)$/i', $attr, $regs)) {
1256 $header_attrib[$regs[1]] = $value;
1257 }
1258 }
1259
1260 if (!empty($MESSAGE->parts)) {
1261 foreach ($MESSAGE->parts as $part) {
1262 if ($part->type == 'headers') {
1263 $out .= html::div('message-partheaders', rcmail_message_headers(count($header_attrib) ? $header_attrib : null, $part->headers));
1264 }
1265 else if ($part->type == 'content') {
1266 // unsupported (e.g. encrypted)
1267 if ($part->realtype) {
1268 if ($part->realtype == 'multipart/encrypted' || $part->realtype == 'application/pkcs7-mime') {
1269 if (!empty($_SESSION['browser_caps']['pgpmime']) && ($pgp_mime_part = $MESSAGE->get_multipart_encrypted_part())) {
1270 $out .= html::span('part-notice', $RCMAIL->gettext('externalmessagedecryption'));
1271 $OUTPUT->set_env('pgp_mime_part', $pgp_mime_part->mime_id);
1272 $OUTPUT->set_env('pgp_mime_container', '#' . $attrib['id']);
1273 $OUTPUT->add_label('loadingdata');
1274 }
1275
1276 if (!$MESSAGE->encrypted_part) {
1277 $out .= html::span('part-notice', $RCMAIL->gettext('encryptedmessage'));
1278 }
1279 }
1280 continue;
1281 }
1282 else if (!$part->size) {
1283 continue;
1284 }
1285
1286 // Check if we have enough memory to handle the message in it
1287 // #1487424: we need up to 10x more memory than the body
1288 else if (!rcube_utils::mem_check($part->size * 10)) {
1289 $out .= html::span('part-notice', $RCMAIL->gettext('messagetoobig'). ' '
1290 . html::a('?_task=mail&_action=get&_download=1&_uid='.$MESSAGE->uid.'&_part='.$part->mime_id
1291 .'&_mbox='. urlencode($MESSAGE->folder), $RCMAIL->gettext('download')));
1292 continue;
1293 }
1294
1295 // fetch part body
1296 $body = $MESSAGE->get_part_body($part->mime_id, true);
1297
1298 // message is cached but not exists (#1485443), or other error
1299 if ($body === false) {
1300 rcmail_message_error($MESSAGE->uid);
1301 }
1302
1303 $plugin = $RCMAIL->plugins->exec_hook('message_body_prefix',
1304 array('part' => $part, 'prefix' => ''));
1305
1306 // Set attributes of the part container
1307 $container_class = $part->ctype_secondary == 'html' ? 'message-htmlpart' : 'message-part';
1308 $container_id = $container_class . (++$part_no);
1309 $container_attrib = array('class' => $container_class, 'id' => $container_id);
1310
1311 // Assign container ID to a global variable for use in rcmail_washtml_link_callback()
1312 $GLOBALS['rcmail_html_container_id'] = $container_id;
1313
1314 // Parse the part content for display
1315 $body = rcmail_print_body($body, $part, array('safe' => $safe_mode, 'plain' => !$RCMAIL->config->get('prefer_html')));
1316
1317 // check if the message body is PGP encrypted
1318 if (strpos($body, '-----BEGIN PGP MESSAGE-----') !== false) {
1319 $OUTPUT->set_env('is_pgp_content', '#' . $container_id);
1320 }
1321
1322 if ($part->ctype_secondary == 'html') {
1323 $body = rcmail_html4inline($body, $container_id, 'rcmBody', $container_attrib, $safe_mode);
1324 }
1325
1326 $out .= html::div($container_attrib, $plugin['prefix'] . $body);
1327 }
1328 }
1329 }
1330 else {
1331 // Check if we have enough memory to handle the message in it
1332 // #1487424: we need up to 10x more memory than the body
1333 if (!rcube_utils::mem_check(strlen($MESSAGE->body) * 10)) {
1334 $out .= html::span('part-notice', $RCMAIL->gettext('messagetoobig'). ' '
1335 . html::a('?_task=mail&_action=get&_download=1&_uid='.$MESSAGE->uid.'&_part=0'
1336 .'&_mbox='. urlencode($MESSAGE->folder), $RCMAIL->gettext('download')));
1337 }
1338 else {
1339 $plugin = $RCMAIL->plugins->exec_hook('message_body_prefix',
1340 array('part' => $MESSAGE, 'prefix' => ''));
1341
1342 $out .= html::div('message-part',
1343 $plugin['prefix'] . rcmail_plain_body($MESSAGE->body));
1344 }
1345 }
1346
1347 // list images after mail body
1348 if ($RCMAIL->config->get('inline_images', true) && !empty($MESSAGE->attachments)) {
1349 $thumbnail_size = $RCMAIL->config->get('image_thumbnail_size', 240);
1350 $client_mimetypes = (array)$RCMAIL->config->get('client_mimetypes');
1351
1352 foreach ($MESSAGE->attachments as $attach_prop) {
1353 // skip inline images
1354 if ($attach_prop->content_id && $attach_prop->disposition == 'inline') {
1355 continue;
1356 }
1357
1358 // Content-Type: image/*...
1359 if ($mimetype = rcmail_part_image_type($attach_prop)) {
1360 // display thumbnails
1361 if ($thumbnail_size) {
1362 $supported = in_array($mimetype, $client_mimetypes);
1363 $show_link = array(
1364 'href' => $MESSAGE->get_part_url($attach_prop->mime_id, false),
1365 'onclick' => sprintf(
1366 'return %s.command(\'load-attachment\',\'%s\',this)',
1367 rcmail_output::JS_OBJECT_NAME,
1368 $attach_prop->mime_id)
1369 );
1370
1371 $out .= html::p(array('class' => 'image-attachment', 'style' => $supported ? '' : 'display:none'),
1372 html::a($show_link + array('class' => 'image-link', 'style' => sprintf('width:%dpx', $thumbnail_size)),
1373 html::img(array(
1374 'class' => 'image-thumbnail',
1375 'src' => $MESSAGE->get_part_url($attach_prop->mime_id, 'image') . '&_thumb=1',
1376 'title' => $attach_prop->filename,
1377 'alt' => $attach_prop->filename,
1378 'style' => sprintf('max-width:%dpx; max-height:%dpx', $thumbnail_size, $thumbnail_size),
1379 'onload' => $supported ? '' : '$(this).parents(\'p.image-attachment\').show()',
1380 ))
1381 ) .
1382 html::span('image-filename', rcube::Q($attach_prop->filename)) .
1383 html::span('image-filesize', rcube::Q($RCMAIL->message_part_size($attach_prop))) .
1384 html::span('attachment-links',
1385 ($supported ? html::a($show_link, $RCMAIL->gettext('showattachment')) . '&nbsp;' : '') .
1386 html::a($show_link['href'] . '&_download=1', $RCMAIL->gettext('download'))
1387 ) .
1388 html::br(array('style' => 'clear:both'))
1389 );
1390 }
1391 else {
1392 $out .= html::tag('fieldset', 'image-attachment',
1393 html::tag('legend', 'image-filename', rcube::Q($attach_prop->filename)) .
1394 html::p(array('align' => 'center'),
1395 html::img(array(
1396 'src' => $MESSAGE->get_part_url($attach_prop->mime_id, 'image'),
1397 'title' => $attach_prop->filename,
1398 'alt' => $attach_prop->filename,
1399 )))
1400 );
1401 }
1402 }
1403 }
1404 }
1405
1406 // tell client that there are blocked remote objects
1407 if ($REMOTE_OBJECTS && !$safe_mode) {
1408 $OUTPUT->set_env('blockedobjects', true);
1409 }
1410
1411 return html::div($attrib, $out);
1412 }
1413
1414 function rcmail_part_image_type($part)
1415 {
1416 $mimetype = strtolower($part->mimetype);
1417
1418 // Skip TIFF/WEBP images if browser doesn't support this format
1419 // ...until we can convert them to JPEG
1420 $tiff_support = !empty($_SESSION['browser_caps']) && !empty($_SESSION['browser_caps']['tiff']);
1421 $tiff_support = $tiff_support || rcube_image::is_convertable('image/tiff');
1422 $webp_support = !empty($_SESSION['browser_caps']) && !empty($_SESSION['browser_caps']['webp']);
1423 $webp_support = $webp_support || rcube_image::is_convertable('image/webp');
1424
1425 if ((!$tiff_support && $mimetype == 'image/tiff') || (!$webp_support && $mimetype == 'image/webp')) {
1426 return;
1427 }
1428
1429 // Content-Type: image/*...
1430 if (strpos($mimetype, 'image/') === 0) {
1431 return rcmail_fix_mimetype($mimetype);
1432 }
1433
1434 // Many clients use application/octet-stream, we'll detect mimetype
1435 // by checking filename extension
1436
1437 // Supported image filename extensions to image type map
1438 $types = array(
1439 'jpg' => 'image/jpeg',
1440 'jpeg' => 'image/jpeg',
1441 'png' => 'image/png',
1442 'gif' => 'image/gif',
1443 'bmp' => 'image/bmp',
1444 );
1445 if ($tiff_support) {
1446 $types['tif'] = 'image/tiff';
1447 $types['tiff'] = 'image/tiff';
1448 }
1449 if ($webp_support) {
1450 $types['webp'] = 'image/webp';
1451 }
1452
1453 if ($part->filename
1454 && $mimetype == 'application/octet-stream'
1455 && preg_match('/\.([^.]+)$/i', $part->filename, $m)
1456 && ($extension = strtolower($m[1]))
1457 && isset($types[$extension])
1458 ) {
1459 return $types[$extension];
1460 }
1461 }
1462
1463 /**
1464 * Modify a HTML message that it can be displayed inside a HTML page
1465 */
1466 function rcmail_html4inline($body, $container_id, $body_class='', &$attributes=array(), $allow_remote=false)
1467 {
1468 $last_style_pos = 0;
1469 $cont_id = $container_id . ($body_class ? ' div.'.$body_class : '');
1470
1471 // find STYLE tags
1472 while (($pos = stripos($body, '<style', $last_style_pos)) && ($pos2 = stripos($body, '</style>', $pos))) {
1473 $pos = strpos($body, '>', $pos) + 1;
1474 $len = $pos2 - $pos;
1475
1476 // replace all css definitions with #container [def]
1477 $styles = substr($body, $pos, $len);
1478 $styles = rcube_utils::mod_css_styles($styles, $cont_id, $allow_remote);
1479
1480 $body = substr_replace($body, $styles, $pos, $len);
1481 $last_style_pos = $pos2 + strlen($styles) - $len;
1482 }
1483
1484 $body = preg_replace(array(
1485 // add comments around html and other tags
1486 '/(<!DOCTYPE[^>]*>)/i',
1487 '/(<\?xml[^>]*>)/i',
1488 '/(<\/?html[^>]*>)/i',
1489 '/(<\/?head[^>]*>)/i',
1490 '/(<title[^>]*>.*<\/title>)/Ui',
1491 '/(<\/?meta[^>]*>)/i',
1492 // quote <? of php and xml files that are specified as text/html
1493 '/<\?/',
1494 '/\?>/',
1495 // replace <body> with <div>
1496 '/<body([^>]*)>/i',
1497 '/<\/body>/i',
1498 ),
1499 array(
1500 '<!--\\1-->',
1501 '<!--\\1-->',
1502 '<!--\\1-->',
1503 '<!--\\1-->',
1504 '<!--\\1-->',
1505 '<!--\\1-->',
1506 '&lt;?',
1507 '?&gt;',
1508 '<div class="' . $body_class . '"\\1>',
1509 '</div>',
1510 ),
1511 $body);
1512
1513 // Handle body attributes that doesn't play nicely with div elements
1514 $regexp = '/<div class="' . preg_quote($body_class, '/') . '"([^>]*)/';
1515 if (preg_match($regexp, $body, $m)) {
1516 $style = array();
1517 $attrs = $m[0];
1518
1519 // Get bgcolor, we'll set it as background-color of the message container
1520 if ($m[1] && preg_match('/bgcolor=["\']*([a-z0-9#]+)["\']*/i', $attrs, $mb)) {
1521 $style['background-color'] = $mb[1];
1522 $attrs = preg_replace('/bgcolor=["\']*[a-z0-9#]+["\']*/i', '', $attrs);
1523 }
1524
1525 // Get background, we'll set it as background-image of the message container
1526 if ($m[1] && preg_match('/background=["\']*([^"\'>\s]+)["\']*/', $attrs, $mb)) {
1527 $style['background-image'] = 'url('.$mb[1].')';
1528 $attrs = preg_replace('/background=["\']*([^"\'>\s]+)["\']*/', '', $attrs);
1529 }
1530
1531 if (!empty($style)) {
1532 $body = preg_replace($regexp, rtrim($attrs), $body, 1);
1533 }
1534
1535 // handle body styles related to background image
1536 if ($style['background-image']) {
1537 // get body style
1538 if (preg_match('/#'.preg_quote($cont_id, '/').'\s+\{([^}]+)}/i', $body, $m)) {
1539 // get background related style
1540 $regexp = '/(background-position|background-repeat)\s*:\s*([^;]+);/i';
1541 if (preg_match_all($regexp, $m[1], $matches, PREG_SET_ORDER)) {
1542 foreach ($matches as $m) {
1543 $style[$m[1]] = $m[2];
1544 }
1545 }
1546 }
1547 }
1548
1549 if (!empty($style)) {
1550 foreach ($style as $idx => $val) {
1551 $style[$idx] = $idx . ': ' . $val;
1552 }
1553
1554 $attributes['style'] = implode('; ', $style);
1555 }
1556 }
1557 // make sure there's 'rcmBody' div, we need it for proper css modification
1558 // its name is hardcoded in rcmail_message_body() also
1559 else {
1560 $body = '<div class="' . $body_class . '">' . $body . '</div>';
1561 }
1562
1563 return $body;
1564 }
1565
1566 /**
1567 * Parse link (a, link, area) attributes and set correct target
1568 */
1569 function rcmail_washtml_link_callback($tag, $attribs, $content, $washtml)
1570 {
1571 global $RCMAIL;
1572
1573 $attrib = html::parse_attrib_string($attribs);
1574
1575 // Remove non-printable characters in URL (#1487805)
1576 if ($attrib['href']) {
1577 $attrib['href'] = preg_replace('/[\x00-\x1F]/', '', $attrib['href']);
1578 }
1579
1580 if ($tag == 'link' && preg_match('/^https?:\/\//i', $attrib['href'])) {
1581 $tempurl = 'tmp-' . md5($attrib['href']) . '.css';
1582 $_SESSION['modcssurls'][$tempurl] = $attrib['href'];
1583 $attrib['href'] = $RCMAIL->url(array('task' => 'utils', 'action' => 'modcss', 'u' => $tempurl, 'c' => $GLOBALS['rcmail_html_container_id']));
1584 $end = ' />';
1585 }
1586 else if (preg_match('/^mailto:(.+)/i', $attrib['href'], $mailto)) {
1587 list($mailto, $url) = explode('?', html_entity_decode($mailto[1], ENT_QUOTES, 'UTF-8'), 2);
1588
1589 // #6020: use raw encoding for correct "+" character handling as specified in RFC6068
1590 $url = rawurldecode($url);
1591 $mailto = rawurldecode($mailto);
1592 $addresses = rcube_mime::decode_address_list($mailto, null, true);
1593 $mailto = array();
1594
1595 // do sanity checks on recipients
1596 foreach ($addresses as $idx => $addr) {
1597 if (rcube_utils::check_email($addr['mailto'], false)) {
1598 $addresses[$idx] = $addr['mailto'];
1599 $mailto[] = $addr['string'];
1600 }
1601 else {
1602 unset($addresses[$idx]);
1603 }
1604 }
1605
1606 if (!empty($addresses)) {
1607 $attrib['href'] = 'mailto:' . implode(',', $addresses);
1608 $attrib['onclick'] = sprintf(
1609 "return %s.command('compose','%s',this)",
1610 rcmail_output::JS_OBJECT_NAME,
1611 rcube::JQ(implode(',', $mailto) . ($url ? "?$url" : '')));
1612 }
1613 else {
1614 $attrib['href'] = '#NOP';
1615 $attrib['onclick'] = '';
1616 }
1617 }
1618 else if (empty($attrib['href']) && !isset($attrib['name'])) {
1619 $attrib['href'] = './#NOP';
1620 $attrib['onclick'] = 'return false';
1621 }
1622 else if (!empty($attrib['href']) && $attrib['href'][0] != '#') {
1623 $attrib['target'] = '_blank';
1624 }
1625
1626 // Better security by adding rel="noreferrer" (#1484686)
1627 if (($tag == 'a' || $tag == 'area') && $attrib['href'] && $attrib['href'][0] != '#') {
1628 $attrib['rel'] = 'noreferrer';
1629 }
1630
1631 // allowed attributes for a|link|area tags
1632 $allow = array('href','name','target','onclick','id','class','style','title',
1633 'rel','type','media','alt','coords','nohref','hreflang','shape');
1634
1635 return html::tag($tag, $attrib, $content, $allow);
1636 }
1637
1638 /**
1639 * Decode address string and re-format it as HTML links
1640 */
1641 function rcmail_address_string($input, $max=null, $linked=false, $addicon=null, $default_charset=null, $title=null)
1642 {
1643 global $RCMAIL, $PRINT_MODE;
1644
1645 $a_parts = rcube_mime::decode_address_list($input, null, true, $default_charset);
1646
1647 if (!count($a_parts)) {
1648 return $input;
1649 }
1650
1651 $c = count($a_parts);
1652 $j = 0;
1653 $out = '';
1654 $allvalues = array();
1655 $show_email = $RCMAIL->config->get('message_show_email');
1656
1657 if ($addicon && !isset($_SESSION['writeable_abook'])) {
1658 $_SESSION['writeable_abook'] = $RCMAIL->get_address_sources(true) ? true : false;
1659 }
1660
1661 foreach ($a_parts as $part) {
1662 $j++;
1663
1664 $name = $part['name'];
1665 $mailto = $part['mailto'];
1666 $string = $part['string'];
1667 $valid = rcube_utils::check_email($mailto, false);
1668
1669 // phishing email prevention (#1488981), e.g. "valid@email.addr <phishing@email.addr>"
1670 if (!$show_email && $valid && $name && $name != $mailto && strpos($name, '@')) {
1671 $name = '';
1672 }
1673
1674 // IDNA ASCII to Unicode
1675 if ($name == $mailto)
1676 $name = rcube_utils::idn_to_utf8($name);
1677 if ($string == $mailto)
1678 $string = rcube_utils::idn_to_utf8($string);
1679 $mailto = rcube_utils::idn_to_utf8($mailto);
1680
1681 if ($PRINT_MODE) {
1682 $address = sprintf('%s &lt;%s&gt;', rcube::Q($name), rcube::Q($mailto));
1683 }
1684 else if ($valid) {
1685 if ($linked) {
1686 $attrs = array(
1687 'href' => 'mailto:' . $mailto,
1688 'class' => 'rcmContactAddress',
1689 'onclick' => sprintf("return %s.command('compose','%s',this)",
1690 rcmail_output::JS_OBJECT_NAME, rcube::JQ(format_email_recipient($mailto, $name))),
1691 );
1692
1693 if ($show_email && $name && $mailto) {
1694 $content = rcube::Q($name ? sprintf('%s <%s>', $name, $mailto) : $mailto);
1695 }
1696 else {
1697 $content = rcube::Q($name ?: $mailto);
1698 $attrs['title'] = $mailto;
1699 }
1700
1701 $address = html::a($attrs, $content);
1702 }
1703 else {
1704 $address = html::span(array('title' => $mailto, 'class' => "rcmContactAddress"),
1705 rcube::Q($name ?: $mailto));
1706 }
1707
1708 if ($addicon && $_SESSION['writeable_abook']) {
1709 $address .= html::a(array(
1710 'href' => "#add",
1711 'title' => $RCMAIL->gettext('addtoaddressbook'),
1712 'class' => 'rcmaddcontact',
1713 'onclick' => sprintf("return %s.command('add-contact','%s',this)",
1714 rcmail_output::JS_OBJECT_NAME, rcube::JQ($string)),
1715 ),
1716 html::img(array(
1717 'src' => $RCMAIL->output->abs_url($addicon, true),
1718 'alt' => "Add contact",
1719 'class' => 'noselect',
1720 )));
1721 }
1722 }
1723 else {
1724 $address = $name ? rcube::Q($name) : '';
1725 if ($mailto) {
1726 $address = trim($address . ' ' . rcube::Q($name ? sprintf('<%s>', $mailto) : $mailto));
1727 }
1728 }
1729
1730 $address = html::span('adr', $address);
1731 $allvalues[] = $address;
1732
1733 if (!$moreadrs) {
1734 $out .= ($out ? ', ' : '') . $address;
1735 }
1736
1737 if ($max && $j == $max && $c > $j) {
1738 if ($linked) {
1739 $moreadrs = $c - $j;
1740 }
1741 else {
1742 $out .= '...';
1743 break;
1744 }
1745 }
1746 }
1747
1748 if ($moreadrs) {
1749 $label = rcube::Q($RCMAIL->gettext(array('name' => 'andnmore', 'vars' => array('nr' => $moreadrs))));
1750
1751 if ($PRINT_MODE) {
1752 $out .= ' ' . html::a(array(
1753 'href' => '#more',
1754 'class' => 'morelink',
1755 'onclick' => '$(this).hide().next().show()',
1756 ), $label)
1757 . html::span(array('style' => 'display:none'), join(', ', $allvalues));
1758 }
1759 else {
1760 $out .= ' ' . html::a(array(
1761 'href' => '#more',
1762 'class' => 'morelink',
1763 'onclick' => sprintf("return %s.show_popup_dialog('%s','%s')",
1764 rcmail_output::JS_OBJECT_NAME,
1765 rcube::JQ(join(', ', $allvalues)),
1766 rcube::JQ($title))
1767 ), $label);
1768 }
1769 }
1770
1771 return $out;
1772 }
1773
1774 /**
1775 * Wrap text to a given number of characters per line
1776 * but respect the mail quotation of replies messages (>).
1777 * Finally add another quotation level by prepending the lines
1778 * with >
1779 *
1780 * @param string Text to wrap
1781 * @param int The line width
1782 * @return string The wrapped text
1783 */
1784 function rcmail_wrap_and_quote($text, $length = 72)
1785 {
1786 // Rebuild the message body with a maximum of $max chars, while keeping quoted message.
1787 $max = max(75, $length + 8);
1788 $lines = preg_split('/\r?\n/', trim($text));
1789 $out = '';
1790
1791 foreach ($lines as $line) {
1792 // don't wrap already quoted lines
1793 if ($line[0] == '>') {
1794 $line = '>' . rtrim($line);
1795 }
1796 else if (mb_strlen($line) > $max) {
1797 $newline = '';
1798
1799 foreach (explode("\n", rcube_mime::wordwrap($line, $length - 2)) as $l) {
1800 $newline .= strlen($l) ? "> $l\n" : ">\n";
1801 }
1802
1803 $line = rtrim($newline);
1804 }
1805 else {
1806 $line = '> ' . $line;
1807 }
1808
1809 // Append the line
1810 $out .= $line . "\n";
1811 }
1812
1813 return rtrim($out, "\n");
1814 }
1815
1816 function rcmail_draftinfo_encode($p)
1817 {
1818 $parts = array();
1819 foreach ($p as $key => $val) {
1820 $encode = $key == 'folder' || strpos($val, ';') !== false;
1821 $parts[] = $key . '=' . ($encode ? 'B::' . base64_encode($val) : $val);
1822 }
1823
1824 return join('; ', $parts);
1825 }
1826
1827 function rcmail_draftinfo_decode($str)
1828 {
1829 $info = array();
1830
1831 foreach (preg_split('/;\s+/', $str) as $part) {
1832 list($key, $val) = explode('=', $part, 2);
1833 if (strpos($val, 'B::') === 0) {
1834 $val = base64_decode(substr($val, 3));
1835 }
1836 else if ($key == 'folder') {
1837 $val = base64_decode($val);
1838 }
1839
1840 $info[$key] = $val;
1841 }
1842
1843 return $info;
1844 }
1845
1846 /**
1847 * Send the MDN response
1848 *
1849 * @param mixed $message Original message object (rcube_message) or UID
1850 * @param array $smtp_error SMTP error array (reference)
1851 *
1852 * @return boolean Send status
1853 */
1854 function rcmail_send_mdn($message, &$smtp_error)
1855 {
1856 global $RCMAIL;
1857
1858 if (!is_object($message) || !is_a($message, 'rcube_message')) {
1859 $message = new rcube_message($message);
1860 }
1861
1862 if ($message->headers->mdn_to && empty($message->headers->flags['MDNSENT']) &&
1863 ($RCMAIL->storage->check_permflag('MDNSENT') || $RCMAIL->storage->check_permflag('*'))
1864 ) {
1865 $identity = rcmail_identity_select($message);
1866 $sender = format_email_recipient($identity['email'], $identity['name']);
1867 $recipient = array_shift(rcube_mime::decode_address_list(
1868 $message->headers->mdn_to, 1, true, $message->headers->charset));
1869 $mailto = $recipient['mailto'];
1870
1871 $compose = new Mail_mime("\r\n");
1872
1873 $compose->setParam('text_encoding', 'quoted-printable');
1874 $compose->setParam('html_encoding', 'quoted-printable');
1875 $compose->setParam('head_encoding', 'quoted-printable');
1876 $compose->setParam('head_charset', RCUBE_CHARSET);
1877 $compose->setParam('html_charset', RCUBE_CHARSET);
1878 $compose->setParam('text_charset', RCUBE_CHARSET);
1879
1880 // compose headers array
1881 $headers = array(
1882 'Date' => $RCMAIL->user_date(),
1883 'From' => $sender,
1884 'To' => $message->headers->mdn_to,
1885 'Subject' => $RCMAIL->gettext('receiptread') . ': ' . $message->subject,
1886 'Message-ID' => $RCMAIL->gen_message_id($identity['email']),
1887 'X-Sender' => $identity['email'],
1888 'References' => trim($message->headers->references . ' ' . $message->headers->messageID),
1889 'In-Reply-To' => $message->headers->messageID,
1890 );
1891
1892 $report = "Final-Recipient: rfc822; {$identity['email']}\r\n"
1893 . "Original-Message-ID: {$message->headers->messageID}\r\n"
1894 . "Disposition: manual-action/MDN-sent-manually; displayed\r\n";
1895
1896 if ($message->headers->to) {
1897 $report .= "Original-Recipient: {$message->headers->to}\r\n";
1898 }
1899
1900 if ($agent = $RCMAIL->config->get('useragent')) {
1901 $headers['User-Agent'] = $agent;
1902 $report .= "Reporting-UA: $agent\r\n";
1903 }
1904
1905 $to = rcube_mime::decode_mime_string($message->headers->to, $message->headers->charset);
1906 $date = $RCMAIL->format_date($message->headers->date, $RCMAIL->config->get('date_long'));
1907 $body = $RCMAIL->gettext("yourmessage") . "\r\n\r\n" .
1908 "\t" . $RCMAIL->gettext("to") . ": {$to}\r\n" .
1909 "\t" . $RCMAIL->gettext("subject") . ": {$message->subject}\r\n" .
1910 "\t" . $RCMAIL->gettext("date") . ": {$date}\r\n" .
1911 "\r\n" . $RCMAIL->gettext("receiptnote");
1912
1913 $compose->headers(array_filter($headers));
1914 $compose->setContentType('multipart/report', array('report-type'=> 'disposition-notification'));
1915 $compose->setTXTBody(rcube_mime::wordwrap($body, 75, "\r\n"));
1916 $compose->addAttachment($report, 'message/disposition-notification', 'MDNPart2.txt', false, '7bit', 'inline');
1917
1918 // SMTP options
1919 $options = array('mdn_use_from' => (bool) $RCMAIL->config->get('mdn_use_from'));
1920
1921 $sent = $RCMAIL->deliver_message($compose, $identity['email'], $mailto, $smtp_error, $body_file, $options, true);
1922
1923 if ($sent) {
1924 $RCMAIL->storage->set_flag($message->uid, 'MDNSENT');
1925 return true;
1926 }
1927 }
1928
1929 return false;
1930 }
1931
1932 /**
1933 * Detect recipient identity from specified message
1934 */
1935 function rcmail_identity_select($MESSAGE, $identities = null, $compose_mode = 'reply')
1936 {
1937 $a_recipients = array();
1938 $a_names = array();
1939
1940 if ($identities === null) {
1941 $identities = rcmail::get_instance()->user->list_identities(null, true);
1942 }
1943
1944 // extract all recipients of the reply-message
1945 if (is_object($MESSAGE->headers) && in_array($compose_mode, array('reply', 'forward'))) {
1946 $a_to = rcube_mime::decode_address_list($MESSAGE->headers->to, null, true, $MESSAGE->headers->charset);
1947 foreach ($a_to as $addr) {
1948 if (!empty($addr['mailto'])) {
1949 $a_recipients[] = strtolower($addr['mailto']);
1950 $a_names[] = $addr['name'];
1951 }
1952 }
1953
1954 if (!empty($MESSAGE->headers->cc)) {
1955 $a_cc = rcube_mime::decode_address_list($MESSAGE->headers->cc, null, true, $MESSAGE->headers->charset);
1956 foreach ($a_cc as $addr) {
1957 if (!empty($addr['mailto'])) {
1958 $a_recipients[] = strtolower($addr['mailto']);
1959 $a_names[] = $addr['name'];
1960 }
1961 }
1962 }
1963 }
1964
1965 // decode From: address
1966 $from = rcube_mime::decode_address_list($MESSAGE->headers->from, null, true, $MESSAGE->headers->charset);
1967 $from = array_shift($from);
1968 $from['mailto'] = strtolower($from['mailto']);
1969
1970 $from_idx = null;
1971 $found_idx = array('to' => null, 'from' => null);
1972 $check_from = in_array($compose_mode, array('draft', 'edit', 'reply'));
1973
1974 // Select identity
1975 foreach ($identities as $idx => $ident) {
1976 // use From: header when in edit/draft or reply-to-self
1977 if ($check_from && $from['mailto'] == strtolower($ident['email_ascii'])) {
1978 // remember first matching identity address
1979 if ($found_idx['from'] === null) {
1980 $found_idx['from'] = $idx;
1981 }
1982 // match identity name
1983 if ($from['name'] && $ident['name'] && $from['name'] == $ident['name']) {
1984 $from_idx = $idx;
1985 break;
1986 }
1987 }
1988 // use replied/forwarded message recipients
1989 else if (($found = array_search(strtolower($ident['email_ascii']), $a_recipients)) !== false) {
1990 // remember first matching identity address
1991 if ($found_idx['to'] === null) {
1992 $found_idx['to'] = $idx;
1993 }
1994 // match identity name
1995 if ($a_names[$found] && $ident['name'] && $a_names[$found] == $ident['name']) {
1996 $from_idx = $idx;
1997 break;
1998 }
1999 }
2000 }
2001
2002 // If matching by name+address didn't find any matches,
2003 // get first found identity (address) if any
2004 if ($from_idx === null) {
2005 $from_idx = $found_idx['from'] !== null ? $found_idx['from'] : $found_idx['to'];
2006 }
2007
2008 // Try Return-Path
2009 if ($from_idx === null && ($return_path = $MESSAGE->headers->others['return-path'])) {
2010 $return_path = array_map('strtolower', (array) $return_path);
2011
2012 foreach ($identities as $idx => $ident) {
2013 // Return-Path header contains an email address, but on some mailing list
2014 // it can be e.g. <pear-dev-return-55250-local=domain.tld@lists.php.net>
2015 // where local@domain.tld is the address we're looking for (#1489241)
2016 $ident1 = strtolower($ident['email_ascii']);
2017 $ident2 = str_replace('@', '=', $ident1);
2018 $ident1 = '<' . $ident1 . '>';
2019 $ident2 = '-' . $ident2 . '@';
2020
2021 foreach ($return_path as $path) {
2022 if ($path == $ident1 || stripos($path, $ident2)) {
2023 $from_idx = $idx;
2024 break 2;
2025 }
2026 }
2027 }
2028 }
2029
2030 // See identity_select plugin for example usage of this hook
2031 $plugin = rcmail::get_instance()->plugins->exec_hook('identity_select',
2032 array('message' => $MESSAGE, 'identities' => $identities, 'selected' => $from_idx));
2033
2034 $selected = $plugin['selected'];
2035
2036 // default identity is always first on the list
2037 return $identities[$selected !== null ? $selected : 0];
2038 }
2039
2040 // Fixes some content-type names
2041 function rcmail_fix_mimetype($name)
2042 {
2043 $map = array(
2044 'image/x-ms-bmp' => 'image/bmp', // #1490282
2045 );
2046
2047 $name = strtolower($name);
2048
2049 if ($alias = $map[$name]) {
2050 $name = $alias;
2051 }
2052 // Some versions of Outlook create garbage Content-Type:
2053 // application/pdf.A520491B_3BF7_494D_8855_7FAC2C6C0608
2054 else if (preg_match('/^application\/pdf.+/', $name)) {
2055 $name = 'application/pdf';
2056 }
2057 // treat image/pjpeg (image/pjpg, image/jpg) as image/jpeg (#1489097)
2058 else if (preg_match('/^image\/p?jpe?g$/', $name)) {
2059 $name = 'image/jpeg';
2060 }
2061
2062 return $name;
2063 }
2064
2065 // return attachment filename, handle empty filename case
2066 function rcmail_attachment_name($attachment, $display = false)
2067 {
2068 global $RCMAIL;
2069
2070 $filename = (string) $attachment->filename;
2071 $filename = preg_replace('/[\x00-\x1F\x7F]/', '', $filename);
2072
2073 if ($filename === '') {
2074 if ($attachment->mimetype == 'text/html') {
2075 $filename = $RCMAIL->gettext('htmlmessage');
2076 }
2077 else {
2078 $ext = (array) rcube_mime::get_mime_extensions($attachment->mimetype);
2079 $ext = array_shift($ext);
2080 $filename = $RCMAIL->gettext('messagepart') . ' ' . $attachment->mime_id;
2081 if ($ext) {
2082 $filename .= '.' . $ext;
2083 }
2084 }
2085 }
2086
2087 // Display smart names for some known mimetypes
2088 if ($display) {
2089 if (preg_match('/application\/(pgp|pkcs7)-signature/i', $attachment->mimetype)) {
2090 $filename = $RCMAIL->gettext('digitalsig');
2091 }
2092 }
2093
2094 return $filename;
2095 }
2096
2097 function rcmail_search_filter($attrib)
2098 {
2099 global $RCMAIL;
2100
2101 if (!strlen($attrib['id'])) {
2102 $attrib['id'] = 'rcmlistfilter';
2103 }
2104
2105 $attrib['onchange'] = rcmail_output::JS_OBJECT_NAME.'.filter_mailbox(this.value)';
2106
2107 // Content-Type values of messages with attachments
2108 // the same as in app.js:add_message_row()
2109 $ctypes = array('application/', 'multipart/m', 'multipart/signed', 'multipart/report');
2110
2111 // Build search string of "with attachment" filter
2112 $attachment = trim(str_repeat(' OR', count($ctypes)-1));
2113 foreach ($ctypes as $type) {
2114 $attachment .= ' HEADER Content-Type ' . rcube_imap_generic::escape($type);
2115 }
2116
2117 $select = new html_select($attrib);
2118 $select->add($RCMAIL->gettext('all'), 'ALL');
2119 $select->add($RCMAIL->gettext('unread'), 'UNSEEN');
2120 $select->add($RCMAIL->gettext('flagged'), 'FLAGGED');
2121 $select->add($RCMAIL->gettext('unanswered'), 'UNANSWERED');
2122 if (!$RCMAIL->config->get('skip_deleted')) {
2123 $select->add($RCMAIL->gettext('deleted'), 'DELETED');
2124 $select->add($RCMAIL->gettext('undeleted'), 'UNDELETED');
2125 }
2126 $select->add($RCMAIL->gettext('withattachment'), $attachment);
2127 $select->add($RCMAIL->gettext('priority').': '.$RCMAIL->gettext('highest'), 'HEADER X-PRIORITY 1');
2128 $select->add($RCMAIL->gettext('priority').': '.$RCMAIL->gettext('high'), 'HEADER X-PRIORITY 2');
2129 $select->add($RCMAIL->gettext('priority').': '.$RCMAIL->gettext('normal'), 'NOT HEADER X-PRIORITY 1 NOT HEADER X-PRIORITY 2 NOT HEADER X-PRIORITY 4 NOT HEADER X-PRIORITY 5');
2130 $select->add($RCMAIL->gettext('priority').': '.$RCMAIL->gettext('low'), 'HEADER X-PRIORITY 4');
2131 $select->add($RCMAIL->gettext('priority').': '.$RCMAIL->gettext('lowest'), 'HEADER X-PRIORITY 5');
2132
2133 $RCMAIL->output->add_gui_object('search_filter', $attrib['id']);
2134
2135 return $select->show($_REQUEST['_search'] ? $_SESSION['search_filter'] : 'ALL');
2136 }
2137
2138 function rcmail_search_interval($attrib)
2139 {
2140 global $RCMAIL;
2141
2142 if (!strlen($attrib['id'])) {
2143 $attrib['id'] = 'rcmsearchinterval';
2144 }
2145
2146 $select = new html_select($attrib);
2147 $select->add('', '');
2148
2149 foreach (array('1W', '1M', '1Y', '-1W', '-1M', '-1Y') as $value) {
2150 $select->add($RCMAIL->gettext('searchinterval' . $value), $value);
2151 }
2152
2153 $RCMAIL->output->add_gui_object('search_interval', $attrib['id']);
2154
2155 return $select->show($_REQUEST['_search'] ? $_SESSION['search_interval'] : '');
2156 }
2157
2158 function rcmail_message_error()
2159 {
2160 global $RCMAIL;
2161
2162 // Set env variables for messageerror.html template
2163 if ($RCMAIL->action == 'show') {
2164 $mbox_name = $RCMAIL->storage->get_folder();
2165
2166 $RCMAIL->output->set_env('mailbox', $mbox_name);
2167 $RCMAIL->output->set_env('uid', null);
2168 }
2169
2170 // display error message
2171 $RCMAIL->output->show_message('messageopenerror', 'error');
2172 // ... display message error page
2173 $RCMAIL->output->send('messageerror');
2174 }
2175
2176 function rcmail_message_import_form($attrib = array())
2177 {
2178 global $RCMAIL;
2179
2180 $RCMAIL->output->add_label('selectimportfile','importwait');
2181
2182 $input_attr = array(
2183 'multiple' => true,
2184 'name' => '_file[]',
2185 'accept' => ".eml, .mbox, message/rfc822, text/*",
2186 );
2187
2188 $attrib['prefix'] = html::tag('input', array('type' => 'hidden', 'name' => '_unlock', 'value' => ''))
2189 . html::tag('input', array('type' => 'hidden', 'name' => '_framed', 'value' => '1'));
2190
2191 return $RCMAIL->upload_form($attrib, 'importform', 'import-messages', $input_attr);
2192 }
2193
2194 /**
2195 * Add groups from the given address source to the address book widget
2196 */
2197 function rcmail_compose_contact_groups($abook, $source_id, $search = null, $search_mode = 0)
2198 {
2199 global $RCMAIL, $OUTPUT;
2200
2201 $jsresult = array();
2202 foreach ($abook->list_groups($search, $search_mode) as $group) {
2203 $abook->reset();
2204 $abook->set_group($group['ID']);
2205
2206 // group (distribution list) with email address(es)
2207 if ($group['email']) {
2208 foreach ((array)$group['email'] as $email) {
2209 $row_id = 'G'.$group['ID'];
2210 $jsresult[$row_id] = format_email_recipient($email, $group['name']);
2211 $OUTPUT->command('add_contact_row', $row_id, array(
2212 'contactgroup' => html::span(array('title' => $email), rcube::Q($group['name']))), 'group');
2213 }
2214 }
2215 // make virtual groups clickable to list their members
2216 else if ($group['virtual']) {
2217 $row_id = 'G'.$group['ID'];
2218 $OUTPUT->command('add_contact_row', $row_id, array(
2219 'contactgroup' => html::a(array(
2220 'href' => '#list',
2221 'rel' => $group['ID'],
2222 'title' => $RCMAIL->gettext('listgroup'),
2223 'onclick' => sprintf("return %s.command('pushgroup',{'source':'%s','id':'%s'},this,event)",
2224 rcmail_output::JS_OBJECT_NAME, $source_id, $group['ID']),
2225 ), rcube::Q($group['name']) . '&nbsp;' . html::span('action', '&raquo;'))),
2226 'group',
2227 array('ID' => $group['ID'], 'name' => $group['name'], 'virtual' => true));
2228 }
2229 // show group with count
2230 else if (($result = $abook->count()) && $result->count) {
2231 $row_id = 'E'.$group['ID'];
2232 $jsresult[$row_id] = $group['name'];
2233 $OUTPUT->command('add_contact_row', $row_id, array(
2234 'contactgroup' => rcube::Q($group['name'] . ' (' . intval($result->count) . ')')), 'group');
2235 }
2236 }
2237
2238 $abook->reset();
2239 $abook->set_group(0);
2240
2241 return $jsresult;
2242 }
2243
2244 function rcmail_save_attachment($message, $pid, $compose_id, $params = array())
2245 {
2246 global $COMPOSE;
2247
2248 $rcmail = rcmail::get_instance();
2249 $storage = $rcmail->get_storage();
2250
2251 if ($pid) {
2252 // attachment requested
2253 $part = $message->mime_parts[$pid];
2254 $size = $part->size;
2255 $mimetype = $part->ctype_primary . '/' . $part->ctype_secondary;
2256 $filename = $params['filename'] ?: rcmail_attachment_name($part);
2257 }
2258 else if (is_object($message)) {
2259 // the whole message requested
2260 $size = $message->size;
2261 $mimetype = 'message/rfc822';
2262 $filename = $params['filename'] ?: 'message_rfc822.eml';
2263 }
2264 else if (is_string($message)) {
2265 // the whole message requested
2266 $size = strlen($message);
2267 $data = $message;
2268 $mimetype = $params['mimetype'];
2269 $filename = $params['filename'];
2270 }
2271
2272 if (!isset($data)) {
2273 // don't load too big attachments into memory
2274 if (!rcube_utils::mem_check($size)) {
2275 $temp_dir = unslashify($rcmail->config->get('temp_dir'));
2276 $path = tempnam($temp_dir, 'rcmAttmnt');
2277
2278 if ($fp = fopen($path, 'w')) {
2279 if ($pid) {
2280 // part body
2281 $message->get_part_body($pid, false, 0, $fp);
2282 }
2283 else {
2284 // complete message
2285 $storage->get_raw_body($message->uid, $fp);
2286 }
2287
2288 fclose($fp);
2289 }
2290 else {
2291 return false;
2292 }
2293 }
2294 else if ($pid) {
2295 // part body
2296 $data = $message->get_part_body($pid);
2297 }
2298 else {
2299 // complete message
2300 $data = $storage->get_raw_body($message->uid);
2301 }
2302 }
2303
2304 $attachment = array(
2305 'group' => $compose_id,
2306 'name' => $filename,
2307 'mimetype' => $mimetype,
2308 'content_id' => $part ? $part->content_id : null,
2309 'data' => $data,
2310 'path' => $path,
2311 'size' => $path ? filesize($path) : strlen($data),
2312 'charset' => $part ? $part->charset : $params['charset'],
2313 );
2314
2315 $attachment = $rcmail->plugins->exec_hook('attachment_save', $attachment);
2316
2317 if ($attachment['status']) {
2318 unset($attachment['data'], $attachment['status'], $attachment['content_id'], $attachment['abort']);
2319
2320 // rcube_session::append() replaces current session data with the old values
2321 // (in rcube_session::reload()). This is a problem in 'compose' action, because before
2322 // the first append() use we set some important data in the session.
2323 // It also overwrites attachments list. Fixing reload() is not so simple if possible
2324 // as we don't really know what has been added and what removed in meantime.
2325 // So, for now we'll do not use append() on 'compose' action (#1490608).
2326
2327 if ($rcmail->action == 'compose') {
2328 $COMPOSE['attachments'][$attachment['id']] = $attachment;
2329 }
2330 else {
2331 $rcmail->session->append('compose_data_' . $compose_id . '.attachments', $attachment['id'], $attachment);
2332 }
2333
2334 return $attachment;
2335 }
2336 else if ($path) {
2337 @unlink($path);
2338 }
2339
2340 return false;
2341 }
2342
2343 // Return mimetypes supported by the browser
2344 function rcmail_supported_mimetypes()
2345 {
2346 $rcmail = rcube::get_instance();
2347
2348 // mimetypes supported by the browser (default settings)
2349 $mimetypes = (array) $rcmail->config->get('client_mimetypes');
2350
2351 // Remove unsupported types, which makes that attachment which cannot be
2352 // displayed in a browser will be downloaded directly without displaying an overlay page
2353 if (empty($_SESSION['browser_caps']['pdf']) && ($key = array_search('application/pdf', $mimetypes)) !== false) {
2354 unset($mimetypes[$key]);
2355 }
2356
2357 if (empty($_SESSION['browser_caps']['flash']) && ($key = array_search('application/x-shockwave-flash', $mimetypes)) !== false) {
2358 unset($mimetypes[$key]);
2359 }
2360
2361 foreach (array('tiff', 'webp') as $type) {
2362 if (empty($_SESSION['browser_caps'][$type]) && ($key = array_search('image/' . $type, $mimetypes)) !== false) {
2363 // can we convert it to jpeg?
2364 if (!rcube_image::is_convertable('image/' . $type)) {
2365 unset($mimetypes[$key]);
2366 }
2367 }
2368 }
2369
2370 // @TODO: support mail preview for compose attachments
2371 if ($rcmail->action != 'compose' && !in_array('message/rfc822', $mimetypes)) {
2372 $mimetypes[] = 'message/rfc822';
2373 }
2374
2375 return array_values($mimetypes);
2376 }