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