]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/media/Bitmap.php
MediaWiki 1.16.4
[autoinstalls/mediawiki.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                 $comment = 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                         $scene = false;
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                                         $scene = 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( $this->escapeMagickInput( $srcPath, $scene ) ) .
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                                 // Add the source url as a comment to the thumb.        
159                                 " -set comment " . wfEscapeShellArg( $this->escapeMagickProperty( $comment ) ) .
160                                 " -depth 8 $sharpen " .
161                                 wfEscapeShellArg( $this->escapeMagickOutput( $dstPath ) ) . " 2>&1";
162                         wfDebug( __METHOD__.": running ImageMagick: $cmd\n" );
163                         wfProfileIn( 'convert' );
164                         $err = wfShellExec( $cmd, $retval );
165                         wfProfileOut( 'convert' );
166                 } elseif( $scaler == 'custom' ) {
167                         # Use a custom convert command
168                         # Variables: %s %d %w %h
169                         $src = wfEscapeShellArg( $srcPath );
170                         $dst = wfEscapeShellArg( $dstPath );
171                         $cmd = $wgCustomConvertCommand;
172                         $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
173                         $cmd = str_replace( '%h', $physicalHeight, str_replace( '%w', $physicalWidth, $cmd ) ); # Size
174                         wfDebug( __METHOD__.": Running custom convert command $cmd\n" );
175                         wfProfileIn( 'convert' );
176                         $err = wfShellExec( $cmd, $retval );
177                         wfProfileOut( 'convert' );
178                 } else /* $scaler == 'gd' */ {
179                         # Use PHP's builtin GD library functions.
180                         #
181                         # First find out what kind of file this is, and select the correct
182                         # input routine for this.
183
184                         $typemap = array(
185                                 'image/gif'          => array( 'imagecreatefromgif',  'palette',   'imagegif'  ),
186                                 'image/jpeg'         => array( 'imagecreatefromjpeg', 'truecolor', array( __CLASS__, 'imageJpegWrapper' ) ),
187                                 'image/png'          => array( 'imagecreatefrompng',  'bits',      'imagepng'  ),
188                                 'image/vnd.wap.wbmp' => array( 'imagecreatefromwbmp', 'palette',   'imagewbmp'  ),
189                                 'image/xbm'          => array( 'imagecreatefromxbm',  'palette',   'imagexbm'  ),
190                         );
191                         if( !isset( $typemap[$mimeType] ) ) {
192                                 $err = 'Image type not supported';
193                                 wfDebug( "$err\n" );
194                                 $errMsg = wfMsg ( 'thumbnail_image-type' );
195                                 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
196                         }
197                         list( $loader, $colorStyle, $saveType ) = $typemap[$mimeType];
198
199                         if( !function_exists( $loader ) ) {
200                                 $err = "Incomplete GD library configuration: missing function $loader";
201                                 wfDebug( "$err\n" );
202                                 $errMsg = wfMsg ( 'thumbnail_gd-library', $loader );
203                                 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
204                         }
205
206                         if ( !file_exists( $srcPath ) ) {
207                                 $err = "File seems to be missing: $srcPath";
208                                 wfDebug( "$err\n" );
209                                 $errMsg = wfMsg ( 'thumbnail_image-missing', $srcPath );
210                                 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $errMsg );
211                         }
212
213                         $src_image = call_user_func( $loader, $srcPath );
214                         $dst_image = imagecreatetruecolor( $physicalWidth, $physicalHeight );
215
216                         // Initialise the destination image to transparent instead of
217                         // the default solid black, to support PNG and GIF transparency nicely
218                         $background = imagecolorallocate( $dst_image, 0, 0, 0 );
219                         imagecolortransparent( $dst_image, $background );
220                         imagealphablending( $dst_image, false );
221
222                         if( $colorStyle == 'palette' ) {
223                                 // Don't resample for paletted GIF images.
224                                 // It may just uglify them, and completely breaks transparency.
225                                 imagecopyresized( $dst_image, $src_image,
226                                         0,0,0,0,
227                                         $physicalWidth, $physicalHeight, imagesx( $src_image ), imagesy( $src_image ) );
228                         } else {
229                                 imagecopyresampled( $dst_image, $src_image,
230                                         0,0,0,0,
231                                         $physicalWidth, $physicalHeight, imagesx( $src_image ), imagesy( $src_image ) );
232                         }
233
234                         imagesavealpha( $dst_image, true );
235
236                         call_user_func( $saveType, $dst_image, $dstPath );
237                         imagedestroy( $dst_image );
238                         imagedestroy( $src_image );
239                         $retval = 0;
240                 }
241
242                 $removed = $this->removeBadFile( $dstPath, $retval );
243                 if ( $retval != 0 || $removed ) {
244                         wfDebugLog( 'thumbnail',
245                                 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
246                                         wfHostname(), $retval, trim($err), $cmd ) );
247                         return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
248                 } else {
249                         return new ThumbnailImage( $image, $dstUrl, $clientWidth, $clientHeight, $dstPath );
250                 }
251         }
252
253         /**
254          * Escape a string for ImageMagick's property input (e.g. -set -comment)
255          * See InterpretImageProperties() in magick/property.c
256          */
257         function escapeMagickProperty( $s ) {
258                 // Double the backslashes
259                 $s = str_replace( '\\', '\\\\', $s );
260                 // Double the percents
261                 $s = str_replace( '%', '%%', $s );
262                 // Escape initial - or @
263                 if ( strlen( $s ) > 0 && ( $s[0] === '-' || $s[0] === '@' ) ) {
264                         $s = '\\' . $s;
265                 }
266                 return $s;
267         }
268
269         /**
270          * Escape a string for ImageMagick's input filenames. See ExpandFilenames() 
271          * and GetPathComponent() in magick/utility.c.
272          *
273          * This won't work with an initial ~ or @, so input files should be prefixed
274          * with the directory name. 
275          *
276          * Glob character unescaping is broken in ImageMagick before 6.6.1-5, but
277          * it's broken in a way that doesn't involve trying to convert every file 
278          * in a directory, so we're better off escaping and waiting for the bugfix
279          * to filter down to users.
280          *
281          * @param $path string The file path
282          * @param $scene string The scene specification, or false if there is none
283          */
284         function escapeMagickInput( $path, $scene = false ) {
285                 # Die on initial metacharacters (caller should prepend path)
286                 $firstChar = substr( $path, 0, 1 );
287                 if ( $firstChar === '~' || $firstChar === '@' ) {
288                         throw new MWException( __METHOD__.': cannot escape this path name' );
289                 }
290
291                 # Escape glob chars
292                 $path = preg_replace( '/[*?\[\]{}]/', '\\\\\0', $path );
293
294                 return $this->escapeMagickPath( $path, $scene );
295         }
296
297         /**
298          * Escape a string for ImageMagick's output filename. See 
299          * InterpretImageFilename() in magick/image.c.
300          */
301         function escapeMagickOutput( $path, $scene = false ) {
302                 $path = str_replace( '%', '%%', $path );
303                 return $this->escapeMagickPath( $path, $scene );
304         }
305
306         /**
307          * Armour a string against ImageMagick's GetPathComponent(). This is a 
308          * helper function for escapeMagickInput() and escapeMagickOutput().
309          *
310          * @param $path string The file path
311          * @param $scene string The scene specification, or false if there is none
312          */
313         protected function escapeMagickPath( $path, $scene = false ) {
314                 # Die on format specifiers (other than drive letters). The regex is
315                 # meant to match all the formats you get from "convert -list format"
316                 if ( preg_match( '/^([a-zA-Z0-9-]+):/', $path, $m ) ) {
317                         if ( wfIsWindows() && is_dir( $m[0] ) ) {
318                                 // OK, it's a drive letter
319                                 // ImageMagick has a similar exception, see IsMagickConflict()
320                         } else {
321                                 throw new MWException( __METHOD__.': unexpected colon character in path name' );
322                         }
323                 }
324
325                 # If there are square brackets, add a do-nothing scene specification 
326                 # to force a literal interpretation
327                 if ( $scene === false ) {
328                         if ( strpos( $path, '[' ) !== false ) {
329                                 $path .= '[0--1]';
330                         }
331                 } else {
332                         $path .= "[$scene]";
333                 }
334                 return $path;
335         }
336
337         static function imageJpegWrapper( $dst_image, $thumbPath ) {
338                 imageinterlace( $dst_image );
339                 imagejpeg( $dst_image, $thumbPath, 95 );
340         }
341
342
343         function getMetadata( $image, $filename ) {
344                 global $wgShowEXIF;
345                 if( $wgShowEXIF && file_exists( $filename ) ) {
346                         $exif = new Exif( $filename );
347                         $data = $exif->getFilteredData();
348                         if ( $data ) {
349                                 $data['MEDIAWIKI_EXIF_VERSION'] = Exif::version();
350                                 return serialize( $data );
351                         } else {
352                                 return '0';
353                         }
354                 } else {
355                         return '';
356                 }
357         }
358
359         function getMetadataType( $image ) {
360                 return 'exif';
361         }
362
363         function isMetadataValid( $image, $metadata ) {
364                 global $wgShowEXIF;
365                 if ( !$wgShowEXIF ) {
366                         # Metadata disabled and so an empty field is expected
367                         return true;
368                 }
369                 if ( $metadata === '0' ) {
370                         # Special value indicating that there is no EXIF data in the file
371                         return true;
372                 }
373                 $exif = @unserialize( $metadata );
374                 if ( !isset( $exif['MEDIAWIKI_EXIF_VERSION'] ) ||
375                         $exif['MEDIAWIKI_EXIF_VERSION'] != Exif::version() )
376                 {
377                         # Wrong version
378                         wfDebug( __METHOD__.": wrong version\n" );
379                         return false;
380                 }
381                 return true;
382         }
383
384         /**
385          * Get a list of EXIF metadata items which should be displayed when
386          * the metadata table is collapsed.
387          *
388          * @return array of strings
389          * @access private
390          */
391         function visibleMetadataFields() {
392                 $fields = array();
393                 $lines = explode( "\n", wfMsgForContent( 'metadata-fields' ) );
394                 foreach( $lines as $line ) {
395                         $matches = array();
396                         if( preg_match( '/^\\*\s*(.*?)\s*$/', $line, $matches ) ) {
397                                 $fields[] = $matches[1];
398                         }
399                 }
400                 $fields = array_map( 'strtolower', $fields );
401                 return $fields;
402         }
403
404         function formatMetadata( $image ) {
405                 $result = array(
406                         'visible' => array(),
407                         'collapsed' => array()
408                 );
409                 $metadata = $image->getMetadata();
410                 if ( !$metadata ) {
411                         return false;
412                 }
413                 $exif = unserialize( $metadata );
414                 if ( !$exif ) {
415                         return false;
416                 }
417                 unset( $exif['MEDIAWIKI_EXIF_VERSION'] );
418                 $format = new FormatExif( $exif );
419
420                 $formatted = $format->getFormattedData();
421                 // Sort fields into visible and collapsed
422                 $visibleFields = $this->visibleMetadataFields();
423                 foreach ( $formatted as $name => $value ) {
424                         $tag = strtolower( $name );
425                         self::addMeta( $result,
426                                 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
427                                 'exif',
428                                 $tag,
429                                 $value
430                         );
431                 }
432                 return $result;
433         }
434 }