From 8282d5cd6361914660f83334ea166d13d76c27ee Mon Sep 17 00:00:00 2001 From: Zankaria Date: Mon, 21 Apr 2025 15:11:32 +0200 Subject: [PATCH] post.php: implement safe PDF thumbnailing --- post.php | 34 ++++++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/post.php b/post.php index 5483600d..e4560bb8 100644 --- a/post.php +++ b/post.php @@ -1447,10 +1447,36 @@ function handle_post(Context $ctx) } $image->destroy(); } else { - if ( - ($file['extension'] == "pdf" && $config['pdf_file_thumbnail']) || - ($file['extension'] == "djvu" && $config['djvu_file_thumbnail']) - ) { + $mime = \mime_content_type($file['tmp_name']); + if ($file['extension'] === "pdf" && $config['pdf_file_thumbnail']) { + if ($mime !== 'application/pdf' && $mime !== 'application/x-pdf') { + error($config['error']['invalidfile']); + } + + $e_thumb_path = \escapeshellarg($file['thumb']); + $e_file_path = \escapeshellarg($file['tmp_name']); + $thumb_width = $config['thumb_width']; + $thumb_height = $config['thumb_height']; + + // Generates a PPM image and pipes it directly into convert for resizing + type conversion. + $error = shell_exec_error("gs -dSAFER -dBATCH -dNOPAUSE -dQUIET + -sDEVICE=ppmraw -r100 -dFirstPage=1 -dLastPage=1 -sOutputFile=- $e_file_path + | convert -thumbnail {$thumb_width}x{$thumb_height} ppm:- $e_thumb_path"); + + if ($error) { + $log = $ctx->get(LogDriver::class); + $log->log(LogDriver::ERROR, 'Could not render thumbnail for PDF file, using static fallback.'); + $path = sprintf($config['file_thumb'], isset($config['file_icons'][$file['extension']]) ? $config['file_icons'][$file['extension']] : $config['file_icons']['default']); + } + + $file['thumb'] = basename($file['thumb']); + $size = @getimagesize($path); + $file['thumbwidth'] = $size[0]; + $file['thumbheight'] = $size[1]; + $file['width'] = $size[0]; + $file['height'] = $size[1]; + } + if ($file['extension'] == "djvu" && $config['djvu_file_thumbnail']) { $path = $file['thumb']; $error = shell_exec_error('convert -size ' . $config['thumb_width'] . 'x' . $config['thumb_height'] . ' -thumbnail ' . $config['thumb_width'] . 'x' . $config['thumb_height'] . ' -background white -alpha remove ' . escapeshellarg($file['tmp_name'] . '[0]') . ' ' .