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