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