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