MediaWiki 1.40.4
JpegHandler.php
Go to the documentation of this file.
1<?php
27
38 private const SRGB_EXIF_COLOR_SPACE = 'sRGB';
39 private const SRGB_ICC_PROFILE_DESCRIPTION = 'sRGB IEC61966-2.1';
40
41 public function normaliseParams( $image, &$params ) {
42 if ( !parent::normaliseParams( $image, $params ) ) {
43 return false;
44 }
45 if ( isset( $params['quality'] ) && !self::validateQuality( $params['quality'] ) ) {
46 return false;
47 }
48 return true;
49 }
50
51 public function validateParam( $name, $value ) {
52 if ( $name === 'quality' ) {
53 return self::validateQuality( $value );
54 }
55 return parent::validateParam( $name, $value );
56 }
57
62 private static function validateQuality( $value ) {
63 return $value === 'low';
64 }
65
66 public function makeParamString( $params ) {
67 // Prepend quality as "qValue-". This has to match parseParamString() below
68 $res = parent::makeParamString( $params );
69 if ( $res && isset( $params['quality'] ) ) {
70 $res = "q{$params['quality']}-$res";
71 }
72 return $res;
73 }
74
75 public function parseParamString( $str ) {
76 // $str contains "qlow-200px" or "200px" strings because thumb.php would strip the filename
77 // first - check if the string begins with "qlow-", and if so, treat it as quality.
78 // Pass the first portion, or the whole string if "qlow-" not found, to the parent
79 // The parsing must match the makeParamString() above
80 $res = false;
81 $m = false;
82 if ( preg_match( '/q([^-]+)-(.*)$/', $str, $m ) ) {
83 $v = $m[1];
84 if ( self::validateQuality( $v ) ) {
85 $res = parent::parseParamString( $m[2] );
86 if ( $res ) {
87 $res['quality'] = $v;
88 }
89 }
90 } else {
91 $res = parent::parseParamString( $str );
92 }
93 return $res;
94 }
95
96 protected function getScriptParams( $params ) {
97 $res = parent::getScriptParams( $params );
98 if ( isset( $params['quality'] ) ) {
99 $res['quality'] = $params['quality'];
100 }
101 return $res;
102 }
103
104 public function getSizeAndMetadata( $state, $filename ) {
105 try {
106 $meta = BitmapMetadataHandler::Jpeg( $filename );
107 if ( !is_array( $meta ) ) {
108 // This should never happen, but doesn't hurt to be paranoid.
109 throw new MWException( 'Metadata array is not an array' );
110 }
111 $meta['MEDIAWIKI_EXIF_VERSION'] = Exif::version();
112
113 $info = [
114 'width' => $meta['SOF']['width'] ?? 0,
115 'height' => $meta['SOF']['height'] ?? 0,
116 ];
117 if ( isset( $meta['SOF']['bits'] ) ) {
118 $info['bits'] = $meta['SOF']['bits'];
119 }
120 $info = $this->applyExifRotation( $info, $meta );
121 unset( $meta['SOF'] );
122 $info['metadata'] = $meta;
123 return $info;
124 } catch ( MWException $e ) {
125 // BitmapMetadataHandler throws an exception in certain exceptional
126 // cases like if file does not exist.
127 wfDebug( __METHOD__ . ': ' . $e->getMessage() );
128
129 // This used to return an integer-like string from getMetadata(),
130 // producing a value which could not be unserialized in
131 // img_metadata. The "_error" array key matches the legacy
132 // unserialization for such image rows.
133 return [ 'metadata' => [ '_error' => ExifBitmapHandler::BROKEN_FILE ] ];
134 }
135 }
136
144 public function rotate( $file, $params ) {
145 $jpegTran = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::JpegTran );
146
147 $rotation = ( $params['rotation'] + $this->getRotation( $file ) ) % 360;
148
149 if ( $jpegTran && is_executable( $jpegTran ) ) {
150 $command = Shell::command( $jpegTran,
151 '-rotate',
152 (string)$rotation,
153 '-outfile',
154 $params['dstPath'],
155 $params['srcPath']
156 );
157 $result = $command
158 ->includeStderr()
159 ->execute();
160 if ( $result->getExitCode() !== 0 ) {
161 $this->logErrorForExternalProcess( $result->getExitCode(),
162 $result->getStdout(),
163 $command
164 );
165
166 return new MediaTransformError( 'thumbnail_error', 0, 0, $result->getStdout() );
167 }
168
169 return false;
170 }
171 return parent::rotate( $file, $params );
172 }
173
174 public function supportsBucketing() {
175 return true;
176 }
177
178 public function sanitizeParamsForBucketing( $params ) {
179 $params = parent::sanitizeParamsForBucketing( $params );
180
181 // Quality needs to be cleared for bucketing. Buckets need to be default quality
182 unset( $params['quality'] );
183
184 return $params;
185 }
186
190 protected function transformImageMagick( $image, $params ) {
191 $useTinyRGBForJPGThumbnails = MediaWikiServices::getInstance()
192 ->getMainConfig()->get( MainConfigNames::UseTinyRGBForJPGThumbnails );
193
194 $ret = parent::transformImageMagick( $image, $params );
195
196 if ( $ret ) {
197 return $ret;
198 }
199
200 if ( $useTinyRGBForJPGThumbnails ) {
201 // T100976 If the profile embedded in the JPG is sRGB, swap it for the smaller
202 // (and free) TinyRGB
203
213 $colorSpaces = [ self::SRGB_EXIF_COLOR_SPACE, '-' ];
214 $profiles = [ self::SRGB_ICC_PROFILE_DESCRIPTION ];
215
216 // we'll also add TinyRGB profile to images lacking a profile, but
217 // only if they're not low quality (which are meant to save bandwidth
218 // and we don't want to increase the filesize by adding a profile)
219 if ( isset( $params['quality'] ) && $params['quality'] > 30 ) {
220 $profiles[] = '-';
221 }
222
223 $this->swapICCProfile(
224 $params['dstPath'],
225 $colorSpaces,
226 $profiles,
227 realpath( __DIR__ ) . '/tinyrgb.icc'
228 );
229 }
230
231 return false;
232 }
233
245 public function swapICCProfile( $filepath, array $colorSpaces,
246 array $oldProfileStrings, $profileFilepath
247 ) {
248 $exiftool = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::Exiftool );
249
250 if ( !$exiftool || !is_executable( $exiftool ) ) {
251 return false;
252 }
253
254 $result = Shell::command(
255 $exiftool,
256 '-EXIF:ColorSpace',
257 '-ICC_Profile:ProfileDescription',
258 '-S',
259 '-T',
260 $filepath
261 )
262 ->includeStderr()
263 ->execute();
264
265 // Explode EXIF data into an array with [0 => Color Space, 1 => Device Model Desc]
266 $data = explode( "\t", trim( $result->getStdout() ), 3 );
267
268 if ( $result->getExitCode() !== 0 ) {
269 return false;
270 }
271
272 // Make a regex out of the source data to match it to an array of color
273 // spaces in a case-insensitive way
274 $colorSpaceRegex = '/' . preg_quote( $data[0], '/' ) . '/i';
275 if ( empty( preg_grep( $colorSpaceRegex, $colorSpaces ) ) ) {
276 // We can't establish that this file matches the color space, don't process it
277 return false;
278 }
279
280 $profileRegex = '/' . preg_quote( $data[1], '/' ) . '/i';
281 if ( empty( preg_grep( $profileRegex, $oldProfileStrings ) ) ) {
282 // We can't establish that this file has the expected ICC profile, don't process it
283 return false;
284 }
285
286 $command = Shell::command( $exiftool,
287 '-overwrite_original',
288 '-icc_profile<=' . $profileFilepath,
289 $filepath
290 );
291 $result = $command
292 ->includeStderr()
293 ->execute();
294
295 if ( $result->getExitCode() !== 0 ) {
296 $this->logErrorForExternalProcess( $result->getExitCode(),
297 $result->getStdout(),
298 $command
299 );
300
301 return false;
302 }
303
304 return true;
305 }
306}
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
static Jpeg( $filename)
Main entry point for jpeg's.
Stuff specific to JPEG and (built-in) TIFF handler.
applyExifRotation( $info, $metadata)
getRotation( $file)
On supporting image formats, try to read out the low-level orientation of the file and return the ang...
const BROKEN_FILE
Error extracting metadata.
static version()
#-
Definition Exif.php:714
JPEG specific handler.
makeParamString( $params)
Merge a parameter array into a string appropriate for inclusion in filenames.stringto overrideto over...
validateParam( $name, $value)
Validate a thumbnail parameter at parse time.Return true to accept the parameter, and false to reject...
getScriptParams( $params)
to override
swapICCProfile( $filepath, array $colorSpaces, array $oldProfileStrings, $profileFilepath)
Swaps an embedded ICC profile for another, if found.
getSizeAndMetadata( $state, $filename)
Get image size information and metadata array.
supportsBucketing()
Returns whether or not this handler supports the chained generation of thumbnails according to bucket...
rotate( $file, $params)
parseParamString( $str)
Parse a param string made with makeParamString back into an array.array|false Array of parameters or ...
sanitizeParamsForBucketing( $params)
Returns a normalised params array for which parameters have been cleaned up for bucketing purposes....
normaliseParams( $image, &$params)
transformImageMagick( $image, $params)
Transform an image using ImageMagick.to overrideMediaTransformError|false Error object if error occur...
MediaWiki exception.
logErrorForExternalProcess( $retval, $err, $cmd)
Log an error that occurred in an external process.
Basic media transform error class.
A class containing constants representing the names of configuration variables.
Service locator for MediaWiki core services.
Executes shell commands.
Definition Shell.php:46
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition router.php:42