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