Debian Codegraph @

includes/media/ImageHandler.php

raw symbols SCIP
1 <?php
2 /**
3 * Media-handling base classes and generic functionality.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Media
22 */
23
24 use MediaWiki\MainConfigNames;
25 use MediaWiki\MediaWikiServices;
26 use Wikimedia\AtEase\AtEase;
27
28 /**
29 * Media handler abstract base class for images
30 *
31 * @stable to extend
32 *
33 * @ingroup Media
34 */
35 abstract class ImageHandler extends MediaHandler {
36 /**
37 * @inheritDoc
38 * @stable to override
39 * @param File $file
40 * @return bool
41 */
42 public function canRender( $file ) {
43 return ( $file->getWidth() && $file->getHeight() );
44 }
45
46 /**
47 * @inheritDoc
48 * @stable to override
49 * @return string[]
50 */
51 public function getParamMap() {
52 return [ 'img_width' => 'width' ];
53 }
54
55 /**
56 * @inheritDoc
57 * @stable to override
58 */
59 public function validateParam( $name, $value ) {
60 return in_array( $name, [ 'width', 'height' ] ) && $value > 0;
61 }
62
63 /**
64 * @inheritDoc
65 * @stable to override
66 * @throws MediaTransformInvalidParametersException
67 */
68 public function makeParamString( $params ) {
69 if ( isset( $params['physicalWidth'] ) ) {
70 $width = $params['physicalWidth'];
71 } elseif ( isset( $params['width'] ) ) {
72 $width = $params['width'];
73 } else {
74 throw new MediaTransformInvalidParametersException( 'No width specified to ' . __METHOD__ );
75 }
76
77 # Removed for ProofreadPage
78 # $width = intval( $width );
79 return "{$width}px";
80 }
81
82 /**
83 * @inheritDoc
84 * @stable to override
85 */
86 public function parseParamString( $str ) {
87 $m = false;
88 if ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
89 return [ 'width' => $m[1] ];
90 }
91 return false;
92 }
93
94 /**
95 * @stable to override
96 * @param array $params
97 * @return array
98 */
99 protected function getScriptParams( $params ) {
100 return [ 'width' => $params['width'] ];
101 }
102
103 /**
104 * @inheritDoc
105 * @stable to override
106 * @param File $image
107 * @param array &$params @phan-ignore-reference
108 * @return bool
109 * @phan-assert array{width:int,physicalWidth:int,height:int,physicalHeight:int,page:int} $params
110 */
111 public function normaliseParams( $image, &$params ) {
112 if ( !isset( $params['width'] ) ) {
113 return false;
114 }
115
116 if ( !isset( $params['page'] ) ) {
117 $params['page'] = 1;
118 } else {
119 $params['page'] = (int)$params['page'];
120 if ( $params['page'] > $image->pageCount() ) {
121 $params['page'] = $image->pageCount();
122 }
123
124 if ( $params['page'] < 1 ) {
125 $params['page'] = 1;
126 }
127 }
128
129 $srcWidth = $image->getWidth( $params['page'] );
130 $srcHeight = $image->getHeight( $params['page'] );
131
132 if ( isset( $params['height'] ) && $params['height'] !== -1 ) {
133 # Height & width were both set
134 if ( $params['width'] * $srcHeight > $params['height'] * $srcWidth ) {
135 # Height is the relative smaller dimension, so scale width accordingly
136 $params['width'] = self::fitBoxWidth( $srcWidth, $srcHeight, $params['height'] );
137
138 if ( $params['width'] == 0 ) {
139 # Very small image, so we need to rely on client side scaling :(
140 $params['width'] = 1;
141 }
142
143 $params['physicalWidth'] = $params['width'];
144 } else {
145 # Height was crap, unset it so that it will be calculated later
146 unset( $params['height'] );
147 }
148 }
149
150 if ( !isset( $params['physicalWidth'] ) ) {
151 # Passed all validations, so set the physicalWidth
152 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive, checked above
153 $params['physicalWidth'] = $params['width'];
154 }
155
156 # Because thumbs are only referred to by width, the height always needs
157 # to be scaled by the width to keep the thumbnail sizes consistent,
158 # even if it was set inside the if block above
159 $params['physicalHeight'] = File::scaleHeight( $srcWidth, $srcHeight,
160 $params['physicalWidth'] );
161
162 # Set the height if it was not validated in the if block higher up
163 if ( !isset( $params['height'] ) || $params['height'] === -1 ) {
164 $params['height'] = $params['physicalHeight'];
165 }
166
167 if ( !$this->validateThumbParams( $params['physicalWidth'],
168 $params['physicalHeight'], $srcWidth, $srcHeight )
169 ) {
170 return false;
171 }
172
173 return true;
174 }
175
176 /**
177 * Adjust the thumbnail size to fit the width steps defined in config via
178 * $wgThumbnailSteps, according to whether $wgThumbnailStepsRatio is set.
179 *
180 * This logic is duplicated client-side in mw.util.adjustThumbWidthForSteps.
181 *
182 * @see FileTest::testThumbNameSteps
183 * @since 1.46 (also backported to 1.43.7, 1.44.4, 1.45.2)
184 */
185 protected function getSteppedThumbWidth(
186 File $image, int $requestWidth, int $srcWidth, int $srcHeight
187 ): int {
188 $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
189 $thumbnailSteps = $mainConfig->get( MainConfigNames::ThumbnailSteps );
190 $thumbnailStepsRatio = $mainConfig->get( MainConfigNames::ThumbnailStepsRatio );
191
192 if ( !$thumbnailSteps || !$thumbnailStepsRatio ) {
193 return $requestWidth;
194 }
195
196 if ( $thumbnailStepsRatio < 1 ) {
197 // If thumbnail ratio is below 100%, build a random number
198 // out of the file name and decide whether to apply adjustments
199 // based on that. This way, we get a good uniformity while not going
200 // back and forth between old and new in different requests.
201 // Also this way, ramping up (e.g. from 0.1 to 0.2) would also
202 // cover the previous values too which would reduce the scale of changes.
203 $hash = hexdec( substr( md5( $image->getName() ), 0, 8 ) ) & 0x7fffffff;
204 if ( ( $hash % 1000 ) > ( $thumbnailStepsRatio * 1000 ) ) {
205 return $requestWidth;
206 }
207 }
208
209 $prevStep = $thumbnailSteps[0];
210 foreach ( $thumbnailSteps as $widthStep ) {
211 if ( ( $widthStep > $srcWidth ) && !$image->isVectorized() ) {
212 if ( $this->mustRender( $image ) ) {
213 // Not web-safe: Round down to previous step
214 //
215 // While unlikely, this tries to upscale an original that is smaller than the smallest step
216 // (e.g. smaller than 20px if that's the smallest step configured), which is disallowed
217 // by default in MediaWiki core with HTTP 400 (ThumbnailEntryPoint::generateThumbnail).
218 return $prevStep;
219 } else {
220 // Web-safe: Round up or down and use the original
221 //
222 // There was no step between the requested width and the original width
223 // (so either a thumb between penultimate step and original,
224 // or a thumb beyond original jpg but under penultimate step).
225 //
226 // NOTE: This thumb-at-original-width is replaced with the original
227 // in a higher-level code path after this method runs.
228 return $srcWidth;
229 }
230 }
231 if ( $widthStep == $requestWidth ) {
232 return $requestWidth;
233 }
234 if ( $widthStep > $requestWidth ) {
235 return $widthStep;
236 }
237 $prevStep = $widthStep;
238 }
239
240 // Respond with the largest step if it's too big.
241 return $prevStep;
242 }
243
244 /**
245 * Validate thumbnail parameters and fill in the correct height
246 *
247 * @param int &$width Specified width (input/output)
248 * @param int &$height Height (output only)
249 * @param int $srcWidth Width of the source image
250 * @param int $srcHeight Height of the source image
251 * @return bool False to indicate that an error should be returned to the user.
252 */
253 private function validateThumbParams( &$width, &$height, $srcWidth, $srcHeight ) {
254 $width = (int)$width;
255
256 if ( $width <= 0 ) {
257 wfDebug( __METHOD__ . ": Invalid destination width: $width" );
258
259 return false;
260 }
261 if ( $srcWidth <= 0 ) {
262 wfDebug( __METHOD__ . ": Invalid source width: $srcWidth" );
263
264 return false;
265 }
266
267 $height = File::scaleHeight( $srcWidth, $srcHeight, $width );
268 if ( $height == 0 ) {
269 # Force height to be at least 1 pixel
270 $height = 1;
271 }
272
273 return true;
274 }
275
276 /**
277 * @inheritDoc
278 * @stable to override
279 * @param File $image
280 * @param string $script
281 * @param array $params
282 * @return MediaTransformOutput|false
283 */
284 public function getScriptedTransform( $image, $script, $params ) {
285 if ( !$this->normaliseParams( $image, $params ) ) {
286 return false;
287 }
288 $url = wfAppendQuery( $script, $this->getScriptParams( $params ) );
289
290 if ( $image->mustRender() || $params['width'] < $image->getWidth() ) {
291 return new ThumbnailImage( $image, $url, false, $params );
292 }
293 }
294
295 public function getImageSize( $image, $path ) {
296 AtEase::suppressWarnings();
297 $gis = getimagesize( $path );
298 AtEase::restoreWarnings();
299
300 return $gis;
301 }
302
303 public function getSizeAndMetadata( $state, $path ) {
304 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
305 $gis = @getimagesize( $path );
306 if ( $gis ) {
307 $info = [
308 'width' => $gis[0],
309 'height' => $gis[1],
310 ];
311 if ( isset( $gis['bits'] ) ) {
312 $info['bits'] = $gis['bits'];
313 }
314 } else {
315 $info = [];
316 }
317 return $info;
318 }
319
320 /**
321 * Function that returns the number of pixels to be thumbnailed.
322 * Intended for animated GIFs to multiply by the number of frames.
323 *
324 * If the file doesn't support a notion of "area" return 0.
325 * @stable to override
326 *
327 * @param File $image
328 * @return int
329 */
330 public function getImageArea( $image ) {
331 return $image->getWidth() * $image->getHeight();
332 }
333
334 /**
335 * @inheritDoc
336 * @stable to override
337 * @param File $file
338 * @return string
339 */
340 public function getShortDesc( $file ) {
341 global $wgLang;
342 $nbytes = htmlspecialchars( $wgLang->formatSize( $file->getSize() ) );
343 $widthheight = wfMessage( 'widthheight' )
344 ->numParams( $file->getWidth(), $file->getHeight() )->escaped();
345
346 return "$widthheight ($nbytes)";
347 }
348
349 /**
350 * @inheritDoc
351 * @stable to override
352 * @param File $file
353 * @return string
354 */
355 public function getLongDesc( $file ) {
356 $pages = $file->pageCount();
357 if ( $pages === false || $pages <= 1 ) {
358 $msg = wfMessage( 'file-info-size' )->numParams( $file->getWidth(),
359 $file->getHeight() )->sizeParams( $file->getSize() )->params(
360 '<span class="mime-type">' . $file->getMimeType() . '</span>' )->parse();
361 } else {
362 $msg = wfMessage( 'file-info-size-pages' )->numParams( $file->getWidth(),
363 $file->getHeight() )->sizeParams( $file->getSize() )->params(
364 '<span class="mime-type">' . $file->getMimeType() . '</span>' )->numParams( $pages )->parse();
365 }
366
367 return $msg;
368 }
369
370 /**
371 * @inheritDoc
372 * @stable to override
373 * @param File $file
374 * @return string
375 */
376 public function getDimensionsString( $file ) {
377 $pages = $file->pageCount();
378 if ( $pages > 1 ) {
379 return wfMessage( 'widthheightpage' )
380 ->numParams( $file->getWidth(), $file->getHeight(), $pages )->text();
381 }
382 return wfMessage( 'widthheight' )
383 ->numParams( $file->getWidth(), $file->getHeight() )->text();
384 }
385
386 /**
387 * @inheritDoc
388 * @stable to override
389 */
390 public function sanitizeParamsForBucketing( $params ) {
391 $params = parent::sanitizeParamsForBucketing( $params );
392
393 // We unset the height parameters in order to let normaliseParams recalculate them
394 // Otherwise there might be a height discrepancy
395 unset( $params['height'] );
396 unset( $params['physicalHeight'] );
397
398 return $params;
399 }
400 }