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