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