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