Add some $retval = '' before some wfShellExec
[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 if ( strval( $wgImageMagickTempDir ) !== '' ) {
151 $tempEnv = 'MAGICK_TMPDIR=' . wfEscapeShellArg( $wgImageMagickTempDir ) . ' ';
152 } else {
153 $tempEnv = '';
154 }
155
156 $cmd =
157 $tempEnv .
158 // Use one thread only, to avoid deadlock bugs on OOM
159 'OMP_NUM_THREADS=1 ' .
160 wfEscapeShellArg( $wgImageMagickConvertCommand ) .
161 // Specify white background color, will be used for transparent images
162 // in Internet Explorer/Windows instead of default black.
163 " {$quality} -background white".
164 " {$decoderHint} " .
165 wfEscapeShellArg( $this->escapeMagickInput( $srcPath, $scene ) ) .
166 " {$animation_pre}" .
167 // For the -thumbnail option a "!" is needed to force exact size,
168 // or ImageMagick may decide your ratio is wrong and slice off
169 // a pixel.
170 " -thumbnail " . wfEscapeShellArg( "{$physicalWidth}x{$physicalHeight}!" ) .
171 // Add the source url as a comment to the thumb.
172 " -set comment " . wfEscapeShellArg( $this->escapeMagickProperty( $comment ) ) .
173 " -depth 8 $sharpen" .
174 " {$animation_post} " .
175 wfEscapeShellArg( $this->escapeMagickOutput( $dstPath ) ) . " 2>&1";
176 wfDebug( __METHOD__.": running ImageMagick: $cmd\n" );
177 wfProfileIn( 'convert' );
178 $err = wfShellExec( $cmd, $retval );
179 wfProfileOut( 'convert' );
180 } elseif( $scaler == 'custom' ) {
181 # Use a custom convert command
182 # Variables: %s %d %w %h
183 $src = wfEscapeShellArg( $srcPath );
184 $dst = wfEscapeShellArg( $dstPath );
185 $cmd = $wgCustomConvertCommand;
186 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
187 $cmd = str_replace( '%h', $physicalHeight, str_replace( '%w', $physicalWidth, $cmd ) ); # Size
188 wfDebug( __METHOD__.": Running custom convert command $cmd\n" );
189 wfProfileIn( 'convert' );
190 $err = wfShellExec( $cmd, $retval );
191 wfProfileOut( 'convert' );
192 } else /* $scaler == 'gd' */ {
193 # Use PHP's builtin GD library functions.
194 #
195 # First find out what kind of file this is, and select the correct
196 # input routine for this.
197
198 $typemap = array(
199 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
200 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( __CLASS__, 'imageJpegWrapper' ) ),
201 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
202 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
203 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
204 );
205 if( !isset( $typemap[$mimeType] ) ) {
206 $err = 'Image type not supported';
207 wfDebug( "$err\n" );
208 $errMsg = wfMsg ( 'thumbnail_image-type' );
209 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
210 }
211 list( $loader, $colorStyle, $saveType ) = $typemap[$mimeType];
212
213 if( !function_exists( $loader ) ) {
214 $err = "Incomplete GD library configuration: missing function $loader";
215 wfDebug( "$err\n" );
216 $errMsg = wfMsg ( 'thumbnail_gd-library', $loader );
217 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
218 }
219
220 if ( !file_exists( $srcPath ) ) {
221 $err = "File seems to be missing: $srcPath";
222 wfDebug( "$err\n" );
223 $errMsg = wfMsg ( 'thumbnail_image-missing', $srcPath );
224 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
225 }
226
227 $src_image = call_user_func( $loader, $srcPath );
228 $dst_image = imagecreatetruecolor( $physicalWidth, $physicalHeight );
229
230 // Initialise the destination image to transparent instead of
231 // the default solid black, to support PNG and GIF transparency nicely
232 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
233 imagecolortransparent( $dst_image, $background );
234 imagealphablending( $dst_image, false );
235
236 if( $colorStyle == 'palette' ) {
237 // Don't resample for paletted GIF images.
238 // It may just uglify them, and completely breaks transparency.
239 imagecopyresized( $dst_image, $src_image,
240 0,0,0,0,
241 $physicalWidth, $physicalHeight, imagesx( $src_image ), imagesy( $src_image ) );
242 } else {
243 imagecopyresampled( $dst_image, $src_image,
244 0,0,0,0,
245 $physicalWidth, $physicalHeight, imagesx( $src_image ), imagesy( $src_image ) );
246 }
247
248 imagesavealpha( $dst_image, true );
249
250 call_user_func( $saveType, $dst_image, $dstPath );
251 imagedestroy( $dst_image );
252 imagedestroy( $src_image );
253 $retval = 0;
254 }
255
256 $removed = $this->removeBadFile( $dstPath, $retval );
257 if ( $retval != 0 || $removed ) {
258 wfDebugLog( 'thumbnail',
259 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
260 wfHostname(), $retval, trim($err), $cmd ) );
261 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
262 } else {
263 return new ThumbnailImage( $image, $dstUrl, $clientWidth, $clientHeight, $dstPath );
264 }
265 }
266
267 /**
268 * Escape a string for ImageMagick's property input (e.g. -set -comment)
269 * See InterpretImageProperties() in magick/property.c
270 */
271 function escapeMagickProperty( $s ) {
272 // Double the backslashes
273 $s = str_replace( '\\', '\\\\', $s );
274 // Double the percents
275 $s = str_replace( '%', '%%', $s );
276 // Escape initial - or @
277 if ( strlen( $s ) > 0 && ( $s[0] === '-' || $s[0] === '@' ) ) {
278 $s = '\\' . $s;
279 }
280 return $s;
281 }
282
283 /**
284 * Escape a string for ImageMagick's input filenames. See ExpandFilenames()
285 * and GetPathComponent() in magick/utility.c.
286 *
287 * This won't work with an initial ~ or @, so input files should be prefixed
288 * with the directory name.
289 *
290 * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
291 * it's broken in a way that doesn't involve trying to convert every file
292 * in a directory, so we're better off escaping and waiting for the bugfix
293 * to filter down to users.
294 *
295 * @param $path string The file path
296 * @param $scene string The scene specification, or false if there is none
297 */
298 function escapeMagickInput( $path, $scene = false ) {
299 # Die on initial metacharacters (caller should prepend path)
300 $firstChar = substr( $path, 0, 1 );
301 if ( $firstChar === '~' || $firstChar === '@' ) {
302 throw new MWException( __METHOD__.': cannot escape this path name' );
303 }
304
305 # Escape glob chars
306 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
307
308 return $this->escapeMagickPath( $path, $scene );
309 }
310
311 /**
312 * Escape a string for ImageMagick's output filename. See
313 * InterpretImageFilename() in magick/image.c.
314 */
315 function escapeMagickOutput( $path, $scene = false ) {
316 $path = str_replace( '%', '%%', $path );
317 return $this->escapeMagickPath( $path, $scene );
318 }
319
320 /**
321 * Armour a string against ImageMagick's GetPathComponent(). This is a
322 * helper function for escapeMagickInput() and escapeMagickOutput().
323 *
324 * @param $path string The file path
325 * @param $scene string The scene specification, or false if there is none
326 */
327 protected function escapeMagickPath( $path, $scene = false ) {
328 # Die on format specifiers (other than drive letters). The regex is
329 # meant to match all the formats you get from "convert -list format"
330 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
331 if ( wfIsWindows() && is_dir( $m[0] ) ) {
332 // OK, it's a drive letter
333 // ImageMagick has a similar exception, see IsMagickConflict()
334 } else {
335 throw new MWException( __METHOD__.': unexpected colon character in path name' );
336 }
337 }
338
339 # If there are square brackets, add a do-nothing scene specification
340 # to force a literal interpretation
341 if ( $scene === false ) {
342 if ( strpos( $path, '[' ) !== false ) {
343 $path .= '[0--1]';
344 }
345 } else {
346 $path .= "[$scene]";
347 }
348 return $path;
349 }
350
351 /**
352 * Retrieve the version of the installed ImageMagick
353 * You can use PHPs version_compare() to use this value
354 * Value is cached for one hour.
355 * @return String representing the IM version.
356 */
357 protected function getMagickVersion() {
358 global $wgMemc;
359
360 $cache = $wgMemc->get( "imagemagick-version" );
361 if( !$cache ) {
362 global $wgImageMagickConvertCommand;
363 $cmd = wfEscapeShellArg( $wgImageMagickConvertCommand ) . ' -version';
364 wfDebug( __METHOD__.": Running convert -version\n" );
365 $retval = '';
366 $return = wfShellExec( $cmd, &$retval );
367 $x = preg_match('/Version: ImageMagick ([0-9]*\.[0-9]*\.[0-9]*)/', $return, $matches);
368 if( $x != 1 ) {
369 wfDebug( __METHOD__.": ImageMagick version check failed\n" );
370 return null;
371 }
372 $wgMemc->set( "imagemagick-version", $matches[1], 3600 );
373 return $matches[1];
374 }
375 return $cache;
376 }
377
378 static function imageJpegWrapper( $dst_image, $thumbPath ) {
379 imageinterlace( $dst_image );
380 imagejpeg( $dst_image, $thumbPath, 95 );
381 }
382
383
384 function getMetadata( $image, $filename ) {
385 global $wgShowEXIF;
386 if( $wgShowEXIF && file_exists( $filename ) ) {
387 $exif = new Exif( $filename );
388 $data = $exif->getFilteredData();
389 if ( $data ) {
390 $data['MEDIAWIKI_EXIF_VERSION'] = Exif::version();
391 return serialize( $data );
392 } else {
393 return '0';
394 }
395 } else {
396 return '';
397 }
398 }
399
400 function getMetadataType( $image ) {
401 return 'exif';
402 }
403
404 function isMetadataValid( $image, $metadata ) {
405 global $wgShowEXIF;
406 if ( !$wgShowEXIF ) {
407 # Metadata disabled and so an empty field is expected
408 return true;
409 }
410 if ( $metadata === '0' ) {
411 # Special value indicating that there is no EXIF data in the file
412 return true;
413 }
414 wfSuppressWarnings();
415 $exif = unserialize( $metadata );
416 wfRestoreWarnings();
417 if ( !isset( $exif['MEDIAWIKI_EXIF_VERSION'] ) ||
418 $exif['MEDIAWIKI_EXIF_VERSION'] != Exif::version() )
419 {
420 # Wrong version
421 wfDebug( __METHOD__.": wrong version\n" );
422 return false;
423 }
424 return true;
425 }
426
427 /**
428 * Get a list of EXIF metadata items which should be displayed when
429 * the metadata table is collapsed.
430 *
431 * @return array of strings
432 * @access private
433 */
434 function visibleMetadataFields() {
435 $fields = array();
436 $lines = explode( "\n", wfMsgForContent( 'metadata-fields' ) );
437 foreach( $lines as $line ) {
438 $matches = array();
439 if( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
440 $fields[] = $matches[1];
441 }
442 }
443 $fields = array_map( 'strtolower', $fields );
444 return $fields;
445 }
446
447 function formatMetadata( $image ) {
448 $result = array(
449 'visible' => array(),
450 'collapsed' => array()
451 );
452 $metadata = $image->getMetadata();
453 if ( !$metadata ) {
454 return false;
455 }
456 $exif = unserialize( $metadata );
457 if ( !$exif ) {
458 return false;
459 }
460 unset( $exif['MEDIAWIKI_EXIF_VERSION'] );
461 $format = new FormatExif( $exif );
462
463 $formatted = $format->getFormattedData();
464 // Sort fields into visible and collapsed
465 $visibleFields = $this->visibleMetadataFields();
466 foreach ( $formatted as $name => $value ) {
467 $tag = strtolower( $name );
468 self::addMeta( $result,
469 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
470 'exif',
471 $tag,
472 $value
473 );
474 }
475 return $result;
476 }
477 }