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