* Reduced some pointless regex capture overhead
[mediawiki.git] / includes / media / Bitmap.php
blobc28e7eb9ce16f5c39aea6bbc23ca68a50fae316b
1 <?php
2 /**
3 * Generic handler for bitmap images
5 * @file
6 * @ingroup Media
7 */
9 /**
10 * Generic handler for bitmap images
12 * @ingroup Media
14 class BitmapHandler extends ImageHandler {
15 function normaliseParams( $image, &$params ) {
16 global $wgMaxImageArea;
17 if ( !parent::normaliseParams( $image, $params ) ) {
18 return false;
21 $mimeType = $image->getMimeType();
22 $srcWidth = $image->getWidth( $params['page'] );
23 $srcHeight = $image->getHeight( $params['page'] );
25 # Don't make an image bigger than the source
26 $params['physicalWidth'] = $params['width'];
27 $params['physicalHeight'] = $params['height'];
29 if ( $params['physicalWidth'] >= $srcWidth ) {
30 $params['physicalWidth'] = $srcWidth;
31 $params['physicalHeight'] = $srcHeight;
32 # Skip scaling limit checks if no scaling is required
33 if ( !$image->mustRender() )
34 return true;
37 # Don't thumbnail an image so big that it will fill hard drives and send servers into swap
38 # JPEG has the handy property of allowing thumbnailing without full decompression, so we make
39 # an exception for it.
40 # FIXME: This actually only applies to ImageMagick
41 if ( $mimeType !== 'image/jpeg' &&
42 $srcWidth * $srcHeight > $wgMaxImageArea )
44 return false;
47 return true;
51 // Function that returns the number of pixels to be thumbnailed.
52 // Intended for animated GIFs to multiply by the number of frames.
53 function getImageArea( $image, $width, $height ) {
54 return $width * $height;
57 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
58 global $wgUseImageMagick;
59 global $wgCustomConvertCommand, $wgUseImageResize;
61 if ( !$this->normaliseParams( $image, $params ) ) {
62 return new TransformParameterError( $params );
64 # Create a parameter array to pass to the scaler
65 $scalerParams = array(
66 # The size to which the image will be resized
67 'physicalWidth' => $params['physicalWidth'],
68 'physicalHeight' => $params['physicalHeight'],
69 'physicalDimensions' => "{$params['physicalWidth']}x{$params['physicalHeight']}",
70 # The size of the image on the page
71 'clientWidth' => $params['width'],
72 'clientHeight' => $params['height'],
73 # Comment as will be added to the EXIF of the thumbnail
74 'comment' => isset( $params['descriptionUrl'] ) ?
75 "File source: {$params['descriptionUrl']}" : '',
76 # Properties of the original image
77 'srcWidth' => $image->getWidth(),
78 'srcHeight' => $image->getHeight(),
79 'mimeType' => $image->getMimeType(),
80 'srcPath' => $image->getPath(),
81 'dstPath' => $dstPath,
84 wfDebug( __METHOD__ . ": creating {$scalerParams['physicalDimensions']} thumbnail at $dstPath\n" );
86 if ( !$image->mustRender() &&
87 $scalerParams['physicalWidth'] == $scalerParams['srcWidth']
88 && $scalerParams['physicalHeight'] == $scalerParams['srcHeight'] ) {
90 # normaliseParams (or the user) wants us to return the unscaled image
91 wfDebug( __METHOD__ . ": returning unscaled image\n" );
92 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
95 # Determine scaler type
96 if ( !$dstPath ) {
97 # No output path available, client side scaling only
98 $scaler = 'client';
99 } elseif ( !$wgUseImageResize ) {
100 $scaler = 'client';
101 } elseif ( $wgUseImageMagick ) {
102 $scaler = 'im';
103 } elseif ( $wgCustomConvertCommand ) {
104 $scaler = 'custom';
105 } elseif ( function_exists( 'imagecreatetruecolor' ) ) {
106 $scaler = 'gd';
107 } else {
108 $scaler = 'client';
110 wfDebug( __METHOD__ . ": scaler $scaler\n" );
112 if ( $scaler == 'client' ) {
113 # Client-side image scaling, use the source URL
114 # Using the destination URL in a TRANSFORM_LATER request would be incorrect
115 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
118 if ( $flags & self::TRANSFORM_LATER ) {
119 wfDebug( __METHOD__ . ": Transforming later per flags.\n" );
120 return new ThumbnailImage( $image, $dstUrl, $scalerParams['clientWidth'],
121 $scalerParams['clientHeight'], $dstPath );
124 # Try to make a target path for the thumbnail
125 if ( !wfMkdirParents( dirname( $dstPath ) ) ) {
126 wfDebug( __METHOD__ . ": Unable to create thumbnail destination directory, falling back to client scaling\n" );
127 return $this->getClientScalingThumbnailImage( $image, $scalerParams );
130 switch ( $scaler ) {
131 case 'im':
132 $err = $this->transformImageMagick( $image, $scalerParams );
133 break;
134 case 'custom':
135 $err = $this->transformCustom( $image, $scalerParams );
136 break;
137 case 'gd':
138 default:
139 $err = $this->transformGd( $image, $scalerParams );
140 break;
143 # Remove the file if a zero-byte thumbnail was created, or if there was an error
144 $removed = $this->removeBadFile( $dstPath, (bool)$err );
145 if ( $err ) {
146 # transform returned MediaTransforError
147 return $err;
148 } elseif ( $removed ) {
149 # Thumbnail was zero-byte and had to be removed
150 return new MediaTransformError( 'thumbnail_error',
151 $scalerParams['clientWidth'], $scalerParams['clientHeight'] );
152 } else {
153 return new ThumbnailImage( $image, $dstUrl, $scalerParams['clientWidth'],
154 $scalerParams['clientHeight'], $dstPath );
159 * Get a ThumbnailImage that respresents an image that will be scaled
160 * client side
162 * @param $image File File associated with this thumbnail
163 * @param $params array Array with scaler params
164 * @return ThumbnailImage
166 protected function getClientScalingThumbnailImage( $image, $params ) {
167 return new ThumbnailImage( $image, $image->getURL(),
168 $params['clientWidth'], $params['clientHeight'], $params['srcPath'] );
172 * Transform an image using ImageMagick
174 * @param $image File File associated with this thumbnail
175 * @param $params array Array with scaler params
177 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
179 protected function transformImageMagick( $image, $params ) {
180 # use ImageMagick
181 global $wgSharpenReductionThreshold, $wgSharpenParameter,
182 $wgMaxAnimatedGifArea,
183 $wgImageMagickTempDir, $wgImageMagickConvertCommand;
185 $quality = '';
186 $sharpen = '';
187 $scene = false;
188 $animation_pre = '';
189 $animation_post = '';
190 $decoderHint = '';
191 if ( $params['mimeType'] == 'image/jpeg' ) {
192 $quality = "-quality 80"; // 80%
193 # Sharpening, see bug 6193
194 if ( ( $params['physicalWidth'] + $params['physicalHeight'] )
195 / ( $params['srcWidth'] + $params['srcHeight'] )
196 < $wgSharpenReductionThreshold ) {
197 $sharpen = "-sharpen " . wfEscapeShellArg( $wgSharpenParameter );
199 // JPEG decoder hint to reduce memory, available since IM 6.5.6-2
200 $decoderHint = "-define jpeg:size={$params['physicalDimensions']}";
202 } elseif ( $params['mimeType'] == 'image/png' ) {
203 $quality = "-quality 95"; // zlib 9, adaptive filtering
205 } elseif ( $params['mimeType'] == 'image/gif' ) {
206 if ( $this->getImageArea( $image, $params['srcWidth'],
207 $params['srcHeight'] ) > $wgMaxAnimatedGifArea ) {
208 // Extract initial frame only; we're so big it'll
209 // be a total drag. :P
210 $scene = 0;
212 } elseif ( $this->isAnimatedImage( $image ) ) {
213 // Coalesce is needed to scale animated GIFs properly (bug 1017).
214 $animation_pre = '-coalesce';
215 // We optimize the output, but -optimize is broken,
216 // use optimizeTransparency instead (bug 11822)
217 if ( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
218 $animation_post = '-fuzz 5% -layers optimizeTransparency +map';
223 // Use one thread only, to avoid deadlock bugs on OOM
224 $env = array( 'OMP_NUM_THREADS' => 1 );
225 if ( strval( $wgImageMagickTempDir ) !== '' ) {
226 $env['MAGICK_TMPDIR'] = $wgImageMagickTempDir;
229 $cmd =
230 wfEscapeShellArg( $wgImageMagickConvertCommand ) .
231 // Specify white background color, will be used for transparent images
232 // in Internet Explorer/Windows instead of default black.
233 " {$quality} -background white" .
234 " {$decoderHint} " .
235 wfEscapeShellArg( $this->escapeMagickInput( $params['srcPath'], $scene ) ) .
236 " {$animation_pre}" .
237 // For the -thumbnail option a "!" is needed to force exact size,
238 // or ImageMagick may decide your ratio is wrong and slice off
239 // a pixel.
240 " -thumbnail " . wfEscapeShellArg( "{$params['physicalDimensions']}!" ) .
241 // Add the source url as a comment to the thumb.
242 " -set comment " . wfEscapeShellArg( $this->escapeMagickProperty( $params['comment'] ) ) .
243 " -depth 8 $sharpen" .
244 " {$animation_post} " .
245 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) ) . " 2>&1";
247 wfDebug( __METHOD__ . ": running ImageMagick: $cmd\n" );
248 wfProfileIn( 'convert' );
249 $retval = 0;
250 $err = wfShellExec( $cmd, $retval, $env );
251 wfProfileOut( 'convert' );
253 if ( $retval !== 0 ) {
254 $this->logErrorForExternalProcess( $retval, $err, $cmd );
255 return $this->getMediaTransformError( $params, $err );
258 return false; # No error
262 * Transform an image using a custom command
264 * @param $image File File associated with this thumbnail
265 * @param $params array Array with scaler params
267 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
269 protected function transformCustom( $image, $params ) {
270 # Use a custom convert command
271 global $wgCustomConvertCommand;
273 # Variables: %s %d %w %h
274 $src = wfEscapeShellArg( $params['srcPath'] );
275 $dst = wfEscapeShellArg( $params['dstPath'] );
276 $cmd = $wgCustomConvertCommand;
277 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
278 $cmd = str_replace( '%h', $params['physicalHeight'],
279 str_replace( '%w', $params['physicalWidth'], $cmd ) ); # Size
280 wfDebug( __METHOD__ . ": Running custom convert command $cmd\n" );
281 wfProfileIn( 'convert' );
282 $retval = 0;
283 $err = wfShellExec( $cmd, $retval );
284 wfProfileOut( 'convert' );
286 if ( $retval !== 0 ) {
287 $this->logErrorForExternalProcess( $retval, $err, $cmd );
288 return $this->getMediaTransformError( $params, $err );
290 return false; # No error
294 * Log an error that occured in an external process
296 * @param $retval int
297 * @param $err int
298 * @param $cmd string
300 protected function logErrorForExternalProcess( $retval, $err, $cmd ) {
301 wfDebugLog( 'thumbnail',
302 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
303 wfHostname(), $retval, trim( $err ), $cmd ) );
306 * Get a MediaTransformError with error 'thumbnail_error'
308 * @param $params array Paramter array as passed to the transform* functions
309 * @param $errMsg string Error message
310 * @return MediaTransformError
312 protected function getMediaTransformError( $params, $errMsg ) {
313 return new MediaTransformError( 'thumbnail_error', $params['clientWidth'],
314 $params['clientHeight'], $errMsg );
318 * Transform an image using the built in GD library
320 * @param $image File File associated with this thumbnail
321 * @param $params array Array with scaler params
323 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
325 protected function transformGd( $image, $params ) {
326 # Use PHP's builtin GD library functions.
328 # First find out what kind of file this is, and select the correct
329 # input routine for this.
331 $typemap = array(
332 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
333 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( __CLASS__, 'imageJpegWrapper' ) ),
334 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
335 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
336 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
338 if ( !isset( $typemap[$params['mimeType']] ) ) {
339 $err = 'Image type not supported';
340 wfDebug( "$err\n" );
341 $errMsg = wfMsg ( 'thumbnail_image-type' );
342 return $this->getMediaTransformError( $params, $errMsg );
344 list( $loader, $colorStyle, $saveType ) = $typemap[$params['mimeType']];
346 if ( !function_exists( $loader ) ) {
347 $err = "Incomplete GD library configuration: missing function $loader";
348 wfDebug( "$err\n" );
349 $errMsg = wfMsg ( 'thumbnail_gd-library', $loader );
350 return $this->getMediaTransformError( $params, $errMsg );
353 if ( !file_exists( $params['srcPath'] ) ) {
354 $err = "File seems to be missing: {$params['srcPath']}";
355 wfDebug( "$err\n" );
356 $errMsg = wfMsg ( 'thumbnail_image-missing', $params['srcPath'] );
357 return $this->getMediaTransformError( $params, $errMsg );
360 $src_image = call_user_func( $loader, $params['srcPath'] );
361 $dst_image = imagecreatetruecolor( $params['physicalWidth'],
362 $params['physicalHeight'] );
364 // Initialise the destination image to transparent instead of
365 // the default solid black, to support PNG and GIF transparency nicely
366 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
367 imagecolortransparent( $dst_image, $background );
368 imagealphablending( $dst_image, false );
370 if ( $colorStyle == 'palette' ) {
371 // Don't resample for paletted GIF images.
372 // It may just uglify them, and completely breaks transparency.
373 imagecopyresized( $dst_image, $src_image,
374 0, 0, 0, 0,
375 $params['physicalWidth'], $params['physicalHeight'],
376 imagesx( $src_image ), imagesy( $src_image ) );
377 } else {
378 imagecopyresampled( $dst_image, $src_image,
379 0, 0, 0, 0,
380 $params['physicalWidth'], $params['physicalHeight'],
381 imagesx( $src_image ), imagesy( $src_image ) );
384 imagesavealpha( $dst_image, true );
386 call_user_func( $saveType, $dst_image, $params['dstPath'] );
387 imagedestroy( $dst_image );
388 imagedestroy( $src_image );
390 return false; # No error
394 * Escape a string for ImageMagick's property input (e.g. -set -comment)
395 * See InterpretImageProperties() in magick/property.c
397 function escapeMagickProperty( $s ) {
398 // Double the backslashes
399 $s = str_replace( '\\', '\\\\', $s );
400 // Double the percents
401 $s = str_replace( '%', '%%', $s );
402 // Escape initial - or @
403 if ( strlen( $s ) > 0 && ( $s[0] === '-' || $s[0] === '@' ) ) {
404 $s = '\\' . $s;
406 return $s;
410 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
411 * and GetPathComponent() in magick/utility.c.
413 * This won't work with an initial ~ or @, so input files should be prefixed
414 * with the directory name.
416 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
417 * it's broken in a way that doesn't involve trying to convert every file
418 * in a directory, so we're better off escaping and waiting for the bugfix
419 * to filter down to users.
421 * @param $path string The file path
422 * @param $scene string The scene specification, or false if there is none
424 function escapeMagickInput( $path, $scene = false ) {
425 # Die on initial metacharacters (caller should prepend path)
426 $firstChar = substr( $path, 0, 1 );
427 if ( $firstChar === '~' || $firstChar === '@' ) {
428 throw new MWException( __METHOD__ . ': cannot escape this path name' );
431 # Escape glob chars
432 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
434 return $this->escapeMagickPath( $path, $scene );
438 * Escape a string for ImageMagick's output filename. See
439 * InterpretImageFilename() in magick/image.c.
441 function escapeMagickOutput( $path, $scene = false ) {
442 $path = str_replace( '%', '%%', $path );
443 return $this->escapeMagickPath( $path, $scene );
447 * Armour a string against ImageMagick's GetPathComponent(). This is a
448 * helper function for escapeMagickInput() and escapeMagickOutput().
450 * @param $path string The file path
451 * @param $scene string The scene specification, or false if there is none
453 protected function escapeMagickPath( $path, $scene = false ) {
454 # Die on format specifiers (other than drive letters). The regex is
455 # meant to match all the formats you get from "convert -list format"
456 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
457 if ( wfIsWindows() && is_dir( $m[0] ) ) {
458 // OK, it's a drive letter
459 // ImageMagick has a similar exception, see IsMagickConflict()
460 } else {
461 throw new MWException( __METHOD__ . ': unexpected colon character in path name' );
465 # If there are square brackets, add a do-nothing scene specification
466 # to force a literal interpretation
467 if ( $scene === false ) {
468 if ( strpos( $path, '[' ) !== false ) {
469 $path .= '[0--1]';
471 } else {
472 $path .= "[$scene]";
474 return $path;
478 * Retrieve the version of the installed ImageMagick
479 * You can use PHPs version_compare() to use this value
480 * Value is cached for one hour.
481 * @return String representing the IM version.
483 protected function getMagickVersion() {
484 global $wgMemc;
486 $cache = $wgMemc->get( "imagemagick-version" );
487 if ( !$cache ) {
488 global $wgImageMagickConvertCommand;
489 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
490 wfDebug( __METHOD__ . ": Running convert -version\n" );
491 $retval = '';
492 $return = wfShellExec( $cmd, $retval );
493 $x = preg_match( '/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches );
494 if ( $x != 1 ) {
495 wfDebug( __METHOD__ . ": ImageMagick version check failed\n" );
496 return null;
498 $wgMemc->set( "imagemagick-version", $matches[1], 3600 );
499 return $matches[1];
501 return $cache;
504 static function imageJpegWrapper( $dst_image, $thumbPath ) {
505 imageinterlace( $dst_image );
506 imagejpeg( $dst_image, $thumbPath, 95 );
510 function getMetadata( $image, $filename ) {
511 global $wgShowEXIF;
512 if ( $wgShowEXIF && file_exists( $filename ) ) {
513 $exif = new Exif( $filename );
514 $data = $exif->getFilteredData();
515 if ( $data ) {
516 $data['MEDIAWIKI_EXIF_VERSION'] = Exif::version();
517 return serialize( $data );
518 } else {
519 return '0';
521 } else {
522 return '';
526 function getMetadataType( $image ) {
527 return 'exif';
530 function isMetadataValid( $image, $metadata ) {
531 global $wgShowEXIF;
532 if ( !$wgShowEXIF ) {
533 # Metadata disabled and so an empty field is expected
534 return true;
536 if ( $metadata === '0' ) {
537 # Special value indicating that there is no EXIF data in the file
538 return true;
540 wfSuppressWarnings();
541 $exif = unserialize( $metadata );
542 wfRestoreWarnings();
543 if ( !isset( $exif['MEDIAWIKI_EXIF_VERSION'] ) ||
544 $exif['MEDIAWIKI_EXIF_VERSION'] != Exif::version() )
546 # Wrong version
547 wfDebug( __METHOD__ . ": wrong version\n" );
548 return false;
550 return true;
554 * Get a list of EXIF metadata items which should be displayed when
555 * the metadata table is collapsed.
557 * @return array of strings
558 * @access private
560 function visibleMetadataFields() {
561 $fields = array();
562 $lines = explode( "\n", wfMsgForContent( 'metadata-fields' ) );
563 foreach ( $lines as $line ) {
564 $matches = array();
565 if ( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
566 $fields[] = $matches[1];
569 $fields = array_map( 'strtolower', $fields );
570 return $fields;
573 function formatMetadata( $image ) {
574 $result = array(
575 'visible' => array(),
576 'collapsed' => array()
578 $metadata = $image->getMetadata();
579 if ( !$metadata ) {
580 return false;
582 $exif = unserialize( $metadata );
583 if ( !$exif ) {
584 return false;
586 unset( $exif['MEDIAWIKI_EXIF_VERSION'] );
587 $format = new FormatExif( $exif );
589 $formatted = $format->getFormattedData();
590 // Sort fields into visible and collapsed
591 $visibleFields = $this->visibleMetadataFields();
592 foreach ( $formatted as $name => $value ) {
593 $tag = strtolower( $name );
594 self::addMeta( $result,
595 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
596 'exif',
597 $tag,
598 $value
601 return $result;