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