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