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