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