Add a Skins category to Special:Version.
[lhc/web/wiklou.git] / includes / media / Bitmap.php
1 <?php
2 /**
3 * Generic handler for bitmap images
4 *
5 * @file
6 * @ingroup Media
7 */
8
9 /**
10 * Generic handler for bitmap images
11 *
12 * @ingroup Media
13 */
14 class BitmapHandler extends ImageHandler {
15 function normaliseParams( $image, &$params ) {
16 global $wgMaxImageArea;
17 if ( !parent::normaliseParams( $image, $params ) ) {
18 return false;
19 }
20
21 $mimeType = $image->getMimeType();
22 $srcWidth = $image->getWidth( $params['page'] );
23 $srcHeight = $image->getHeight( $params['page'] );
24
25 # Don't make an image bigger than the source
26 $params['physicalWidth'] = $params['width'];
27 $params['physicalHeight'] = $params['height'];
28
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;
35 }
36
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 )
43 {
44 return false;
45 }
46
47 return true;
48 }
49
50
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;
55 }
56
57 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
58 global $wgUseImageMagick;
59 global $wgCustomConvertCommand, $wgUseImageResize;
60
61 if ( !$this->normaliseParams( $image, $params ) ) {
62 return new TransformParameterError( $params );
63 }
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,
82 );
83
84 wfDebug( __METHOD__ . ": creating {$scalerParams['physicalDimensions']} thumbnail at $dstPath\n" );
85
86 if ( !$image->mustRender() &&
87 $scalerParams['physicalWidth'] == $scalerParams['srcWidth']
88 && $scalerParams['physicalHeight'] == $scalerParams['srcHeight'] ) {
89
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 );
93 }
94
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';
109 }
110 wfDebug( __METHOD__ . ": scaler $scaler\n" );
111
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 );
116 }
117
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 );
122 }
123
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 );
128 }
129
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;
141 }
142
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 );
155 }
156 }
157
158 /**
159 * Get a ThumbnailImage that respresents an image that will be scaled
160 * client side
161 *
162 * @param $image File File associated with this thumbnail
163 * @param $params array Array with scaler params
164 * @return ThumbnailImage
165 */
166 protected function getClientScalingThumbnailImage( $image, $params ) {
167 return new ThumbnailImage( $image, $image->getURL(),
168 $params['clientWidth'], $params['clientHeight'], $params['srcPath'] );
169 }
170
171 /**
172 * Transform an image using ImageMagick
173 *
174 * @param $image File File associated with this thumbnail
175 * @param $params array Array with scaler params
176 *
177 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
178 */
179 protected function transformImageMagick( $image, $params ) {
180 # use ImageMagick
181 global $wgSharpenReductionThreshold, $wgSharpenParameter,
182 $wgMaxAnimatedGifArea,
183 $wgImageMagickTempDir, $wgImageMagickConvertCommand;
184
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 );
198 }
199 // JPEG decoder hint to reduce memory, available since IM 6.5.6-2
200 $decoderHint = "-define jpeg:size={$params['physicalDimensions']}";
201
202 } elseif ( $params['mimeType'] == 'image/png' ) {
203 $quality = "-quality 95"; // zlib 9, adaptive filtering
204
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;
211
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';
219 }
220 }
221 }
222
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;
227 }
228
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, but don't add the flag if there's no comment
242 ( $params['comment'] !== ''
243 ? " -set comment " . wfEscapeShellArg( $this->escapeMagickProperty( $params['comment'] ) )
244 : '' ) .
245 " -depth 8 $sharpen" .
246 " {$animation_post} " .
247 wfEscapeShellArg( $this->escapeMagickOutput( $params['dstPath'] ) ) . " 2>&1";
248
249 wfDebug( __METHOD__ . ": running ImageMagick: $cmd\n" );
250 wfProfileIn( 'convert' );
251 $retval = 0;
252 $err = wfShellExec( $cmd, $retval, $env );
253 wfProfileOut( 'convert' );
254
255 if ( $retval !== 0 ) {
256 $this->logErrorForExternalProcess( $retval, $err, $cmd );
257 return $this->getMediaTransformError( $params, $err );
258 }
259
260 return false; # No error
261 }
262
263 /**
264 * Transform an image using a custom command
265 *
266 * @param $image File File associated with this thumbnail
267 * @param $params array Array with scaler params
268 *
269 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
270 */
271 protected function transformCustom( $image, $params ) {
272 # Use a custom convert command
273 global $wgCustomConvertCommand;
274
275 # Variables: %s %d %w %h
276 $src = wfEscapeShellArg( $params['srcPath'] );
277 $dst = wfEscapeShellArg( $params['dstPath'] );
278 $cmd = $wgCustomConvertCommand;
279 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
280 $cmd = str_replace( '%h', $params['physicalHeight'],
281 str_replace( '%w', $params['physicalWidth'], $cmd ) ); # Size
282 wfDebug( __METHOD__ . ": Running custom convert command $cmd\n" );
283 wfProfileIn( 'convert' );
284 $retval = 0;
285 $err = wfShellExec( $cmd, $retval );
286 wfProfileOut( 'convert' );
287
288 if ( $retval !== 0 ) {
289 $this->logErrorForExternalProcess( $retval, $err, $cmd );
290 return $this->getMediaTransformError( $params, $err );
291 }
292 return false; # No error
293 }
294
295 /**
296 * Log an error that occured in an external process
297 *
298 * @param $retval int
299 * @param $err int
300 * @param $cmd string
301 */
302 protected function logErrorForExternalProcess( $retval, $err, $cmd ) {
303 wfDebugLog( 'thumbnail',
304 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
305 wfHostname(), $retval, trim( $err ), $cmd ) );
306 }
307 /**
308 * Get a MediaTransformError with error 'thumbnail_error'
309 *
310 * @param $params array Parameter array as passed to the transform* functions
311 * @param $errMsg string Error message
312 * @return MediaTransformError
313 */
314 protected function getMediaTransformError( $params, $errMsg ) {
315 return new MediaTransformError( 'thumbnail_error', $params['clientWidth'],
316 $params['clientHeight'], $errMsg );
317 }
318
319 /**
320 * Transform an image using the built in GD library
321 *
322 * @param $image File File associated with this thumbnail
323 * @param $params array Array with scaler params
324 *
325 * @return MediaTransformError Error object if error occured, false (=no error) otherwise
326 */
327 protected function transformGd( $image, $params ) {
328 # Use PHP's builtin GD library functions.
329 #
330 # First find out what kind of file this is, and select the correct
331 # input routine for this.
332
333 $typemap = array(
334 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
335 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( __CLASS__, 'imageJpegWrapper' ) ),
336 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
337 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
338 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
339 );
340 if ( !isset( $typemap[$params['mimeType']] ) ) {
341 $err = 'Image type not supported';
342 wfDebug( "$err\n" );
343 $errMsg = wfMsg ( 'thumbnail_image-type' );
344 return $this->getMediaTransformError( $params, $errMsg );
345 }
346 list( $loader, $colorStyle, $saveType ) = $typemap[$params['mimeType']];
347
348 if ( !function_exists( $loader ) ) {
349 $err = "Incomplete GD library configuration: missing function $loader";
350 wfDebug( "$err\n" );
351 $errMsg = wfMsg ( 'thumbnail_gd-library', $loader );
352 return $this->getMediaTransformError( $params, $errMsg );
353 }
354
355 if ( !file_exists( $params['srcPath'] ) ) {
356 $err = "File seems to be missing: {$params['srcPath']}";
357 wfDebug( "$err\n" );
358 $errMsg = wfMsg ( 'thumbnail_image-missing', $params['srcPath'] );
359 return $this->getMediaTransformError( $params, $errMsg );
360 }
361
362 $src_image = call_user_func( $loader, $params['srcPath'] );
363 $dst_image = imagecreatetruecolor( $params['physicalWidth'],
364 $params['physicalHeight'] );
365
366 // Initialise the destination image to transparent instead of
367 // the default solid black, to support PNG and GIF transparency nicely
368 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
369 imagecolortransparent( $dst_image, $background );
370 imagealphablending( $dst_image, false );
371
372 if ( $colorStyle == 'palette' ) {
373 // Don't resample for paletted GIF images.
374 // It may just uglify them, and completely breaks transparency.
375 imagecopyresized( $dst_image, $src_image,
376 0, 0, 0, 0,
377 $params['physicalWidth'], $params['physicalHeight'],
378 imagesx( $src_image ), imagesy( $src_image ) );
379 } else {
380 imagecopyresampled( $dst_image, $src_image,
381 0, 0, 0, 0,
382 $params['physicalWidth'], $params['physicalHeight'],
383 imagesx( $src_image ), imagesy( $src_image ) );
384 }
385
386 imagesavealpha( $dst_image, true );
387
388 call_user_func( $saveType, $dst_image, $params['dstPath'] );
389 imagedestroy( $dst_image );
390 imagedestroy( $src_image );
391
392 return false; # No error
393 }
394
395 /**
396 * Escape a string for ImageMagick's property input (e.g. -set -comment)
397 * See InterpretImageProperties() in magick/property.c
398 */
399 function escapeMagickProperty( $s ) {
400 // Double the backslashes
401 $s = str_replace( '\\', '\\\\', $s );
402 // Double the percents
403 $s = str_replace( '%', '%%', $s );
404 // Escape initial - or @
405 if ( strlen( $s ) > 0 && ( $s[0] === '-' || $s[0] === '@' ) ) {
406 $s = '\\' . $s;
407 }
408 return $s;
409 }
410
411 /**
412 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
413 * and GetPathComponent() in magick/utility.c.
414 *
415 * This won't work with an initial ~ or @, so input files should be prefixed
416 * with the directory name.
417 *
418 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
419 * it's broken in a way that doesn't involve trying to convert every file
420 * in a directory, so we're better off escaping and waiting for the bugfix
421 * to filter down to users.
422 *
423 * @param $path string The file path
424 * @param $scene string The scene specification, or false if there is none
425 */
426 function escapeMagickInput( $path, $scene = false ) {
427 # Die on initial metacharacters (caller should prepend path)
428 $firstChar = substr( $path, 0, 1 );
429 if ( $firstChar === '~' || $firstChar === '@' ) {
430 throw new MWException( __METHOD__ . ': cannot escape this path name' );
431 }
432
433 # Escape glob chars
434 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
435
436 return $this->escapeMagickPath( $path, $scene );
437 }
438
439 /**
440 * Escape a string for ImageMagick's output filename. See
441 * InterpretImageFilename() in magick/image.c.
442 */
443 function escapeMagickOutput( $path, $scene = false ) {
444 $path = str_replace( '%', '%%', $path );
445 return $this->escapeMagickPath( $path, $scene );
446 }
447
448 /**
449 * Armour a string against ImageMagick's GetPathComponent(). This is a
450 * helper function for escapeMagickInput() and escapeMagickOutput().
451 *
452 * @param $path string The file path
453 * @param $scene string The scene specification, or false if there is none
454 */
455 protected function escapeMagickPath( $path, $scene = false ) {
456 # Die on format specifiers (other than drive letters). The regex is
457 # meant to match all the formats you get from "convert -list format"
458 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
459 if ( wfIsWindows() && is_dir( $m[0] ) ) {
460 // OK, it's a drive letter
461 // ImageMagick has a similar exception, see IsMagickConflict()
462 } else {
463 throw new MWException( __METHOD__ . ': unexpected colon character in path name' );
464 }
465 }
466
467 # If there are square brackets, add a do-nothing scene specification
468 # to force a literal interpretation
469 if ( $scene === false ) {
470 if ( strpos( $path, '[' ) !== false ) {
471 $path .= '[0--1]';
472 }
473 } else {
474 $path .= "[$scene]";
475 }
476 return $path;
477 }
478
479 /**
480 * Retrieve the version of the installed ImageMagick
481 * You can use PHPs version_compare() to use this value
482 * Value is cached for one hour.
483 * @return String representing the IM version.
484 */
485 protected function getMagickVersion() {
486 global $wgMemc;
487
488 $cache = $wgMemc->get( "imagemagick-version" );
489 if ( !$cache ) {
490 global $wgImageMagickConvertCommand;
491 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
492 wfDebug( __METHOD__ . ": Running convert -version\n" );
493 $retval = '';
494 $return = wfShellExec( $cmd, $retval );
495 $x = preg_match( '/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches );
496 if ( $x != 1 ) {
497 wfDebug( __METHOD__ . ": ImageMagick version check failed\n" );
498 return null;
499 }
500 $wgMemc->set( "imagemagick-version", $matches[1], 3600 );
501 return $matches[1];
502 }
503 return $cache;
504 }
505
506 static function imageJpegWrapper( $dst_image, $thumbPath ) {
507 imageinterlace( $dst_image );
508 imagejpeg( $dst_image, $thumbPath, 95 );
509 }
510
511
512 function getMetadata( $image, $filename ) {
513 global $wgShowEXIF;
514 if ( $wgShowEXIF && file_exists( $filename ) ) {
515 $exif = new Exif( $filename );
516 $data = $exif->getFilteredData();
517 if ( $data ) {
518 $data['MEDIAWIKI_EXIF_VERSION'] = Exif::version();
519 return serialize( $data );
520 } else {
521 return '0';
522 }
523 } else {
524 return '';
525 }
526 }
527
528 function getMetadataType( $image ) {
529 return 'exif';
530 }
531
532 function isMetadataValid( $image, $metadata ) {
533 global $wgShowEXIF;
534 if ( !$wgShowEXIF ) {
535 # Metadata disabled and so an empty field is expected
536 return true;
537 }
538 if ( $metadata === '0' ) {
539 # Special value indicating that there is no EXIF data in the file
540 return true;
541 }
542 wfSuppressWarnings();
543 $exif = unserialize( $metadata );
544 wfRestoreWarnings();
545 if ( !isset( $exif['MEDIAWIKI_EXIF_VERSION'] ) ||
546 $exif['MEDIAWIKI_EXIF_VERSION'] != Exif::version() )
547 {
548 # Wrong version
549 wfDebug( __METHOD__ . ": wrong version\n" );
550 return false;
551 }
552 return true;
553 }
554
555 /**
556 * Get a list of EXIF metadata items which should be displayed when
557 * the metadata table is collapsed.
558 *
559 * @return array of strings
560 * @access private
561 */
562 function visibleMetadataFields() {
563 $fields = array();
564 $lines = explode( "\n", wfMsgForContent( 'metadata-fields' ) );
565 foreach ( $lines as $line ) {
566 $matches = array();
567 if ( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
568 $fields[] = $matches[1];
569 }
570 }
571 $fields = array_map( 'strtolower', $fields );
572 return $fields;
573 }
574
575 function formatMetadata( $image ) {
576 $result = array(
577 'visible' => array(),
578 'collapsed' => array()
579 );
580 $metadata = $image->getMetadata();
581 if ( !$metadata ) {
582 return false;
583 }
584 $exif = unserialize( $metadata );
585 if ( !$exif ) {
586 return false;
587 }
588 unset( $exif['MEDIAWIKI_EXIF_VERSION'] );
589 $format = new FormatExif( $exif );
590
591 $formatted = $format->getFormattedData();
592 // Sort fields into visible and collapsed
593 $visibleFields = $this->visibleMetadataFields();
594 foreach ( $formatted as $name => $value ) {
595 $tag = strtolower( $name );
596 self::addMeta( $result,
597 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
598 'exif',
599 $tag,
600 $value
601 );
602 }
603 return $result;
604 }
605 }