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