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