Aleksander Machniak
2015-09-10 357cd5103d1c27f8416ef316c4a4c31588db45b8
commit | author | age
4e17e6 1 <?php
T 2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/steps/mail/get.inc                                            |
6  |                                                                       |
e019f2 7  | This file is part of the Roundcube Webmail client                     |
c97625 8  | Copyright (C) 2005-2013, 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  |   Delivering a specific part of a mail message                        |
16  |                                                                       |
17  +-----------------------------------------------------------------------+
18  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
19  +-----------------------------------------------------------------------+
20 */
21
22
23 // show loading page
8fa58e 24 if (!empty($_GET['_preload'])) {
c14c21 25     $_get = $_GET + array('_mimewarning' => 1, '_embed' => 1);
TB 26     unset($_get['_preload']);
27     $url = $RCMAIL->url($_get);
c97625 28     $message = $RCMAIL->gettext('loadingdata');
4e17e6 29
c97625 30     header('Content-Type: text/html; charset=' . RCUBE_CHARSET);
AM 31     print "<html>\n<head>\n"
6b2b2e 32         . '<meta http-equiv="refresh" content="0; url='.rcube::Q($url).'">' . "\n"
AM 33         . '<meta http-equiv="content-type" content="text/html; charset='.RCUBE_CHARSET.'">' . "\n"
3e8b11 34         . "</head>\n<body>\n$message\n</body>\n</html>";
c97625 35     exit;
8fa58e 36 }
4e17e6 37
d51c93 38 ob_end_clean();
4e17e6 39
1ef403 40
4e17e6 41 // similar code as in program/steps/mail/show.inc
8fa58e 42 if (!empty($_GET['_uid'])) {
c97625 43     $uid = rcube_utils::get_input_value('_uid', rcube_utils::INPUT_GET);
AM 44     $RCMAIL->config->set('prefer_html', true);
45     $MESSAGE = new rcube_message($uid);
8fa58e 46 }
4bfe4e 47
AM 48 // check connection status
49 check_storage_status();
4e17e6 50
6b2b2e 51 $part_id = rcube_utils::get_input_value('_part', rcube_utils::INPUT_GPC);
eaf383 52
4e17e6 53 // show part page
8fa58e 54 if (!empty($_GET['_frame'])) {
c97625 55     if ($part_id && ($part = $MESSAGE->mime_parts[$part_id])) {
AM 56         $filename = rcmail_attachment_name($part);
57         $OUTPUT->set_pagetitle($filename);
58     }
b6da0b 59
c97625 60     // register UI objects
AM 61     $OUTPUT->add_handlers(array(
62         'messagepartframe'    => 'rcmail_message_part_frame',
63         'messagepartcontrols' => 'rcmail_message_part_controls',
64     ));
eaf383 65
c97625 66     $OUTPUT->set_env('mailbox', $RCMAIL->storage->get_folder());
AM 67     $OUTPUT->set_env('uid', $uid);
68     $OUTPUT->set_env('part', $part_id);
69     $OUTPUT->set_env('filename', $filename);
049428 70
c97625 71     $OUTPUT->send('messagepart');
AM 72     exit;
8fa58e 73 }
4e17e6 74
031491 75 // render thumbnail of an image attachment
TB 76 else if ($_GET['_thumb']) {
c97625 77     $pid = rcube_utils::get_input_value('_part', rcube_utils::INPUT_GET);
AM 78     if ($part = $MESSAGE->mime_parts[$pid]) {
79         $thumbnail_size = $RCMAIL->config->get('image_thumbnail_size', 240);
80         $temp_dir       = $RCMAIL->config->get('temp_dir');
81         $mimetype       = $part->mimetype;
82         $file_ident     = $MESSAGE->headers->messageID . ':' . $part->mime_id . ':' . $part->size . ':' . $part->mimetype;
83         $cache_basename = $temp_dir . '/' . md5($file_ident . ':' . $RCMAIL->user->ID . ':' . $thumbnail_size);
84af0d 84         $cache_file     = $cache_basename . '.thumb';
031491 85
c97625 86         // render thumbnail image if not done yet
AM 87         if (!is_file($cache_file)) {
84af0d 88             if ($fp = fopen(($orig_name = $cache_basename . '.tmp'), 'w')) {
26c993 89                 $MESSAGE->get_part_body($part->mime_id, false, 0, $fp);
c97625 90                 fclose($fp);
031491 91
c97625 92                 $image = new rcube_image($orig_name);
AM 93                 if ($imgtype = $image->resize($thumbnail_size, $cache_file, true)) {
94                     $mimetype = 'image/' . $imgtype;
95                     unlink($orig_name);
96                 }
97                 else {
98                     rename($orig_name, $cache_file);
99                 }
100             }
19cc5b 101         }
AM 102
c97625 103         if (is_file($cache_file)) {
AM 104             header('Content-Type: ' . $mimetype);
105             readfile($cache_file);
19cc5b 106         }
8fa58e 107     }
8d4bcd 108
4e17e6 109     exit;
8fa58e 110 }
4e17e6 111
c97625 112 else if (strlen($part_id)) {
AM 113     if ($part = $MESSAGE->mime_parts[$part_id]) {
114         $mimetype = rcmail_fix_mimetype($part->mimetype);
115
116         // allow post-processing of the message body
117         $plugin = $RCMAIL->plugins->exec_hook('message_part_get', array(
118             'uid'      => $MESSAGE->uid,
119             'id'       => $part->mime_id,
120             'mimetype' => $mimetype,
121             'part'     => $part,
122             'download' => !empty($_GET['_download'])
123         ));
124
125         if ($plugin['abort']) {
126             exit;
127         }
128
129         // overwrite modified vars from plugin
130         $mimetype   = $plugin['mimetype'];
131         $extensions = rcube_mime::get_mime_extensions($mimetype);
132
133         if ($plugin['body']) {
48ba44 134             $body = $plugin['body'];
c97625 135         }
AM 136
137         // compare file mimetype with the stated content-type headers and file extension to avoid malicious operations
138         if (!empty($_REQUEST['_embed']) && empty($_REQUEST['_nocheck'])) {
139             $file_extension = strtolower(pathinfo($part->filename, PATHINFO_EXTENSION));
140
141             // 1. compare filename suffix with expected suffix derived from mimetype
afd5e4 142             $valid = $file_extension && in_array($file_extension, (array)$extensions) || empty($extensions) || !empty($_REQUEST['_mimeclass']);
c97625 143
AM 144             // 2. detect the real mimetype of the attachment part and compare it with the stated mimetype and filename extension
145             if ($valid || !$file_extension || $mimetype == 'application/octet-stream' || stripos($mimetype, 'text/') === 0) {
48ba44 146                 $tmp_body = $body ?: $MESSAGE->get_part_body($part->mime_id, false, 2048);
c97625 147
AM 148                 // detect message part mimetype
48ba44 149                 $real_mimetype = rcube_mime::file_content_type($tmp_body, $part->filename, $mimetype, true, true);
c97625 150                 list($real_ctype_primary, $real_ctype_secondary) = explode('/', $real_mimetype);
AM 151
152                 // accept text/plain with any extension
153                 if ($real_mimetype == 'text/plain' && $real_mimetype == $mimetype) {
154                     $valid_extension = true;
155                 }
556d28 156                 // ignore differences in text/* mimetypes. Filetype detection isn't very reliable here
AM 157                 else if ($real_ctype_primary == 'text' && strpos($mimetype, $real_ctype_primary) === 0) {
158                     $real_mimetype   = $mimetype;
159                     $valid_extension = true;
160                 }
161                 // ignore filename extension if mimeclass matches (#1489029)
162                 else if (!empty($_REQUEST['_mimeclass']) && $real_ctype_primary == $_REQUEST['_mimeclass']) {
163                     $valid_extension = true;
164                 }
165                 else {
166                     // get valid file extensions
167                     $extensions      = rcube_mime::get_mime_extensions($real_mimetype);
c8468c 168                     $valid_extension = !$file_extension || empty($extensions) || in_array($file_extension, (array)$extensions);
556d28 169                 }
c97625 170
AM 171                 // fix mimetype for images wrongly declared as octet-stream
172                 if ($mimetype == 'application/octet-stream' && strpos($real_mimetype, 'image/') === 0 && $valid_extension) {
173                     $mimetype = $real_mimetype;
174                 }
175
afd5e4 176                 // "fix" real mimetype the same way the original is before comparison
AM 177                 $real_mimetype = rcmail_fix_mimetype($real_mimetype);
178
179                 $valid = $real_mimetype == $mimetype && $valid_extension;
c97625 180             }
AM 181             else {
182                 $real_mimetype = $mimetype;
183             }
184
185             // show warning if validity checks failed
186             if (!$valid) {
187                 // send blocked.gif for expected images
188                 if (empty($_REQUEST['_mimewarning']) && strpos($mimetype, 'image/') === 0) {
189                     // Do not cache. Failure might be the result of a misconfiguration, thus real content should be returned once fixed. 
c6efcf 190                     $content = $RCMAIL->get_resource_content('blocked.gif');
c97625 191                     $OUTPUT->nocacheing_headers();
AM 192                     header("Content-Type: image/gif");
193                     header("Content-Transfer-Encoding: binary");
c6efcf 194                     header("Content-Length: " . strlen($content));
AM 195                     echo $content;
c97625 196                 }
AM 197                 else {  // html warning with a button to load the file anyway
198                     $OUTPUT = new rcmail_html_page();
199                     $OUTPUT->write(html::tag('html', null, html::tag('body', 'embed',
200                         html::div(array('class' => 'rcmail-inline-message rcmail-inline-warning'),
201                             $RCMAIL->gettext(array(
202                                 'name' => 'attachmentvalidationerror',
203                                 'vars' => array(
204                                     'expected' => $mimetype . ($file_extension ? " (.$file_extension)" : ''),
205                                     'detected' => $real_mimetype . ($extensions[0] ? " (.$extensions[0])" : ''),
206                                 )
207                             ))
208                             . html::p(array('class' => 'rcmail-inline-buttons'),
209                                 html::tag('button', array(
210                                     'onclick' => "location.href='" . $RCMAIL->url(array_merge($_GET, array('_nocheck' => 1))) . "'"
211                                 ),
212                                 $RCMAIL->gettext('showanyway'))
213                             )
214                         ))));
215                 }
216
217                 exit;
218             }
219         }
220
221
222         // TIFF to JPEG conversion, if needed
223         $tiff_support = !empty($_SESSION['browser_caps']) && !empty($_SESSION['browser_caps']['tif']);
224         if (!empty($_REQUEST['_embed']) && !$tiff_support
8968f9 225             && rcube_image::is_convertable('image/tiff')
c97625 226             && rcmail_part_image_type($part) == 'image/tiff'
AM 227         ) {
228             $tiff2jpeg = true;
229             $mimetype  = 'image/jpeg';
230         }
231
232
233         $browser = $RCMAIL->output->browser;
234         list($ctype_primary, $ctype_secondary) = explode('/', $mimetype);
235
236         if (!$plugin['download'] && $ctype_primary == 'text') {
237             header("Content-Type: text/$ctype_secondary; charset=" . ($part->charset ? $part->charset : RCUBE_CHARSET));
238         }
239         else {
240             header("Content-Type: $mimetype");
241             header("Content-Transfer-Encoding: binary");
242         }
243
244         // deliver part content
245         if ($ctype_primary == 'text' && $ctype_secondary == 'html' && empty($plugin['download'])) {
246             // Check if we have enough memory to handle the message in it
247             // #1487424: we need up to 10x more memory than the body
248             if (!rcube_utils::mem_check($part->size * 10)) {
249                 $out = '<body>' . $RCMAIL->gettext('messagetoobig'). ' '
250                     . html::a('?_task=mail&_action=get&_download=1&_uid='.$MESSAGE->uid.'&_part='.$part->mime_id
c83940 251                         .'&_mbox='. urlencode($MESSAGE->folder), $RCMAIL->gettext('download')) . '</body></html>';
c97625 252             }
AM 253             else {
254                 // get part body if not available
48ba44 255                 if (!isset($body)) {
AM 256                     $body = $MESSAGE->get_part_body($part->mime_id, true);
c97625 257                 }
AM 258
259                 // show images?
260                 rcmail_check_safe($MESSAGE);
261
262                 // render HTML body
48ba44 263                 $out = rcmail_print_body($body, $part, array('safe' => $MESSAGE->is_safe, 'inline_html' => false));
c97625 264
AM 265                 // insert remote objects warning into HTML body
266                 if ($REMOTE_OBJECTS) {
267                     $body_start = 0;
268                     if ($body_pos = strpos($out, '<body')) {
269                         $body_start = strpos($out, '>', $body_pos) + 1;
270                     }
271
272                     $out = substr($out, 0, $body_start)
273                         . html::div(array('class' => 'rcmail-inline-message rcmail-inline-warning'),
274                             rcube::Q($RCMAIL->gettext('blockedimages')) . '&nbsp;' .
275                             html::tag('button',
276                                 array('onclick' => "location.href='" . $RCMAIL->url(array_merge($_GET, array('_safe' => 1))) . "'"),
277                                 rcube::Q($RCMAIL->gettext('showimages')))
278                         )
279                         . substr($out, $body_start);
280                 }
281             }
282
283             // check connection status
48ba44 284             if ($part->size && empty($body)) {
c97625 285                 check_storage_status();
AM 286             }
287
288             $OUTPUT = new rcmail_html_page();
289             $OUTPUT->write($out);
290         }
291         else {
292             // don't kill the connection if download takes more than 30 sec.
293             @set_time_limit(0);
294
295             $filename = rcmail_attachment_name($part);
296
5515db 297             if ($browser->ie)
c97625 298                 $filename = rawurlencode($filename);
AM 299             else
300                 $filename = addcslashes($filename, '"');
301
302             $disposition = !empty($plugin['download']) ? 'attachment' : 'inline';
303
304             // Workaround for nasty IE bug (#1488844)
305             // If Content-Disposition header contains string "attachment" e.g. in filename
306             // IE handles data as attachment not inline
307             if ($disposition == 'inline' && $browser->ie && $browser->ver < 9) {
308                 $filename = str_ireplace('attachment', 'attach', $filename);
309             }
310
311             // add filename extension if missing
312             if (!pathinfo($filename, PATHINFO_EXTENSION) && ($extensions = rcube_mime::get_mime_extensions($mimetype))) {
313                 $filename .= '.' . $extensions[0];
314             }
315
316             header("Content-Disposition: $disposition; filename=\"$filename\"");
317
318             // handle tiff to jpeg conversion
319             if (!empty($tiff2jpeg)) {
320                 $temp_dir  = unslashify($RCMAIL->config->get('temp_dir'));
321                 $file_path = tempnam($temp_dir, 'rcmAttmnt');
322
323                 // write content to temp file
48ba44 324                 if ($body) {
AM 325                     $saved = file_put_contents($file_path, $body);
c97625 326                 }
AM 327                 else if ($part->size) {
328                     $fd    = fopen($file_path, 'w');
48ba44 329                     $saved = $MESSAGE->get_part_body($part->mime_id, false, 0, $fd);
c97625 330                     fclose($fd);
AM 331                 }
332
333                 // convert image to jpeg and send it to the browser
334                 if ($saved) {
335                     $image = new rcube_image($file_path);
336                     if ($image->convert(rcube_image::TYPE_JPG, $file_path)) {
337                         header("Content-Length: " . filesize($file_path));
338                         readfile($file_path);
339                     }
340                     unlink($file_path);
341                 }
342             }
343             // do content filtering to avoid XSS through fake images
344             else if (!empty($_REQUEST['_embed']) && $browser->ie && $browser->ver <= 8) {
48ba44 345                 if ($body) {
AM 346                     echo preg_match('/<(script|iframe|object)/i', $body) ? '' : $body;
c97625 347                     $sent = true;
AM 348                 }
349                 else if ($part->size) {
350                     $stdout = fopen('php://output', 'w');
351                     stream_filter_register('rcube_content', 'rcube_content_filter') or die('Failed to register content filter');
352                     stream_filter_append($stdout, 'rcube_content');
48ba44 353                     $sent = $MESSAGE->get_part_body($part->mime_id, true, 0, $stdout);
c97625 354                 }
AM 355             }
356             // send part as-it-is
357             else {
48ba44 358                 if ($body && empty($plugin['download'])) {
AM 359                     header("Content-Length: " . strlen($body));
360                     echo $body;
c97625 361                     $sent = true;
AM 362                 }
363                 else if ($part->size) {
357cd5 364                     // Don't be tempted to set Content-Length to $part->d_parameters['size'] (#1490482)
AM 365                     // RFC2183 says "The size parameter indicates an approximate size"
c97625 366
48ba44 367                     $sent = $MESSAGE->get_part_body($part->mime_id, false, 0, -1);
c97625 368                 }
AM 369             }
370
371             // check connection status
372             if ($part->size && !$sent) {
373                 check_storage_status();
374             }
375         }
376
377         exit;
378     }
379 }
4e17e6 380 // print message
8fa58e 381 else {
c97625 382     // send correct headers for content type
AM 383     header("Content-Type: text/html");
4e17e6 384
c97625 385     $cont = "<html>\n<head><title></title>\n</head>\n<body>";
AM 386     $cont .= rcmail_message_body(array());
387     $cont .= "\n</body>\n</html>";
4e17e6 388
c97625 389     $OUTPUT = new rcmail_html_page();
AM 390     $OUTPUT->write($cont);
4e17e6 391
c97625 392     exit;
8fa58e 393 }
4e17e6 394
T 395
396 // if we arrive here, the requested part was not found
397 header('HTTP/1.1 404 Not Found');
398 exit;
399
eaf383 400 /**
AM 401  * Handles nicely storage connection errors
402  */
4bfe4e 403 function check_storage_status()
AM 404 {
405     $error = rcmail::get_instance()->storage->get_error_code();
406
407     // Check if we have a connection error
408     if ($error == rcube_imap_generic::ERROR_BAD) {
409         ob_end_clean();
410
411         // Get action is often executed simultanously.
412         // Some servers have MAXPERIP or other limits.
413         // To workaround this we'll wait for some time
414         // and try again (once).
415         // Note: Random sleep interval is used to minimize concurency
416         // in getting message parts
417
418         if (!isset($_GET['_redirected'])) {
419             usleep(rand(10,30)*100000); // 1-3 sec.
420             header('Location: ' . $_SERVER['REQUEST_URI'] . '&_redirected=1');
421         }
422         else {
6b2b2e 423             rcube::raise_error(array(
4bfe4e 424                 'code' => 500, 'type' => 'php',
AM 425                 'file' => __FILE__, 'line' => __LINE__,
426                 'message' => 'Unable to get/display message part. IMAP connection error'),
427                 true, true);
428         }
429
430         // Don't kill session, just quit (#1486995)
431         exit;
432     }
433 }
049428 434
eaf383 435 /**
AM 436  * Attachment properties table
437  */
049428 438 function rcmail_message_part_controls($attrib)
AM 439 {
440     global $MESSAGE, $RCMAIL;
441
6b2b2e 442     $part = asciiwords(rcube_utils::get_input_value('_part', rcube_utils::INPUT_GPC));
049428 443     if (!is_object($MESSAGE) || !is_array($MESSAGE->parts)
AM 444         || !($_GET['_uid'] && $_GET['_part']) || !$MESSAGE->mime_parts[$part]
445     ) {
446         return '';
447     }
448
449     $part  = $MESSAGE->mime_parts[$part];
450     $table = new html_table(array('cols' => 2));
451
6b2b2e 452     $table->add('title', rcube::Q($RCMAIL->gettext('namex')).':');
AM 453     $table->add('header', rcube::Q(rcmail_attachment_name($part)));
049428 454
6b2b2e 455     $table->add('title', rcube::Q($RCMAIL->gettext('type')).':');
AM 456     $table->add('header', rcube::Q($part->mimetype));
049428 457
6b2b2e 458     $table->add('title', rcube::Q($RCMAIL->gettext('size')).':');
AM 459     $table->add('header', rcube::Q($RCMAIL->message_part_size($part)));
049428 460
AM 461     return $table->show($attrib);
462 }
463
eaf383 464 /**
AM 465  * Attachment preview frame
466  */
049428 467 function rcmail_message_part_frame($attrib)
AM 468 {
469     global $MESSAGE, $RCMAIL;
470
6b2b2e 471     $part = $MESSAGE->mime_parts[asciiwords(rcube_utils::get_input_value('_part', rcube_utils::INPUT_GPC))];
049428 472     $ctype_primary = strtolower($part->ctype_primary);
AM 473
474     $attrib['src'] = './?' . str_replace('_frame=', ($ctype_primary=='text' ? '_embed=' : '_preload='), $_SERVER['QUERY_STRING']);
475
476     $RCMAIL->output->add_gui_object('messagepartframe', $attrib['id']);
477
478     return html::iframe($attrib);
479 }