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