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