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