Debian Codegraph @

includes/media/TransformationalImageHandler.php

raw symbols SCIP
1 <?php
2 /**
3 * Base class for handlers which require transforming images in a
4 * similar way as BitmapHandler does.
5 *
6 * This was split from BitmapHandler on the basis that some extensions
7 * might want to work in a similar way to BitmapHandler, but for
8 * different formats.
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * http://www.gnu.org/copyleft/gpl.html
24 *
25 * @file
26 * @ingroup Media
27 */
28
29 use MediaWiki\HookContainer\HookRunner;
30 use MediaWiki\MainConfigNames;
31 use MediaWiki\MediaWikiServices;
32 use MediaWiki\Shell\Shell;
33
34 /**
35 * Handler for images that need to be transformed
36 *
37 * @stable to extend
38 *
39 * @since 1.24
40 * @ingroup Media
41 */
42 abstract class TransformationalImageHandler extends ImageHandler {
43 /**
44 * @stable to override
45 * @param File $image
46 * @param array &$params Transform parameters. Entries with the keys 'width'
47 * and 'height' are the respective screen width and height, while the keys
48 * 'physicalWidth' and 'physicalHeight' indicate the thumbnail dimensions.
49 * @return bool
50 */
51 public function normaliseParams( $image, &$params ) {
52 if ( !parent::normaliseParams( $image, $params ) ) {
53 return false;
54 }
55
56 # Obtain the source, pre-rotation dimensions
57 $srcWidth = $image->getWidth( $params['page'] );
58 $srcHeight = $image->getHeight( $params['page'] );
59
60 $params['physicalWidth'] = $this->getSteppedThumbWidth(
61 $image, $params['physicalWidth'], $srcWidth, $srcHeight
62 );
63 $params['physicalHeight'] = File::scaleHeight( $srcWidth, $srcHeight, $params['physicalWidth'] );
64
65 # Don't make an image bigger than the source
66 if ( $params['physicalWidth'] >= $srcWidth ) {
67 $params['physicalWidth'] = $srcWidth;
68 $params['physicalHeight'] = $srcHeight;
69
70 # Skip scaling limit checks if no scaling is required
71 # due to requested size being bigger than source.
72 if ( !$image->mustRender() ) {
73 return true;
74 }
75 }
76
77 return true;
78 }
79
80 /**
81 * Extracts the width/height if the image will be scaled before rotating
82 *
83 * This will match the physical size/aspect ratio of the original image
84 * prior to application of the rotation -- so for a portrait image that's
85 * stored as raw landscape with 90-degress rotation, the resulting size
86 * will be wider than it is tall.
87 *
88 * @param array $params Parameters as returned by normaliseParams
89 * @param int $rotation The rotation angle that will be applied
90 * @return array ($width, $height) array
91 */
92 public function extractPreRotationDimensions( $params, $rotation ) {
93 if ( $rotation === 90 || $rotation === 270 ) {
94 // We'll resize before rotation, so swap the dimensions again
95 $width = $params['physicalHeight'];
96 $height = $params['physicalWidth'];
97 } else {
98 $width = $params['physicalWidth'];
99 $height = $params['physicalHeight'];
100 }
101
102 return [ $width, $height ];
103 }
104
105 /**
106 * Create a thumbnail.
107 *
108 * This sets up various parameters, and then calls a helper method
109 * based on $this->getScalerType in order to scale the image.
110 * @stable to override
111 *
112 * @param File $image
113 * @param string $dstPath
114 * @param string $dstUrl
115 * @param array $params
116 * @param int $flags
117 * @return MediaTransformError|ThumbnailImage|TransformParameterError
118 */
119 public function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
120 if ( !$this->normaliseParams( $image, $params ) ) {
121 return new TransformParameterError( $params );
122 }
123
124 // Create a parameter array to pass to the scaler
125 $scalerParams = [
126 // The size to which the image will be resized
127 'physicalWidth' => $params['physicalWidth'],
128 'physicalHeight' => $params['physicalHeight'],
129 'physicalDimensions' => "{$params['physicalWidth']}x{$params['physicalHeight']}",
130 // The size of the image on the page
131 'clientWidth' => $params['width'],
132 'clientHeight' => $params['height'],
133 // Comment as will be added to the Exif of the thumbnail
134 'comment' => isset( $params['descriptionUrl'] )
135 ? "File source: {$params['descriptionUrl']}"
136 : '',
137 // Properties of the original image
138 'srcWidth' => $image->getWidth(),
139 'srcHeight' => $image->getHeight(),
140 'mimeType' => $image->getMimeType(),
141 'dstPath' => $dstPath,
142 'dstUrl' => $dstUrl,
143 'interlace' => $params['interlace'] ?? false,
144 'isFilePageThumb' => $params['isFilePageThumb'] ?? false,
145 ];
146
147 if ( isset( $params['quality'] ) && $params['quality'] === 'low' ) {
148 $scalerParams['quality'] = 30;
149 }
150
151 // For subclasses that might be paged.
152 if ( $image->isMultipage() && isset( $params['page'] ) ) {
153 $scalerParams['page'] = (int)$params['page'];
154 }
155
156 # Determine scaler type
157 $scaler = $this->getScalerType( $dstPath );
158
159 if ( is_array( $scaler ) ) {
160 $scalerName = get_class( $scaler[0] );
161 } else {
162 $scalerName = $scaler;
163 }
164
165 wfDebug( __METHOD__ . ": creating {$scalerParams['physicalDimensions']} " .
166 "thumbnail at $dstPath using scaler $scalerName" );
167
168 if ( !$image->mustRender() &&
169 $scalerParams['physicalWidth'] == $scalerParams['srcWidth']
170 && $scalerParams['physicalHeight'] == $scalerParams['srcHeight']
171 && !isset( $scalerParams['quality'] )
172 ) {
173 # normaliseParams (or the user) wants us to return the unscaled image
174 wfDebug( __METHOD__ . ": returning unscaled image" );
175
176 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
177 }
178
179 if ( $scaler === 'client' ) {
180 # Client-side image scaling, use the source URL
181 # Using the destination URL in a TRANSFORM_LATER request would be incorrect
182 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
183 }
184
185 if ( $image->isTransformedLocally() && !$this->isImageAreaOkForThumbnaling( $image, $params ) ) {
186 $maxImageArea = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::MaxImageArea );
187 return new TransformTooBigImageAreaError( $params, $maxImageArea );
188 }
189
190 if ( $flags & self::TRANSFORM_LATER ) {
191 wfDebug( __METHOD__ . ": Transforming later per flags." );
192 $newParams = [
193 'width' => $scalerParams['clientWidth'],
194 'height' => $scalerParams['clientHeight']
195 ];
196 if ( isset( $params['quality'] ) ) {
197 $newParams['quality'] = $params['quality'];
198 }
199 if ( isset( $params['page'] ) && $params['page'] ) {
200 $newParams['page'] = $params['page'];
201 }
202 return new ThumbnailImage( $image, $dstUrl, false, $newParams );
203 }
204
205 # Try to make a target path for the thumbnail
206 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
207 wfDebug( __METHOD__ . ": Unable to create thumbnail destination " .
208 "directory, falling back to client scaling" );
209
210 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
211 }
212
213 # Transform functions and binaries need a FS source file
214 $thumbnailSource = $this->getThumbnailSource( $image, $params );
215
216 // If the source isn't the original, disable EXIF rotation because it's already been applied
217 if ( $scalerParams['srcWidth'] != $thumbnailSource['width']
218 || $scalerParams['srcHeight'] != $thumbnailSource['height'] ) {
219 $scalerParams['disableRotation'] = true;
220 }
221
222 $scalerParams['srcPath'] = $thumbnailSource['path'];
223 $scalerParams['srcWidth'] = $thumbnailSource['width'];
224 $scalerParams['srcHeight'] = $thumbnailSource['height'];
225
226 if ( $scalerParams['srcPath'] === false ) { // Failed to get local copy
227 wfDebugLog( 'thumbnail',
228 sprintf( 'Thumbnail failed on %s: could not get local copy of "%s"',
229 wfHostname(), $image->getName() ) );
230
231 return new MediaTransformError( 'thumbnail_error',
232 $scalerParams['clientWidth'], $scalerParams['clientHeight'],
233 wfMessage( 'filemissing' )
234 );
235 }
236
237 // Try a hook. Called "Bitmap" for historical reasons.
238 /** @var MediaTransformOutput $mto */
239 $mto = null;
240 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
241 ->onBitmapHandlerTransform( $this, $image, $scalerParams, $mto );
242 if ( $mto !== null ) {
243 wfDebug( __METHOD__ . ": Hook to BitmapHandlerTransform created an mto" );
244 $scaler = 'hookaborted';
245 }
246
247 // $scaler will return a MediaTransformError on failure, or false on success.
248 // If the scaler is successful, it will have created a thumbnail at the destination
249 // path.
250 if ( is_array( $scaler ) && is_callable( $scaler ) ) {
251 // Allow subclasses to specify their own rendering methods.
252 $err = call_user_func( $scaler, $image, $scalerParams );
253 } else {
254 switch ( $scaler ) {
255 case 'hookaborted':
256 # Handled by the hook above
257 $err = $mto->isError() ? $mto : false;
258 break;
259 case 'im':
260 $err = $this->transformImageMagick( $image, $scalerParams );
261 break;
262 case 'custom':
263 $err = $this->transformCustom( $image, $scalerParams );
264 break;
265 case 'imext':
266 $err = $this->transformImageMagickExt( $image, $scalerParams );
267 break;
268 case 'gd':
269 default:
270 $err = $this->transformGd( $image, $scalerParams );
271 break;
272 }
273 }
274
275 // Remove the file if a zero-byte thumbnail was created, or if there was an error
276 // @phan-suppress-next-line PhanTypeMismatchArgument Relaying on bool/int conversion to cast objects correct
277 $removed = $this->removeBadFile( $dstPath, (bool)$err );
278 if ( $err ) {
279 # transform returned MediaTransforError
280 return $err;
281 }
282
283 if ( $removed ) {
284 // Thumbnail was zero-byte and had to be removed
285 return new MediaTransformError( 'thumbnail_error',
286 $scalerParams['clientWidth'], $scalerParams['clientHeight'],
287 wfMessage( 'unknown-error' )
288 );
289 }
290
291 if ( $mto ) {
292 // @phan-suppress-next-line PhanTypeMismatchReturnSuperType
293 return $mto;
294 }
295
296 $newParams = [
297 'width' => $scalerParams['clientWidth'],
298 'height' => $scalerParams['clientHeight']
299 ];
300 if ( isset( $params['quality'] ) ) {
301 $newParams['quality'] = $params['quality'];
302 }
303 if ( isset( $params['page'] ) && $params['page'] ) {
304 $newParams['page'] = $params['page'];
305 }
306 return new ThumbnailImage( $image, $dstUrl, $dstPath, $newParams );
307 }
308
309 /**
310 * Get the source file for the transform
311 *
312 * @param File $file
313 * @param array $params
314 * @return array Array with keys width, height and path.
315 */
316 protected function getThumbnailSource( $file, $params ) {
317 return $file->getThumbnailSource( $params );
318 }
319
320 /**
321 * Returns what sort of scaler type should be used.
322 *
323 * Values can be one of client, im, custom, gd, imext, or an array
324 * of object, method-name to call that specific method.
325 *
326 * If specifying a custom scaler command with [ Obj, method ],
327 * the method in question should take 2 parameters, a File object,
328 * and a $scalerParams array with various options (See doTransform
329 * for what is in $scalerParams). On error it should return a
330 * MediaTransformError object. On success it should return false,
331 * and simply make sure the thumbnail file is located at
332 * $scalerParams['dstPath'].
333 *
334 * If there is a problem with the output path, it returns "client"
335 * to do client side scaling.
336 *
337 * @param string|null $dstPath
338 * @param bool $checkDstPath Check that $dstPath is valid
339 * @return string|callable One of client, im, custom, gd, imext, or a callable
340 */
341 abstract protected function getScalerType( $dstPath, $checkDstPath = true );
342
343 /**
344 * Get a ThumbnailImage that respresents an image that will be scaled
345 * client side
346 *
347 * @stable to override
348 * @param File $image File associated with this thumbnail
349 * @param array $scalerParams Array with scaler params
350 * @return ThumbnailImage
351 *
352 * @todo FIXME: No rotation support
353 */
354 protected function getClientScalingThumbnailImage( $image, $scalerParams ) {
355 $params = [
356 'width' => $scalerParams['clientWidth'],
357 'height' => $scalerParams['clientHeight']
358 ];
359
360 $url = $image->getUrl();
361 if ( isset( $scalerParams['isFilePageThumb'] ) && $scalerParams['isFilePageThumb'] ) {
362 // Use a versioned URL on file description pages
363 $url = $image->getFilePageThumbUrl( $url );
364 }
365
366 return new ThumbnailImage( $image, $url, null, $params );
367 }
368
369 /**
370 * Transform an image using ImageMagick
371 *
372 * This is a stub method. The real method is in BitmapHander.
373 *
374 * @stable to override
375 * @param File $image File associated with this thumbnail
376 * @param array $params Array with scaler params
377 *
378 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
379 */
380 protected function transformImageMagick( $image, $params ) {
381 return $this->getMediaTransformError( $params, "Unimplemented" );
382 }
383
384 /**
385 * Transform an image using the Imagick PHP extension
386 *
387 * This is a stub method. The real method is in BitmapHander.
388 *
389 * @stable to override
390 * @param File $image File associated with this thumbnail
391 * @param array $params Array with scaler params
392 *
393 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
394 */
395 protected function transformImageMagickExt( $image, $params ) {
396 return $this->getMediaTransformError( $params, "Unimplemented" );
397 }
398
399 /**
400 * Transform an image using a custom command
401 *
402 * This is a stub method. The real method is in BitmapHander.
403 *
404 * @stable to override
405 * @param File $image File associated with this thumbnail
406 * @param array $params Array with scaler params
407 *
408 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
409 */
410 protected function transformCustom( $image, $params ) {
411 return $this->getMediaTransformError( $params, "Unimplemented" );
412 }
413
414 /**
415 * Get a MediaTransformError with error 'thumbnail_error'
416 *
417 * @param array $params Parameter array as passed to the transform* functions
418 * @param string $errMsg Error message
419 * @return MediaTransformError
420 */
421 public function getMediaTransformError( $params, $errMsg ) {
422 return new MediaTransformError( 'thumbnail_error', $params['clientWidth'],
423 $params['clientHeight'], $errMsg );
424 }
425
426 /**
427 * Transform an image using the built in GD library
428 *
429 * This is a stub method. The real method is in BitmapHander.
430 *
431 * @param File $image File associated with this thumbnail
432 * @param array $params Array with scaler params
433 *
434 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
435 */
436 protected function transformGd( $image, $params ) {
437 return $this->getMediaTransformError( $params, "Unimplemented" );
438 }
439
440 /**
441 * Escape a string for ImageMagick's property input (e.g. -set -comment)
442 * See InterpretImageProperties() in magick/property.c
443 * @param string $s
444 * @return string
445 */
446 protected function escapeMagickProperty( $s ) {
447 // Double the backslashes
448 $s = str_replace( '\\', '\\\\', $s );
449 // Double the percents
450 $s = str_replace( '%', '%%', $s );
451 // Escape initial - or @
452 if ( strlen( $s ) > 0 && ( $s[0] === '-' || $s[0] === '@' ) ) {
453 $s = '\\' . $s;
454 }
455
456 return $s;
457 }
458
459 /**
460 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
461 * and GetPathComponent() in magick/utility.c.
462 *
463 * This won't work with an initial ~ or @, so input files should be prefixed
464 * with the directory name.
465 *
466 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
467 * it's broken in a way that doesn't involve trying to convert every file
468 * in a directory, so we're better off escaping and waiting for the bugfix
469 * to filter down to users.
470 *
471 * @param string $path The file path
472 * @param string|false $scene The scene specification, or false if there is none
473 * @return string
474 */
475 protected function escapeMagickInput( $path, $scene = false ) {
476 # Die on initial metacharacters (caller should prepend path)
477 $firstChar = substr( $path, 0, 1 );
478 if ( $firstChar === '~' || $firstChar === '@' ) {
479 throw new InvalidArgumentException( __METHOD__ . ': cannot escape this path name' );
480 }
481
482 # Escape glob chars
483 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
484
485 return $this->escapeMagickPath( $path, $scene );
486 }
487
488 /**
489 * Escape a string for ImageMagick's output filename. See
490 * InterpretImageFilename() in magick/image.c.
491 * @param string $path The file path
492 * @param string|false $scene The scene specification, or false if there is none
493 * @return string
494 */
495 protected function escapeMagickOutput( $path, $scene = false ) {
496 $path = str_replace( '%', '%%', $path );
497
498 return $this->escapeMagickPath( $path, $scene );
499 }
500
501 /**
502 * Armour a string against ImageMagick's GetPathComponent(). This is a
503 * helper function for escapeMagickInput() and escapeMagickOutput().
504 *
505 * @param string $path The file path
506 * @param string|false $scene The scene specification, or false if there is none
507 * @return string
508 */
509 protected function escapeMagickPath( $path, $scene = false ) {
510 # Die on format specifiers (other than drive letters). The regex is
511 # meant to match all the formats you get from "convert -list format"
512 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
513 if ( wfIsWindows() && is_dir( $m[0] ) ) {
514 // OK, it's a drive letter
515 // ImageMagick has a similar exception, see IsMagickConflict()
516 } else {
517 throw new InvalidArgumentException( __METHOD__ . ': unexpected colon character in path name' );
518 }
519 }
520
521 # If there are square brackets, add a do-nothing scene specification
522 # to force a literal interpretation
523 if ( $scene === false ) {
524 if ( strpos( $path, '[' ) !== false ) {
525 $path .= '[0--1]';
526 }
527 } else {
528 $path .= "[$scene]";
529 }
530
531 return $path;
532 }
533
534 /**
535 * Retrieve the version of the installed ImageMagick
536 * You can use PHPs version_compare() to use this value
537 * Value is cached for one hour.
538 * @return string|false Representing the IM version; false on error
539 */
540 protected function getMagickVersion() {
541 $cache = MediaWikiServices::getInstance()->getLocalServerObjectCache();
542 $method = __METHOD__;
543 return $cache->getWithSetCallback(
544 $cache->makeGlobalKey( 'imagemagick-version' ),
545 $cache::TTL_HOUR,
546 static function () use ( $method ) {
547 $imageMagickConvertCommand = MediaWikiServices::getInstance()
548 ->getMainConfig()->get( MainConfigNames::ImageMagickConvertCommand );
549
550 $cmd = Shell::escape( $imageMagickConvertCommand ) . ' -version';
551 wfDebug( $method . ": Running convert -version" );
552 $retval = '';
553 $return = wfShellExecWithStderr( $cmd, $retval );
554 $x = preg_match(
555 '/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches
556 );
557 if ( $x != 1 ) {
558 wfDebug( $method . ": ImageMagick version check failed" );
559 return false;
560 }
561
562 return $matches[1];
563 }
564 );
565 }
566
567 /**
568 * Returns whether the current scaler supports rotation.
569 *
570 * @since 1.24 No longer static
571 * @stable to override
572 * @return bool
573 */
574 public function canRotate() {
575 return false;
576 }
577
578 /**
579 * Should we automatically rotate an image based on exif
580 *
581 * @since 1.24 No longer static
582 * @stable to override
583 * @see $wgEnableAutoRotation
584 * @return bool Whether auto rotation is enabled
585 */
586 public function autoRotateEnabled() {
587 return false;
588 }
589
590 /**
591 * Rotate a thumbnail.
592 *
593 * This is a stub. See BitmapHandler::rotate.
594 *
595 * @stable to override
596 * @param File $file
597 * @param array $params Rotate parameters.
598 * 'rotation' clockwise rotation in degrees, allowed are multiples of 90
599 * @since 1.24 Is non-static. From 1.21 it was static
600 * @return MediaTransformError|false
601 */
602 public function rotate( $file, $params ) {
603 return new MediaTransformError( 'thumbnail_error', 0, 0,
604 static::class . ' rotation not implemented' );
605 }
606
607 /**
608 * Returns whether the file needs to be rendered. Returns true if the
609 * file requires rotation and we are able to rotate it.
610 *
611 * @stable to override
612 * @param File $file
613 * @return bool
614 */
615 public function mustRender( $file ) {
616 return $this->canRotate() && $this->getRotation( $file ) != 0;
617 }
618
619 /**
620 * Check if the file is smaller than the maximum image area for thumbnailing.
621 *
622 * Runs the 'BitmapHandlerCheckImageArea' hook.
623 *
624 * @stable to override
625 * @param File $file
626 * @param array &$params
627 * @return bool
628 * @since 1.25
629 */
630 public function isImageAreaOkForThumbnaling( $file, &$params ) {
631 $maxImageArea = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::MaxImageArea );
632
633 # For historical reasons, hook starts with BitmapHandler
634 $checkImageAreaHookResult = null;
635 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )->onBitmapHandlerCheckImageArea(
636 $file, $params, $checkImageAreaHookResult );
637
638 if ( $checkImageAreaHookResult !== null ) {
639 // was set by hook, so return that value
640 return (bool)$checkImageAreaHookResult;
641 }
642
643 if ( $maxImageArea === false ) {
644 // Checking is disabled, fine to thumbnail
645 return true;
646 }
647
648 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset Checked by normaliseParams
649 $srcWidth = $file->getWidth( $params['page'] );
650 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset Checked by normaliseParams
651 $srcHeight = $file->getHeight( $params['page'] );
652
653 if ( $srcWidth * $srcHeight > $maxImageArea
654 && !( $file->getMimeType() === 'image/jpeg'
655 && $this->getScalerType( null, false ) === 'im' )
656 ) {
657 # Only ImageMagick can efficiently downsize jpg images without loading
658 # the entire file in memory
659 return false;
660 }
661 return true;
662 }
663 }