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