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