(bug 23063) Reverse handling of $wgMaxImageArea and $wgMaxAnimatedGifArea: the former...
[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 $descriptionUrl = 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 $frame = '';
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 $frame = '[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($srcPath . $frame) .
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 " -set comment " . wfEscapeShellArg( "{$descriptionUrl}" ) .
161 " -depth 8 $sharpen " .
162 wfEscapeShellArg($dstPath) . " 2>&1";
163 wfDebug( __METHOD__.": running ImageMagick: $cmd\n");
164 wfProfileIn( 'convert' );
165 $err = wfShellExec( $cmd, $retval );
166 wfProfileOut( 'convert' );
167 } elseif( $scaler == 'custom' ) {
168 # Use a custom convert command
169 # Variables: %s %d %w %h
170 $src = wfEscapeShellArg( $srcPath );
171 $dst = wfEscapeShellArg( $dstPath );
172 $cmd = $wgCustomConvertCommand;
173 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
174 $cmd = str_replace( '%h', $physicalHeight, str_replace( '%w', $physicalWidth, $cmd ) ); # Size
175 wfDebug( __METHOD__.": Running custom convert command $cmd\n" );
176 wfProfileIn( 'convert' );
177 $err = wfShellExec( $cmd, $retval );
178 wfProfileOut( 'convert' );
179 } else /* $scaler == 'gd' */ {
180 # Use PHP's builtin GD library functions.
181 #
182 # First find out what kind of file this is, and select the correct
183 # input routine for this.
184
185 $typemap = array(
186 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
187 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( __CLASS__, 'imageJpegWrapper' ) ),
188 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
189 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
190 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
191 );
192 if( !isset( $typemap[$mimeType] ) ) {
193 $err = 'Image type not supported';
194 wfDebug( "$err\n" );
195 $errMsg = wfMsg ( 'thumbnail_image-type' );
196 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
197 }
198 list( $loader, $colorStyle, $saveType ) = $typemap[$mimeType];
199
200 if( !function_exists( $loader ) ) {
201 $err = "Incomplete GD library configuration: missing function $loader";
202 wfDebug( "$err\n" );
203 $errMsg = wfMsg ( 'thumbnail_gd-library', $loader );
204 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
205 }
206
207 if ( !file_exists( $srcPath ) ) {
208 $err = "File seems to be missing: $srcPath";
209 wfDebug( "$err\n" );
210 $errMsg = wfMsg ( 'thumbnail_image-missing', $srcPath );
211 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
212 }
213
214 $src_image = call_user_func( $loader, $srcPath );
215 $dst_image = imagecreatetruecolor( $physicalWidth, $physicalHeight );
216
217 // Initialise the destination image to transparent instead of
218 // the default solid black, to support PNG and GIF transparency nicely
219 $background = imagecolorallocate( $dst_image, 0, 0, 0 );
220 imagecolortransparent( $dst_image, $background );
221 imagealphablending( $dst_image, false );
222
223 if( $colorStyle == 'palette' ) {
224 // Don't resample for paletted GIF images.
225 // It may just uglify them, and completely breaks transparency.
226 imagecopyresized( $dst_image, $src_image,
227 0,0,0,0,
228 $physicalWidth, $physicalHeight, imagesx( $src_image ), imagesy( $src_image ) );
229 } else {
230 imagecopyresampled( $dst_image, $src_image,
231 0,0,0,0,
232 $physicalWidth, $physicalHeight, imagesx( $src_image ), imagesy( $src_image ) );
233 }
234
235 imagesavealpha( $dst_image, true );
236
237 call_user_func( $saveType, $dst_image, $dstPath );
238 imagedestroy( $dst_image );
239 imagedestroy( $src_image );
240 $retval = 0;
241 }
242
243 $removed = $this->removeBadFile( $dstPath, $retval );
244 if ( $retval != 0 || $removed ) {
245 wfDebugLog( 'thumbnail',
246 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
247 wfHostname(), $retval, trim($err), $cmd ) );
248 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
249 } else {
250 return new ThumbnailImage( $image, $dstUrl, $clientWidth, $clientHeight, $dstPath );
251 }
252 }
253
254 static function imageJpegWrapper( $dst_image, $thumbPath ) {
255 imageinterlace( $dst_image );
256 imagejpeg( $dst_image, $thumbPath, 95 );
257 }
258
259
260 function getMetadata( $image, $filename ) {
261 global $wgShowEXIF;
262 if( $wgShowEXIF && file_exists( $filename ) ) {
263 $exif = new Exif( $filename );
264 $data = $exif->getFilteredData();
265 if ( $data ) {
266 $data['MEDIAWIKI_EXIF_VERSION'] = Exif::version();
267 return serialize( $data );
268 } else {
269 return '0';
270 }
271 } else {
272 return '';
273 }
274 }
275
276 function getMetadataType( $image ) {
277 return 'exif';
278 }
279
280 function isMetadataValid( $image, $metadata ) {
281 global $wgShowEXIF;
282 if ( !$wgShowEXIF ) {
283 # Metadata disabled and so an empty field is expected
284 return true;
285 }
286 if ( $metadata === '0' ) {
287 # Special value indicating that there is no EXIF data in the file
288 return true;
289 }
290 $exif = @unserialize( $metadata );
291 if ( !isset( $exif['MEDIAWIKI_EXIF_VERSION'] ) ||
292 $exif['MEDIAWIKI_EXIF_VERSION'] != Exif::version() )
293 {
294 # Wrong version
295 wfDebug( __METHOD__.": wrong version\n" );
296 return false;
297 }
298 return true;
299 }
300
301 /**
302 * Get a list of EXIF metadata items which should be displayed when
303 * the metadata table is collapsed.
304 *
305 * @return array of strings
306 * @access private
307 */
308 function visibleMetadataFields() {
309 $fields = array();
310 $lines = explode( "\n", wfMsgForContent( 'metadata-fields' ) );
311 foreach( $lines as $line ) {
312 $matches = array();
313 if( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
314 $fields[] = $matches[1];
315 }
316 }
317 $fields = array_map( 'strtolower', $fields );
318 return $fields;
319 }
320
321 function formatMetadata( $image ) {
322 $result = array(
323 'visible' => array(),
324 'collapsed' => array()
325 );
326 $metadata = $image->getMetadata();
327 if ( !$metadata ) {
328 return false;
329 }
330 $exif = unserialize( $metadata );
331 if ( !$exif ) {
332 return false;
333 }
334 unset( $exif['MEDIAWIKI_EXIF_VERSION'] );
335 $format = new FormatExif( $exif );
336
337 $formatted = $format->getFormattedData();
338 // Sort fields into visible and collapsed
339 $visibleFields = $this->visibleMetadataFields();
340 foreach ( $formatted as $name => $value ) {
341 $tag = strtolower( $name );
342 self::addMeta( $result,
343 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
344 'exif',
345 $tag,
346 $value
347 );
348 }
349 return $result;
350 }
351 }