r71546 broke imagemagick usage in Windows, since cmd.exe takes the variable
[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 if ( $mimeType !== 'image/jpeg' &&
41 $srcWidth * $srcHeight > $wgMaxImageArea )
42 {
43 return false;
44 }
45
46 return true;
47 }
48
49
50 // Function that returns the number of pixels to be thumbnailed.
51 // Intended for animated GIFs to multiply by the number of frames.
52 function getImageArea( $image, $width, $height ) {
53 return $width * $height;
54 }
55
56 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
57 global $wgUseImageMagick, $wgImageMagickConvertCommand, $wgImageMagickTempDir;
58 global $wgCustomConvertCommand, $wgUseImageResize;
59 global $wgSharpenParameter, $wgSharpenReductionThreshold;
60 global $wgMaxAnimatedGifArea;
61
62 if ( !$this->normaliseParams( $image, $params ) ) {
63 return new TransformParameterError( $params );
64 }
65 $physicalWidth = $params['physicalWidth'];
66 $physicalHeight = $params['physicalHeight'];
67 $clientWidth = $params['width'];
68 $clientHeight = $params['height'];
69 $comment = isset( $params['descriptionUrl'] ) ? "File source: ". $params['descriptionUrl'] : '';
70 $srcWidth = $image->getWidth();
71 $srcHeight = $image->getHeight();
72 $mimeType = $image->getMimeType();
73 $srcPath = $image->getPath();
74 $retval = 0;
75 wfDebug( __METHOD__.": creating {$physicalWidth}x{$physicalHeight} thumbnail at $dstPath\n" );
76
77 if ( !$image->mustRender() && $physicalWidth == $srcWidth && $physicalHeight == $srcHeight ) {
78 # normaliseParams (or the user) wants us to return the unscaled image
79 wfDebug( __METHOD__.": returning unscaled image\n" );
80 return new ThumbnailImage( $image, $image->getURL(), $clientWidth, $clientHeight, $srcPath );
81 }
82
83 if ( !$dstPath ) {
84 // No output path available, client side scaling only
85 $scaler = 'client';
86 } elseif( !$wgUseImageResize ) {
87 $scaler = 'client';
88 } elseif ( $wgUseImageMagick ) {
89 $scaler = 'im';
90 } elseif ( $wgCustomConvertCommand ) {
91 $scaler = 'custom';
92 } elseif ( function_exists( 'imagecreatetruecolor' ) ) {
93 $scaler = 'gd';
94 } else {
95 $scaler = 'client';
96 }
97 wfDebug( __METHOD__.": scaler $scaler\n" );
98
99 if ( $scaler == 'client' ) {
100 # Client-side image scaling, use the source URL
101 # Using the destination URL in a TRANSFORM_LATER request would be incorrect
102 return new ThumbnailImage( $image, $image->getURL(), $clientWidth, $clientHeight, $srcPath );
103 }
104
105 if ( $flags & self::TRANSFORM_LATER ) {
106 wfDebug( __METHOD__.": Transforming later per flags.\n" );
107 return new ThumbnailImage( $image, $dstUrl, $clientWidth, $clientHeight, $dstPath );
108 }
109
110 if ( !wfMkdirParents( dirname( $dstPath ) ) ) {
111 wfDebug( __METHOD__.": Unable to create thumbnail destination directory, falling back to client scaling\n" );
112 return new ThumbnailImage( $image, $image->getURL(), $clientWidth, $clientHeight, $srcPath );
113 }
114
115 if ( $scaler == 'im' ) {
116 # use ImageMagick
117
118 $quality = '';
119 $sharpen = '';
120 $scene = false;
121 $animation_pre = '';
122 $animation_post = '';
123 $decoderHint = '';
124 if ( $mimeType == 'image/jpeg' ) {
125 $quality = "-quality 80"; // 80%
126 # Sharpening, see bug 6193
127 if ( ( $physicalWidth + $physicalHeight ) / ( $srcWidth + $srcHeight ) < $wgSharpenReductionThreshold ) {
128 $sharpen = "-sharpen " . wfEscapeShellArg( $wgSharpenParameter );
129 }
130 // JPEG decoder hint to reduce memory, available since IM 6.5.6-2
131 $decoderHint = "-define jpeg:size={$physicalWidth}x{$physicalHeight}";
132 } elseif ( $mimeType == 'image/png' ) {
133 $quality = "-quality 95"; // zlib 9, adaptive filtering
134 } elseif( $mimeType == 'image/gif' ) {
135 if( $this->getImageArea( $image, $srcWidth, $srcHeight ) > $wgMaxAnimatedGifArea ) {
136 // Extract initial frame only; we're so big it'll
137 // be a total drag. :P
138 $scene = 0;
139 } elseif( $this->isAnimatedImage( $image ) ) {
140 // Coalesce is needed to scale animated GIFs properly (bug 1017).
141 $animation_pre = '-coalesce';
142 // We optimize the output, but -optimize is broken,
143 // use optimizeTransparency instead (bug 11822)
144 if( version_compare( $this->getMagickVersion(), "6.3.5" ) >= 0 ) {
145 $animation_post = '-fuzz 5% -layers optimizeTransparency +map';
146 }
147 }
148 }
149
150 // Use one thread only, to avoid deadlock bugs on OOM
151 $tempEnv = 'OMP_NUM_THREADS=1 ';
152 if ( strval( $wgImageMagickTempDir ) !== '' ) {
153 $tempEnv .= 'MAGICK_TMPDIR=' . wfEscapeShellArg( $wgImageMagickTempDir ) . ' ';
154 }
155
156 $cmd =
157 wfEscapeShellArg( $wgImageMagickConvertCommand ) .
158 // Specify white background color, will be used for transparent images
159 // in Internet Explorer/Windows instead of default black.
160 " {$quality} -background white".
161 " {$decoderHint} " .
162 wfEscapeShellArg( $this->escapeMagickInput( $srcPath, $scene ) ) .
163 " {$animation_pre}" .
164 // For the -thumbnail option a "!" is needed to force exact size,
165 // or ImageMagick may decide your ratio is wrong and slice off
166 // a pixel.
167 " -thumbnail " . wfEscapeShellArg( "{$physicalWidth}x{$physicalHeight}!" ) .
168 // Add the source url as a comment to the thumb.
169 " -set comment " . wfEscapeShellArg( $this->escapeMagickProperty( $comment ) ) .
170 " -depth 8 $sharpen" .
171 " {$animation_post} " .
172 wfEscapeShellArg( $this->escapeMagickOutput( $dstPath ) ) . " 2>&1";
173
174 if ( !wfIsWindows() ) {
175 // Assume we have a POSIX compliant shell which accepts variable assignments preceding the command
176 $cmd = $tempEnv . $cmd;
177 }
178
179 wfDebug( __METHOD__.": running ImageMagick: $cmd\n" );
180 wfProfileIn( 'convert' );
181 $err = wfShellExec( $cmd, $retval );
182 wfProfileOut( 'convert' );
183 } elseif( $scaler == 'custom' ) {
184 # Use a custom convert command
185 # Variables: %s %d %w %h
186 $src = wfEscapeShellArg( $srcPath );
187 $dst = wfEscapeShellArg( $dstPath );
188 $cmd = $wgCustomConvertCommand;
189 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
190 $cmd = str_replace( '%h', $physicalHeight, str_replace( '%w', $physicalWidth, $cmd ) ); # Size
191 wfDebug( __METHOD__.": Running custom convert command $cmd\n" );
192 wfProfileIn( 'convert' );
193 $err = wfShellExec( $cmd, $retval );
194 wfProfileOut( 'convert' );
195 } else /* $scaler == 'gd' */ {
196 # Use PHP's builtin GD library functions.
197 #
198 # First find out what kind of file this is, and select the correct
199 # input routine for this.
200
201 $typemap = array(
202 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
203 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( __CLASS__, 'imageJpegWrapper' ) ),
204 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
205 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
206 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
207 );
208 if( !isset( $typemap[$mimeType] ) ) {
209 $err = 'Image type not supported';
210 wfDebug( "$err\n" );
211 $errMsg = wfMsg ( 'thumbnail_image-type' );
212 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
213 }
214 list( $loader, $colorStyle, $saveType ) = $typemap[$mimeType];
215
216 if( !function_exists( $loader ) ) {
217 $err = "Incomplete GD library configuration: missing function $loader";
218 wfDebug( "$err\n" );
219 $errMsg = wfMsg ( 'thumbnail_gd-library', $loader );
220 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
221 }
222
223 if ( !file_exists( $srcPath ) ) {
224 $err = "File seems to be missing: $srcPath";
225 wfDebug( "$err\n" );
226 $errMsg = wfMsg ( 'thumbnail_image-missing', $srcPath );
227 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
228 }
229
230 $src_image = call_user_func( $loader, $srcPath );
231 $dst_image = imagecreatetruecolor( $physicalWidth, $physicalHeight );
232
233 // Initialise the destination image to transparent instead of
234 // the default solid black, to support PNG and GIF transparency nicely
235 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
236 imagecolortransparent( $dst_image, $background );
237 imagealphablending( $dst_image, false );
238
239 if( $colorStyle == 'palette' ) {
240 // Don't resample for paletted GIF images.
241 // It may just uglify them, and completely breaks transparency.
242 imagecopyresized( $dst_image, $src_image,
243 0,0,0,0,
244 $physicalWidth, $physicalHeight, imagesx( $src_image ), imagesy( $src_image ) );
245 } else {
246 imagecopyresampled( $dst_image, $src_image,
247 0,0,0,0,
248 $physicalWidth, $physicalHeight, imagesx( $src_image ), imagesy( $src_image ) );
249 }
250
251 imagesavealpha( $dst_image, true );
252
253 call_user_func( $saveType, $dst_image, $dstPath );
254 imagedestroy( $dst_image );
255 imagedestroy( $src_image );
256 $retval = 0;
257 }
258
259 $removed = $this->removeBadFile( $dstPath, $retval );
260 if ( $retval != 0 || $removed ) {
261 wfDebugLog( 'thumbnail',
262 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
263 wfHostname(), $retval, trim($err), $cmd ) );
264 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
265 } else {
266 return new ThumbnailImage( $image, $dstUrl, $clientWidth, $clientHeight, $dstPath );
267 }
268 }
269
270 /**
271 * Escape a string for ImageMagick's property input (e.g. -set -comment)
272 * See InterpretImageProperties() in magick/property.c
273 */
274 function escapeMagickProperty( $s ) {
275 // Double the backslashes
276 $s = str_replace( '\\', '\\\\', $s );
277 // Double the percents
278 $s = str_replace( '%', '%%', $s );
279 // Escape initial - or @
280 if ( strlen( $s ) > 0 && ( $s[0] === '-' || $s[0] === '@' ) ) {
281 $s = '\\' . $s;
282 }
283 return $s;
284 }
285
286 /**
287 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
288 * and GetPathComponent() in magick/utility.c.
289 *
290 * This won't work with an initial ~ or @, so input files should be prefixed
291 * with the directory name.
292 *
293 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
294 * it's broken in a way that doesn't involve trying to convert every file
295 * in a directory, so we're better off escaping and waiting for the bugfix
296 * to filter down to users.
297 *
298 * @param $path string The file path
299 * @param $scene string The scene specification, or false if there is none
300 */
301 function escapeMagickInput( $path, $scene = false ) {
302 # Die on initial metacharacters (caller should prepend path)
303 $firstChar = substr( $path, 0, 1 );
304 if ( $firstChar === '~' || $firstChar === '@' ) {
305 throw new MWException( __METHOD__.': cannot escape this path name' );
306 }
307
308 # Escape glob chars
309 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
310
311 return $this->escapeMagickPath( $path, $scene );
312 }
313
314 /**
315 * Escape a string for ImageMagick's output filename. See
316 * InterpretImageFilename() in magick/image.c.
317 */
318 function escapeMagickOutput( $path, $scene = false ) {
319 $path = str_replace( '%', '%%', $path );
320 return $this->escapeMagickPath( $path, $scene );
321 }
322
323 /**
324 * Armour a string against ImageMagick's GetPathComponent(). This is a
325 * helper function for escapeMagickInput() and escapeMagickOutput().
326 *
327 * @param $path string The file path
328 * @param $scene string The scene specification, or false if there is none
329 */
330 protected function escapeMagickPath( $path, $scene = false ) {
331 # Die on format specifiers (other than drive letters). The regex is
332 # meant to match all the formats you get from "convert -list format"
333 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
334 if ( wfIsWindows() && is_dir( $m[0] ) ) {
335 // OK, it's a drive letter
336 // ImageMagick has a similar exception, see IsMagickConflict()
337 } else {
338 throw new MWException( __METHOD__.': unexpected colon character in path name' );
339 }
340 }
341
342 # If there are square brackets, add a do-nothing scene specification
343 # to force a literal interpretation
344 if ( $scene === false ) {
345 if ( strpos( $path, '[' ) !== false ) {
346 $path .= '[0--1]';
347 }
348 } else {
349 $path .= "[$scene]";
350 }
351 return $path;
352 }
353
354 /**
355 * Retrieve the version of the installed ImageMagick
356 * You can use PHPs version_compare() to use this value
357 * Value is cached for one hour.
358 * @return String representing the IM version.
359 */
360 protected function getMagickVersion() {
361 global $wgMemc;
362
363 $cache = $wgMemc->get( "imagemagick-version" );
364 if( !$cache ) {
365 global $wgImageMagickConvertCommand;
366 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
367 wfDebug( __METHOD__.": Running convert -version\n" );
368 $retval = '';
369 $return = wfShellExec( $cmd, $retval );
370 $x = preg_match('/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches);
371 if( $x != 1 ) {
372 wfDebug( __METHOD__.": ImageMagick version check failed\n" );
373 return null;
374 }
375 $wgMemc->set( "imagemagick-version", $matches[1], 3600 );
376 return $matches[1];
377 }
378 return $cache;
379 }
380
381 static function imageJpegWrapper( $dst_image, $thumbPath ) {
382 imageinterlace( $dst_image );
383 imagejpeg( $dst_image, $thumbPath, 95 );
384 }
385
386
387 function getMetadata( $image, $filename ) {
388 global $wgShowEXIF;
389 if( $wgShowEXIF && file_exists( $filename ) ) {
390 $exif = new Exif( $filename );
391 $data = $exif->getFilteredData();
392 if ( $data ) {
393 $data['MEDIAWIKI_EXIF_VERSION'] = Exif::version();
394 return serialize( $data );
395 } else {
396 return '0';
397 }
398 } else {
399 return '';
400 }
401 }
402
403 function getMetadataType( $image ) {
404 return 'exif';
405 }
406
407 function isMetadataValid( $image, $metadata ) {
408 global $wgShowEXIF;
409 if ( !$wgShowEXIF ) {
410 # Metadata disabled and so an empty field is expected
411 return true;
412 }
413 if ( $metadata === '0' ) {
414 # Special value indicating that there is no EXIF data in the file
415 return true;
416 }
417 wfSuppressWarnings();
418 $exif = unserialize( $metadata );
419 wfRestoreWarnings();
420 if ( !isset( $exif['MEDIAWIKI_EXIF_VERSION'] ) ||
421 $exif['MEDIAWIKI_EXIF_VERSION'] != Exif::version() )
422 {
423 # Wrong version
424 wfDebug( __METHOD__.": wrong version\n" );
425 return false;
426 }
427 return true;
428 }
429
430 /**
431 * Get a list of EXIF metadata items which should be displayed when
432 * the metadata table is collapsed.
433 *
434 * @return array of strings
435 * @access private
436 */
437 function visibleMetadataFields() {
438 $fields = array();
439 $lines = explode( "\n", wfMsgForContent( 'metadata-fields' ) );
440 foreach( $lines as $line ) {
441 $matches = array();
442 if( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
443 $fields[] = $matches[1];
444 }
445 }
446 $fields = array_map( 'strtolower', $fields );
447 return $fields;
448 }
449
450 function formatMetadata( $image ) {
451 $result = array(
452 'visible' => array(),
453 'collapsed' => array()
454 );
455 $metadata = $image->getMetadata();
456 if ( !$metadata ) {
457 return false;
458 }
459 $exif = unserialize( $metadata );
460 if ( !$exif ) {
461 return false;
462 }
463 unset( $exif['MEDIAWIKI_EXIF_VERSION'] );
464 $format = new FormatExif( $exif );
465
466 $formatted = $format->getFormattedData();
467 // Sort fields into visible and collapsed
468 $visibleFields = $this->visibleMetadataFields();
469 foreach ( $formatted as $name => $value ) {
470 $tag = strtolower( $name );
471 self::addMeta( $result,
472 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
473 'exif',
474 $tag,
475 $value
476 );
477 }
478 return $result;
479 }
480 }