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