You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

get.inc 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. <?php
  2. /**
  3. +-----------------------------------------------------------------------+
  4. | program/steps/mail/get.inc |
  5. | |
  6. | This file is part of the Roundcube Webmail client |
  7. | Copyright (C) 2005-2013, The Roundcube Dev Team |
  8. | |
  9. | Licensed under the GNU General Public License version 3 or |
  10. | any later version with exceptions for skins & plugins. |
  11. | See the README file for a full license statement. |
  12. | |
  13. | PURPOSE: |
  14. | Delivering a specific part of a mail message |
  15. | |
  16. +-----------------------------------------------------------------------+
  17. | Author: Thomas Bruederli <roundcube@gmail.com> |
  18. +-----------------------------------------------------------------------+
  19. */
  20. // show loading page
  21. if (!empty($_GET['_preload'])) {
  22. $_get = $_GET + array('_mimewarning' => 1, '_embed' => 1);
  23. unset($_get['_preload']);
  24. $url = $RCMAIL->url($_get);
  25. $message = $RCMAIL->gettext('loadingdata');
  26. header('Content-Type: text/html; charset=' . RCUBE_CHARSET);
  27. print "<html>\n<head>\n"
  28. . '<meta http-equiv="refresh" content="0; url='.rcube::Q($url).'">' . "\n"
  29. . '<meta http-equiv="content-type" content="text/html; charset='.RCUBE_CHARSET.'">' . "\n"
  30. . "</head>\n<body>\n$message\n</body>\n</html>";
  31. exit;
  32. }
  33. ob_end_clean();
  34. // similar code as in program/steps/mail/show.inc
  35. if (!empty($_GET['_uid'])) {
  36. $uid = rcube_utils::get_input_value('_uid', rcube_utils::INPUT_GET);
  37. $RCMAIL->config->set('prefer_html', true);
  38. $MESSAGE = new rcube_message($uid, null, intval($_GET['_safe']));
  39. }
  40. // check connection status
  41. check_storage_status();
  42. $part_id = rcube_utils::get_input_value('_part', rcube_utils::INPUT_GPC);
  43. // show part page
  44. if (!empty($_GET['_frame'])) {
  45. if ($part_id && ($part = $MESSAGE->mime_parts[$part_id])) {
  46. $filename = rcmail_attachment_name($part);
  47. $OUTPUT->set_pagetitle($filename);
  48. }
  49. // register UI objects
  50. $OUTPUT->add_handlers(array(
  51. 'messagepartframe' => 'rcmail_message_part_frame',
  52. 'messagepartcontrols' => 'rcmail_message_part_controls',
  53. ));
  54. $OUTPUT->set_env('mailbox', $RCMAIL->storage->get_folder());
  55. $OUTPUT->set_env('uid', $uid);
  56. $OUTPUT->set_env('part', $part_id);
  57. $OUTPUT->set_env('filename', $filename);
  58. $OUTPUT->send('messagepart');
  59. exit;
  60. }
  61. // render thumbnail of an image attachment
  62. else if ($_GET['_thumb']) {
  63. $pid = rcube_utils::get_input_value('_part', rcube_utils::INPUT_GET);
  64. if ($part = $MESSAGE->mime_parts[$pid]) {
  65. $thumbnail_size = $RCMAIL->config->get('image_thumbnail_size', 240);
  66. $temp_dir = $RCMAIL->config->get('temp_dir');
  67. $mimetype = $part->mimetype;
  68. $file_ident = $MESSAGE->headers->messageID . ':' . $part->mime_id . ':' . $part->size . ':' . $part->mimetype;
  69. $cache_basename = $temp_dir . '/' . md5($file_ident . ':' . $RCMAIL->user->ID . ':' . $thumbnail_size);
  70. $cache_file = $cache_basename . '.thumb';
  71. // render thumbnail image if not done yet
  72. if (!is_file($cache_file)) {
  73. if ($fp = fopen(($orig_name = $cache_basename . '.tmp'), 'w')) {
  74. $MESSAGE->get_part_body($part->mime_id, false, 0, $fp);
  75. fclose($fp);
  76. $image = new rcube_image($orig_name);
  77. if ($imgtype = $image->resize($thumbnail_size, $cache_file, true)) {
  78. $mimetype = 'image/' . $imgtype;
  79. unlink($orig_name);
  80. }
  81. else if (stripos($mimetype, 'image/svg') === 0) {
  82. $content = rcmail_svg_filter(file_get_contents($orig_name));
  83. file_put_contents($cache_file, $content);
  84. unlink($orig_name);
  85. }
  86. else {
  87. rename($orig_name, $cache_file);
  88. }
  89. }
  90. }
  91. if (is_file($cache_file)) {
  92. header('Content-Type: ' . $mimetype);
  93. readfile($cache_file);
  94. }
  95. }
  96. exit;
  97. }
  98. else if (strlen($part_id)) {
  99. if ($part = $MESSAGE->mime_parts[$part_id]) {
  100. $mimetype = rcmail_fix_mimetype($part->mimetype);
  101. // allow post-processing of the message body
  102. $plugin = $RCMAIL->plugins->exec_hook('message_part_get', array(
  103. 'uid' => $MESSAGE->uid,
  104. 'id' => $part->mime_id,
  105. 'mimetype' => $mimetype,
  106. 'part' => $part,
  107. 'download' => !empty($_GET['_download'])
  108. ));
  109. if ($plugin['abort']) {
  110. exit;
  111. }
  112. // require CSRF protected url for downloads
  113. if ($plugin['download'])
  114. $RCMAIL->request_security_check(rcube_utils::INPUT_GET);
  115. // overwrite modified vars from plugin
  116. $mimetype = $plugin['mimetype'];
  117. $extensions = rcube_mime::get_mime_extensions($mimetype);
  118. if ($plugin['body']) {
  119. $body = $plugin['body'];
  120. }
  121. // compare file mimetype with the stated content-type headers and file extension to avoid malicious operations
  122. if (!empty($_REQUEST['_embed']) && empty($_REQUEST['_nocheck'])) {
  123. $file_extension = strtolower(pathinfo($part->filename, PATHINFO_EXTENSION));
  124. // 1. compare filename suffix with expected suffix derived from mimetype
  125. $valid = $file_extension && in_array($file_extension, (array)$extensions) || empty($extensions) || !empty($_REQUEST['_mimeclass']);
  126. // 2. detect the real mimetype of the attachment part and compare it with the stated mimetype and filename extension
  127. if ($valid || !$file_extension || $mimetype == 'application/octet-stream' || stripos($mimetype, 'text/') === 0) {
  128. $tmp_body = $body ?: $MESSAGE->get_part_body($part->mime_id, false, 2048);
  129. // detect message part mimetype
  130. $real_mimetype = rcube_mime::file_content_type($tmp_body, $part->filename, $mimetype, true, true);
  131. list($real_ctype_primary, $real_ctype_secondary) = explode('/', $real_mimetype);
  132. // accept text/plain with any extension
  133. if ($real_mimetype == 'text/plain' && $real_mimetype == $mimetype) {
  134. $valid_extension = true;
  135. }
  136. // ignore differences in text/* mimetypes. Filetype detection isn't very reliable here
  137. else if ($real_ctype_primary == 'text' && strpos($mimetype, $real_ctype_primary) === 0) {
  138. $real_mimetype = $mimetype;
  139. $valid_extension = true;
  140. }
  141. // ignore filename extension if mimeclass matches (#1489029)
  142. else if (!empty($_REQUEST['_mimeclass']) && $real_ctype_primary == $_REQUEST['_mimeclass']) {
  143. $valid_extension = true;
  144. }
  145. else {
  146. // get valid file extensions
  147. $extensions = rcube_mime::get_mime_extensions($real_mimetype);
  148. $valid_extension = !$file_extension || empty($extensions) || in_array($file_extension, (array)$extensions);
  149. }
  150. // fix mimetype for images wrongly declared as octet-stream
  151. if ($mimetype == 'application/octet-stream' && strpos($real_mimetype, 'image/') === 0 && $valid_extension) {
  152. $mimetype = $real_mimetype;
  153. }
  154. // "fix" real mimetype the same way the original is before comparison
  155. $real_mimetype = rcmail_fix_mimetype($real_mimetype);
  156. $valid = $real_mimetype == $mimetype && $valid_extension;
  157. }
  158. else {
  159. $real_mimetype = $mimetype;
  160. }
  161. // show warning if validity checks failed
  162. if (!$valid) {
  163. // send blocked.gif for expected images
  164. if (empty($_REQUEST['_mimewarning']) && strpos($mimetype, 'image/') === 0) {
  165. // Do not cache. Failure might be the result of a misconfiguration, thus real content should be returned once fixed.
  166. $content = $RCMAIL->get_resource_content('blocked.gif');
  167. $OUTPUT->nocacheing_headers();
  168. header("Content-Type: image/gif");
  169. header("Content-Transfer-Encoding: binary");
  170. header("Content-Length: " . strlen($content));
  171. echo $content;
  172. }
  173. else { // html warning with a button to load the file anyway
  174. $OUTPUT = new rcmail_html_page();
  175. $OUTPUT->write(html::tag('html', null, html::tag('body', 'embed',
  176. html::div(array('class' => 'rcmail-inline-message rcmail-inline-warning'),
  177. $RCMAIL->gettext(array(
  178. 'name' => 'attachmentvalidationerror',
  179. 'vars' => array(
  180. 'expected' => $mimetype . ($file_extension ? " (.$file_extension)" : ''),
  181. 'detected' => $real_mimetype . ($extensions[0] ? " (.$extensions[0])" : ''),
  182. )
  183. ))
  184. . html::p(array('class' => 'rcmail-inline-buttons'),
  185. html::tag('button', array(
  186. 'onclick' => "location.href='" . $RCMAIL->url(array_merge($_GET, array('_nocheck' => 1))) . "'"
  187. ),
  188. $RCMAIL->gettext('showanyway'))
  189. )
  190. ))));
  191. }
  192. exit;
  193. }
  194. }
  195. // TIFF to JPEG conversion, if needed
  196. $tiff_support = !empty($_SESSION['browser_caps']) && !empty($_SESSION['browser_caps']['tif']);
  197. if (!empty($_REQUEST['_embed']) && !$tiff_support
  198. && rcube_image::is_convertable('image/tiff')
  199. && rcmail_part_image_type($part) == 'image/tiff'
  200. ) {
  201. $tiff2jpeg = true;
  202. $mimetype = 'image/jpeg';
  203. }
  204. $browser = $RCMAIL->output->browser;
  205. list($ctype_primary, $ctype_secondary) = explode('/', $mimetype);
  206. if (!$plugin['download'] && $ctype_primary == 'text') {
  207. header("Content-Type: text/$ctype_secondary; charset=" . ($part->charset ?: RCUBE_CHARSET));
  208. }
  209. else {
  210. header("Content-Type: $mimetype");
  211. header("Content-Transfer-Encoding: binary");
  212. }
  213. // deliver part content
  214. if ($ctype_primary == 'text' && $ctype_secondary == 'html' && empty($plugin['download'])) {
  215. // Check if we have enough memory to handle the message in it
  216. // #1487424: we need up to 10x more memory than the body
  217. if (!rcube_utils::mem_check($part->size * 10)) {
  218. $out = '<body>' . $RCMAIL->gettext('messagetoobig'). ' '
  219. . html::a('?_task=mail&_action=get&_download=1&_uid='.$MESSAGE->uid.'&_part='.$part->mime_id
  220. .'&_mbox='. urlencode($MESSAGE->folder), $RCMAIL->gettext('download')) . '</body></html>';
  221. }
  222. else {
  223. // get part body if not available
  224. if (!isset($body)) {
  225. $body = $MESSAGE->get_part_body($part->mime_id, true);
  226. }
  227. // show images?
  228. rcmail_check_safe($MESSAGE);
  229. // render HTML body
  230. $out = rcmail_print_body($body, $part, array('safe' => $MESSAGE->is_safe, 'inline_html' => false));
  231. // insert remote objects warning into HTML body
  232. if ($REMOTE_OBJECTS) {
  233. $body_start = 0;
  234. if ($body_pos = strpos($out, '<body')) {
  235. $body_start = strpos($out, '>', $body_pos) + 1;
  236. }
  237. $out = substr($out, 0, $body_start)
  238. . html::div(array('class' => 'rcmail-inline-message rcmail-inline-warning'),
  239. rcube::Q($RCMAIL->gettext('blockedimages')) . '&nbsp;' .
  240. html::tag('button',
  241. array('onclick' => "location.href='" . $RCMAIL->url(array_merge($_GET, array('_safe' => 1))) . "'"),
  242. rcube::Q($RCMAIL->gettext('showimages')))
  243. )
  244. . substr($out, $body_start);
  245. }
  246. }
  247. // check connection status
  248. if ($part->size && empty($body)) {
  249. check_storage_status();
  250. }
  251. $OUTPUT = new rcmail_html_page();
  252. $OUTPUT->write($out);
  253. }
  254. else {
  255. // don't kill the connection if download takes more than 30 sec.
  256. @set_time_limit(0);
  257. $filename = rcmail_attachment_name($part);
  258. if ($browser->ie)
  259. $filename = rawurlencode($filename);
  260. else
  261. $filename = addcslashes($filename, '"');
  262. $disposition = !empty($plugin['download']) ? 'attachment' : 'inline';
  263. // Workaround for nasty IE bug (#1488844)
  264. // If Content-Disposition header contains string "attachment" e.g. in filename
  265. // IE handles data as attachment not inline
  266. if ($disposition == 'inline' && $browser->ie && $browser->ver < 9) {
  267. $filename = str_ireplace('attachment', 'attach', $filename);
  268. }
  269. // add filename extension if missing
  270. if (!pathinfo($filename, PATHINFO_EXTENSION) && ($extensions = rcube_mime::get_mime_extensions($mimetype))) {
  271. $filename .= '.' . $extensions[0];
  272. }
  273. header("Content-Disposition: $disposition; filename=\"$filename\"");
  274. // handle tiff to jpeg conversion
  275. if (!empty($tiff2jpeg)) {
  276. $temp_dir = unslashify($RCMAIL->config->get('temp_dir'));
  277. $file_path = tempnam($temp_dir, 'rcmAttmnt');
  278. // write content to temp file
  279. if ($body) {
  280. $saved = file_put_contents($file_path, $body);
  281. }
  282. else if ($part->size) {
  283. $fd = fopen($file_path, 'w');
  284. $saved = $MESSAGE->get_part_body($part->mime_id, false, 0, $fd);
  285. fclose($fd);
  286. }
  287. // convert image to jpeg and send it to the browser
  288. if ($sent = $saved) {
  289. $image = new rcube_image($file_path);
  290. if ($image->convert(rcube_image::TYPE_JPG, $file_path)) {
  291. header("Content-Length: " . filesize($file_path));
  292. readfile($file_path);
  293. }
  294. unlink($file_path);
  295. }
  296. }
  297. else {
  298. $sent = rcmail_message_part_output($body, $part, $mimetype, $plugin['download']);
  299. }
  300. // check connection status
  301. if ($part->size && !$sent) {
  302. check_storage_status();
  303. }
  304. }
  305. exit;
  306. }
  307. }
  308. // print message
  309. else {
  310. // send correct headers for content type
  311. header("Content-Type: text/html");
  312. $cont = "<html>\n<head><title></title>\n</head>\n<body>";
  313. $cont .= rcmail_message_body(array());
  314. $cont .= "\n</body>\n</html>";
  315. $OUTPUT = new rcmail_html_page();
  316. $OUTPUT->write($cont);
  317. exit;
  318. }
  319. // if we arrive here, the requested part was not found
  320. header('HTTP/1.1 404 Not Found');
  321. exit;
  322. /**
  323. * Handles nicely storage connection errors
  324. */
  325. function check_storage_status()
  326. {
  327. $error = rcmail::get_instance()->storage->get_error_code();
  328. // Check if we have a connection error
  329. if ($error == rcube_imap_generic::ERROR_BAD) {
  330. ob_end_clean();
  331. // Get action is often executed simultanously.
  332. // Some servers have MAXPERIP or other limits.
  333. // To workaround this we'll wait for some time
  334. // and try again (once).
  335. // Note: Random sleep interval is used to minimize concurency
  336. // in getting message parts
  337. if (!isset($_GET['_redirected'])) {
  338. usleep(rand(10,30)*100000); // 1-3 sec.
  339. header('Location: ' . $_SERVER['REQUEST_URI'] . '&_redirected=1');
  340. }
  341. else {
  342. rcube::raise_error(array(
  343. 'code' => 500, 'type' => 'php',
  344. 'file' => __FILE__, 'line' => __LINE__,
  345. 'message' => 'Unable to get/display message part. IMAP connection error'),
  346. true, true);
  347. }
  348. // Don't kill session, just quit (#1486995)
  349. exit;
  350. }
  351. }
  352. /**
  353. * Attachment properties table
  354. */
  355. function rcmail_message_part_controls($attrib)
  356. {
  357. global $MESSAGE, $RCMAIL;
  358. $part = asciiwords(rcube_utils::get_input_value('_part', rcube_utils::INPUT_GPC));
  359. if (!is_object($MESSAGE) || !is_array($MESSAGE->parts)
  360. || !($_GET['_uid'] && $_GET['_part']) || !$MESSAGE->mime_parts[$part]
  361. ) {
  362. return '';
  363. }
  364. $part = $MESSAGE->mime_parts[$part];
  365. $table = new html_table(array('cols' => 2));
  366. $table->add('title', rcube::Q($RCMAIL->gettext('namex')).':');
  367. $table->add('header', rcube::Q(rcmail_attachment_name($part)));
  368. $table->add('title', rcube::Q($RCMAIL->gettext('type')).':');
  369. $table->add('header', rcube::Q($part->mimetype));
  370. $table->add('title', rcube::Q($RCMAIL->gettext('size')).':');
  371. $table->add('header', rcube::Q($RCMAIL->message_part_size($part)));
  372. return $table->show($attrib);
  373. }
  374. /**
  375. * Attachment preview frame
  376. */
  377. function rcmail_message_part_frame($attrib)
  378. {
  379. global $MESSAGE, $RCMAIL;
  380. $part = $MESSAGE->mime_parts[asciiwords(rcube_utils::get_input_value('_part', rcube_utils::INPUT_GPC))];
  381. $ctype_primary = strtolower($part->ctype_primary);
  382. $attrib['src'] = './?' . str_replace('_frame=', ($ctype_primary=='text' ? '_embed=' : '_preload='), $_SERVER['QUERY_STRING']);
  383. $RCMAIL->output->add_gui_object('messagepartframe', $attrib['id']);
  384. return html::iframe($attrib);
  385. }
  386. /**
  387. * Output attachment body with content filtering
  388. */
  389. function rcmail_message_part_output($body, $part, $mimetype, $download)
  390. {
  391. global $MESSAGE, $RCMAIL;
  392. if (!$part->size && !$body) {
  393. return false;
  394. }
  395. $browser = $RCMAIL->output->browser;
  396. $secure = stripos($mimetype, 'image/') === false || $download;
  397. // Remove <script> in SVG images
  398. if (!$secure && stripos($mimetype, 'image/svg') === 0) {
  399. if (!$body) {
  400. $body = $MESSAGE->get_part_body($part->mime_id, false);
  401. if (empty($body)) {
  402. return false;
  403. }
  404. }
  405. echo rcmail_svg_filter($body);
  406. return true;
  407. }
  408. // Remove dangerous content in images for older IE (to be removed)
  409. if (!$secure && $browser->ie && $browser->ver <= 8) {
  410. if ($body) {
  411. echo preg_match('/<(script|iframe|object)/i', $body) ? '' : $body;
  412. return true;
  413. }
  414. else {
  415. $stdout = fopen('php://output', 'w');
  416. stream_filter_register('rcube_content', 'rcube_content_filter') or die('Failed to register content filter');
  417. stream_filter_append($stdout, 'rcube_content');
  418. return $MESSAGE->get_part_body($part->mime_id, true, 0, $stdout);
  419. }
  420. }
  421. if ($body && !$download) {
  422. header("Content-Length: " . strlen($body));
  423. echo $body;
  424. return true;
  425. }
  426. // Don't be tempted to set Content-Length to $part->d_parameters['size'] (#1490482)
  427. // RFC2183 says "The size parameter indicates an approximate size"
  428. return $MESSAGE->get_part_body($part->mime_id, false, 0, -1);
  429. }
  430. /**
  431. * Remove <script> in SVG images
  432. */
  433. function rcmail_svg_filter($body)
  434. {
  435. // clean SVG with washhtml
  436. $wash_opts = array(
  437. 'show_washed' => false,
  438. 'allow_remote' => false,
  439. 'charset' => RCUBE_CHARSET,
  440. 'html_elements' => array('title'),
  441. // 'blocked_src' => 'program/resources/blocked.gif',
  442. );
  443. // initialize HTML washer
  444. $washer = new rcube_washtml($wash_opts);
  445. // allow CSS styles, will be sanitized by rcmail_washtml_callback()
  446. $washer->add_callback('style', 'rcmail_washtml_callback');
  447. return $washer->wash($body);
  448. }