MediaWiki  master
ImageHandler.php
Go to the documentation of this file.
1 <?php
24 use Wikimedia\AtEase\AtEase;
25 
33 abstract class ImageHandler extends MediaHandler {
40  public function canRender( $file ) {
41  return ( $file->getWidth() && $file->getHeight() );
42  }
43 
49  public function getParamMap() {
50  return [ 'img_width' => 'width' ];
51  }
52 
57  public function validateParam( $name, $value ) {
58  return in_array( $name, [ 'width', 'height' ] ) && $value > 0;
59  }
60 
65  public function makeParamString( $params ) {
66  if ( isset( $params['physicalWidth'] ) ) {
67  $width = $params['physicalWidth'];
68  } elseif ( isset( $params['width'] ) ) {
69  $width = $params['width'];
70  } else {
71  throw new MediaTransformInvalidParametersException( 'No width specified to ' . __METHOD__ );
72  }
73 
74  # Removed for ProofreadPage
75  # $width = intval( $width );
76  return "{$width}px";
77  }
78 
83  public function parseParamString( $str ) {
84  $m = false;
85  if ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
86  return [ 'width' => $m[1] ];
87  } else {
88  return false;
89  }
90  }
91 
96  protected function getScriptParams( $params ) {
97  return [ 'width' => $params['width'] ];
98  }
99 
108  public function normaliseParams( $image, &$params ) {
109  $mimeType = $image->getMimeType();
110 
111  if ( !isset( $params['width'] ) ) {
112  return false;
113  }
114 
115  if ( !isset( $params['page'] ) ) {
116  $params['page'] = 1;
117  } else {
118  $params['page'] = intval( $params['page'] );
119  if ( $params['page'] > $image->pageCount() ) {
120  $params['page'] = $image->pageCount();
121  }
122 
123  if ( $params['page'] < 1 ) {
124  $params['page'] = 1;
125  }
126  }
127 
128  $srcWidth = $image->getWidth( $params['page'] );
129  $srcHeight = $image->getHeight( $params['page'] );
130 
131  if ( isset( $params['height'] ) && $params['height'] != -1 ) {
132  # Height & width were both set
133  if ( $params['width'] * $srcHeight > $params['height'] * $srcWidth ) {
134  # Height is the relative smaller dimension, so scale width accordingly
135  $params['width'] = self::fitBoxWidth( $srcWidth, $srcHeight, $params['height'] );
136 
137  if ( $params['width'] == 0 ) {
138  # Very small image, so we need to rely on client side scaling :(
139  $params['width'] = 1;
140  }
141 
142  $params['physicalWidth'] = $params['width'];
143  } else {
144  # Height was crap, unset it so that it will be calculated later
145  unset( $params['height'] );
146  }
147  }
148 
149  if ( !isset( $params['physicalWidth'] ) ) {
150  # Passed all validations, so set the physicalWidth
151  // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive, checked above
152  $params['physicalWidth'] = $params['width'];
153  }
154 
155  # Because thumbs are only referred to by width, the height always needs
156  # to be scaled by the width to keep the thumbnail sizes consistent,
157  # even if it was set inside the if block above
158  $params['physicalHeight'] = File::scaleHeight( $srcWidth, $srcHeight,
159  $params['physicalWidth'] );
160 
161  # Set the height if it was not validated in the if block higher up
162  if ( !isset( $params['height'] ) || $params['height'] == -1 ) {
163  $params['height'] = $params['physicalHeight'];
164  }
165 
166  if ( !$this->validateThumbParams( $params['physicalWidth'],
167  $params['physicalHeight'], $srcWidth, $srcHeight, $mimeType )
168  ) {
169  return false;
170  }
171 
172  return true;
173  }
174 
185  private function validateThumbParams( &$width, &$height, $srcWidth, $srcHeight, $mimeType ) {
186  $width = intval( $width );
187 
188  if ( $width <= 0 ) {
189  wfDebug( __METHOD__ . ": Invalid destination width: $width" );
190 
191  return false;
192  }
193  if ( $srcWidth <= 0 ) {
194  wfDebug( __METHOD__ . ": Invalid source width: $srcWidth" );
195 
196  return false;
197  }
198 
199  $height = File::scaleHeight( $srcWidth, $srcHeight, $width );
200  if ( $height == 0 ) {
201  # Force height to be at least 1 pixel
202  $height = 1;
203  }
204 
205  return true;
206  }
207 
216  public function getScriptedTransform( $image, $script, $params ) {
217  if ( !$this->normaliseParams( $image, $params ) ) {
218  return false;
219  }
220  $url = wfAppendQuery( $script, $this->getScriptParams( $params ) );
221 
222  if ( $image->mustRender() || $params['width'] < $image->getWidth() ) {
223  return new ThumbnailImage( $image, $url, false, $params );
224  }
225  }
226 
227  public function getImageSize( $image, $path ) {
228  AtEase::suppressWarnings();
229  $gis = getimagesize( $path );
230  AtEase::restoreWarnings();
231 
232  return $gis;
233  }
234 
235  public function getSizeAndMetadata( $state, $path ) {
236  // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
237  $gis = @getimagesize( $path );
238  if ( $gis ) {
239  $info = [
240  'width' => $gis[0],
241  'height' => $gis[1],
242  ];
243  if ( isset( $gis['bits'] ) ) {
244  $info['bits'] = $gis['bits'];
245  }
246  } else {
247  $info = [];
248  }
249  return $info;
250  }
251 
262  public function getImageArea( $image ) {
263  return $image->getWidth() * $image->getHeight();
264  }
265 
272  public function getShortDesc( $file ) {
273  global $wgLang;
274  $nbytes = htmlspecialchars( $wgLang->formatSize( $file->getSize() ) );
275  $widthheight = wfMessage( 'widthheight' )
276  ->numParams( $file->getWidth(), $file->getHeight() )->escaped();
277 
278  return "$widthheight ($nbytes)";
279  }
280 
287  public function getLongDesc( $file ) {
288  $pages = $file->pageCount();
289  if ( $pages === false || $pages <= 1 ) {
290  $msg = wfMessage( 'file-info-size' )->numParams( $file->getWidth(),
291  $file->getHeight() )->sizeParams( $file->getSize() )->params(
292  '<span class="mime-type">' . $file->getMimeType() . '</span>' )->parse();
293  } else {
294  $msg = wfMessage( 'file-info-size-pages' )->numParams( $file->getWidth(),
295  $file->getHeight() )->sizeParams( $file->getSize() )->params(
296  '<span class="mime-type">' . $file->getMimeType() . '</span>' )->numParams( $pages )->parse();
297  }
298 
299  return $msg;
300  }
301 
308  public function getDimensionsString( $file ) {
309  $pages = $file->pageCount();
310  if ( $pages > 1 ) {
311  return wfMessage( 'widthheightpage' )
312  ->numParams( $file->getWidth(), $file->getHeight(), $pages )->text();
313  } else {
314  return wfMessage( 'widthheight' )
315  ->numParams( $file->getWidth(), $file->getHeight() )->text();
316  }
317  }
318 
323  public function sanitizeParamsForBucketing( $params ) {
324  $params = parent::sanitizeParamsForBucketing( $params );
325 
326  // We unset the height parameters in order to let normaliseParams recalculate them
327  // Otherwise there might be a height discrepancy
328  unset( $params['height'] );
329  unset( $params['physicalHeight'] );
330 
331  return $params;
332  }
333 }
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode) $wgLang
Definition: Setup.php:493
static scaleHeight( $srcWidth, $srcHeight, $dstWidth)
Calculate the height of a thumbnail using the source and destination width.
Definition: File.php:2195
Media handler abstract base class for images.
canRender( $file)
True if the handled types can be transformed.Stability: stableto overridebool
getImageSize( $image, $path)
Get an image size array like that returned by getimagesize(), or false if it can't be determined.
sanitizeParamsForBucketing( $params)
Returns a normalised params array for which parameters have been cleaned up for bucketing purposes....
getImageArea( $image)
Function that returns the number of pixels to be thumbnailed.
getParamMap()
Get an associative array mapping magic word IDs to parameter names.Will be used by the parser to iden...
getSizeAndMetadata( $state, $path)
Get image size information and metadata array.
normaliseParams( $image, &$params)
Changes the parameter array as necessary, ready for transformation.Should be idempotent....
parseParamString( $str)
Parse a param string made with makeParamString back into an array.The parameter string without file n...
makeParamString( $params)
Merge a parameter array into a string appropriate for inclusion in filenames.Array of parameters that...
getLongDesc( $file)
Long description.Shown under image on image description page surrounded by ().Stability: stableto ove...
validateParam( $name, $value)
Validate a thumbnail parameter at parse time.Return true to accept the parameter, and false to reject...
getScriptedTransform( $image, $script, $params)
Get a MediaTransformOutput object representing an alternate of the transformed output which will call...
getScriptParams( $params)
getDimensionsString( $file)
Shown in file history box on image description page.Stability: stableto overridestring Dimensions
getShortDesc( $file)
Short description.Shown on Special:Search results.Stability: stableto overridestring
Base media handler class.
static fitBoxWidth( $boxWidth, $boxHeight, $maxHeight)
Calculate the largest thumbnail width for a given original file size such that the thumbnail's height...
MediaWiki exception thrown by some methods when the transform parameter array is invalid.
Media transform output for images.
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42