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