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