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