MediaWiki REL1_32
TransformationalImageHandler.php
Go to the documentation of this file.
1<?php
29
45 if ( !parent::normaliseParams( $image, $params ) ) {
46 return false;
47 }
48
49 # Obtain the source, pre-rotation dimensions
50 $srcWidth = $image->getWidth( $params['page'] );
51 $srcHeight = $image->getHeight( $params['page'] );
52
53 # Don't make an image bigger than the source
54 if ( $params['physicalWidth'] >= $srcWidth ) {
55 $params['physicalWidth'] = $srcWidth;
56 $params['physicalHeight'] = $srcHeight;
57
58 # Skip scaling limit checks if no scaling is required
59 # due to requested size being bigger than source.
60 if ( !$image->mustRender() ) {
61 return true;
62 }
63 }
64
65 return true;
66 }
67
80 public function extractPreRotationDimensions( $params, $rotation ) {
81 if ( $rotation == 90 || $rotation == 270 ) {
82 # We'll resize before rotation, so swap the dimensions again
83 $width = $params['physicalHeight'];
84 $height = $params['physicalWidth'];
85 } else {
86 $width = $params['physicalWidth'];
87 $height = $params['physicalHeight'];
88 }
89
90 return [ $width, $height ];
91 }
92
106 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
107 if ( !$this->normaliseParams( $image, $params ) ) {
108 return new TransformParameterError( $params );
109 }
110
111 # Create a parameter array to pass to the scaler
112 $scalerParams = [
113 # The size to which the image will be resized
114 'physicalWidth' => $params['physicalWidth'],
115 'physicalHeight' => $params['physicalHeight'],
116 'physicalDimensions' => "{$params['physicalWidth']}x{$params['physicalHeight']}",
117 # The size of the image on the page
118 'clientWidth' => $params['width'],
119 'clientHeight' => $params['height'],
120 # Comment as will be added to the Exif of the thumbnail
121 'comment' => isset( $params['descriptionUrl'] )
122 ? "File source: {$params['descriptionUrl']}"
123 : '',
124 # Properties of the original image
125 'srcWidth' => $image->getWidth(),
126 'srcHeight' => $image->getHeight(),
127 'mimeType' => $image->getMimeType(),
128 'dstPath' => $dstPath,
129 'dstUrl' => $dstUrl,
130 'interlace' => $params['interlace'] ?? false,
131 ];
132
133 if ( isset( $params['quality'] ) && $params['quality'] === 'low' ) {
134 $scalerParams['quality'] = 30;
135 }
136
137 // For subclasses that might be paged.
138 if ( $image->isMultipage() && isset( $params['page'] ) ) {
139 $scalerParams['page'] = intval( $params['page'] );
140 }
141
142 # Determine scaler type
143 $scaler = $this->getScalerType( $dstPath );
144
145 if ( is_array( $scaler ) ) {
146 $scalerName = get_class( $scaler[0] );
147 } else {
148 $scalerName = $scaler;
149 }
150
151 wfDebug( __METHOD__ . ": creating {$scalerParams['physicalDimensions']} " .
152 "thumbnail at $dstPath using scaler $scalerName\n" );
153
154 if ( !$image->mustRender() &&
155 $scalerParams['physicalWidth'] == $scalerParams['srcWidth']
156 && $scalerParams['physicalHeight'] == $scalerParams['srcHeight']
157 && !isset( $scalerParams['quality'] )
158 ) {
159 # normaliseParams (or the user) wants us to return the unscaled image
160 wfDebug( __METHOD__ . ": returning unscaled image\n" );
161
162 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
163 }
164
165 if ( $scaler == 'client' ) {
166 # Client-side image scaling, use the source URL
167 # Using the destination URL in a TRANSFORM_LATER request would be incorrect
168 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
169 }
170
171 if ( $image->isTransformedLocally() && !$this->isImageAreaOkForThumbnaling( $image, $params ) ) {
172 global $wgMaxImageArea;
174 }
175
176 if ( $flags & self::TRANSFORM_LATER ) {
177 wfDebug( __METHOD__ . ": Transforming later per flags.\n" );
178 $newParams = [
179 'width' => $scalerParams['clientWidth'],
180 'height' => $scalerParams['clientHeight']
181 ];
182 if ( isset( $params['quality'] ) ) {
183 $newParams['quality'] = $params['quality'];
184 }
185 if ( isset( $params['page'] ) && $params['page'] ) {
186 $newParams['page'] = $params['page'];
187 }
188 return new ThumbnailImage( $image, $dstUrl, false, $newParams );
189 }
190
191 # Try to make a target path for the thumbnail
192 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
193 wfDebug( __METHOD__ . ": Unable to create thumbnail destination " .
194 "directory, falling back to client scaling\n" );
195
196 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
197 }
198
199 # Transform functions and binaries need a FS source file
200 $thumbnailSource = $this->getThumbnailSource( $image, $params );
201
202 // If the source isn't the original, disable EXIF rotation because it's already been applied
203 if ( $scalerParams['srcWidth'] != $thumbnailSource['width']
204 || $scalerParams['srcHeight'] != $thumbnailSource['height'] ) {
205 $scalerParams['disableRotation'] = true;
206 }
207
208 $scalerParams['srcPath'] = $thumbnailSource['path'];
209 $scalerParams['srcWidth'] = $thumbnailSource['width'];
210 $scalerParams['srcHeight'] = $thumbnailSource['height'];
211
212 if ( $scalerParams['srcPath'] === false ) { // Failed to get local copy
213 wfDebugLog( 'thumbnail',
214 sprintf( 'Thumbnail failed on %s: could not get local copy of "%s"',
215 wfHostname(), $image->getName() ) );
216
217 return new MediaTransformError( 'thumbnail_error',
218 $scalerParams['clientWidth'], $scalerParams['clientHeight'],
219 wfMessage( 'filemissing' )
220 );
221 }
222
223 # Try a hook. Called "Bitmap" for historical reasons.
225 $mto = null;
226 Hooks::run( 'BitmapHandlerTransform', [ $this, $image, &$scalerParams, &$mto ] );
227 if ( !is_null( $mto ) ) {
228 wfDebug( __METHOD__ . ": Hook to BitmapHandlerTransform created an mto\n" );
229 $scaler = 'hookaborted';
230 }
231
232 // $scaler will return a MediaTransformError on failure, or false on success.
233 // If the scaler is succesful, it will have created a thumbnail at the destination
234 // path.
235 if ( is_array( $scaler ) && is_callable( $scaler ) ) {
236 // Allow subclasses to specify their own rendering methods.
237 $err = call_user_func( $scaler, $image, $scalerParams );
238 } else {
239 switch ( $scaler ) {
240 case 'hookaborted':
241 # Handled by the hook above
242 $err = $mto->isError() ? $mto : false;
243 break;
244 case 'im':
245 $err = $this->transformImageMagick( $image, $scalerParams );
246 break;
247 case 'custom':
248 $err = $this->transformCustom( $image, $scalerParams );
249 break;
250 case 'imext':
251 $err = $this->transformImageMagickExt( $image, $scalerParams );
252 break;
253 case 'gd':
254 default:
255 $err = $this->transformGd( $image, $scalerParams );
256 break;
257 }
258 }
259
260 # Remove the file if a zero-byte thumbnail was created, or if there was an error
261 $removed = $this->removeBadFile( $dstPath, (bool)$err );
262 if ( $err ) {
263 # transform returned MediaTransforError
264 return $err;
265 } elseif ( $removed ) {
266 # Thumbnail was zero-byte and had to be removed
267 return new MediaTransformError( 'thumbnail_error',
268 $scalerParams['clientWidth'], $scalerParams['clientHeight'],
269 wfMessage( 'unknown-error' )
270 );
271 } elseif ( $mto ) {
272 return $mto;
273 } else {
274 $newParams = [
275 'width' => $scalerParams['clientWidth'],
276 'height' => $scalerParams['clientHeight']
277 ];
278 if ( isset( $params['quality'] ) ) {
279 $newParams['quality'] = $params['quality'];
280 }
281 if ( isset( $params['page'] ) && $params['page'] ) {
282 $newParams['page'] = $params['page'];
283 }
284 return new ThumbnailImage( $image, $dstUrl, $dstPath, $newParams );
285 }
286 }
287
295 protected function getThumbnailSource( $file, $params ) {
296 return $file->getThumbnailSource( $params );
297 }
298
320 abstract protected function getScalerType( $dstPath, $checkDstPath = true );
321
332 protected function getClientScalingThumbnailImage( $image, $scalerParams ) {
333 $params = [
334 'width' => $scalerParams['clientWidth'],
335 'height' => $scalerParams['clientHeight']
336 ];
337
338 return new ThumbnailImage( $image, $image->getUrl(), null, $params );
339 }
340
351 protected function transformImageMagick( $image, $params ) {
352 return $this->getMediaTransformError( $params, "Unimplemented" );
353 }
354
365 protected function transformImageMagickExt( $image, $params ) {
366 return $this->getMediaTransformError( $params, "Unimplemented" );
367 }
368
379 protected function transformCustom( $image, $params ) {
380 return $this->getMediaTransformError( $params, "Unimplemented" );
381 }
382
390 public function getMediaTransformError( $params, $errMsg ) {
391 return new MediaTransformError( 'thumbnail_error', $params['clientWidth'],
392 $params['clientHeight'], $errMsg );
393 }
394
405 protected function transformGd( $image, $params ) {
406 return $this->getMediaTransformError( $params, "Unimplemented" );
407 }
408
416 // Double the backslashes
417 $s = str_replace( '\\', '\\\\', $s );
418 // Double the percents
419 $s = str_replace( '%', '%%', $s );
420 // Escape initial - or @
421 if ( strlen( $s ) > 0 && ( $s[0] === '-' || $s[0] === '@' ) ) {
422 $s = '\\' . $s;
423 }
424
425 return $s;
426 }
427
445 function escapeMagickInput( $path, $scene = false ) {
446 # Die on initial metacharacters (caller should prepend path)
447 $firstChar = substr( $path, 0, 1 );
448 if ( $firstChar === '~' || $firstChar === '@' ) {
449 throw new MWException( __METHOD__ . ': cannot escape this path name' );
450 }
451
452 # Escape glob chars
453 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
454
455 return $this->escapeMagickPath( $path, $scene );
456 }
457
465 function escapeMagickOutput( $path, $scene = false ) {
466 $path = str_replace( '%', '%%', $path );
467
468 return $this->escapeMagickPath( $path, $scene );
469 }
470
480 protected function escapeMagickPath( $path, $scene = false ) {
481 # Die on format specifiers (other than drive letters). The regex is
482 # meant to match all the formats you get from "convert -list format"
483 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
484 if ( wfIsWindows() && is_dir( $m[0] ) ) {
485 // OK, it's a drive letter
486 // ImageMagick has a similar exception, see IsMagickConflict()
487 } else {
488 throw new MWException( __METHOD__ . ': unexpected colon character in path name' );
489 }
490 }
491
492 # If there are square brackets, add a do-nothing scene specification
493 # to force a literal interpretation
494 if ( $scene === false ) {
495 if ( strpos( $path, '[' ) !== false ) {
496 $path .= '[0--1]';
497 }
498 } else {
499 $path .= "[$scene]";
500 }
501
502 return $path;
503 }
504
511 protected function getMagickVersion() {
512 $cache = MediaWikiServices::getInstance()->getLocalServerObjectCache();
513 $method = __METHOD__;
514 return $cache->getWithSetCallback(
515 $cache->makeGlobalKey( 'imagemagick-version' ),
516 $cache::TTL_HOUR,
517 function () use ( $method ) {
519
520 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
521 wfDebug( $method . ": Running convert -version\n" );
522 $retval = '';
523 $return = wfShellExecWithStderr( $cmd, $retval );
524 $x = preg_match(
525 '/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches
526 );
527 if ( $x != 1 ) {
528 wfDebug( $method . ": ImageMagick version check failed\n" );
529 return false;
530 }
531
532 return $matches[1];
533 }
534 );
535 }
536
543 public function canRotate() {
544 return false;
545 }
546
554 public function autoRotateEnabled() {
555 return false;
556 }
557
569 public function rotate( $file, $params ) {
570 return new MediaTransformError( 'thumbnail_error', 0, 0,
571 static::class . ' rotation not implemented' );
572 }
573
581 public function mustRender( $file ) {
582 return $this->canRotate() && $this->getRotation( $file ) != 0;
583 }
584
595 public function isImageAreaOkForThumbnaling( $file, &$params ) {
596 global $wgMaxImageArea;
597
598 # For historical reasons, hook starts with BitmapHandler
599 $checkImageAreaHookResult = null;
600 Hooks::run(
601 'BitmapHandlerCheckImageArea',
602 [ $file, &$params, &$checkImageAreaHookResult ]
603 );
604
605 if ( !is_null( $checkImageAreaHookResult ) ) {
606 // was set by hook, so return that value
607 return (bool)$checkImageAreaHookResult;
608 }
609
610 $srcWidth = $file->getWidth( $params['page'] );
611 $srcHeight = $file->getHeight( $params['page'] );
612
613 if ( $srcWidth * $srcHeight > $wgMaxImageArea
614 && !( $file->getMimeType() == 'image/jpeg'
615 && $this->getScalerType( false, false ) == 'im' )
616 ) {
617 # Only ImageMagick can efficiently downsize jpg images without loading
618 # the entire file in memory
619 return false;
620 }
621 return true;
622 }
623}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
$wgMaxImageArea
The maximum number of pixels a source image can have if it is to be scaled down by a scaler that requ...
$wgImageMagickConvertCommand
The convert command shipped with ImageMagick.
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfEscapeShellArg(... $args)
Version of escapeshellarg() that works better on Windows.
wfHostname()
Fetch server name for use in error reporting etc.
wfShellExecWithStderr( $cmd, &$retval=null, $environ=[], $limits=[])
Execute a shell command, returning both stdout and stderr.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
wfIsWindows()
Check if the operating system is Windows.
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
Media handler abstract base class for images.
MediaWiki exception.
getRotation( $file)
On supporting image formats, try to read out the low-level orientation of the file and return the ang...
removeBadFile( $dstPath, $retval=0)
Check for zero-sized thumbnails.
Basic media transform error class.
MediaWikiServices is the service locator for the application scope of MediaWiki.
Media transform output for images.
Shortcut class for parameter validation errors.
Shortcut class for parameter file size errors.
Handler for images that need to be transformed.
getMagickVersion()
Retrieve the version of the installed ImageMagick You can use PHPs version_compare() to use this valu...
escapeMagickInput( $path, $scene=false)
Escape a string for ImageMagick's input filenames.
autoRotateEnabled()
Should we automatically rotate an image based on exif.
isImageAreaOkForThumbnaling( $file, &$params)
Check if the file is smaller than the maximum image area for thumbnailing.
getThumbnailSource( $file, $params)
Get the source file for the transform.
getClientScalingThumbnailImage( $image, $scalerParams)
Get a ThumbnailImage that respresents an image that will be scaled client side.
getScalerType( $dstPath, $checkDstPath=true)
Returns what sort of scaler type should be used.
doTransform( $image, $dstPath, $dstUrl, $params, $flags=0)
Create a thumbnail.
escapeMagickPath( $path, $scene=false)
Armour a string against ImageMagick's GetPathComponent().
escapeMagickProperty( $s)
Escape a string for ImageMagick's property input (e.g.
canRotate()
Returns whether the current scaler supports rotation.
transformImageMagick( $image, $params)
Transform an image using ImageMagick.
transformGd( $image, $params)
Transform an image using the built in GD library.
escapeMagickOutput( $path, $scene=false)
Escape a string for ImageMagick's output filename.
extractPreRotationDimensions( $params, $rotation)
Extracts the width/height if the image will be scaled before rotating.
transformCustom( $image, $params)
Transform an image using a custom command.
mustRender( $file)
Returns whether the file needs to be rendered.
transformImageMagickExt( $image, $params)
Transform an image using the Imagick PHP extension.
getMediaTransformError( $params, $errMsg)
Get a MediaTransformError with error 'thumbnail_error'.
rotate( $file, $params)
Rotate a thumbnail.
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account incomplete not yet checked for validity & $retval
Definition hooks.txt:266
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check $image
Definition hooks.txt:925
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt;div ...>$1&lt;/div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback function
Definition injection.txt:30
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
$cache
Definition mcc.php:33
$params