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