(bug 16451) Fix application of scaling limits for animated GIFs.
[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 thumbnail an image so big that it will fill hard drives and send servers into swap
22 # JPEG has the handy property of allowing thumbnailing without full decompression, so we make
23 # an exception for it.
24 if ( $mimeType !== 'image/jpeg' &&
25 $this->getImageArea( $image, $srcWidth, $srcHeight ) > $wgMaxImageArea )
26 {
27 return false;
28 }
29
30 # Don't make an image bigger than the source
31 $params['physicalWidth'] = $params['width'];
32 $params['physicalHeight'] = $params['height'];
33
34 if ( $params['physicalWidth'] >= $srcWidth ) {
35 $params['physicalWidth'] = $srcWidth;
36 $params['physicalHeight'] = $srcHeight;
37 return true;
38 }
39
40 return true;
41 }
42
43
44 // Function that returns the number of pixels to be thumbnailed.
45 // Intended for animated GIFs to multiply by the number of frames.
46 function getImageArea( $image, $width, $height ) {
47 return $width * $height;
48 }
49
50 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
51 global $wgUseImageMagick, $wgImageMagickConvertCommand, $wgImageMagickTempDir;
52 global $wgCustomConvertCommand, $wgUseImageResize;
53 global $wgSharpenParameter, $wgSharpenReductionThreshold;
54 global $wgMaxAnimatedGifArea;
55
56 if ( !$this->normaliseParams( $image, $params ) ) {
57 return new TransformParameterError( $params );
58 }
59 $physicalWidth = $params['physicalWidth'];
60 $physicalHeight = $params['physicalHeight'];
61 $clientWidth = $params['width'];
62 $clientHeight = $params['height'];
63 $srcWidth = $image->getWidth();
64 $srcHeight = $image->getHeight();
65 $mimeType = $image->getMimeType();
66 $srcPath = $image->getPath();
67 $retval = 0;
68 wfDebug( __METHOD__.": creating {$physicalWidth}x{$physicalHeight} thumbnail at $dstPath\n" );
69
70 if ( !$image->mustRender() && $physicalWidth == $srcWidth && $physicalHeight == $srcHeight ) {
71 # normaliseParams (or the user) wants us to return the unscaled image
72 wfDebug( __METHOD__.": returning unscaled image\n" );
73 return new ThumbnailImage( $image, $image->getURL(), $clientWidth, $clientHeight, $srcPath );
74 }
75
76 if ( !$dstPath ) {
77 // No output path available, client side scaling only
78 $scaler = 'client';
79 } elseif( !$wgUseImageResize ) {
80 $scaler = 'client';
81 } elseif ( $wgUseImageMagick ) {
82 $scaler = 'im';
83 } elseif ( $wgCustomConvertCommand ) {
84 $scaler = 'custom';
85 } elseif ( function_exists( 'imagecreatetruecolor' ) ) {
86 $scaler = 'gd';
87 } else {
88 $scaler = 'client';
89 }
90 wfDebug( __METHOD__.": scaler $scaler\n" );
91
92 if ( $scaler == 'client' ) {
93 # Client-side image scaling, use the source URL
94 # Using the destination URL in a TRANSFORM_LATER request would be incorrect
95 return new ThumbnailImage( $image, $image->getURL(), $clientWidth, $clientHeight, $srcPath );
96 }
97
98 if ( $flags & self::TRANSFORM_LATER ) {
99 wfDebug( __METHOD__.": Transforming later per flags.\n" );
100 return new ThumbnailImage( $image, $dstUrl, $clientWidth, $clientHeight, $dstPath );
101 }
102
103 if ( !wfMkdirParents( dirname( $dstPath ) ) ) {
104 wfDebug( __METHOD__.": Unable to create thumbnail destination directory, falling back to client scaling\n" );
105 return new ThumbnailImage( $image, $image->getURL(), $clientWidth, $clientHeight, $srcPath );
106 }
107
108 if ( $scaler == 'im' ) {
109 # use ImageMagick
110
111 $quality = '';
112 $sharpen = '';
113 $frame = '';
114 $animation = '';
115 if ( $mimeType == 'image/jpeg' ) {
116 $quality = "-quality 80"; // 80%
117 # Sharpening, see bug 6193
118 if ( ( $physicalWidth + $physicalHeight ) / ( $srcWidth + $srcHeight ) < $wgSharpenReductionThreshold ) {
119 $sharpen = "-sharpen " . wfEscapeShellArg( $wgSharpenParameter );
120 }
121 } elseif ( $mimeType == 'image/png' ) {
122 $quality = "-quality 95"; // zlib 9, adaptive filtering
123 } elseif( $mimeType == 'image/gif' ) {
124 if( $srcWidth * $srcHeight > $wgMaxAnimatedGifArea ) {
125 // Extract initial frame only; we're so big it'll
126 // be a total drag. :P
127 $frame = '[0]';
128 } else {
129 // Coalesce is needed to scale animated GIFs properly (bug 1017).
130 $animation = ' -coalesce ';
131 }
132 }
133
134 if ( strval( $wgImageMagickTempDir ) !== '' ) {
135 $tempEnv = 'MAGICK_TMPDIR=' . wfEscapeShellArg( $wgImageMagickTempDir ) . ' ';
136 } else {
137 $tempEnv = '';
138 }
139
140 # Specify white background color, will be used for transparent images
141 # in Internet Explorer/Windows instead of default black.
142
143 # Note, we specify "-size {$physicalWidth}" and NOT "-size {$physicalWidth}x{$physicalHeight}".
144 # It seems that ImageMagick has a bug wherein it produces thumbnails of
145 # the wrong size in the second case.
146
147 $cmd =
148 $tempEnv .
149 wfEscapeShellArg($wgImageMagickConvertCommand) .
150 " {$quality} -background white -size {$physicalWidth} ".
151 wfEscapeShellArg($srcPath . $frame) .
152 $animation .
153 // For the -resize option a "!" is needed to force exact size,
154 // or ImageMagick may decide your ratio is wrong and slice off
155 // a pixel.
156 " -thumbnail " . wfEscapeShellArg( "{$physicalWidth}x{$physicalHeight}!" ) .
157 " -depth 8 $sharpen " .
158 wfEscapeShellArg($dstPath) . " 2>&1";
159 wfDebug( __METHOD__.": running ImageMagick: $cmd\n");
160 wfProfileIn( 'convert' );
161 $err = wfShellExec( $cmd, $retval );
162 wfProfileOut( 'convert' );
163 } elseif( $scaler == 'custom' ) {
164 # Use a custom convert command
165 # Variables: %s %d %w %h
166 $src = wfEscapeShellArg( $srcPath );
167 $dst = wfEscapeShellArg( $dstPath );
168 $cmd = $wgCustomConvertCommand;
169 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
170 $cmd = str_replace( '%h', $physicalHeight, str_replace( '%w', $physicalWidth, $cmd ) ); # Size
171 wfDebug( __METHOD__.": Running custom convert command $cmd\n" );
172 wfProfileIn( 'convert' );
173 $err = wfShellExec( $cmd, $retval );
174 wfProfileOut( 'convert' );
175 } else /* $scaler == 'gd' */ {
176 # Use PHP's builtin GD library functions.
177 #
178 # First find out what kind of file this is, and select the correct
179 # input routine for this.
180
181 $typemap = array(
182 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
183 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( __CLASS__, 'imageJpegWrapper' ) ),
184 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
185 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
186 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
187 );
188 if( !isset( $typemap[$mimeType] ) ) {
189 $err = 'Image type not supported';
190 wfDebug( "$err\n" );
191 $errMsg = wfMsg ( 'thumbnail_image-type' );
192 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
193 }
194 list( $loader, $colorStyle, $saveType ) = $typemap[$mimeType];
195
196 if( !function_exists( $loader ) ) {
197 $err = "Incomplete GD library configuration: missing function $loader";
198 wfDebug( "$err\n" );
199 $errMsg = wfMsg ( 'thumbnail_gd-library', $loader );
200 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
201 }
202
203 if ( !file_exists( $srcPath ) ) {
204 $err = "File seems to be missing: $srcPath";
205 wfDebug( "$err\n" );
206 $errMsg = wfMsg ( 'thumbnail_image-missing', $srcPath );
207 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
208 }
209
210 $src_image = call_user_func( $loader, $srcPath );
211 $dst_image = imagecreatetruecolor( $physicalWidth, $physicalHeight );
212
213 // Initialise the destination image to transparent instead of
214 // the default solid black, to support PNG and GIF transparency nicely
215 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
216 imagecolortransparent( $dst_image, $background );
217 imagealphablending( $dst_image, false );
218
219 if( $colorStyle == 'palette' ) {
220 // Don't resample for paletted GIF images.
221 // It may just uglify them, and completely breaks transparency.
222 imagecopyresized( $dst_image, $src_image,
223 0,0,0,0,
224 $physicalWidth, $physicalHeight, imagesx( $src_image ), imagesy( $src_image ) );
225 } else {
226 imagecopyresampled( $dst_image, $src_image,
227 0,0,0,0,
228 $physicalWidth, $physicalHeight, imagesx( $src_image ), imagesy( $src_image ) );
229 }
230
231 imagesavealpha( $dst_image, true );
232
233 call_user_func( $saveType, $dst_image, $dstPath );
234 imagedestroy( $dst_image );
235 imagedestroy( $src_image );
236 $retval = 0;
237 }
238
239 $removed = $this->removeBadFile( $dstPath, $retval );
240 if ( $retval != 0 || $removed ) {
241 wfDebugLog( 'thumbnail',
242 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
243 wfHostname(), $retval, trim($err), $cmd ) );
244 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
245 } else {
246 return new ThumbnailImage( $image, $dstUrl, $clientWidth, $clientHeight, $dstPath );
247 }
248 }
249
250 static function imageJpegWrapper( $dst_image, $thumbPath ) {
251 imageinterlace( $dst_image );
252 imagejpeg( $dst_image, $thumbPath, 95 );
253 }
254
255
256 function getMetadata( $image, $filename ) {
257 global $wgShowEXIF;
258 if( $wgShowEXIF && file_exists( $filename ) ) {
259 $exif = new Exif( $filename );
260 $data = $exif->getFilteredData();
261 if ( $data ) {
262 $data['MEDIAWIKI_EXIF_VERSION'] = Exif::version();
263 return serialize( $data );
264 } else {
265 return '0';
266 }
267 } else {
268 return '';
269 }
270 }
271
272 function getMetadataType( $image ) {
273 return 'exif';
274 }
275
276 function isMetadataValid( $image, $metadata ) {
277 global $wgShowEXIF;
278 if ( !$wgShowEXIF ) {
279 # Metadata disabled and so an empty field is expected
280 return true;
281 }
282 if ( $metadata === '0' ) {
283 # Special value indicating that there is no EXIF data in the file
284 return true;
285 }
286 $exif = @unserialize( $metadata );
287 if ( !isset( $exif['MEDIAWIKI_EXIF_VERSION'] ) ||
288 $exif['MEDIAWIKI_EXIF_VERSION'] != Exif::version() )
289 {
290 # Wrong version
291 wfDebug( __METHOD__.": wrong version\n" );
292 return false;
293 }
294 return true;
295 }
296
297 /**
298 * Get a list of EXIF metadata items which should be displayed when
299 * the metadata table is collapsed.
300 *
301 * @return array of strings
302 * @access private
303 */
304 function visibleMetadataFields() {
305 $fields = array();
306 $lines = explode( "\n", wfMsgForContent( 'metadata-fields' ) );
307 foreach( $lines as $line ) {
308 $matches = array();
309 if( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
310 $fields[] = $matches[1];
311 }
312 }
313 $fields = array_map( 'strtolower', $fields );
314 return $fields;
315 }
316
317 function formatMetadata( $image ) {
318 $result = array(
319 'visible' => array(),
320 'collapsed' => array()
321 );
322 $metadata = $image->getMetadata();
323 if ( !$metadata ) {
324 return false;
325 }
326 $exif = unserialize( $metadata );
327 if ( !$exif ) {
328 return false;
329 }
330 unset( $exif['MEDIAWIKI_EXIF_VERSION'] );
331 $format = new FormatExif( $exif );
332
333 $formatted = $format->getFormattedData();
334 // Sort fields into visible and collapsed
335 $visibleFields = $this->visibleMetadataFields();
336 foreach ( $formatted as $name => $value ) {
337 $tag = strtolower( $name );
338 self::addMeta( $result,
339 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
340 'exif',
341 $tag,
342 $value
343 );
344 }
345 return $result;
346 }
347 }