3838 */
3939abstract class Bitmap extends ProviderV2 {
4040
41+ /**
42+ * List of MIME types that this preview provider is allowed to process.
43+ *
44+ * These should correspond to the MIME types *identified* by Imagemagick
45+ * for files to be processed by this provider. These do / will not
46+ * necessarily need to match the MIME types stored in the database
47+ * (which are identified by IMimeTypeDetector).
48+ *
49+ * @return string Regular expression
50+ */
51+ abstract protected function getAllowedMimeTypes ();
52+
53+ /**
54+ * @return list<string>
55+ */
56+ abstract protected function getMagicStrings ();
57+
58+ abstract protected function getImagickFormatHint ();
59+
4160 /**
4261 * {@inheritDoc}
4362 */
@@ -78,12 +97,25 @@ public function getThumbnail(File $file, int $maxX, int $maxY): ?IImage {
7897 * @param int $maxY
7998 *
8099 * @return \Imagick
100+ *
101+ * @throws \Exception
81102 */
82103 private function getResizedPreview ($ tmpPath , $ maxX , $ maxY ) {
83104 $ bp = new Imagick ();
84105
106+ if (!$ this ->isMagicStringSupported ($ tmpPath )) {
107+ throw new \Exception ('Invalid image type: magic string not recognized ' );
108+ }
109+
110+ // Validate mime type
111+ $ bp ->pingImage ($ this ->getImagickFormatHint () . ': ' . $ tmpPath . '[0] ' );
112+ $ mimeType = $ bp ->getImageMimeType ();
113+ if (!preg_match ($ this ->getAllowedMimeTypes (), $ mimeType )) {
114+ throw new \Exception ('File mime type does not match the preview provider: ' . $ mimeType );
115+ }
116+
85117 // Layer 0 contains either the bitmap or a flat representation of all vector layers
86- $ bp ->readImage ($ tmpPath . '[0] ' );
118+ $ bp ->readImage ($ this -> getImagickFormatHint () . ' : ' . $ tmpPath . '[0] ' );
87119
88120 $ bp = $ this ->resize ($ bp , $ maxX , $ maxY );
89121
@@ -92,6 +124,22 @@ private function getResizedPreview($tmpPath, $maxX, $maxY) {
92124 return $ bp ;
93125 }
94126
127+ private function isMagicStringSupported (string $ filepath ) {
128+ $ signatures = $ this ->getMagicStrings ();
129+ if (empty ($ signatures )) {
130+ return true ;
131+ }
132+ $ length = array_reduce ($ signatures , static fn (int $ carry , string $ signature ) => max ($ carry , strlen ($ signature )), 0 );
133+ $ firstBytes = file_get_contents ($ filepath , false , null , 0 , $ length );
134+ foreach ($ signatures as $ signature ) {
135+ if (str_starts_with ($ firstBytes , $ signature )) {
136+ return true ;
137+ }
138+ }
139+
140+ return false ;
141+ }
142+
95143 /**
96144 * Returns a resized \Imagick object
97145 *
0 commit comments