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