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