Aleksander Machniak
2015-09-06 175ca6fd65ed08b6011e8b66288acb039d3c68cd
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  *
65cc1c 790  * @param object rcube_message_part Message part
ec603f 791  * @param array  Display parameters array 
65cc1c 792  * @return string Formatted HTML string
45f56c 793  */
21e724 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',
800         array('type' => $part->ctype_secondary, 'body' => $part->body, 'id' => $part->mime_id)
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
826         $body = $part->body;
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                 // extract headers from message/rfc822 parts
1204                 if ($part->mimetype == 'message/rfc822') {
1205                     $msgpart = rcube_mime::parse_message($part->body);
1206                     if (!empty($msgpart->headers)) {
1207                         $part = $msgpart;
1208                         $out .= html::div('message-partheaders', rcmail_message_headers(sizeof($header_attrib) ? $header_attrib : null, $part->headers));
1209                     }
1210                 }
1211
1212                 // message is cached but not exists (#1485443), or other error
1213                 if ($part->body === false) {
1214                     rcmail_message_error($MESSAGE->uid);
1215                 }
1216
1217                 $plugin = $RCMAIL->plugins->exec_hook('message_body_prefix',
1218                     array('part' => $part, 'prefix' => ''));
1219
1220                 $body = rcmail_print_body($part, array('safe' => $safe_mode, 'plain' => !$RCMAIL->config->get('prefer_html')));
1221
1222                 if ($part->ctype_secondary == 'html') {
1223                     $body     = rcmail_html4inline($body, $attrib['id'], 'rcmBody', $attrs, $safe_mode);
1224                     $div_attr = array('class' => 'message-htmlpart');
1225                     $style    = array();
1226
1227                     if (!empty($attrs)) {
1228                         foreach ($attrs as $a_idx => $a_val)
1229                             $style[] = $a_idx . ': ' . $a_val;
1230                         if (!empty($style))
1231                             $div_attr['style'] = implode('; ', $style);
1232                     }
1233
1234                     $out .= html::div($div_attr, $plugin['prefix'] . $body);
1235                 }
1236                 else
1237                     $out .= html::div('message-part', $plugin['prefix'] . $body);
1238             }
1239         }
3c3433 1240     }
e0960f 1241     else {
f5d2ee 1242         // Check if we have enough memory to handle the message in it
AM 1243         // #1487424: we need up to 10x more memory than the body
1244         if (!rcube_utils::mem_check(strlen($MESSAGE->body) * 10)) {
1245             $out .= html::span('part-notice', $RCMAIL->gettext('messagetoobig'). ' '
1246                 . html::a('?_task=mail&_action=get&_download=1&_uid='.$MESSAGE->uid.'&_part=0'
e03bcf 1247                     .'&_mbox='. urlencode($MESSAGE->folder), $RCMAIL->gettext('download')));
031491 1248         }
TB 1249         else {
f5d2ee 1250             $plugin = $RCMAIL->plugins->exec_hook('message_body_prefix',
AM 1251                 array('part' => $MESSAGE, 'prefix' => ''));
1252
1253             $out .= html::div('message-part', $plugin['prefix'] . html::tag('pre', array(),
1254                 rcmail_plain_body(rcube::Q($MESSAGE->body, 'strict', false))));
031491 1255         }
4e17e6 1256     }
9800a8 1257
f5d2ee 1258     // list images after mail body
AM 1259     if ($RCMAIL->config->get('inline_images', true) && !empty($MESSAGE->attachments)) {
1260         $thumbnail_size   = $RCMAIL->config->get('image_thumbnail_size', 240);
1261         $client_mimetypes = (array)$RCMAIL->config->get('client_mimetypes');
4e17e6 1262
f5d2ee 1263         foreach ($MESSAGE->attachments as $attach_prop) {
AM 1264             // skip inline images
1265             if ($attach_prop->content_id && $attach_prop->disposition == 'inline') {
1266                 continue;
1267             }
1268
1269             // Content-Type: image/*...
1270             if ($mimetype = rcmail_part_image_type($attach_prop)) {
1271                 // display thumbnails
1272                 if ($thumbnail_size) {
1273                     $show_link = array(
1274                         'href'    => $MESSAGE->get_part_url($attach_prop->mime_id, false),
1275                         'onclick' => sprintf(
1276                             'return %s.command(\'load-attachment\',\'%s\',this)',
1277                             rcmail_output::JS_OBJECT_NAME,
1278                             $attach_prop->mime_id)
1279                     );
1280                     $out .= html::p('image-attachment',
1281                         html::a($show_link + array('class' => 'image-link', 'style' => sprintf('width:%dpx', $thumbnail_size)),
1282                             html::img(array(
1283                                 'class' => 'image-thumbnail',
1284                                 'src'   => $MESSAGE->get_part_url($attach_prop->mime_id, 'image') . '&_thumb=1',
1285                                 'title' => $attach_prop->filename,
1286                                 'alt'   => $attach_prop->filename,
1287                                 'style' => sprintf('max-width:%dpx; max-height:%dpx', $thumbnail_size, $thumbnail_size),
1288                             ))
1289                         ) .
1290                         html::span('image-filename', rcube::Q($attach_prop->filename)) .
1291                         html::span('image-filesize', rcube::Q($RCMAIL->message_part_size($attach_prop))) .
1292                         html::span('attachment-links',
1293                             (in_array($mimetype, $client_mimetypes) ? html::a($show_link, $RCMAIL->gettext('showattachment')) . '&nbsp;' : '') .
1294                                 html::a($show_link['href'] . '&_download=1', $RCMAIL->gettext('download'))
1295                         ) .
1296                         html::br(array('style' => 'clear:both'))
1297                     );
1298                 }
1299                 else {
1300                     $out .= html::tag('fieldset', 'image-attachment',
1301                         html::tag('legend', 'image-filename', rcube::Q($attach_prop->filename)) .
1302                         html::p(array('align' => 'center'),
1303                             html::img(array(
1304                                 'src'   => $MESSAGE->get_part_url($attach_prop->mime_id, 'image'),
1305                                 'title' => $attach_prop->filename,
1306                                 'alt'   => $attach_prop->filename,
1307                         )))
1308                     );
1309                 }
1310             }
1311         }
1312     }
1313
1314     // tell client that there are blocked remote objects
1315     if ($REMOTE_OBJECTS && !$safe_mode) {
1316         $OUTPUT->set_env('blockedobjects', true);
1317     }
1318
1319     return html::div($attrib, $out);
e0960f 1320 }
4e17e6 1321
19cc5b 1322 function rcmail_part_image_type($part)
AM 1323 {
f5d2ee 1324     $rcmail = rcmail::get_instance();
19cc5b 1325
f5d2ee 1326     // Skip TIFF images if browser doesn't support this format...
AM 1327     $tiff_support = !empty($_SESSION['browser_caps']) && !empty($_SESSION['browser_caps']['tif']);
1328     // until we can convert them to JPEG
1329     $tiff_support = $tiff_support || $rcmail->config->get('im_convert_path');
19cc5b 1330
f5d2ee 1331     // Content-type regexp
AM 1332     $mime_regex = $tiff_support ? '/^image\//i' : '/^image\/(?!tif)/i';
19cc5b 1333
f5d2ee 1334     // Content-Type: image/*...
AM 1335     if (preg_match($mime_regex, $part->mimetype)) {
1336         return rcmail_fix_mimetype($part->mimetype);
1337     }
19cc5b 1338
f5d2ee 1339     // Many clients use application/octet-stream, we'll detect mimetype
AM 1340     // by checking filename extension
19cc5b 1341
f5d2ee 1342     // Supported image filename extensions to image type map
AM 1343     $types = array(
1344         'jpg'  => 'image/jpeg',
1345         'jpeg' => 'image/jpeg',
1346         'png'  => 'image/png',
1347         'gif'  => 'image/gif',
1348         'bmp'  => 'image/bmp',
1349     );
1350     if ($tiff_support) {
1351         $types['tif']  = 'image/tiff';
1352         $types['tiff'] = 'image/tiff';
1353     }
19cc5b 1354
f5d2ee 1355     if ($part->filename
AM 1356         && preg_match('/^application\/octet-stream$/i', $part->mimetype)
1357         && preg_match('/\.([^.]+)$/i', $part->filename, $m)
1358         && ($extension = strtolower($m[1]))
1359         && isset($types[$extension])
1360     ) {
1361         return $types[$extension];
1362     }
aa055c 1363 }
f5d62f 1364
45f56c 1365 /**
T 1366  * modify a HTML message that it can be displayed inside a HTML page
1367  */
2b017e 1368 function rcmail_html4inline($body, $container_id, $body_id='', &$attributes=null, $allow_remote=false)
cb3dfd 1369 {
f5d2ee 1370     $last_style_pos = 0;
AM 1371     $cont_id        = $container_id.($body_id ? ' div.'.$body_id : '');
9800a8 1372
f5d2ee 1373     // find STYLE tags
AM 1374     while (($pos = stripos($body, '<style', $last_style_pos)) && ($pos2 = stripos($body, '</style>', $pos))) {
1375         $pos = strpos($body, '>', $pos) + 1;
1376         $len = $pos2 - $pos;
ea206d 1377
f5d2ee 1378         // replace all css definitions with #container [def]
AM 1379         $styles = substr($body, $pos, $len);
1380         $styles = rcube_utils::mod_css_styles($styles, $cont_id, $allow_remote);
ea206d 1381
f5d2ee 1382         $body = substr_replace($body, $styles, $pos, $len);
AM 1383         $last_style_pos = $pos2 + strlen($styles) - $len;
ceb708 1384     }
cb3dfd 1385
f5d2ee 1386     // modify HTML links to open a new window if clicked
AM 1387     $GLOBALS['rcmail_html_container_id'] = $container_id;
1388     $body = preg_replace_callback('/<(a|link|area)\s+([^>]+)>/Ui', 'rcmail_alter_html_link', $body);
1389     unset($GLOBALS['rcmail_html_container_id']);
1390
1391     $body = preg_replace(array(
1392             // add comments arround html and other tags
1393             '/(<!DOCTYPE[^>]*>)/i',
1394             '/(<\?xml[^>]*>)/i',
1395             '/(<\/?html[^>]*>)/i',
1396             '/(<\/?head[^>]*>)/i',
1397             '/(<title[^>]*>.*<\/title>)/Ui',
1398             '/(<\/?meta[^>]*>)/i',
1399             // quote <? of php and xml files that are specified as text/html
1400             '/<\?/',
1401             '/\?>/',
1402             // replace <body> with <div>
1403             '/<body([^>]*)>/i',
1404             '/<\/body>/i',
1405         ),
1406         array(
1407             '<!--\\1-->',
1408             '<!--\\1-->',
1409             '<!--\\1-->',
1410             '<!--\\1-->',
1411             '<!--\\1-->',
1412             '<!--\\1-->',
1413             '&lt;?',
1414             '?&gt;',
1415             '<div class="'.$body_id.'"\\1>',
1416             '</div>',
1417         ),
1418         $body);
1419
1420     $attributes = array();
1421
1422     // Handle body attributes that doesn't play nicely with div elements
1423     $regexp = '/<div class="' . preg_quote($body_id, '/') . '"([^>]*)/';
1424     if (preg_match($regexp, $body, $m)) {
1425         $attrs = $m[0];
1426
1427         // Get bgcolor, we'll set it as background-color of the message container
1428         if ($m[1] && preg_match('/bgcolor=["\']*([a-z0-9#]+)["\']*/i', $attrs, $mb)) {
1429             $attributes['background-color'] = $mb[1];
1430             $attrs = preg_replace('/bgcolor=["\']*[a-z0-9#]+["\']*/i', '', $attrs);
cb3dfd 1431         }
f5d2ee 1432
AM 1433         // Get background, we'll set it as background-image of the message container
1434         if ($m[1] && preg_match('/background=["\']*([^"\'>\s]+)["\']*/', $attrs, $mb)) {
1435             $attributes['background-image'] = 'url('.$mb[1].')';
1436             $attrs = preg_replace('/background=["\']*([^"\'>\s]+)["\']*/', '', $attrs);
1437         }
1438
1439         if (!empty($attributes)) {
1440             $body = preg_replace($regexp, rtrim($attrs), $body, 1);
1441         }
1442
1443         // handle body styles related to background image
1444         if ($attributes['background-image']) {
1445             // get body style
1446             if (preg_match('/#'.preg_quote($cont_id, '/').'\s+\{([^}]+)}/i', $body, $m)) {
1447                 // get background related style
1448                 $regexp = '/(background-position|background-repeat)\s*:\s*([^;]+);/i';
1449                 if (preg_match_all($regexp, $m[1], $ma, PREG_SET_ORDER)) {
1450                     foreach ($ma as $style) {
1451                         $attributes[$style[1]] = $style[2];
1452                     }
1453                 }
1454             }
1455         }
cb3dfd 1456     }
f5d2ee 1457     // make sure there's 'rcmBody' div, we need it for proper css modification
AM 1458     // its name is hardcoded in rcmail_message_body() also
1459     else {
1460         $body = '<div class="' . $body_id . '">' . $body . '</div>';
1461     }
86958f 1462
f5d2ee 1463     return $body;
cb3dfd 1464 }
4e17e6 1465
45f56c 1466 /**
1e3254 1467  * parse link (a, link, area) attributes and set correct target
45f56c 1468  */
115263 1469 function rcmail_alter_html_link($matches)
e5af2f 1470 {
f5d2ee 1471     global $RCMAIL;
5c1dfb 1472
f5d2ee 1473     $tag    = strtolower($matches[1]);
AM 1474     $attrib = html::parse_attrib_string($matches[2]);
1475     $end    = '>';
84f5b7 1476
f5d2ee 1477     // Remove non-printable characters in URL (#1487805)
AM 1478     if ($attrib['href'])
1479         $attrib['href'] = preg_replace('/[\x00-\x1F]/', '', $attrib['href']);
29c542 1480
f5d2ee 1481     if ($tag == 'link' && preg_match('/^https?:\/\//i', $attrib['href'])) {
AM 1482         $tempurl = 'tmp-' . md5($attrib['href']) . '.css';
1483         $_SESSION['modcssurls'][$tempurl] = $attrib['href'];
1484         $attrib['href'] = $RCMAIL->url(array('task' => 'utils', 'action' => 'modcss', 'u' => $tempurl, 'c' => $GLOBALS['rcmail_html_container_id']));
1485         $end = ' />';
1486     }
1487     else if (preg_match('/^mailto:(.+)/i', $attrib['href'], $mailto)) {
1488         list($mailto, $url) = explode('?', html_entity_decode($mailto[1], ENT_QUOTES, 'UTF-8'), 2);
eafd5b 1489
f5d2ee 1490         $url       = urldecode($url);
AM 1491         $mailto    = urldecode($mailto);
1492         $addresses = rcube_mime::decode_address_list($mailto, null, true);
1493         $mailto    = array();
eafd5b 1494
f5d2ee 1495         // do sanity checks on recipients
AM 1496         foreach ($addresses as $idx => $addr) {
1497             if (rcube_utils::check_email($addr['mailto'], false)) {
1498                 $addresses[$idx] = $addr['mailto'];
1499                 $mailto[]        = $addr['string'];
1500             }
1501             else {
1502                 unset($addresses[$idx]);
1503             }
1504         }
1505
1506         if (!empty($addresses)) {
1507             $attrib['href']    = 'mailto:' . implode(',', $addresses);
1508             $attrib['onclick'] = sprintf(
1509                 "return %s.command('compose','%s',this)",
1510                 rcmail_output::JS_OBJECT_NAME,
1511                 rcube::JQ(implode(',', $mailto) . ($url ? "?$url" : '')));
1512         }
1513         else {
1514             $attrib['href']    = '#NOP';
1515             $attrib['onclick'] = '';
1516         }
1517     }
1518     else if (empty($attrib['href']) && !$attrib['name']) {
1519         $attrib['href']    = './#NOP';
1520         $attrib['onclick'] = 'return false';
1521     }
1522     else if (!empty($attrib['href']) && $attrib['href'][0] != '#') {
1523         $attrib['target'] = '_blank';
eafd5b 1524     }
AM 1525
f5d2ee 1526     // Better security by adding rel="noreferrer" (#1484686)
AM 1527     if (($tag == 'a' || $tag == 'area') && $attrib['href'] && $attrib['href'][0] != '#') {
1528         $attrib['rel'] = 'noreferrer';
eafd5b 1529     }
e5af2f 1530
f5d2ee 1531     // allowed attributes for a|link|area tags
AM 1532     $allow = array('href','name','target','onclick','id','class','style','title',
1533         'rel','type','media','alt','coords','nohref','hreflang','shape');
1e3254 1534
f5d2ee 1535     return "<$tag" . html::attrib_string($attrib, $allow) . $end;
e5af2f 1536 }
4e17e6 1537
45f56c 1538 /**
T 1539  * decode address string and re-format it as HTML links
1540  */
765ecb 1541 function rcmail_address_string($input, $max=null, $linked=false, $addicon=null, $default_charset=null, $title=null)
8e44f4 1542 {
f5d2ee 1543     global $RCMAIL, $PRINT_MODE;
1088d6 1544
f5d2ee 1545     $a_parts = rcube_mime::decode_address_list($input, null, true, $default_charset);
4e17e6 1546
f5d2ee 1547     if (!sizeof($a_parts)) {
AM 1548         return $input;
ff7542 1549     }
AM 1550
f5d2ee 1551     $c   = count($a_parts);
AM 1552     $j   = 0;
1553     $out = '';
1554     $allvalues  = array();
1555     $show_email = $RCMAIL->config->get('message_show_email');
e99991 1556
f5d2ee 1557     if ($addicon && !isset($_SESSION['writeable_abook'])) {
AM 1558         $_SESSION['writeable_abook'] = $RCMAIL->get_address_sources(true) ? true : false;
8e44f4 1559     }
969cb0 1560
f5d2ee 1561     foreach ($a_parts as $part) {
AM 1562         $j++;
1563
1564         $name   = $part['name'];
1565         $mailto = $part['mailto'];
1566         $string = $part['string'];
1567         $valid  = rcube_utils::check_email($mailto, false);
1568
1569         // phishing email prevention (#1488981), e.g. "valid@email.addr <phishing@email.addr>"
1570         if (!$show_email && $valid && $name && $name != $mailto && strpos($name, '@')) {
1571             $name = '';
1572         }
1573
1574         // IDNA ASCII to Unicode
1575         if ($name == $mailto)
1576             $name = rcube_utils::idn_to_utf8($name);
1577         if ($string == $mailto)
1578             $string = rcube_utils::idn_to_utf8($string);
1579         $mailto = rcube_utils::idn_to_utf8($mailto);
1580
1581         if ($PRINT_MODE) {
1582             $address = sprintf('%s &lt;%s&gt;', rcube::Q($name), rcube::Q($mailto));
1583         }
1584         else if ($valid) {
1585             if ($linked) {
1586                 $attrs = array(
1587                     'href'    => 'mailto:' . $mailto,
1588                     'class'   => 'rcmContactAddress',
1589                     'onclick' => sprintf("return %s.command('compose','%s',this)",
1590                         rcmail_output::JS_OBJECT_NAME, rcube::JQ(format_email_recipient($mailto, $name))),
1591                 );
1592
1593                 if ($show_email && $name && $mailto) {
1594                     $content = rcube::Q($name ? sprintf('%s <%s>', $name, $mailto) : $mailto);
1595                 }
1596                 else {
1597                     $content = rcube::Q($name ? $name : $mailto);
1598                     $attrs['title'] = $mailto;
1599                 }
1600
1601                 $address = html::a($attrs, $content);
1602             }
1603             else {
1604                 $address = html::span(array('title' => $mailto, 'class' => "rcmContactAddress"),
1605                     rcube::Q($name ? $name : $mailto));
1606             }
1607
1608             if ($addicon && $_SESSION['writeable_abook']) {
1609                 $address .= html::a(array(
1610                         'href'    => "#add",
1611                         'title'   => $RCMAIL->gettext('addtoaddressbook'),
1612                         'class'   => 'rcmaddcontact',
1613                         'onclick' => sprintf("return %s.command('add-contact','%s',this)",
1614                             rcmail_output::JS_OBJECT_NAME, rcube::JQ($string)),
1615                     ),
1616                     html::img(array(
1617                         'src' => $RCMAIL->config->get('skin_path') . $addicon,
1618                         'alt' => "Add contact",
1619                 )));
1620             }
969cb0 1621         }
AM 1622         else {
f5d2ee 1623             $address = '';
AM 1624             if ($name)
1625                 $address .= rcube::Q($name);
1626             if ($mailto)
1627                 $address = trim($address . ' ' . rcube::Q($name ? sprintf('<%s>', $mailto) : $mailto));
969cb0 1628         }
AM 1629
f5d2ee 1630         $address = html::span('adr', $address);
AM 1631         $allvalues[] = $address;
8e44f4 1632
f5d2ee 1633         if (!$moreadrs)
AM 1634             $out .= ($out ? ', ' : '') . $address;
1635
1636         if ($max && $j == $max && $c > $j) {
1637             if ($linked) {
1638                 $moreadrs = $c - $j;
1639             }
1640             else {
1641                 $out .= '...';
1642                 break;
1643             }
1644         }
8e44f4 1645     }
9800a8 1646
f5d2ee 1647     if ($moreadrs) {
AM 1648         if ($PRINT_MODE) {
1649             $out .= ' ' . html::a(array(
1650                     'href'    => '#more',
1651                     'class'   => 'morelink',
1652                     'onclick' => '$(this).hide().next().show()',
1653                 ),
1654                 rcube::Q($RCMAIL->gettext(array('name' => 'andnmore', 'vars' => array('nr' => $moreadrs)))))
1655                 . html::span(array('style' => 'display:none'), join(', ', $allvalues));
1656         }
1657         else {
1658             $out .= ' ' . html::a(array(
1659                     'href'    => '#more',
1660                     'class'   => 'morelink',
1661                     'onclick' => sprintf("return %s.show_popup_dialog('%s','%s')",
1662                         rcmail_output::JS_OBJECT_NAME,
1663                         rcube::JQ(join(', ', $allvalues)),
1664                         rcube::JQ($title))
1665                 ),
1666                 rcube::Q($RCMAIL->gettext(array('name' => 'andnmore', 'vars' => array('nr' => $moreadrs)))));
1667         }
4e17e6 1668     }
9800a8 1669
f5d2ee 1670     return $out;
8e44f4 1671 }
4e17e6 1672
ccd63c 1673 /**
T 1674  * Wrap text to a given number of characters per line
6b6f2e 1675  * but respect the mail quotation of replies messages (>).
db108e 1676  * Finally add another quotation level by prepending the lines
6b6f2e 1677  * with >
ccd63c 1678  *
T 1679  * @param string Text to wrap
db108e 1680  * @param int    The line width
ccd63c 1681  * @return string The wrapped text
T 1682  */
6b6f2e 1683 function rcmail_wrap_and_quote($text, $length = 72)
ccd63c 1684 {
f5d2ee 1685     // Rebuild the message body with a maximum of $max chars, while keeping quoted message.
AM 1686     $max = max(75, $length + 8);
1687     $lines = preg_split('/\r?\n/', trim($text));
1688     $out = '';
ccd63c 1689
f5d2ee 1690     foreach ($lines as $line) {
AM 1691         // don't wrap already quoted lines
1692         if ($line[0] == '>') {
1693             $line = '>' . rtrim($line);
1694         }
1695         else if (mb_strlen($line) > $max) {
1696             $newline = '';
1697
1698             foreach (explode("\n", rcube_mime::wordwrap($line, $length - 2)) as $l) {
1699                 if (strlen($l))
1700                     $newline .= '> ' . $l . "\n";
1701                 else
1702                     $newline .= ">\n";
1703             }
1704
1705             $line = rtrim($newline);
1706         }
1707         else {
1708             $line = '> ' . $line;
1709         }
1710
1711         // Append the line
1712         $out .= $line . "\n";
ccd63c 1713     }
T 1714
f5d2ee 1715     return rtrim($out, "\n");
ccd63c 1716 }
T 1717
bc404f 1718 function rcmail_draftinfo_encode($p)
T 1719 {
f5d2ee 1720     $parts = array();
AM 1721     foreach ($p as $key => $val) {
1722         $parts[] = $key . '=' . ($key == 'folder' ? base64_encode($val) : $val);
1723     }
9800a8 1724
f5d2ee 1725     return join('; ', $parts);
bc404f 1726 }
T 1727
1728 function rcmail_draftinfo_decode($str)
1729 {
f5d2ee 1730     $info = array();
9800a8 1731
f5d2ee 1732     foreach (preg_split('/;\s+/', $str) as $part) {
AM 1733         list($key, $val) = explode('=', $part, 2);
1734         if ($key == 'folder') {
1735             $val = base64_decode($val);
1736         }
1737
1738         $info[$key] = $val;
1739     }
1740
1741     return $info;
bc404f 1742 }
T 1743
45f56c 1744 /**
T 1745  * clear message composing settings
1746  */
4591de 1747 function rcmail_compose_cleanup($id)
e99991 1748 {
f5d2ee 1749     if (!isset($_SESSION['compose_data_'.$id])) {
AM 1750         return;
1751     }
70d4b9 1752
f5d2ee 1753     $rcmail = rcmail::get_instance();
AM 1754     $rcmail->plugins->exec_hook('attachments_cleanup', array('group' => $id));
1755     $rcmail->session->remove('compose_data_'.$id);
e99991 1756 }
fba1f5 1757
T 1758 /**
a99968 1759  * Send the MDN response
A 1760  *
1761  * @param mixed $message    Original message object (rcube_message) or UID
1762  * @param array $smtp_error SMTP error array (reference)
1763  *
1764  * @return boolean Send status
1765  */
1766 function rcmail_send_mdn($message, &$smtp_error)
0ea884 1767 {
f5d2ee 1768     global $RCMAIL;
8fa58e 1769
f5d2ee 1770     if (!is_object($message) || !is_a($message, 'rcube_message')) {
AM 1771         $message = new rcube_message($message);
f59cfe 1772     }
AM 1773
f5d2ee 1774     if ($message->headers->mdn_to && empty($message->headers->flags['MDNSENT']) &&
AM 1775         ($RCMAIL->storage->check_permflag('MDNSENT') || $RCMAIL->storage->check_permflag('*'))
1776     ) {
1777         $identity  = rcmail_identity_select($message);
1778         $sender    = format_email_recipient($identity['email'], $identity['name']);
1779         $recipient = array_shift(rcube_mime::decode_address_list(
1780             $message->headers->mdn_to, 1, true, $message->headers->charset));
1781         $mailto    = $recipient['mailto'];
1782
1783         $compose = new Mail_mime("\r\n");
1784
1785         $compose->setParam('text_encoding', 'quoted-printable');
1786         $compose->setParam('html_encoding', 'quoted-printable');
1787         $compose->setParam('head_encoding', 'quoted-printable');
1788         $compose->setParam('head_charset', RCUBE_CHARSET);
1789         $compose->setParam('html_charset', RCUBE_CHARSET);
1790         $compose->setParam('text_charset', RCUBE_CHARSET);
1791
1792         // compose headers array
1793         $headers = array(
1794             'Date'       => $RCMAIL->user_date(),
1795             'From'       => $sender,
1796             'To'         => $message->headers->mdn_to,
1797             'Subject'    => $RCMAIL->gettext('receiptread') . ': ' . $message->subject,
1798             'Message-ID' => $RCMAIL->gen_message_id(),
1799             'X-Sender'   => $identity['email'],
1800             'References' => trim($message->headers->references . ' ' . $message->headers->messageID),
175ca6 1801             'In-Reply-To' => $message->headers->messageID,
f5d2ee 1802         );
AM 1803
1804         $report = "Final-Recipient: rfc822; {$identity['email']}\r\n"
1805             . "Original-Message-ID: {$message->headers->messageID}\r\n"
1806             . "Disposition: manual-action/MDN-sent-manually; displayed\r\n";
1807
1808         if ($message->headers->to) {
1809             $report .= "Original-Recipient: {$message->headers->to}\r\n";
1810         }
1811
1812         if ($agent = $RCMAIL->config->get('useragent')) {
1813             $headers['User-Agent'] = $agent;
1814             $report .= "Reporting-UA: $agent\r\n";
1815         }
1816
175ca6 1817         $to   = rcube_mime::decode_mime_string($message->headers->to, $message->headers->charset);
AM 1818         $date = $RCMAIL->format_date($message->headers->date, $RCMAIL->config->get('date_long'));
f5d2ee 1819         $body = $RCMAIL->gettext("yourmessage") . "\r\n\r\n" .
175ca6 1820             "\t" . $RCMAIL->gettext("to") . ": {$to}\r\n" .
AM 1821             "\t" . $RCMAIL->gettext("subject") . ": {$message->subject}\r\n" .
1822             "\t" . $RCMAIL->gettext("date") . ": {$date}\r\n" .
f5d2ee 1823             "\r\n" . $RCMAIL->gettext("receiptnote");
AM 1824
175ca6 1825         $compose->headers(array_filter($headers));
f5d2ee 1826         $compose->setContentType('multipart/report', array('report-type'=> 'disposition-notification'));
AM 1827         $compose->setTXTBody(rcube_mime::wordwrap($body, 75, "\r\n"));
1828         $compose->addAttachment($report, 'message/disposition-notification', 'MDNPart2.txt', false, '7bit', 'inline');
1829
175ca6 1830         // SMTP options
AM 1831         $options = array('mdn_use_from' => (bool) $RCMAIL->config->get('mdn_use_from'));
f5d2ee 1832
AM 1833         $sent = $RCMAIL->deliver_message($compose, $identity['email'], $mailto, $smtp_error, $body_file, $options);
1834
1835         if ($sent) {
1836             $RCMAIL->storage->set_flag($message->uid, 'MDNSENT');
1837             return true;
1838         }
f59cfe 1839     }
232535 1840
f5d2ee 1841     return false;
0ea884 1842 }
T 1843
a0e3dc 1844 /**
AM 1845  * Detect recipient identity from specified message
1846  */
1847 function rcmail_identity_select($MESSAGE, $identities = null, $compose_mode = 'reply')
1848 {
1849     $a_recipients = array();
1850     $a_names      = array();
1851
1852     if ($identities === null) {
1853         $identities = rcmail::get_instance()->user->list_identities(null, true);
1854     }
1855
1856     // extract all recipients of the reply-message
1857     if (is_object($MESSAGE->headers) && in_array($compose_mode, array('reply', 'forward'))) {
1858         $a_to = rcube_mime::decode_address_list($MESSAGE->headers->to, null, true, $MESSAGE->headers->charset);
1859         foreach ($a_to 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         if (!empty($MESSAGE->headers->cc)) {
1867             $a_cc = rcube_mime::decode_address_list($MESSAGE->headers->cc, null, true, $MESSAGE->headers->charset);
1868             foreach ($a_cc 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     }
1876
a8b004 1877     // decode From: address
AM 1878     $from = rcube_mime::decode_address_list($MESSAGE->headers->from, null, true, $MESSAGE->headers->charset);
1879     $from = array_shift($from);
1880     $from['mailto'] = strtolower($from['mailto']);
1881
1882     $from_idx   = null;
1883     $found_idx  = array('to' => null, 'from' => null);
1884     $check_from = in_array($compose_mode, array('draft', 'edit', 'reply'));
a0e3dc 1885
AM 1886     // Select identity
1887     foreach ($identities as $idx => $ident) {
a8b004 1888         // use From: header when in edit/draft or reply-to-self
AM 1889         if ($check_from && $from['mailto'] == strtolower($ident['email_ascii'])) {
1890             // remember first matching identity address
1891             if ($found_idx['from'] === null) {
1892                 $found_idx['from'] = $idx;
1893             }
1894             // match identity name
1895             if ($from['name'] && $ident['name'] && $from['name'] == $ident['name']) {
a0e3dc 1896                 $from_idx = $idx;
AM 1897                 break;
1898             }
1899         }
a8b004 1900         // use replied/forwarded message recipients
53b4c7 1901         else if (($found = array_search(strtolower($ident['email_ascii']), $a_recipients)) !== false) {
a8b004 1902             // remember first matching identity address
AM 1903             if ($found_idx['to'] === null) {
1904                 $found_idx['to'] = $idx;
a0e3dc 1905             }
AM 1906             // match identity name
1907             if ($a_names[$found] && $ident['name'] && $a_names[$found] == $ident['name']) {
1908                 $from_idx = $idx;
1909                 break;
1910             }
1911         }
1912     }
1913
a8b004 1914     // If matching by name+address didn't find any matches,
AM 1915     // get first found identity (address) if any
a0e3dc 1916     if ($from_idx === null) {
a8b004 1917         $from_idx = $found_idx['from'] !== null ? $found_idx['from'] : $found_idx['to'];
a0e3dc 1918     }
AM 1919
1920     // Try Return-Path
1921     if ($from_idx === null && ($return_path = $MESSAGE->headers->others['return-path'])) {
c20fa4 1922         $return_path = array_map('strtolower', (array) $return_path);
AM 1923
a0e3dc 1924         foreach ($identities as $idx => $ident) {
f09b16 1925             // Return-Path header contains an email address, but on some mailing list
AM 1926             // it can be e.g. <pear-dev-return-55250-local=domain.tld@lists.php.net>
1927             // where local@domain.tld is the address we're looking for (#1489241)
c20fa4 1928             $ident1 = strtolower($ident['email_ascii']);
f09b16 1929             $ident2 = str_replace('@', '=', $ident1);
c20fa4 1930             $ident1 = '<' . $ident1 . '>';
AM 1931             $ident2 = '-' . $ident2 . '@';
f09b16 1932
c20fa4 1933             foreach ($return_path as $path) {
AM 1934                 if ($path == $ident1 || stripos($path, $ident2)) {
af9dbd 1935                     $from_idx = $idx;
AM 1936                     break 2;
1937                 }
a0e3dc 1938             }
AM 1939         }
1940     }
1941
b825f8 1942     // See identity_select plugin for example usage of this hook
AM 1943     $plugin = rcmail::get_instance()->plugins->exec_hook('identity_select',
1944         array('message' => $MESSAGE, 'identities' => $identities, 'selected' => $from_idx));
a0e3dc 1945
b825f8 1946     $selected = $plugin['selected'];
a0e3dc 1947
a8b004 1948     // default identity is always first on the list
AM 1949     return $identities[$selected !== null ? $selected : 0];
a0e3dc 1950 }
2bf3cc 1951
e0bd70 1952 // Fixes some content-type names
A 1953 function rcmail_fix_mimetype($name)
1954 {
f5d2ee 1955     // Some versions of Outlook create garbage Content-Type:
AM 1956     // application/pdf.A520491B_3BF7_494D_8855_7FAC2C6C0608
1957     if (preg_match('/^application\/pdf.+/', $name)) {
1958         $name = 'application/pdf';
1959     }
1960     // treat image/pjpeg (image/pjpg, image/jpg) as image/jpeg (#1489097)
1961     else if (preg_match('/^image\/p?jpe?g$/', $name)) {
1962         $name = 'image/jpeg';
1963     }
090c49 1964
f5d2ee 1965     return $name;
e0bd70 1966 }
2bf3cc 1967
be72fb 1968 // return attachment filename, handle empty filename case
830fd2 1969 function rcmail_attachment_name($attachment, $display = false)
be72fb 1970 {
6b2b2e 1971     global $RCMAIL;
AM 1972
be72fb 1973     $filename = $attachment->filename;
AM 1974
1975     if ($filename === null || $filename === '') {
1976         if ($attachment->mimetype == 'text/html') {
6b2b2e 1977             $filename = $RCMAIL->gettext('htmlmessage');
be72fb 1978         }
AM 1979         else {
726297 1980             $ext      = (array) rcube_mime::get_mime_extensions($attachment->mimetype);
be72fb 1981             $ext      = array_shift($ext);
6b2b2e 1982             $filename = $RCMAIL->gettext('messagepart') . ' ' . $attachment->mime_id;
be72fb 1983             if ($ext) {
AM 1984                 $filename .= '.' . $ext;
1985             }
1986         }
1987     }
1988
1989     $filename = preg_replace('[\r\n]', '', $filename);
1990
830fd2 1991     // Display smart names for some known mimetypes
AM 1992     if ($display) {
1993         if (preg_match('/application\/(pgp|pkcs7)-signature/i', $attachment->mimetype)) {
6b2b2e 1994             $filename = $RCMAIL->gettext('digitalsig');
830fd2 1995         }
AM 1996     }
1997
be72fb 1998     return $filename;
AM 1999 }
2000
e538b3 2001 function rcmail_search_filter($attrib)
A 2002 {
f5d2ee 2003     global $RCMAIL;
e538b3 2004
f5d2ee 2005     if (!strlen($attrib['id']))
AM 2006         $attrib['id'] = 'rcmlistfilter';
e538b3 2007
f5d2ee 2008     $attrib['onchange'] = rcmail_output::JS_OBJECT_NAME.'.filter_mailbox(this.value)';
9800a8 2009
f5d2ee 2010     // Content-Type values of messages with attachments
AM 2011     // the same as in app.js:add_message_row()
2012     $ctypes = array('application/', 'multipart/m', 'multipart/signed', 'multipart/report');
bb7c52 2013
f5d2ee 2014     // Build search string of "with attachment" filter
ceff79 2015     $attachment = trim(str_repeat(' OR', count($ctypes)-1));
f5d2ee 2016     foreach ($ctypes as $type) {
AM 2017         $attachment .= ' HEADER Content-Type ' . rcube_imap_generic::escape($type);
2018     }
e538b3 2019
f5d2ee 2020     $select_filter = new html_select($attrib);
AM 2021     $select_filter->add($RCMAIL->gettext('all'), 'ALL');
2022     $select_filter->add($RCMAIL->gettext('unread'), 'UNSEEN');
2023     $select_filter->add($RCMAIL->gettext('flagged'), 'FLAGGED');
2024     $select_filter->add($RCMAIL->gettext('unanswered'), 'UNANSWERED');
2025     if (!$RCMAIL->config->get('skip_deleted')) {
2026         $select_filter->add($RCMAIL->gettext('deleted'), 'DELETED');
2027         $select_filter->add($RCMAIL->gettext('undeleted'), 'UNDELETED');
2028     }
2029     $select_filter->add($RCMAIL->gettext('withattachment'), $attachment);
2030     $select_filter->add($RCMAIL->gettext('priority').': '.$RCMAIL->gettext('highest'), 'HEADER X-PRIORITY 1');
2031     $select_filter->add($RCMAIL->gettext('priority').': '.$RCMAIL->gettext('high'), 'HEADER X-PRIORITY 2');
2032     $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');
2033     $select_filter->add($RCMAIL->gettext('priority').': '.$RCMAIL->gettext('low'), 'HEADER X-PRIORITY 4');
2034     $select_filter->add($RCMAIL->gettext('priority').': '.$RCMAIL->gettext('lowest'), 'HEADER X-PRIORITY 5');
e538b3 2035
f5d2ee 2036     $out = $select_filter->show($_SESSION['search_filter']);
e538b3 2037
f5d2ee 2038     $RCMAIL->output->add_gui_object('search_filter', $attrib['id']);
e538b3 2039
f5d2ee 2040     return $out;
e538b3 2041 }
A 2042
64e3e8 2043 function rcmail_message_error($uid=null)
A 2044 {
f5d2ee 2045     global $RCMAIL;
64e3e8 2046
f5d2ee 2047     // Set env variables for messageerror.html template
AM 2048     if ($RCMAIL->action == 'show') {
2049         $mbox_name = $RCMAIL->storage->get_folder();
2050
2051         $RCMAIL->output->set_env('mailbox', $mbox_name);
2052         $RCMAIL->output->set_env('uid', null);
2053     }
2054
2055     // display error message
2056     $RCMAIL->output->show_message('messageopenerror', 'error');
2057     // ... display message error page
2058     $RCMAIL->output->send('messageerror');
64e3e8 2059 }
9b3fdc 2060
4f53ab 2061 function rcmail_message_import_form($attrib = array())
TB 2062 {
f5d2ee 2063     global $RCMAIL;
4f53ab 2064
f5d2ee 2065     // set defaults
AM 2066     $attrib += array('id' => 'rcmImportform', 'buttons' => 'yes');
4f53ab 2067
f5d2ee 2068     // Get filesize, enable upload progress bar
AM 2069     $max_filesize = $RCMAIL->upload_init();
4f53ab 2070
f5d2ee 2071     $button    = new html_inputfield(array('type' => 'button'));
AM 2072     $fileinput = new html_inputfield(array(
2073             'type'     => 'file',
2074             'name'     => '_file[]',
2075             'multiple' => 'multiple',
2076             'accept'   => ".eml, .mbox, message/rfc822, text/*",
2077     ));
4f53ab 2078
f5d2ee 2079     $content = html::tag('input', array('type' => 'hidden', 'name' => '_unlock', 'value' => ''))
AM 2080         . html::div(null, $fileinput->show())
2081         . html::div('hint', $RCMAIL->gettext(array('name' => 'maxuploadsize', 'vars' => array('size' => $max_filesize))));
4f53ab 2082
f5d2ee 2083     if (rcube_utils::get_boolean($attrib['buttons'])) {
AM 2084         $content .= html::div('buttons',
2085             $button->show($RCMAIL->gettext('close'), array('class' => 'button', 'onclick' => "$('#$attrib[id]').hide()"))
2086             . ' ' .
2087             $button->show($RCMAIL->gettext('upload'), array(
2088                 'class'   => 'button mainaction',
2089                 'onclick' => rcmail_output::JS_OBJECT_NAME . ".command('import-messages', this.form)"
2090             )));
2091     }
2092
2093     $out = $RCMAIL->output->form_tag(array(
2094             'id'      => $attrib['id'].'Frm',
2095             'method'  => 'post',
2096             'enctype' => 'multipart/form-data'
2097         ),
2098         $content);
2099
2100     $RCMAIL->output->add_gui_object('importform', $attrib['id'].'Frm');
8d3b27 2101     $RCMAIL->output->add_label('selectimportfile','importwait');
f5d2ee 2102
AM 2103     return html::div($attrib, $out);
4f53ab 2104 }
700e3c 2105
TB 2106 /**
2107  * Add groups from the given address source to the address book widget
2108  */
2109 function rcmail_compose_contact_groups($abook, $source_id, $search = null, $search_mode = 0)
2110 {
2111     global $RCMAIL, $OUTPUT;
2112
2113     $jsresult = array();
2114     foreach ($abook->list_groups($search, $search_mode) as $group) {
2115         $abook->reset();
2116         $abook->set_group($group['ID']);
2117         $group_prop = $abook->get_group($group['ID']);
2118
2119         // group (distribution list) with email address(es)
2120         if ($group_prop['email']) {
2121             foreach ((array)$group_prop['email'] as $email) {
2122                 $row_id = 'G'.$group['ID'];
2123                 $jsresult[$row_id] = format_email_recipient($email, $group['name']);
2124                 $OUTPUT->command('add_contact_row', $row_id, array(
2125                     'contactgroup' => html::span(array('title' => $email), rcube::Q($group['name']))), 'group');
2126             }
2127         }
2128         // make virtual groups clickable to list their members
2129         else if ($group_prop['virtual']) {
2130             $row_id = 'G'.$group['ID'];
2131             $OUTPUT->command('add_contact_row', $row_id, array(
2132                 'contactgroup' => html::a(array(
2133                     'href' => '#list',
2134                     'rel' => $group['ID'],
2135                     'title' => $RCMAIL->gettext('listgroup'),
2136                     'onclick' => sprintf("return %s.command('pushgroup',{'source':'%s','id':'%s'},this,event)",
2137                                     rcmail_output::JS_OBJECT_NAME, $source_id, $group['ID']),
2138                 ), rcube::Q($group['name']) . '&nbsp;' . html::span('action', '&raquo;'))),
2139                 'group',
2140                 array('ID' => $group['ID'], 'name' => $group['name'], 'virtual' => true));
2141         }
2142         // show group with count
2143         else if (($result = $abook->count()) && $result->count) {
2144             $row_id = 'E'.$group['ID'];
2145             $jsresult[$row_id] = $group['name'];
2146             $OUTPUT->command('add_contact_row', $row_id, array(
2147                 'contactgroup' => rcube::Q($group['name'] . ' (' . intval($result->count) . ')')), 'group');
2148         }
2149     }
2150
2151     $abook->reset();
2152     $abook->set_group(0);
2153
2154     return $jsresult;
2155 }