Make mediawiki.special.pageLanguage work again
[lhc/web/wiklou.git] / includes / media / TransformationalImageHandler.php
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 /**
30 * Handler for images that need to be transformed
31 *
32 * @since 1.24
33 * @ingroup Media
34 */
35 abstract class TransformationalImageHandler extends ImageHandler {
36 /**
37 * @param File $image
38 * @param array $params Transform parameters. Entries with the keys 'width'
39 * and 'height' are the respective screen width and height, while the keys
40 * 'physicalWidth' and 'physicalHeight' indicate the thumbnail dimensions.
41 * @return bool
42 */
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
67 /**
68 * Extracts the width/height if the image will be scaled before rotating
69 *
70 * This will match the physical size/aspect ratio of the original image
71 * prior to application of the rotation -- so for a portrait image that's
72 * stored as raw landscape with 90-degress rotation, the resulting size
73 * will be wider than it is tall.
74 *
75 * @param array $params Parameters as returned by normaliseParams
76 * @param int $rotation The rotation angle that will be applied
77 * @return array ($width, $height) array
78 */
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 array( $width, $height );
90 }
91
92 /**
93 * Create a thumbnail.
94 *
95 * This sets up various parameters, and then calls a helper method
96 * based on $this->getScalerType in order to scale the image.
97 *
98 * @param File $image
99 * @param string $dstPath
100 * @param string $dstUrl
101 * @param array $params
102 * @param int $flags
103 * @return MediaTransformError|ThumbnailImage|TransformParameterError
104 */
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 = array(
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 );
130
131 if ( isset( $params['quality'] ) && $params['quality'] === 'low' ) {
132 $scalerParams['quality'] = 30;
133 }
134
135 // For subclasses that might be paged.
136 if ( $image->isMultipage() && isset( $params['page'] ) ) {
137 $scalerParams['page'] = intval( $params['page'] );
138 }
139
140 # Determine scaler type
141 $scaler = $this->getScalerType( $dstPath );
142
143 if ( is_array( $scaler ) ) {
144 $scalerName = get_class( $scaler[0] );
145 } else {
146 $scalerName = $scaler;
147 }
148
149 wfDebug( __METHOD__ . ": creating {$scalerParams['physicalDimensions']} " .
150 "thumbnail at $dstPath using scaler $scalerName\n" );
151
152 if ( !$image->mustRender() &&
153 $scalerParams['physicalWidth'] == $scalerParams['srcWidth']
154 && $scalerParams['physicalHeight'] == $scalerParams['srcHeight']
155 && !isset( $scalerParams['quality'] )
156 ) {
157
158 # normaliseParams (or the user) wants us to return the unscaled image
159 wfDebug( __METHOD__ . ": returning unscaled image\n" );
160
161 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
162 }
163
164 if ( $scaler == 'client' ) {
165 # Client-side image scaling, use the source URL
166 # Using the destination URL in a TRANSFORM_LATER request would be incorrect
167 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
168 }
169
170 if ( $image->isTransformedLocally() && !$this->isImageAreaOkForThumbnaling( $image, $params ) ) {
171 global $wgMaxImageArea;
172 return new TransformTooBigImageAreaError( $params, $wgMaxImageArea );
173 }
174
175 if ( $flags & self::TRANSFORM_LATER ) {
176 wfDebug( __METHOD__ . ": Transforming later per flags.\n" );
177 $newParams = array(
178 'width' => $scalerParams['clientWidth'],
179 'height' => $scalerParams['clientHeight']
180 );
181 if ( isset( $params['quality'] ) ) {
182 $newParams['quality'] = $params['quality'];
183 }
184 if ( isset( $params['page'] ) && $params['page'] ) {
185 $newParams['page'] = $params['page'];
186 }
187 return new ThumbnailImage( $image, $dstUrl, false, $newParams );
188 }
189
190 # Try to make a target path for the thumbnail
191 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
192 wfDebug( __METHOD__ . ": Unable to create thumbnail destination " .
193 "directory, falling back to client scaling\n" );
194
195 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
196 }
197
198 # Transform functions and binaries need a FS source file
199 $thumbnailSource = $this->getThumbnailSource( $image, $params );
200
201 // If the source isn't the original, disable EXIF rotation because it's already been applied
202 if ( $scalerParams['srcWidth'] != $thumbnailSource['width']
203 || $scalerParams['srcHeight'] != $thumbnailSource['height'] ) {
204 $scalerParams['disableRotation'] = true;
205 }
206
207 $scalerParams['srcPath'] = $thumbnailSource['path'];
208 $scalerParams['srcWidth'] = $thumbnailSource['width'];
209 $scalerParams['srcHeight'] = $thumbnailSource['height'];
210
211 if ( $scalerParams['srcPath'] === false ) { // Failed to get local copy
212 wfDebugLog( 'thumbnail',
213 sprintf( 'Thumbnail failed on %s: could not get local copy of "%s"',
214 wfHostname(), $image->getName() ) );
215
216 return new MediaTransformError( 'thumbnail_error',
217 $scalerParams['clientWidth'], $scalerParams['clientHeight'],
218 wfMessage( 'filemissing' )->text()
219 );
220 }
221
222 # Try a hook. Called "Bitmap" for historical reasons.
223 /** @var $mto MediaTransformOutput */
224 $mto = null;
225 Hooks::run( 'BitmapHandlerTransform', array( $this, $image, &$scalerParams, &$mto ) );
226 if ( !is_null( $mto ) ) {
227 wfDebug( __METHOD__ . ": Hook to BitmapHandlerTransform created an mto\n" );
228 $scaler = 'hookaborted';
229 }
230
231 // $scaler will return a MediaTransformError on failure, or false on success.
232 // If the scaler is succesful, it will have created a thumbnail at the destination
233 // path.
234 if ( is_array( $scaler ) && is_callable( $scaler ) ) {
235 // Allow subclasses to specify their own rendering methods.
236 $err = call_user_func( $scaler, $image, $scalerParams );
237 } else {
238 switch ( $scaler ) {
239 case 'hookaborted':
240 # Handled by the hook above
241 $err = $mto->isError() ? $mto : false;
242 break;
243 case 'im':
244 $err = $this->transformImageMagick( $image, $scalerParams );
245 break;
246 case 'custom':
247 $err = $this->transformCustom( $image, $scalerParams );
248 break;
249 case 'imext':
250 $err = $this->transformImageMagickExt( $image, $scalerParams );
251 break;
252 case 'gd':
253 default:
254 $err = $this->transformGd( $image, $scalerParams );
255 break;
256 }
257 }
258
259 # Remove the file if a zero-byte thumbnail was created, or if there was an error
260 $removed = $this->removeBadFile( $dstPath, (bool)$err );
261 if ( $err ) {
262 # transform returned MediaTransforError
263 return $err;
264 } elseif ( $removed ) {
265 # Thumbnail was zero-byte and had to be removed
266 return new MediaTransformError( 'thumbnail_error',
267 $scalerParams['clientWidth'], $scalerParams['clientHeight'],
268 wfMessage( 'unknown-error' )->text()
269 );
270 } elseif ( $mto ) {
271 return $mto;
272 } else {
273 $newParams = array(
274 'width' => $scalerParams['clientWidth'],
275 'height' => $scalerParams['clientHeight']
276 );
277 if ( isset( $params['quality'] ) ) {
278 $newParams['quality'] = $params['quality'];
279 }
280 if ( isset( $params['page'] ) && $params['page'] ) {
281 $newParams['page'] = $params['page'];
282 }
283 return new ThumbnailImage( $image, $dstUrl, $dstPath, $newParams );
284 }
285 }
286
287 /**
288 * Get the source file for the transform
289 *
290 * @param $file File
291 * @param $params Array
292 * @return Array Array with keys width, height and path.
293 */
294 protected function getThumbnailSource( $file, $params ) {
295 return $file->getThumbnailSource( $params );
296 }
297
298 /**
299 * Returns what sort of scaler type should be used.
300 *
301 * Values can be one of client, im, custom, gd, imext, or an array
302 * of object, method-name to call that specific method.
303 *
304 * If specifying a custom scaler command with array( Obj, method ),
305 * the method in question should take 2 parameters, a File object,
306 * and a $scalerParams array with various options (See doTransform
307 * for what is in $scalerParams). On error it should return a
308 * MediaTransformError object. On success it should return false,
309 * and simply make sure the thumbnail file is located at
310 * $scalerParams['dstPath'].
311 *
312 * If there is a problem with the output path, it returns "client"
313 * to do client side scaling.
314 *
315 * @param string $dstPath
316 * @param bool $checkDstPath Check that $dstPath is valid
317 * @return string|Callable One of client, im, custom, gd, imext, or a Callable array.
318 */
319 abstract protected function getScalerType( $dstPath, $checkDstPath = true );
320
321 /**
322 * Get a ThumbnailImage that respresents an image that will be scaled
323 * client side
324 *
325 * @param File $image File associated with this thumbnail
326 * @param array $scalerParams Array with scaler params
327 * @return ThumbnailImage
328 *
329 * @todo FIXME: No rotation support
330 */
331 protected function getClientScalingThumbnailImage( $image, $scalerParams ) {
332 $params = array(
333 'width' => $scalerParams['clientWidth'],
334 'height' => $scalerParams['clientHeight']
335 );
336
337 return new ThumbnailImage( $image, $image->getURL(), null, $params );
338 }
339
340 /**
341 * Transform an image using ImageMagick
342 *
343 * This is a stub method. The real method is in BitmapHander.
344 *
345 * @param File $image File associated with this thumbnail
346 * @param array $params Array with scaler params
347 *
348 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
349 */
350 protected function transformImageMagick( $image, $params ) {
351 return $this->getMediaTransformError( $params, "Unimplemented" );
352 }
353
354 /**
355 * Transform an image using the Imagick PHP extension
356 *
357 * This is a stub method. The real method is in BitmapHander.
358 *
359 * @param File $image File associated with this thumbnail
360 * @param array $params Array with scaler params
361 *
362 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
363 */
364 protected function transformImageMagickExt( $image, $params ) {
365 return $this->getMediaTransformError( $params, "Unimplemented" );
366 }
367
368 /**
369 * Transform an image using a custom command
370 *
371 * This is a stub method. The real method is in BitmapHander.
372 *
373 * @param File $image File associated with this thumbnail
374 * @param array $params Array with scaler params
375 *
376 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
377 */
378 protected function transformCustom( $image, $params ) {
379 return $this->getMediaTransformError( $params, "Unimplemented" );
380 }
381
382 /**
383 * Get a MediaTransformError with error 'thumbnail_error'
384 *
385 * @param array $params Parameter array as passed to the transform* functions
386 * @param string $errMsg Error message
387 * @return MediaTransformError
388 */
389 public function getMediaTransformError( $params, $errMsg ) {
390 return new MediaTransformError( 'thumbnail_error', $params['clientWidth'],
391 $params['clientHeight'], $errMsg );
392 }
393
394 /**
395 * Transform an image using the built in GD library
396 *
397 * This is a stub method. The real method is in BitmapHander.
398 *
399 * @param File $image File associated with this thumbnail
400 * @param array $params Array with scaler params
401 *
402 * @return MediaTransformError Error object if error occurred, false (=no error) otherwise
403 */
404 protected function transformGd( $image, $params ) {
405 return $this->getMediaTransformError( $params, "Unimplemented" );
406 }
407
408 /**
409 * Escape a string for ImageMagick's property input (e.g. -set -comment)
410 * See InterpretImageProperties() in magick/property.c
411 * @param string $s
412 * @return string
413 */
414 function escapeMagickProperty( $s ) {
415 // Double the backslashes
416 $s = str_replace( '\\', '\\\\', $s );
417 // Double the percents
418 $s = str_replace( '%', '%%', $s );
419 // Escape initial - or @
420 if ( strlen( $s ) > 0 && ( $s[0] === '-' || $s[0] === '@' ) ) {
421 $s = '\\' . $s;
422 }
423
424 return $s;
425 }
426
427 /**
428 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
429 * and GetPathComponent() in magick/utility.c.
430 *
431 * This won't work with an initial ~ or @, so input files should be prefixed
432 * with the directory name.
433 *
434 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
435 * it's broken in a way that doesn't involve trying to convert every file
436 * in a directory, so we're better off escaping and waiting for the bugfix
437 * to filter down to users.
438 *
439 * @param string $path The file path
440 * @param bool|string $scene The scene specification, or false if there is none
441 * @throws MWException
442 * @return string
443 */
444 function escapeMagickInput( $path, $scene = false ) {
445 # Die on initial metacharacters (caller should prepend path)
446 $firstChar = substr( $path, 0, 1 );
447 if ( $firstChar === '~' || $firstChar === '@' ) {
448 throw new MWException( __METHOD__ . ': cannot escape this path name' );
449 }
450
451 # Escape glob chars
452 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
453
454 return $this->escapeMagickPath( $path, $scene );
455 }
456
457 /**
458 * Escape a string for ImageMagick's output filename. See
459 * InterpretImageFilename() in magick/image.c.
460 * @param string $path The file path
461 * @param bool|string $scene The scene specification, or false if there is none
462 * @return string
463 */
464 function escapeMagickOutput( $path, $scene = false ) {
465 $path = str_replace( '%', '%%', $path );
466
467 return $this->escapeMagickPath( $path, $scene );
468 }
469
470 /**
471 * Armour a string against ImageMagick's GetPathComponent(). This is a
472 * helper function for escapeMagickInput() and escapeMagickOutput().
473 *
474 * @param string $path The file path
475 * @param bool|string $scene The scene specification, or false if there is none
476 * @throws MWException
477 * @return string
478 */
479 protected function escapeMagickPath( $path, $scene = false ) {
480 # Die on format specifiers (other than drive letters). The regex is
481 # meant to match all the formats you get from "convert -list format"
482 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
483 if ( wfIsWindows() && is_dir( $m[0] ) ) {
484 // OK, it's a drive letter
485 // ImageMagick has a similar exception, see IsMagickConflict()
486 } else {
487 throw new MWException( __METHOD__ . ': unexpected colon character in path name' );
488 }
489 }
490
491 # If there are square brackets, add a do-nothing scene specification
492 # to force a literal interpretation
493 if ( $scene === false ) {
494 if ( strpos( $path, '[' ) !== false ) {
495 $path .= '[0--1]';
496 }
497 } else {
498 $path .= "[$scene]";
499 }
500
501 return $path;
502 }
503
504 /**
505 * Retrieve the version of the installed ImageMagick
506 * You can use PHPs version_compare() to use this value
507 * Value is cached for one hour.
508 * @return string|bool Representing the IM version; false on error
509 */
510 protected function getMagickVersion() {
511 $cache = ObjectCache::getLocalServerInstance( CACHE_NONE );
512 return $cache->getWithSetCallback(
513 'imagemagick-version',
514 $cache::TTL_HOUR,
515 function () {
516 global $wgImageMagickConvertCommand;
517
518 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
519 wfDebug( __METHOD__ . ": Running convert -version\n" );
520 $retval = '';
521 $return = wfShellExec( $cmd, $retval );
522 $x = preg_match(
523 '/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches
524 );
525 if ( $x != 1 ) {
526 wfDebug( __METHOD__ . ": ImageMagick version check failed\n" );
527 return false;
528 }
529
530 return $matches[1];
531 }
532 );
533 }
534
535 /**
536 * Returns whether the current scaler supports rotation.
537 *
538 * @since 1.24 No longer static
539 * @return bool
540 */
541 public function canRotate() {
542 return false;
543 }
544
545 /**
546 * Should we automatically rotate an image based on exif
547 *
548 * @since 1.24 No longer static
549 * @see $wgEnableAutoRotation
550 * @return bool Whether auto rotation is enabled
551 */
552 public function autoRotateEnabled() {
553 return false;
554 }
555
556 /**
557 * Rotate a thumbnail.
558 *
559 * This is a stub. See BitmapHandler::rotate.
560 *
561 * @param File $file
562 * @param array $params Rotate parameters.
563 * 'rotation' clockwise rotation in degrees, allowed are multiples of 90
564 * @since 1.24 Is non-static. From 1.21 it was static
565 * @return bool
566 */
567 public function rotate( $file, $params ) {
568 return new MediaTransformError( 'thumbnail_error', 0, 0,
569 get_class( $this ) . ' rotation not implemented' );
570 }
571
572 /**
573 * Returns whether the file needs to be rendered. Returns true if the
574 * file requires rotation and we are able to rotate it.
575 *
576 * @param File $file
577 * @return bool
578 */
579 public function mustRender( $file ) {
580 return $this->canRotate() && $this->getRotation( $file ) != 0;
581 }
582
583 /**
584 * Check if the file is smaller than the maximum image area for thumbnailing.
585 *
586 * Runs the 'BitmapHandlerCheckImageArea' hook.
587 *
588 * @param File $file
589 * @param array $params
590 * @return bool
591 * @since 1.25
592 */
593 public function isImageAreaOkForThumbnaling( $file, &$params ) {
594 global $wgMaxImageArea;
595
596 # For historical reasons, hook starts with BitmapHandler
597 $checkImageAreaHookResult = null;
598 Hooks::run(
599 'BitmapHandlerCheckImageArea',
600 array( $file, &$params, &$checkImageAreaHookResult )
601 );
602
603 if ( !is_null( $checkImageAreaHookResult ) ) {
604 // was set by hook, so return that value
605 return (bool)$checkImageAreaHookResult;
606 }
607
608 $srcWidth = $file->getWidth( $params['page'] );
609 $srcHeight = $file->getHeight( $params['page'] );
610
611 if ( $srcWidth * $srcHeight > $wgMaxImageArea
612 && !( $file->getMimeType() == 'image/jpeg'
613 && $this->getScalerType( false, false ) == 'im' )
614 ) {
615 # Only ImageMagick can efficiently downsize jpg images without loading
616 # the entire file in memory
617 return false;
618 }
619 return true;
620 }
621 }