Aleksander Machniak
2015-12-16 6402eb7f7880c0c0e5ab87a300808306a695a814
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
792  * @param string             Part body
65cc1c 793  * @return string Formatted HTML string
45f56c 794  */
6402eb 795 function rcmail_print_body($part, $p = array(), $body = null)
45f56c 796 {
f5d2ee 797     global $RCMAIL;
9800a8 798
6402eb 799     if ($body === null) {
AM 800         $body = $part->body;
801     }
802
f5d2ee 803     // trigger plugin hook
AM 804     $data = $RCMAIL->plugins->exec_hook('message_part_before',
6402eb 805         array('type' => $part->ctype_secondary, 'body' => $body, 'id' => $part->mime_id)
f5d2ee 806             + $p + array('safe' => false, 'plain' => false, 'inline_html' => true));
ec603f 807
f5d2ee 808     // convert html to text/plain
AM 809     if ($data['plain'] && ($data['type'] == 'html' || $data['type'] == 'enriched')) {
810         if ($data['type'] == 'enriched') {
811             $data['body'] = rcube_enriched::to_html($data['body']);
812         }
813
814         $txt  = new rcube_html2text($data['body'], false, true);
815         $body = $txt->get_text();
816         $part->ctype_secondary = 'plain';
542f15 817     }
f5d2ee 818     // text/html
AM 819     else if ($data['type'] == 'html') {
820         $body = rcmail_wash_html($data['body'], $data, $part->replaces);
821         $part->ctype_secondary = $data['type'];
822     }
823     // text/enriched
824     else if ($data['type'] == 'enriched') {
825         $body = rcube_enriched::to_html($data['body']);
826         $body = rcmail_wash_html($body, $data, $part->replaces);
827         $part->ctype_secondary = 'html';
828     }
829     else {
830         // assert plaintext
6402eb 831         $body = $data['body'];
f5d2ee 832         $part->ctype_secondary = $data['type'] = 'plain';
621a2e 833     }
AM 834
f5d2ee 835     // free some memory (hopefully)
AM 836     unset($data['body']);
88ed23 837
f5d2ee 838     // plaintext postprocessing
AM 839     if ($part->ctype_secondary == 'plain') {
840         if ($part->ctype_secondary == 'plain' && $part->ctype_parameters['format'] == 'flowed') {
841             $body = rcube_mime::unfold_flowed($body);
842         }
cc97ea 843
f5d2ee 844         $body = rcmail_plain_body($body);
AM 845     }
846
847     // allow post-processing of the message body
848     $data = $RCMAIL->plugins->exec_hook('message_part_after',
849         array('type' => $part->ctype_secondary, 'body' => $body, 'id' => $part->mime_id) + $data);
850
851     return $data['type'] == 'html' ? $data['body'] : html::tag('pre', array(), $data['body']);
4f6932 852 }
f96ffd 853
4f6932 854 /**
A 855  * Handle links and citation marks in plain text message
856  *
99b8c1 857  * @param string  Plain text string
A 858  *
4f6932 859  * @return string Formatted HTML string
A 860  */
621a2e 861 function rcmail_plain_body($body)
4f6932 862 {
f5d2ee 863     global $RCMAIL;
33dfdd 864
f5d2ee 865     // make links and email-addresses clickable
AM 866     $attribs  = array('link_attribs' => array('rel' => 'noreferrer', 'target' => '_blank'));
867     $replacer = new rcmail_string_replacer($attribs);
9800a8 868
f5d2ee 869     // search for patterns like links and e-mail addresses and replace with tokens
AM 870     $body = $replacer->replace($body);
4f6932 871
f5d2ee 872     // split body into single lines
AM 873     $body        = preg_split('/\r?\n/', $body);
874     $quote_level = 0;
875     $last        = -1;
4f6932 876
f5d2ee 877     // find/mark quoted lines...
AM 878     for ($n=0, $cnt=count($body); $n < $cnt; $n++) {
879         if ($body[$n][0] == '>' && preg_match('/^(>+ {0,1})+/', $body[$n], $regs)) {
880             $q        = substr_count($regs[0], '>');
881             $body[$n] = substr($body[$n], strlen($regs[0]));
4f6932 882
f5d2ee 883             if ($q > $quote_level) {
AM 884                 $body[$n] = $replacer->get_replacement($replacer->add(
885                     str_repeat('<blockquote>', $q - $quote_level))) . $body[$n];
886                 $last = $n;
887             }
888             else if ($q < $quote_level) {
889                 $body[$n] = $replacer->get_replacement($replacer->add(
890                     str_repeat('</blockquote>', $quote_level - $q))) . $body[$n];
891                 $last = $n;
892             }
893         }
894         else {
895             $q = 0;
896             if ($quote_level > 0)
897                 $body[$n] = $replacer->get_replacement($replacer->add(
898                     str_repeat('</blockquote>', $quote_level))) . $body[$n];
899         }
900
901         $quote_level = $q;
99b8c1 902     }
4f6932 903
f5d2ee 904     $body = join("\n", $body);
4f6932 905
f5d2ee 906     // quote plain text (don't use rcube::Q() here, to display entities "as is")
AM 907     $table = get_html_translation_table(HTML_SPECIALCHARS);
908     unset($table['?']);
909     $body = strtr($body, $table);
a4c970 910
f5d2ee 911     // colorize signature (up to <sig_max_lines> lines)
AM 912     $len = strlen($body);
913     $sig_max_lines = $RCMAIL->config->get('sig_max_lines', 15);
4f6932 914
f5d2ee 915     while (($sp = strrpos($body, "-- \n", $sp ? -$len+$sp-1 : 0)) !== false) {
AM 916         if ($sp == 0 || $body[$sp-1] == "\n") {
917             // do not touch blocks with more that X lines
918             if (substr_count($body, "\n", $sp) < $sig_max_lines) {
919                 $body = substr($body, 0, max(0, $sp))
920                     . '<span class="sig">'.substr($body, $sp).'</span>';
921             }
922
923             break;
924         }
4f6932 925     }
A 926
f5d2ee 927     // insert url/mailto links and citation tags
AM 928     $body = $replacer->resolve($body);
4f6932 929
f5d2ee 930     return $body;
21e724 931 }
T 932
933 /**
934  * Callback function for washtml cleaning class
935  */
2b017e 936 function rcmail_washtml_callback($tagname, $attrib, $content, $washtml)
21e724 937 {
f5d2ee 938     switch ($tagname) {
21e724 939     case 'form':
f5d2ee 940         $out = html::div('form', $content);
AM 941         break;
9800a8 942
1c499a 943     case 'style':
f5d2ee 944         // decode all escaped entities and reduce to ascii strings
AM 945         $stripped = preg_replace('/[^a-zA-Z\(:;]/', '', rcube_utils::xss_entity_decode($content));
9800a8 946
f5d2ee 947         // now check for evil strings like expression, behavior or url()
AM 948         if (!preg_match('/expression|behavior|javascript:|import[^a]/i', $stripped)) {
949             if (!$washtml->get_config('allow_remote') && stripos($stripped, 'url('))
950                 $washtml->extlinks = true;
951             else
952                 $out = html::tag('style', array('type' => 'text/css'), $content);
953             break;
954         }
9800a8 955
21e724 956     default:
f5d2ee 957         $out = '';
AM 958     }
9800a8 959
f5d2ee 960     return $out;
2337a8 961 }
A 962
963 /**
45f56c 964  * return table with message headers
T 965  */
a8a72e 966 function rcmail_message_headers($attrib, $headers=null)
4fdaa0 967 {
f5d2ee 968     global $MESSAGE, $PRINT_MODE, $RCMAIL;
AM 969     static $sa_attrib;
9800a8 970
f5d2ee 971     // keep header table attrib
AM 972     if (is_array($attrib) && !$sa_attrib && !$attrib['valueof'])
973         $sa_attrib = $attrib;
974     else if (!is_array($attrib) && is_array($sa_attrib))
975         $attrib = $sa_attrib;
9800a8 976
f5d2ee 977     if (!isset($MESSAGE)) {
AM 978         return false;
a49a00 979     }
9800a8 980
f5d2ee 981     // get associative array of headers object
AM 982     if (!$headers) {
983         $headers_obj = $MESSAGE->headers;
984         $headers     = get_object_vars($MESSAGE->headers);
985     }
986     else if (is_object($headers)) {
987         $headers_obj = $headers;
988         $headers     = get_object_vars($headers_obj);
989     }
990     else {
991         $headers_obj = rcube_message_header::from_array($headers);
992     }
9800a8 993
f5d2ee 994     // show these headers
AM 995     $standard_headers = array('subject', 'from', 'sender', 'to', 'cc', 'bcc', 'replyto',
996         'mail-reply-to', 'mail-followup-to', 'date', 'priority');
997     $exclude_headers = $attrib['exclude'] ? explode(',', $attrib['exclude']) : array();
998     $output_headers  = array();
faea23 999
f5d2ee 1000     foreach ($standard_headers as $hkey) {
AM 1001         $ishtml = false;
9800a8 1002
f5d2ee 1003         if ($headers[$hkey])
AM 1004             $value = $headers[$hkey];
1005         else if ($headers['others'][$hkey])
1006             $value = $headers['others'][$hkey];
1007         else if (!$attrib['valueof'])
1008             continue;
9800a8 1009
f5d2ee 1010         if (in_array($hkey, $exclude_headers))
AM 1011             continue;
4e17e6 1012
f5d2ee 1013         $header_title = $RCMAIL->gettext(preg_replace('/(^mail-|-)/', '', $hkey));
AM 1014
1015         if ($hkey == 'date') {
1016             if ($PRINT_MODE)
1017                 $header_value = $RCMAIL->format_date($value, $RCMAIL->config->get('date_long', 'x'));
1018             else
1019                 $header_value = $RCMAIL->format_date($value);
1020         }
1021         else if ($hkey == 'priority') {
1022             if ($value) {
1023                 $header_value = html::span('prio' . $value, rcmail_localized_priority($value));
1024             }
1025             else
1026                 continue;
1027         }
1028         else if ($hkey == 'replyto') {
1029             if ($headers['replyto'] != $headers['from']) {
1030                 $header_value = rcmail_address_string($value, $attrib['max'], true,
1031                     $attrib['addicon'], $headers['charset'], $header_title);
1032                 $ishtml = true;
1033             }
1034             else
1035                 continue;
1036         }
1037         else if ($hkey == 'mail-reply-to') {
1038             if ($headers['mail-replyto'] != $headers['reply-to']
1039                 && $headers['reply-to'] != $headers['from']
1040             ) {
1041                 $header_value = rcmail_address_string($value, $attrib['max'], true,
1042                     $attrib['addicon'], $headers['charset'], $header_title);
1043                 $ishtml = true;
1044             }
1045             else
1046                 continue;
1047         }
1048         else if ($hkey == 'sender') {
1049             if ($headers['sender'] != $headers['from']) {
1050                 $header_value = rcmail_address_string($value, $attrib['max'], true,
1051                     $attrib['addicon'], $headers['charset'], $header_title);
1052                 $ishtml = true;
1053             }
1054             else
1055                 continue;
1056         }
1057         else if ($hkey == 'mail-followup-to') {
1058             $header_value = rcmail_address_string($value, $attrib['max'], true,
1059                 $attrib['addicon'], $headers['charset'], $header_title);
1060             $ishtml = true;
1061         }
1062         else if (in_array($hkey, array('from', 'to', 'cc', 'bcc'))) {
1063             $header_value = rcmail_address_string($value, $attrib['max'], true,
1064                 $attrib['addicon'], $headers['charset'], $header_title);
1065             $ishtml = true;
1066         }
1067         else if ($hkey == 'subject' && empty($value))
1068             $header_value = $RCMAIL->gettext('nosubject');
1069         else
1070             $header_value = trim(rcube_mime::decode_header($value, $headers['charset']));
1071
1072         $output_headers[$hkey] = array(
1073             'title' => $header_title,
1074             'value' => $header_value,
1075             'raw'   => $value,
1076             'html'  => $ishtml,
1077         );
1078     }
1079
1080     $plugin = $RCMAIL->plugins->exec_hook('message_headers_output', array(
1081         'output'  => $output_headers,
1082         'headers' => $headers_obj,
1083         'exclude' => $exclude_headers
1084     ));
1085
1086     // single header value is requested
1087     if (!empty($attrib['valueof'])) {
1088         return rcube::Q($plugin['output'][$attrib['valueof']]['value'], ($attrib['valueof'] == 'subject' ? 'strict' : 'show'));
1089     }
1090
1091     // compose html table
1092     $table = new html_table(array('cols' => 2));
1093
1094     foreach ($plugin['output'] as $hkey => $row) {
1095         $val = $row['html'] ? $row['value'] : rcube::Q($row['value'], ($hkey == 'subject' ? 'strict' : 'show'));
1096
1097         $table->add(array('class' => 'header-title'), rcube::Q($row['title']));
1098         $table->add(array('class' => 'header '.$hkey), $val);
1099     }
1100
1101     return $table->show($attrib);
c6be45 1102 }
T 1103
a49a00 1104 /**
T 1105  * Convert Priority header value into a localized string
1106  */
1107 function rcmail_localized_priority($value)
1108 {
f5d2ee 1109     global $RCMAIL;
6b2b2e 1110
f5d2ee 1111     $labels_map = array(
AM 1112         '1' => 'highest',
1113         '2' => 'high',
1114         '3' => 'normal',
1115         '4' => 'low',
1116         '5' => 'lowest',
1117     );
297c1a 1118
f5d2ee 1119     if ($value && $labels_map[$value]) {
AM 1120         return $RCMAIL->gettext($labels_map[$value]);
1121     }
297c1a 1122
f5d2ee 1123     return '';
a49a00 1124 }
c6be45 1125
T 1126 /**
1127  * return block to show full message headers
1128  */
1129 function rcmail_message_full_headers($attrib, $headers=NULL)
1130 {
f5d2ee 1131     global $OUTPUT, $RCMAIL;
c08b18 1132
f5d2ee 1133     $html = html::div(array('id' => "all-headers", 'class' => "all", 'style' => 'display:none'), html::div(array('id' => 'headers-source'), ''));
AM 1134     $html .= html::div(array(
1135             'class'   => "more-headers show-headers",
1136             'onclick' => "return ".rcmail_output::JS_OBJECT_NAME.".command('show-headers','',this)",
1137             'title'   => $RCMAIL->gettext('togglefullheaders')
1138         ), '');
c08b18 1139
f5d2ee 1140     $OUTPUT->add_gui_object('all_headers_row', 'all-headers');
AM 1141     $OUTPUT->add_gui_object('all_headers_box', 'headers-source');
c08b18 1142
f5d2ee 1143     return html::div($attrib, $html);
c6be45 1144 }
4e17e6 1145
45f56c 1146 /**
21605c 1147  * Handler for the 'messagebody' GUI object
45f56c 1148  *
21605c 1149  * @param array Named parameters
T 1150  * @return string HTML content showing the message body
45f56c 1151  */
4e17e6 1152 function rcmail_message_body($attrib)
e0960f 1153 {
f5d2ee 1154     global $OUTPUT, $MESSAGE, $RCMAIL, $REMOTE_OBJECTS;
5f8686 1155
f5d2ee 1156     if (!is_array($MESSAGE->parts) && empty($MESSAGE->body)) {
AM 1157         return '';
4e17e6 1158     }
f5d2ee 1159
AM 1160     if (!$attrib['id'])
1161         $attrib['id'] = 'rcmailMsgBody';
1162
1163     $safe_mode = $MESSAGE->is_safe || intval($_GET['_safe']);
1164     $out = '';
1165
1166     $header_attrib = array();
1167     foreach ($attrib as $attr => $value) {
1168         if (preg_match('/^headertable([a-z]+)$/i', $attr, $regs)) {
1169             $header_attrib[$regs[1]] = $value;
1170         }
1171     }
1172
1173     if (!empty($MESSAGE->parts)) {
1174         foreach ($MESSAGE->parts as $part) {
1175             if ($part->type == 'headers') {
1176                 $out .= html::div('message-partheaders', rcmail_message_headers(sizeof($header_attrib) ? $header_attrib : null, $part->headers));
1177             }
1178             else if ($part->type == 'content') {
1179                 // unsupported (e.g. encrypted)
1180                 if ($part->realtype) {
1181                     if ($part->realtype == 'multipart/encrypted' || $part->realtype == 'application/pkcs7-mime') {
1182                         $out .= html::span('part-notice', $RCMAIL->gettext('encryptedmessage'));
1183                     }
1184                     continue;
1185                 }
1186                 else if (!$part->size) {
1187                     continue;
1188                 }
1189
1190                 // Check if we have enough memory to handle the message in it
1191                 // #1487424: we need up to 10x more memory than the body
1192                 else if (!rcube_utils::mem_check($part->size * 10)) {
1193                     $out .= html::span('part-notice', $RCMAIL->gettext('messagetoobig'). ' '
1194                         . html::a('?_task=mail&_action=get&_download=1&_uid='.$MESSAGE->uid.'&_part='.$part->mime_id
e03bcf 1195                             .'&_mbox='. urlencode($MESSAGE->folder), $RCMAIL->gettext('download')));
f5d2ee 1196                     continue;
AM 1197                 }
1198
1199                 if (empty($part->ctype_parameters) || empty($part->ctype_parameters['charset'])) {
1200                     $part->ctype_parameters['charset'] = $MESSAGE->headers->charset;
1201                 }
1202
1203                 // fetch part if not available
1204                 if (!isset($part->body)) {
1205                     $part->body = $MESSAGE->get_part_content($part->mime_id);
1206                 }
1207
6402eb 1208                 $body = $part->body;
AM 1209
f5d2ee 1210                 // extract headers from message/rfc822 parts
AM 1211                 if ($part->mimetype == 'message/rfc822') {
1212                     $msgpart = rcube_mime::parse_message($part->body);
6402eb 1213                     $body    = rcube_charset::convert($msgpart->body, $msgpart->charset);
AM 1214
f5d2ee 1215                     if (!empty($msgpart->headers)) {
AM 1216                         $part = $msgpart;
1217                         $out .= html::div('message-partheaders', rcmail_message_headers(sizeof($header_attrib) ? $header_attrib : null, $part->headers));
1218                     }
1219                 }
1220
1221                 // message is cached but not exists (#1485443), or other error
6402eb 1222                 if ($body === false) {
f5d2ee 1223                     rcmail_message_error($MESSAGE->uid);
AM 1224                 }
1225
1226                 $plugin = $RCMAIL->plugins->exec_hook('message_body_prefix',
1227                     array('part' => $part, 'prefix' => ''));
1228
6402eb 1229                 $body = rcmail_print_body($part, array('safe' => $safe_mode, 'plain' => !$RCMAIL->config->get('prefer_html')), $body);
f5d2ee 1230
AM 1231                 if ($part->ctype_secondary == 'html') {
1232                     $body     = rcmail_html4inline($body, $attrib['id'], 'rcmBody', $attrs, $safe_mode);
1233                     $div_attr = array('class' => 'message-htmlpart');
1234                     $style    = array();
1235
1236                     if (!empty($attrs)) {
1237                         foreach ($attrs as $a_idx => $a_val)
1238                             $style[] = $a_idx . ': ' . $a_val;
1239                         if (!empty($style))
1240                             $div_attr['style'] = implode('; ', $style);
1241                     }
1242
1243                     $out .= html::div($div_attr, $plugin['prefix'] . $body);
1244                 }
1245                 else
1246                     $out .= html::div('message-part', $plugin['prefix'] . $body);
1247             }
1248         }
3c3433 1249     }
e0960f 1250     else {
f5d2ee 1251         // Check if we have enough memory to handle the message in it
AM 1252         // #1487424: we need up to 10x more memory than the body
1253         if (!rcube_utils::mem_check(strlen($MESSAGE->body) * 10)) {
1254             $out .= html::span('part-notice', $RCMAIL->gettext('messagetoobig'). ' '
1255                 . html::a('?_task=mail&_action=get&_download=1&_uid='.$MESSAGE->uid.'&_part=0'
e03bcf 1256                     .'&_mbox='. urlencode($MESSAGE->folder), $RCMAIL->gettext('download')));
031491 1257         }
TB 1258         else {
f5d2ee 1259             $plugin = $RCMAIL->plugins->exec_hook('message_body_prefix',
AM 1260                 array('part' => $MESSAGE, 'prefix' => ''));
1261
1262             $out .= html::div('message-part', $plugin['prefix'] . html::tag('pre', array(),
1263                 rcmail_plain_body(rcube::Q($MESSAGE->body, 'strict', false))));
031491 1264         }
4e17e6 1265     }
9800a8 1266
f5d2ee 1267     // list images after mail body
AM 1268     if ($RCMAIL->config->get('inline_images', true) && !empty($MESSAGE->attachments)) {
1269         $thumbnail_size   = $RCMAIL->config->get('image_thumbnail_size', 240);
1270         $client_mimetypes = (array)$RCMAIL->config->get('client_mimetypes');
4e17e6 1271
f5d2ee 1272         foreach ($MESSAGE->attachments as $attach_prop) {
AM 1273             // skip inline images
1274             if ($attach_prop->content_id && $attach_prop->disposition == 'inline') {
1275                 continue;
1276             }
1277
1278             // Content-Type: image/*...
1279             if ($mimetype = rcmail_part_image_type($attach_prop)) {
1280                 // display thumbnails
1281                 if ($thumbnail_size) {
1282                     $show_link = array(
1283                         'href'    => $MESSAGE->get_part_url($attach_prop->mime_id, false),
1284                         'onclick' => sprintf(
1285                             'return %s.command(\'load-attachment\',\'%s\',this)',
1286                             rcmail_output::JS_OBJECT_NAME,
1287                             $attach_prop->mime_id)
1288                     );
1289                     $out .= html::p('image-attachment',
1290                         html::a($show_link + array('class' => 'image-link', 'style' => sprintf('width:%dpx', $thumbnail_size)),
1291                             html::img(array(
1292                                 'class' => 'image-thumbnail',
1293                                 'src'   => $MESSAGE->get_part_url($attach_prop->mime_id, 'image') . '&_thumb=1',
1294                                 'title' => $attach_prop->filename,
1295                                 'alt'   => $attach_prop->filename,
1296                                 'style' => sprintf('max-width:%dpx; max-height:%dpx', $thumbnail_size, $thumbnail_size),
1297                             ))
1298                         ) .
1299                         html::span('image-filename', rcube::Q($attach_prop->filename)) .
1300                         html::span('image-filesize', rcube::Q($RCMAIL->message_part_size($attach_prop))) .
1301                         html::span('attachment-links',
1302                             (in_array($mimetype, $client_mimetypes) ? html::a($show_link, $RCMAIL->gettext('showattachment')) . '&nbsp;' : '') .
1303                                 html::a($show_link['href'] . '&_download=1', $RCMAIL->gettext('download'))
1304                         ) .
1305                         html::br(array('style' => 'clear:both'))
1306                     );
1307                 }
1308                 else {
1309                     $out .= html::tag('fieldset', 'image-attachment',
1310                         html::tag('legend', 'image-filename', rcube::Q($attach_prop->filename)) .
1311                         html::p(array('align' => 'center'),
1312                             html::img(array(
1313                                 'src'   => $MESSAGE->get_part_url($attach_prop->mime_id, 'image'),
1314                                 'title' => $attach_prop->filename,
1315                                 'alt'   => $attach_prop->filename,
1316                         )))
1317                     );
1318                 }
1319             }
1320         }
1321     }
1322
1323     // tell client that there are blocked remote objects
1324     if ($REMOTE_OBJECTS && !$safe_mode) {
1325         $OUTPUT->set_env('blockedobjects', true);
1326     }
1327
1328     return html::div($attrib, $out);
e0960f 1329 }
4e17e6 1330
19cc5b 1331 function rcmail_part_image_type($part)
AM 1332 {
f5d2ee 1333     $rcmail = rcmail::get_instance();
19cc5b 1334
f5d2ee 1335     // Skip TIFF images if browser doesn't support this format...
AM 1336     $tiff_support = !empty($_SESSION['browser_caps']) && !empty($_SESSION['browser_caps']['tif']);
1337     // until we can convert them to JPEG
1338     $tiff_support = $tiff_support || $rcmail->config->get('im_convert_path');
19cc5b 1339
f5d2ee 1340     // Content-type regexp
AM 1341     $mime_regex = $tiff_support ? '/^image\//i' : '/^image\/(?!tif)/i';
19cc5b 1342
f5d2ee 1343     // Content-Type: image/*...
AM 1344     if (preg_match($mime_regex, $part->mimetype)) {
1345         return rcmail_fix_mimetype($part->mimetype);
1346     }
19cc5b 1347
f5d2ee 1348     // Many clients use application/octet-stream, we'll detect mimetype
AM 1349     // by checking filename extension
19cc5b 1350
f5d2ee 1351     // Supported image filename extensions to image type map
AM 1352     $types = array(
1353         'jpg'  => 'image/jpeg',
1354         'jpeg' => 'image/jpeg',
1355         'png'  => 'image/png',
1356         'gif'  => 'image/gif',
1357         'bmp'  => 'image/bmp',
1358     );
1359     if ($tiff_support) {
1360         $types['tif']  = 'image/tiff';
1361         $types['tiff'] = 'image/tiff';
1362     }
19cc5b 1363
f5d2ee 1364     if ($part->filename
AM 1365         && preg_match('/^application\/octet-stream$/i', $part->mimetype)
1366         && preg_match('/\.([^.]+)$/i', $part->filename, $m)
1367         && ($extension = strtolower($m[1]))
1368         && isset($types[$extension])
1369     ) {
1370         return $types[$extension];
1371     }
aa055c 1372 }
f5d62f 1373
45f56c 1374 /**
T 1375  * modify a HTML message that it can be displayed inside a HTML page
1376  */
2b017e 1377 function rcmail_html4inline($body, $container_id, $body_id='', &$attributes=null, $allow_remote=false)
cb3dfd 1378 {
f5d2ee 1379     $last_style_pos = 0;
AM 1380     $cont_id        = $container_id.($body_id ? ' div.'.$body_id : '');
9800a8 1381
f5d2ee 1382     // find STYLE tags
AM 1383     while (($pos = stripos($body, '<style', $last_style_pos)) && ($pos2 = stripos($body, '</style>', $pos))) {
1384         $pos = strpos($body, '>', $pos) + 1;
1385         $len = $pos2 - $pos;
ea206d 1386
f5d2ee 1387         // replace all css definitions with #container [def]
AM 1388         $styles = substr($body, $pos, $len);
1389         $styles = rcube_utils::mod_css_styles($styles, $cont_id, $allow_remote);
ea206d 1390
f5d2ee 1391         $body = substr_replace($body, $styles, $pos, $len);
AM 1392         $last_style_pos = $pos2 + strlen($styles) - $len;
ceb708 1393     }
cb3dfd 1394
f5d2ee 1395     // modify HTML links to open a new window if clicked
AM 1396     $GLOBALS['rcmail_html_container_id'] = $container_id;
1397     $body = preg_replace_callback('/<(a|link|area)\s+([^>]+)>/Ui', 'rcmail_alter_html_link', $body);
1398     unset($GLOBALS['rcmail_html_container_id']);
1399
1400     $body = preg_replace(array(
1401             // add comments arround html and other tags
1402             '/(<!DOCTYPE[^>]*>)/i',
1403             '/(<\?xml[^>]*>)/i',
1404             '/(<\/?html[^>]*>)/i',
1405             '/(<\/?head[^>]*>)/i',
1406             '/(<title[^>]*>.*<\/title>)/Ui',
1407             '/(<\/?meta[^>]*>)/i',
1408             // quote <? of php and xml files that are specified as text/html
1409             '/<\?/',
1410             '/\?>/',
1411             // replace <body> with <div>
1412             '/<body([^>]*)>/i',
1413             '/<\/body>/i',
1414         ),
1415         array(
1416             '<!--\\1-->',
1417             '<!--\\1-->',
1418             '<!--\\1-->',
1419             '<!--\\1-->',
1420             '<!--\\1-->',
1421             '<!--\\1-->',
1422             '&lt;?',
1423             '?&gt;',
1424             '<div class="'.$body_id.'"\\1>',
1425             '</div>',
1426         ),
1427         $body);
1428
1429     $attributes = array();
1430
1431     // Handle body attributes that doesn't play nicely with div elements
1432     $regexp = '/<div class="' . preg_quote($body_id, '/') . '"([^>]*)/';
1433     if (preg_match($regexp, $body, $m)) {
1434         $attrs = $m[0];
1435
1436         // Get bgcolor, we'll set it as background-color of the message container
1437         if ($m[1] && preg_match('/bgcolor=["\']*([a-z0-9#]+)["\']*/i', $attrs, $mb)) {
1438             $attributes['background-color'] = $mb[1];
1439             $attrs = preg_replace('/bgcolor=["\']*[a-z0-9#]+["\']*/i', '', $attrs);
cb3dfd 1440         }
f5d2ee 1441
AM 1442         // Get background, we'll set it as background-image of the message container
1443         if ($m[1] && preg_match('/background=["\']*([^"\'>\s]+)["\']*/', $attrs, $mb)) {
1444             $attributes['background-image'] = 'url('.$mb[1].')';
1445             $attrs = preg_replace('/background=["\']*([^"\'>\s]+)["\']*/', '', $attrs);
1446         }
1447
1448         if (!empty($attributes)) {
1449             $body = preg_replace($regexp, rtrim($attrs), $body, 1);
1450         }
1451
1452         // handle body styles related to background image
1453         if ($attributes['background-image']) {
1454             // get body style
1455             if (preg_match('/#'.preg_quote($cont_id, '/').'\s+\{([^}]+)}/i', $body, $m)) {
1456                 // get background related style
1457                 $regexp = '/(background-position|background-repeat)\s*:\s*([^;]+);/i';
1458                 if (preg_match_all($regexp, $m[1], $ma, PREG_SET_ORDER)) {
1459                     foreach ($ma as $style) {
1460                         $attributes[$style[1]] = $style[2];
1461                     }
1462                 }
1463             }
1464         }
cb3dfd 1465     }
f5d2ee 1466     // make sure there's 'rcmBody' div, we need it for proper css modification
AM 1467     // its name is hardcoded in rcmail_message_body() also
1468     else {
1469         $body = '<div class="' . $body_id . '">' . $body . '</div>';
1470     }
86958f 1471
f5d2ee 1472     return $body;
cb3dfd 1473 }
4e17e6 1474
45f56c 1475 /**
1e3254 1476  * parse link (a, link, area) attributes and set correct target
45f56c 1477  */
115263 1478 function rcmail_alter_html_link($matches)
e5af2f 1479 {
f5d2ee 1480     global $RCMAIL;
5c1dfb 1481
f5d2ee 1482     $tag    = strtolower($matches[1]);
AM 1483     $attrib = html::parse_attrib_string($matches[2]);
1484     $end    = '>';
84f5b7 1485
f5d2ee 1486     // Remove non-printable characters in URL (#1487805)
AM 1487     if ($attrib['href'])
1488         $attrib['href'] = preg_replace('/[\x00-\x1F]/', '', $attrib['href']);
29c542 1489
f5d2ee 1490     if ($tag == 'link' && preg_match('/^https?:\/\//i', $attrib['href'])) {
AM 1491         $tempurl = 'tmp-' . md5($attrib['href']) . '.css';
1492         $_SESSION['modcssurls'][$tempurl] = $attrib['href'];
1493         $attrib['href'] = $RCMAIL->url(array('task' => 'utils', 'action' => 'modcss', 'u' => $tempurl, 'c' => $GLOBALS['rcmail_html_container_id']));
1494         $end = ' />';
1495     }
1496     else if (preg_match('/^mailto:(.+)/i', $attrib['href'], $mailto)) {
1497         list($mailto, $url) = explode('?', html_entity_decode($mailto[1], ENT_QUOTES, 'UTF-8'), 2);
eafd5b 1498
f5d2ee 1499         $url       = urldecode($url);
AM 1500         $mailto    = urldecode($mailto);
1501         $addresses = rcube_mime::decode_address_list($mailto, null, true);
1502         $mailto    = array();
eafd5b 1503
f5d2ee 1504         // do sanity checks on recipients
AM 1505         foreach ($addresses as $idx => $addr) {
1506             if (rcube_utils::check_email($addr['mailto'], false)) {
1507                 $addresses[$idx] = $addr['mailto'];
1508                 $mailto[]        = $addr['string'];
1509             }
1510             else {
1511                 unset($addresses[$idx]);
1512             }
1513         }
1514
1515         if (!empty($addresses)) {
1516             $attrib['href']    = 'mailto:' . implode(',', $addresses);
1517             $attrib['onclick'] = sprintf(
1518                 "return %s.command('compose','%s',this)",
1519                 rcmail_output::JS_OBJECT_NAME,
1520                 rcube::JQ(implode(',', $mailto) . ($url ? "?$url" : '')));
1521         }
1522         else {
1523             $attrib['href']    = '#NOP';
1524             $attrib['onclick'] = '';
1525         }
1526     }
1527     else if (empty($attrib['href']) && !$attrib['name']) {
1528         $attrib['href']    = './#NOP';
1529         $attrib['onclick'] = 'return false';
1530     }
1531     else if (!empty($attrib['href']) && $attrib['href'][0] != '#') {
1532         $attrib['target'] = '_blank';
eafd5b 1533     }
AM 1534
f5d2ee 1535     // Better security by adding rel="noreferrer" (#1484686)
AM 1536     if (($tag == 'a' || $tag == 'area') && $attrib['href'] && $attrib['href'][0] != '#') {
1537         $attrib['rel'] = 'noreferrer';
eafd5b 1538     }
e5af2f 1539
f5d2ee 1540     // allowed attributes for a|link|area tags
AM 1541     $allow = array('href','name','target','onclick','id','class','style','title',
1542         'rel','type','media','alt','coords','nohref','hreflang','shape');
1e3254 1543
f5d2ee 1544     return "<$tag" . html::attrib_string($attrib, $allow) . $end;
e5af2f 1545 }
4e17e6 1546
45f56c 1547 /**
T 1548  * decode address string and re-format it as HTML links
1549  */
765ecb 1550 function rcmail_address_string($input, $max=null, $linked=false, $addicon=null, $default_charset=null, $title=null)
8e44f4 1551 {
f5d2ee 1552     global $RCMAIL, $PRINT_MODE;
1088d6 1553
f5d2ee 1554     $a_parts = rcube_mime::decode_address_list($input, null, true, $default_charset);
4e17e6 1555
f5d2ee 1556     if (!sizeof($a_parts)) {
AM 1557         return $input;
ff7542 1558     }
AM 1559
f5d2ee 1560     $c   = count($a_parts);
AM 1561     $j   = 0;
1562     $out = '';
1563     $allvalues  = array();
1564     $show_email = $RCMAIL->config->get('message_show_email');
e99991 1565
f5d2ee 1566     if ($addicon && !isset($_SESSION['writeable_abook'])) {
AM 1567         $_SESSION['writeable_abook'] = $RCMAIL->get_address_sources(true) ? true : false;
8e44f4 1568     }
969cb0 1569
f5d2ee 1570     foreach ($a_parts as $part) {
AM 1571         $j++;
1572
1573         $name   = $part['name'];
1574         $mailto = $part['mailto'];
1575         $string = $part['string'];
1576         $valid  = rcube_utils::check_email($mailto, false);
1577
1578         // phishing email prevention (#1488981), e.g. "valid@email.addr <phishing@email.addr>"
1579         if (!$show_email && $valid && $name && $name != $mailto && strpos($name, '@')) {
1580             $name = '';
1581         }
1582
1583         // IDNA ASCII to Unicode
1584         if ($name == $mailto)
1585             $name = rcube_utils::idn_to_utf8($name);
1586         if ($string == $mailto)
1587             $string = rcube_utils::idn_to_utf8($string);
1588         $mailto = rcube_utils::idn_to_utf8($mailto);
1589
1590         if ($PRINT_MODE) {
1591             $address = sprintf('%s &lt;%s&gt;', rcube::Q($name), rcube::Q($mailto));
1592         }
1593         else if ($valid) {
1594             if ($linked) {
1595                 $attrs = array(
1596                     'href'    => 'mailto:' . $mailto,
1597                     'class'   => 'rcmContactAddress',
1598                     'onclick' => sprintf("return %s.command('compose','%s',this)",
1599                         rcmail_output::JS_OBJECT_NAME, rcube::JQ(format_email_recipient($mailto, $name))),
1600                 );
1601
1602                 if ($show_email && $name && $mailto) {
1603                     $content = rcube::Q($name ? sprintf('%s <%s>', $name, $mailto) : $mailto);
1604                 }
1605                 else {
1606                     $content = rcube::Q($name ? $name : $mailto);
1607                     $attrs['title'] = $mailto;
1608                 }
1609
1610                 $address = html::a($attrs, $content);
1611             }
1612             else {
1613                 $address = html::span(array('title' => $mailto, 'class' => "rcmContactAddress"),
1614                     rcube::Q($name ? $name : $mailto));
1615             }
1616
1617             if ($addicon && $_SESSION['writeable_abook']) {
1618                 $address .= html::a(array(
1619                         'href'    => "#add",
1620                         'title'   => $RCMAIL->gettext('addtoaddressbook'),
1621                         'class'   => 'rcmaddcontact',
1622                         'onclick' => sprintf("return %s.command('add-contact','%s',this)",
1623                             rcmail_output::JS_OBJECT_NAME, rcube::JQ($string)),
1624                     ),
1625                     html::img(array(
1626                         'src' => $RCMAIL->config->get('skin_path') . $addicon,
1627                         'alt' => "Add contact",
1628                 )));
1629             }
969cb0 1630         }
AM 1631         else {
f5d2ee 1632             $address = '';
AM 1633             if ($name)
1634                 $address .= rcube::Q($name);
1635             if ($mailto)
1636                 $address = trim($address . ' ' . rcube::Q($name ? sprintf('<%s>', $mailto) : $mailto));
969cb0 1637         }
AM 1638
f5d2ee 1639         $address = html::span('adr', $address);
AM 1640         $allvalues[] = $address;
8e44f4 1641
f5d2ee 1642         if (!$moreadrs)
AM 1643             $out .= ($out ? ', ' : '') . $address;
1644
1645         if ($max && $j == $max && $c > $j) {
1646             if ($linked) {
1647                 $moreadrs = $c - $j;
1648             }
1649             else {
1650                 $out .= '...';
1651                 break;
1652             }
1653         }
8e44f4 1654     }
9800a8 1655
f5d2ee 1656     if ($moreadrs) {
AM 1657         if ($PRINT_MODE) {
1658             $out .= ' ' . html::a(array(
1659                     'href'    => '#more',
1660                     'class'   => 'morelink',
1661                     'onclick' => '$(this).hide().next().show()',
1662                 ),
1663                 rcube::Q($RCMAIL->gettext(array('name' => 'andnmore', 'vars' => array('nr' => $moreadrs)))))
1664                 . html::span(array('style' => 'display:none'), join(', ', $allvalues));
1665         }
1666         else {
1667             $out .= ' ' . html::a(array(
1668                     'href'    => '#more',
1669                     'class'   => 'morelink',
1670                     'onclick' => sprintf("return %s.show_popup_dialog('%s','%s')",
1671                         rcmail_output::JS_OBJECT_NAME,
1672                         rcube::JQ(join(', ', $allvalues)),
1673                         rcube::JQ($title))
1674                 ),
1675                 rcube::Q($RCMAIL->gettext(array('name' => 'andnmore', 'vars' => array('nr' => $moreadrs)))));
1676         }
4e17e6 1677     }
9800a8 1678
f5d2ee 1679     return $out;
8e44f4 1680 }
4e17e6 1681
ccd63c 1682 /**
T 1683  * Wrap text to a given number of characters per line
6b6f2e 1684  * but respect the mail quotation of replies messages (>).
db108e 1685  * Finally add another quotation level by prepending the lines
6b6f2e 1686  * with >
ccd63c 1687  *
T 1688  * @param string Text to wrap
db108e 1689  * @param int    The line width
ccd63c 1690  * @return string The wrapped text
T 1691  */
6b6f2e 1692 function rcmail_wrap_and_quote($text, $length = 72)
ccd63c 1693 {
f5d2ee 1694     // Rebuild the message body with a maximum of $max chars, while keeping quoted message.
AM 1695     $max = max(75, $length + 8);
1696     $lines = preg_split('/\r?\n/', trim($text));
1697     $out = '';
ccd63c 1698
f5d2ee 1699     foreach ($lines as $line) {
AM 1700         // don't wrap already quoted lines
1701         if ($line[0] == '>') {
1702             $line = '>' . rtrim($line);
1703         }
1704         else if (mb_strlen($line) > $max) {
1705             $newline = '';
1706
1707             foreach (explode("\n", rcube_mime::wordwrap($line, $length - 2)) as $l) {
1708                 if (strlen($l))
1709                     $newline .= '> ' . $l . "\n";
1710                 else
1711                     $newline .= ">\n";
1712             }
1713
1714             $line = rtrim($newline);
1715         }
1716         else {
1717             $line = '> ' . $line;
1718         }
1719
1720         // Append the line
1721         $out .= $line . "\n";
ccd63c 1722     }
T 1723
f5d2ee 1724     return rtrim($out, "\n");
ccd63c 1725 }
T 1726
bc404f 1727 function rcmail_draftinfo_encode($p)
T 1728 {
f5d2ee 1729     $parts = array();
AM 1730     foreach ($p as $key => $val) {
1731         $parts[] = $key . '=' . ($key == 'folder' ? base64_encode($val) : $val);
1732     }
9800a8 1733
f5d2ee 1734     return join('; ', $parts);
bc404f 1735 }
T 1736
1737 function rcmail_draftinfo_decode($str)
1738 {
f5d2ee 1739     $info = array();
9800a8 1740
f5d2ee 1741     foreach (preg_split('/;\s+/', $str) as $part) {
AM 1742         list($key, $val) = explode('=', $part, 2);
1743         if ($key == 'folder') {
1744             $val = base64_decode($val);
1745         }
1746
1747         $info[$key] = $val;
1748     }
1749
1750     return $info;
bc404f 1751 }
T 1752
45f56c 1753 /**
T 1754  * clear message composing settings
1755  */
4591de 1756 function rcmail_compose_cleanup($id)
e99991 1757 {
f5d2ee 1758     if (!isset($_SESSION['compose_data_'.$id])) {
AM 1759         return;
1760     }
70d4b9 1761
f5d2ee 1762     $rcmail = rcmail::get_instance();
AM 1763     $rcmail->plugins->exec_hook('attachments_cleanup', array('group' => $id));
1764     $rcmail->session->remove('compose_data_'.$id);
e99991 1765 }
fba1f5 1766
T 1767 /**
a99968 1768  * Send the MDN response
A 1769  *
1770  * @param mixed $message    Original message object (rcube_message) or UID
1771  * @param array $smtp_error SMTP error array (reference)
1772  *
1773  * @return boolean Send status
1774  */
1775 function rcmail_send_mdn($message, &$smtp_error)
0ea884 1776 {
f5d2ee 1777     global $RCMAIL;
8fa58e 1778
f5d2ee 1779     if (!is_object($message) || !is_a($message, 'rcube_message')) {
AM 1780         $message = new rcube_message($message);
f59cfe 1781     }
AM 1782
f5d2ee 1783     if ($message->headers->mdn_to && empty($message->headers->flags['MDNSENT']) &&
AM 1784         ($RCMAIL->storage->check_permflag('MDNSENT') || $RCMAIL->storage->check_permflag('*'))
1785     ) {
1786         $identity  = rcmail_identity_select($message);
1787         $sender    = format_email_recipient($identity['email'], $identity['name']);
1788         $recipient = array_shift(rcube_mime::decode_address_list(
1789             $message->headers->mdn_to, 1, true, $message->headers->charset));
1790         $mailto    = $recipient['mailto'];
1791
1792         $compose = new Mail_mime("\r\n");
1793
1794         $compose->setParam('text_encoding', 'quoted-printable');
1795         $compose->setParam('html_encoding', 'quoted-printable');
1796         $compose->setParam('head_encoding', 'quoted-printable');
1797         $compose->setParam('head_charset', RCUBE_CHARSET);
1798         $compose->setParam('html_charset', RCUBE_CHARSET);
1799         $compose->setParam('text_charset', RCUBE_CHARSET);
1800
1801         // compose headers array
1802         $headers = array(
1803             'Date'       => $RCMAIL->user_date(),
1804             'From'       => $sender,
1805             'To'         => $message->headers->mdn_to,
1806             'Subject'    => $RCMAIL->gettext('receiptread') . ': ' . $message->subject,
1807             'Message-ID' => $RCMAIL->gen_message_id(),
1808             'X-Sender'   => $identity['email'],
1809             'References' => trim($message->headers->references . ' ' . $message->headers->messageID),
175ca6 1810             'In-Reply-To' => $message->headers->messageID,
f5d2ee 1811         );
AM 1812
1813         $report = "Final-Recipient: rfc822; {$identity['email']}\r\n"
1814             . "Original-Message-ID: {$message->headers->messageID}\r\n"
1815             . "Disposition: manual-action/MDN-sent-manually; displayed\r\n";
1816
1817         if ($message->headers->to) {
1818             $report .= "Original-Recipient: {$message->headers->to}\r\n";
1819         }
1820
1821         if ($agent = $RCMAIL->config->get('useragent')) {
1822             $headers['User-Agent'] = $agent;
1823             $report .= "Reporting-UA: $agent\r\n";
1824         }
1825
175ca6 1826         $to   = rcube_mime::decode_mime_string($message->headers->to, $message->headers->charset);
AM 1827         $date = $RCMAIL->format_date($message->headers->date, $RCMAIL->config->get('date_long'));
f5d2ee 1828         $body = $RCMAIL->gettext("yourmessage") . "\r\n\r\n" .
175ca6 1829             "\t" . $RCMAIL->gettext("to") . ": {$to}\r\n" .
AM 1830             "\t" . $RCMAIL->gettext("subject") . ": {$message->subject}\r\n" .
1831             "\t" . $RCMAIL->gettext("date") . ": {$date}\r\n" .
f5d2ee 1832             "\r\n" . $RCMAIL->gettext("receiptnote");
AM 1833
175ca6 1834         $compose->headers(array_filter($headers));
f5d2ee 1835         $compose->setContentType('multipart/report', array('report-type'=> 'disposition-notification'));
AM 1836         $compose->setTXTBody(rcube_mime::wordwrap($body, 75, "\r\n"));
1837         $compose->addAttachment($report, 'message/disposition-notification', 'MDNPart2.txt', false, '7bit', 'inline');
1838
175ca6 1839         // SMTP options
AM 1840         $options = array('mdn_use_from' => (bool) $RCMAIL->config->get('mdn_use_from'));
f5d2ee 1841
AM 1842         $sent = $RCMAIL->deliver_message($compose, $identity['email'], $mailto, $smtp_error, $body_file, $options);
1843
1844         if ($sent) {
1845             $RCMAIL->storage->set_flag($message->uid, 'MDNSENT');
1846             return true;
1847         }
f59cfe 1848     }
232535 1849
f5d2ee 1850     return false;
0ea884 1851 }
T 1852
a0e3dc 1853 /**
AM 1854  * Detect recipient identity from specified message
1855  */
1856 function rcmail_identity_select($MESSAGE, $identities = null, $compose_mode = 'reply')
1857 {
1858     $a_recipients = array();
1859     $a_names      = array();
1860
1861     if ($identities === null) {
1862         $identities = rcmail::get_instance()->user->list_identities(null, true);
1863     }
1864
1865     // extract all recipients of the reply-message
1866     if (is_object($MESSAGE->headers) && in_array($compose_mode, array('reply', 'forward'))) {
1867         $a_to = rcube_mime::decode_address_list($MESSAGE->headers->to, null, true, $MESSAGE->headers->charset);
1868         foreach ($a_to as $addr) {
1869             if (!empty($addr['mailto'])) {
53b4c7 1870                 $a_recipients[] = strtolower($addr['mailto']);
a0e3dc 1871                 $a_names[]      = $addr['name'];
AM 1872             }
1873         }
1874
1875         if (!empty($MESSAGE->headers->cc)) {
1876             $a_cc = rcube_mime::decode_address_list($MESSAGE->headers->cc, null, true, $MESSAGE->headers->charset);
1877             foreach ($a_cc as $addr) {
1878                 if (!empty($addr['mailto'])) {
53b4c7 1879                     $a_recipients[] = strtolower($addr['mailto']);
a0e3dc 1880                     $a_names[]      = $addr['name'];
AM 1881                 }
1882             }
1883         }
1884     }
1885
a8b004 1886     // decode From: address
AM 1887     $from = rcube_mime::decode_address_list($MESSAGE->headers->from, null, true, $MESSAGE->headers->charset);
1888     $from = array_shift($from);
1889     $from['mailto'] = strtolower($from['mailto']);
1890
1891     $from_idx   = null;
1892     $found_idx  = array('to' => null, 'from' => null);
1893     $check_from = in_array($compose_mode, array('draft', 'edit', 'reply'));
a0e3dc 1894
AM 1895     // Select identity
1896     foreach ($identities as $idx => $ident) {
a8b004 1897         // use From: header when in edit/draft or reply-to-self
AM 1898         if ($check_from && $from['mailto'] == strtolower($ident['email_ascii'])) {
1899             // remember first matching identity address
1900             if ($found_idx['from'] === null) {
1901                 $found_idx['from'] = $idx;
1902             }
1903             // match identity name
1904             if ($from['name'] && $ident['name'] && $from['name'] == $ident['name']) {
a0e3dc 1905                 $from_idx = $idx;
AM 1906                 break;
1907             }
1908         }
a8b004 1909         // use replied/forwarded message recipients
53b4c7 1910         else if (($found = array_search(strtolower($ident['email_ascii']), $a_recipients)) !== false) {
a8b004 1911             // remember first matching identity address
AM 1912             if ($found_idx['to'] === null) {
1913                 $found_idx['to'] = $idx;
a0e3dc 1914             }
AM 1915             // match identity name
1916             if ($a_names[$found] && $ident['name'] && $a_names[$found] == $ident['name']) {
1917                 $from_idx = $idx;
1918                 break;
1919             }
1920         }
1921     }
1922
a8b004 1923     // If matching by name+address didn't find any matches,
AM 1924     // get first found identity (address) if any
a0e3dc 1925     if ($from_idx === null) {
a8b004 1926         $from_idx = $found_idx['from'] !== null ? $found_idx['from'] : $found_idx['to'];
a0e3dc 1927     }
AM 1928
1929     // Try Return-Path
1930     if ($from_idx === null && ($return_path = $MESSAGE->headers->others['return-path'])) {
c20fa4 1931         $return_path = array_map('strtolower', (array) $return_path);
AM 1932
a0e3dc 1933         foreach ($identities as $idx => $ident) {
f09b16 1934             // Return-Path header contains an email address, but on some mailing list
AM 1935             // it can be e.g. <pear-dev-return-55250-local=domain.tld@lists.php.net>
1936             // where local@domain.tld is the address we're looking for (#1489241)
c20fa4 1937             $ident1 = strtolower($ident['email_ascii']);
f09b16 1938             $ident2 = str_replace('@', '=', $ident1);
c20fa4 1939             $ident1 = '<' . $ident1 . '>';
AM 1940             $ident2 = '-' . $ident2 . '@';
f09b16 1941
c20fa4 1942             foreach ($return_path as $path) {
AM 1943                 if ($path == $ident1 || stripos($path, $ident2)) {
af9dbd 1944                     $from_idx = $idx;
AM 1945                     break 2;
1946                 }
a0e3dc 1947             }
AM 1948         }
1949     }
1950
b825f8 1951     // See identity_select plugin for example usage of this hook
AM 1952     $plugin = rcmail::get_instance()->plugins->exec_hook('identity_select',
1953         array('message' => $MESSAGE, 'identities' => $identities, 'selected' => $from_idx));
a0e3dc 1954
b825f8 1955     $selected = $plugin['selected'];
a0e3dc 1956
a8b004 1957     // default identity is always first on the list
AM 1958     return $identities[$selected !== null ? $selected : 0];
a0e3dc 1959 }
2bf3cc 1960
e0bd70 1961 // Fixes some content-type names
A 1962 function rcmail_fix_mimetype($name)
1963 {
f5d2ee 1964     // Some versions of Outlook create garbage Content-Type:
AM 1965     // application/pdf.A520491B_3BF7_494D_8855_7FAC2C6C0608
1966     if (preg_match('/^application\/pdf.+/', $name)) {
1967         $name = 'application/pdf';
1968     }
1969     // treat image/pjpeg (image/pjpg, image/jpg) as image/jpeg (#1489097)
1970     else if (preg_match('/^image\/p?jpe?g$/', $name)) {
1971         $name = 'image/jpeg';
1972     }
090c49 1973
f5d2ee 1974     return $name;
e0bd70 1975 }
2bf3cc 1976
be72fb 1977 // return attachment filename, handle empty filename case
830fd2 1978 function rcmail_attachment_name($attachment, $display = false)
be72fb 1979 {
6b2b2e 1980     global $RCMAIL;
AM 1981
be72fb 1982     $filename = $attachment->filename;
AM 1983
1984     if ($filename === null || $filename === '') {
1985         if ($attachment->mimetype == 'text/html') {
6b2b2e 1986             $filename = $RCMAIL->gettext('htmlmessage');
be72fb 1987         }
AM 1988         else {
726297 1989             $ext      = (array) rcube_mime::get_mime_extensions($attachment->mimetype);
be72fb 1990             $ext      = array_shift($ext);
6b2b2e 1991             $filename = $RCMAIL->gettext('messagepart') . ' ' . $attachment->mime_id;
be72fb 1992             if ($ext) {
AM 1993                 $filename .= '.' . $ext;
1994             }
1995         }
1996     }
1997
1998     $filename = preg_replace('[\r\n]', '', $filename);
1999
830fd2 2000     // Display smart names for some known mimetypes
AM 2001     if ($display) {
2002         if (preg_match('/application\/(pgp|pkcs7)-signature/i', $attachment->mimetype)) {
6b2b2e 2003             $filename = $RCMAIL->gettext('digitalsig');
830fd2 2004         }
AM 2005     }
2006
be72fb 2007     return $filename;
AM 2008 }
2009
e538b3 2010 function rcmail_search_filter($attrib)
A 2011 {
f5d2ee 2012     global $RCMAIL;
e538b3 2013
f5d2ee 2014     if (!strlen($attrib['id']))
AM 2015         $attrib['id'] = 'rcmlistfilter';
e538b3 2016
f5d2ee 2017     $attrib['onchange'] = rcmail_output::JS_OBJECT_NAME.'.filter_mailbox(this.value)';
9800a8 2018
f5d2ee 2019     // Content-Type values of messages with attachments
AM 2020     // the same as in app.js:add_message_row()
2021     $ctypes = array('application/', 'multipart/m', 'multipart/signed', 'multipart/report');
bb7c52 2022
f5d2ee 2023     // Build search string of "with attachment" filter
ceff79 2024     $attachment = trim(str_repeat(' OR', count($ctypes)-1));
f5d2ee 2025     foreach ($ctypes as $type) {
AM 2026         $attachment .= ' HEADER Content-Type ' . rcube_imap_generic::escape($type);
2027     }
e538b3 2028
f5d2ee 2029     $select_filter = new html_select($attrib);
AM 2030     $select_filter->add($RCMAIL->gettext('all'), 'ALL');
2031     $select_filter->add($RCMAIL->gettext('unread'), 'UNSEEN');
2032     $select_filter->add($RCMAIL->gettext('flagged'), 'FLAGGED');
2033     $select_filter->add($RCMAIL->gettext('unanswered'), 'UNANSWERED');
2034     if (!$RCMAIL->config->get('skip_deleted')) {
2035         $select_filter->add($RCMAIL->gettext('deleted'), 'DELETED');
2036         $select_filter->add($RCMAIL->gettext('undeleted'), 'UNDELETED');
2037     }
2038     $select_filter->add($RCMAIL->gettext('withattachment'), $attachment);
2039     $select_filter->add($RCMAIL->gettext('priority').': '.$RCMAIL->gettext('highest'), 'HEADER X-PRIORITY 1');
2040     $select_filter->add($RCMAIL->gettext('priority').': '.$RCMAIL->gettext('high'), 'HEADER X-PRIORITY 2');
2041     $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');
2042     $select_filter->add($RCMAIL->gettext('priority').': '.$RCMAIL->gettext('low'), 'HEADER X-PRIORITY 4');
2043     $select_filter->add($RCMAIL->gettext('priority').': '.$RCMAIL->gettext('lowest'), 'HEADER X-PRIORITY 5');
e538b3 2044
f5d2ee 2045     $out = $select_filter->show($_SESSION['search_filter']);
e538b3 2046
f5d2ee 2047     $RCMAIL->output->add_gui_object('search_filter', $attrib['id']);
e538b3 2048
f5d2ee 2049     return $out;
e538b3 2050 }
A 2051
64e3e8 2052 function rcmail_message_error($uid=null)
A 2053 {
f5d2ee 2054     global $RCMAIL;
64e3e8 2055
f5d2ee 2056     // Set env variables for messageerror.html template
AM 2057     if ($RCMAIL->action == 'show') {
2058         $mbox_name = $RCMAIL->storage->get_folder();
2059
2060         $RCMAIL->output->set_env('mailbox', $mbox_name);
2061         $RCMAIL->output->set_env('uid', null);
2062     }
2063
2064     // display error message
2065     $RCMAIL->output->show_message('messageopenerror', 'error');
2066     // ... display message error page
2067     $RCMAIL->output->send('messageerror');
64e3e8 2068 }
9b3fdc 2069
4f53ab 2070 function rcmail_message_import_form($attrib = array())
TB 2071 {
f5d2ee 2072     global $RCMAIL;
4f53ab 2073
f5d2ee 2074     // set defaults
AM 2075     $attrib += array('id' => 'rcmImportform', 'buttons' => 'yes');
4f53ab 2076
f5d2ee 2077     // Get filesize, enable upload progress bar
AM 2078     $max_filesize = $RCMAIL->upload_init();
4f53ab 2079
f5d2ee 2080     $button    = new html_inputfield(array('type' => 'button'));
AM 2081     $fileinput = new html_inputfield(array(
2082             'type'     => 'file',
2083             'name'     => '_file[]',
2084             'multiple' => 'multiple',
2085             'accept'   => ".eml, .mbox, message/rfc822, text/*",
2086     ));
4f53ab 2087
f5d2ee 2088     $content = html::tag('input', array('type' => 'hidden', 'name' => '_unlock', 'value' => ''))
AM 2089         . html::div(null, $fileinput->show())
2090         . html::div('hint', $RCMAIL->gettext(array('name' => 'maxuploadsize', 'vars' => array('size' => $max_filesize))));
4f53ab 2091
f5d2ee 2092     if (rcube_utils::get_boolean($attrib['buttons'])) {
AM 2093         $content .= html::div('buttons',
2094             $button->show($RCMAIL->gettext('close'), array('class' => 'button', 'onclick' => "$('#$attrib[id]').hide()"))
2095             . ' ' .
2096             $button->show($RCMAIL->gettext('upload'), array(
2097                 'class'   => 'button mainaction',
2098                 'onclick' => rcmail_output::JS_OBJECT_NAME . ".command('import-messages', this.form)"
2099             )));
2100     }
2101
2102     $out = $RCMAIL->output->form_tag(array(
2103             'id'      => $attrib['id'].'Frm',
2104             'method'  => 'post',
2105             'enctype' => 'multipart/form-data'
2106         ),
2107         $content);
2108
2109     $RCMAIL->output->add_gui_object('importform', $attrib['id'].'Frm');
8d3b27 2110     $RCMAIL->output->add_label('selectimportfile','importwait');
f5d2ee 2111
AM 2112     return html::div($attrib, $out);
4f53ab 2113 }
700e3c 2114
TB 2115 /**
2116  * Add groups from the given address source to the address book widget
2117  */
2118 function rcmail_compose_contact_groups($abook, $source_id, $search = null, $search_mode = 0)
2119 {
2120     global $RCMAIL, $OUTPUT;
2121
2122     $jsresult = array();
2123     foreach ($abook->list_groups($search, $search_mode) as $group) {
2124         $abook->reset();
2125         $abook->set_group($group['ID']);
2126         $group_prop = $abook->get_group($group['ID']);
2127
2128         // group (distribution list) with email address(es)
2129         if ($group_prop['email']) {
2130             foreach ((array)$group_prop['email'] as $email) {
2131                 $row_id = 'G'.$group['ID'];
2132                 $jsresult[$row_id] = format_email_recipient($email, $group['name']);
2133                 $OUTPUT->command('add_contact_row', $row_id, array(
2134                     'contactgroup' => html::span(array('title' => $email), rcube::Q($group['name']))), 'group');
2135             }
2136         }
2137         // make virtual groups clickable to list their members
2138         else if ($group_prop['virtual']) {
2139             $row_id = 'G'.$group['ID'];
2140             $OUTPUT->command('add_contact_row', $row_id, array(
2141                 'contactgroup' => html::a(array(
2142                     'href' => '#list',
2143                     'rel' => $group['ID'],
2144                     'title' => $RCMAIL->gettext('listgroup'),
2145                     'onclick' => sprintf("return %s.command('pushgroup',{'source':'%s','id':'%s'},this,event)",
2146                                     rcmail_output::JS_OBJECT_NAME, $source_id, $group['ID']),
2147                 ), rcube::Q($group['name']) . '&nbsp;' . html::span('action', '&raquo;'))),
2148                 'group',
2149                 array('ID' => $group['ID'], 'name' => $group['name'], 'virtual' => true));
2150         }
2151         // show group with count
2152         else if (($result = $abook->count()) && $result->count) {
2153             $row_id = 'E'.$group['ID'];
2154             $jsresult[$row_id] = $group['name'];
2155             $OUTPUT->command('add_contact_row', $row_id, array(
2156                 'contactgroup' => rcube::Q($group['name'] . ' (' . intval($result->count) . ')')), 'group');
2157         }
2158     }
2159
2160     $abook->reset();
2161     $abook->set_group(0);
2162
2163     return $jsresult;
2164 }