MediaWiki  1.27.2
TransformationalImageHandler.php
Go to the documentation of this file.
1 <?php
43  function normaliseParams( $image, &$params ) {
44  if ( !parent::normaliseParams( $image, $params ) ) {
45  return false;
46  }
47 
48  # Obtain the source, pre-rotation dimensions
49  $srcWidth = $image->getWidth( $params['page'] );
50  $srcHeight = $image->getHeight( $params['page'] );
51 
52  # Don't make an image bigger than the source
53  if ( $params['physicalWidth'] >= $srcWidth ) {
54  $params['physicalWidth'] = $srcWidth;
55  $params['physicalHeight'] = $srcHeight;
56 
57  # Skip scaling limit checks if no scaling is required
58  # due to requested size being bigger than source.
59  if ( !$image->mustRender() ) {
60  return true;
61  }
62  }
63 
64  return true;
65  }
66 
79  public function extractPreRotationDimensions( $params, $rotation ) {
80  if ( $rotation == 90 || $rotation == 270 ) {
81  # We'll resize before rotation, so swap the dimensions again
82  $width = $params['physicalHeight'];
83  $height = $params['physicalWidth'];
84  } else {
85  $width = $params['physicalWidth'];
86  $height = $params['physicalHeight'];
87  }
88 
89  return [ $width, $height ];
90  }
91 
105  function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
106  if ( !$this->normaliseParams( $image, $params ) ) {
107  return new TransformParameterError( $params );
108  }
109 
110  # Create a parameter array to pass to the scaler
111  $scalerParams = [
112  # The size to which the image will be resized
113  'physicalWidth' => $params['physicalWidth'],
114  'physicalHeight' => $params['physicalHeight'],
115  'physicalDimensions' => "{$params['physicalWidth']}x{$params['physicalHeight']}",
116  # The size of the image on the page
117  'clientWidth' => $params['width'],
118  'clientHeight' => $params['height'],
119  # Comment as will be added to the Exif of the thumbnail
120  'comment' => isset( $params['descriptionUrl'] )
121  ? "File source: {$params['descriptionUrl']}"
122  : '',
123  # Properties of the original image
124  'srcWidth' => $image->getWidth(),
125  'srcHeight' => $image->getHeight(),
126  'mimeType' => $image->getMimeType(),
127  'dstPath' => $dstPath,
128  'dstUrl' => $dstUrl,
129  'interlace' => isset( $params['interlace'] ) ? $params['interlace'] : false,
130  ];
131 
132  if ( isset( $params['quality'] ) && $params['quality'] === 'low' ) {
133  $scalerParams['quality'] = 30;
134  }
135 
136  // For subclasses that might be paged.
137  if ( $image->isMultipage() && isset( $params['page'] ) ) {
138  $scalerParams['page'] = intval( $params['page'] );
139  }
140 
141  # Determine scaler type
142  $scaler = $this->getScalerType( $dstPath );
143 
144  if ( is_array( $scaler ) ) {
145  $scalerName = get_class( $scaler[0] );
146  } else {
147  $scalerName = $scaler;
148  }
149 
150  wfDebug( __METHOD__ . ": creating {$scalerParams['physicalDimensions']} " .
151  "thumbnail at $dstPath using scaler $scalerName\n" );
152 
153  if ( !$image->mustRender() &&
154  $scalerParams['physicalWidth'] == $scalerParams['srcWidth']
155  && $scalerParams['physicalHeight'] == $scalerParams['srcHeight']
156  && !isset( $scalerParams['quality'] )
157  ) {
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 ) ) {
173  return new TransformTooBigImageAreaError( $params, $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' )->text()
220  );
221  }
222 
223  # Try a hook. Called "Bitmap" for historical reasons.
224 
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' )->text()
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 
415  function escapeMagickProperty( $s ) {
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() {
513  return $cache->getWithSetCallback(
514  'imagemagick-version',
515  $cache::TTL_HOUR,
516  function () {
518 
519  $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
520  wfDebug( __METHOD__ . ": Running convert -version\n" );
521  $retval = '';
522  $return = wfShellExec( $cmd, $retval );
523  $x = preg_match(
524  '/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches
525  );
526  if ( $x != 1 ) {
527  wfDebug( __METHOD__ . ": ImageMagick version check failed\n" );
528  return false;
529  }
530 
531  return $matches[1];
532  }
533  );
534  }
535 
542  public function canRotate() {
543  return false;
544  }
545 
553  public function autoRotateEnabled() {
554  return false;
555  }
556 
568  public function rotate( $file, $params ) {
569  return new MediaTransformError( 'thumbnail_error', 0, 0,
570  get_class( $this ) . ' rotation not implemented' );
571  }
572 
580  public function mustRender( $file ) {
581  return $this->canRotate() && $this->getRotation( $file ) != 0;
582  }
583 
594  public function isImageAreaOkForThumbnaling( $file, &$params ) {
596 
597  # For historical reasons, hook starts with BitmapHandler
598  $checkImageAreaHookResult = null;
599  Hooks::run(
600  'BitmapHandlerCheckImageArea',
601  [ $file, &$params, &$checkImageAreaHookResult ]
602  );
603 
604  if ( !is_null( $checkImageAreaHookResult ) ) {
605  // was set by hook, so return that value
606  return (bool)$checkImageAreaHookResult;
607  }
608 
609  $srcWidth = $file->getWidth( $params['page'] );
610  $srcHeight = $file->getHeight( $params['page'] );
611 
612  if ( $srcWidth * $srcHeight > $wgMaxImageArea
613  && !( $file->getMimeType() == 'image/jpeg'
614  && $this->getScalerType( false, false ) == 'im' )
615  ) {
616  # Only ImageMagick can efficiently downsize jpg images without loading
617  # the entire file in memory
618  return false;
619  }
620  return true;
621  }
622 }
canRotate()
Returns whether the current scaler supports rotation.
rotate($file, $params)
Rotate a thumbnail.
transformCustom($image, $params)
Transform an image using a custom command.
$wgImageMagickConvertCommand
The convert command shipped with ImageMagick.
removeBadFile($dstPath, $retval=0)
Check for zero-sized thumbnails.
escapeMagickInput($path, $scene=false)
Escape a string for ImageMagick's input filenames.
wfMkdirParents($dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
escapeMagickOutput($path, $scene=false)
Escape a string for ImageMagick's output filename.
wfHostname()
Fetch server name for use in error reporting etc.
Handler for images that need to be transformed.
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2548
$wgMaxImageArea
The maximum number of pixels a source image can have if it is to be scaled down by a scaler that requ...
wfShellExec($cmd, &$retval=null, $environ=[], $limits=[], $options=[])
Execute a shell command, with time and memory limits mirrored from the PHP configuration if supported...
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
getClientScalingThumbnailImage($image, $scalerParams)
Get a ThumbnailImage that respresents an image that will be scaled client side.
wfIsWindows()
Check if the operating system is Windows.
wfDebug($text, $dest= 'all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
getRotation($file)
On supporting image formats, try to read out the low-level orientation of the file and return the ang...
Shortcut class for parameter validation errors.
wfDebugLog($logGroup, $text, $dest= 'all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not...
getThumbnailSource($file, $params)
Get the source file for the transform.
doTransform($image, $dstPath, $dstUrl, $params, $flags=0)
Create a thumbnail.
Media transform output for images.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation 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 unsetoffset-wrap String Wrap the message in html(usually something like"&lt
$cache
Definition: mcc.php:33
$params
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
extractPreRotationDimensions($params, $rotation)
Extracts the width/height if the image will be scaled before rotating.
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
Definition: design.txt:12
Shortcut class for parameter file size errors.
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:35
getMediaTransformError($params, $errMsg)
Get a MediaTransformError with error 'thumbnail_error'.
isImageAreaOkForThumbnaling($file, &$params)
Check if the file is smaller than the maximum image area for thumbnailing.
autoRotateEnabled()
Should we automatically rotate an image based on exif.
mustRender($file)
Returns whether the file needs to be rendered.
Media handler abstract base class for images.
transformImageMagick($image, $params)
Transform an image using ImageMagick.
escapeMagickPath($path, $scene=false)
Armour a string against ImageMagick's GetPathComponent().
static getLocalServerInstance($fallback=CACHE_NONE)
Factory function for CACHE_ACCEL (referenced from DefaultSettings.php)
transformGd($image, $params)
Transform an image using the built in GD library.
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:762
wfEscapeShellArg()
Windows-compatible version of escapeshellarg() Windows doesn't recognise single-quotes in the shell...
getMagickVersion()
Retrieve the version of the installed ImageMagick You can use PHPs version_compare() to use this valu...
const CACHE_NONE
Definition: Defines.php:102
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:242
escapeMagickProperty($s)
Escape a string for ImageMagick's property input (e.g.
getScalerType($dstPath, $checkDstPath=true)
Returns what sort of scaler type should be used.
Basic media transform error class.
transformImageMagickExt($image, $params)
Transform an image using the Imagick PHP extension.
$matches