MediaWiki REL1_39
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 } else {
55 return parent::validateParam( $name, $value );
56 }
57 }
58
63 private static function validateQuality( $value ) {
64 return $value === 'low';
65 }
66
67 public function makeParamString( $params ) {
68 // Prepend quality as "qValue-". This has to match parseParamString() below
69 $res = parent::makeParamString( $params );
70 if ( $res && isset( $params['quality'] ) ) {
71 $res = "q{$params['quality']}-$res";
72 }
73 return $res;
74 }
75
76 public function parseParamString( $str ) {
77 // $str contains "qlow-200px" or "200px" strings because thumb.php would strip the filename
78 // first - check if the string begins with "qlow-", and if so, treat it as quality.
79 // Pass the first portion, or the whole string if "qlow-" not found, to the parent
80 // The parsing must match the makeParamString() above
81 $res = false;
82 $m = false;
83 if ( preg_match( '/q([^-]+)-(.*)$/', $str, $m ) ) {
84 $v = $m[1];
85 if ( self::validateQuality( $v ) ) {
86 $res = parent::parseParamString( $m[2] );
87 if ( $res ) {
88 $res['quality'] = $v;
89 }
90 }
91 } else {
92 $res = parent::parseParamString( $str );
93 }
94 return $res;
95 }
96
97 protected function getScriptParams( $params ) {
98 $res = parent::getScriptParams( $params );
99 if ( isset( $params['quality'] ) ) {
100 $res['quality'] = $params['quality'];
101 }
102 return $res;
103 }
104
105 public function getSizeAndMetadata( $state, $filename ) {
106 try {
107 $meta = BitmapMetadataHandler::Jpeg( $filename );
108 if ( !is_array( $meta ) ) {
109 // This should never happen, but doesn't hurt to be paranoid.
110 throw new MWException( 'Metadata array is not an array' );
111 }
112 $meta['MEDIAWIKI_EXIF_VERSION'] = Exif::version();
113
114 $info = [
115 'width' => $meta['SOF']['width'] ?? 0,
116 'height' => $meta['SOF']['height'] ?? 0,
117 ];
118 if ( isset( $meta['SOF']['bits'] ) ) {
119 $info['bits'] = $meta['SOF']['bits'];
120 }
121 $info = $this->applyExifRotation( $info, $meta );
122 unset( $meta['SOF'] );
123 $info['metadata'] = $meta;
124 return $info;
125 } catch ( MWException $e ) {
126 // BitmapMetadataHandler throws an exception in certain exceptional
127 // cases like if file does not exist.
128 wfDebug( __METHOD__ . ': ' . $e->getMessage() );
129
130 // This used to return an integer-like string from getMetadata(),
131 // producing a value which could not be unserialized in
132 // img_metadata. The "_error" array key matches the legacy
133 // unserialization for such image rows.
134 return [ 'metadata' => [ '_error' => ExifBitmapHandler::BROKEN_FILE ] ];
135 }
136 }
137
145 public function rotate( $file, $params ) {
146 $jpegTran = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::JpegTran );
147
148 $rotation = ( $params['rotation'] + $this->getRotation( $file ) ) % 360;
149
150 if ( $jpegTran && is_executable( $jpegTran ) ) {
151 $command = Shell::command( $jpegTran,
152 '-rotate',
153 (string)$rotation,
154 '-outfile',
155 $params['dstPath'],
156 $params['srcPath']
157 );
158 $result = $command
159 ->includeStderr()
160 ->execute();
161 if ( $result->getExitCode() !== 0 ) {
162 $this->logErrorForExternalProcess( $result->getExitCode(),
163 $result->getStdout(),
165 );
166
167 return new MediaTransformError( 'thumbnail_error', 0, 0, $result->getStdout() );
168 }
169
170 return false;
171 } else {
172 return parent::rotate( $file, $params );
173 }
174 }
175
176 public function supportsBucketing() {
177 return true;
178 }
179
180 public function sanitizeParamsForBucketing( $params ) {
181 $params = parent::sanitizeParamsForBucketing( $params );
182
183 // Quality needs to be cleared for bucketing. Buckets need to be default quality
184 unset( $params['quality'] );
185
186 return $params;
187 }
188
192 protected function transformImageMagick( $image, $params ) {
193 $useTinyRGBForJPGThumbnails = MediaWikiServices::getInstance()
194 ->getMainConfig()->get( MainConfigNames::UseTinyRGBForJPGThumbnails );
195
196 $ret = parent::transformImageMagick( $image, $params );
197
198 if ( $ret ) {
199 return $ret;
200 }
201
202 if ( $useTinyRGBForJPGThumbnails ) {
203 // T100976 If the profile embedded in the JPG is sRGB, swap it for the smaller
204 // (and free) TinyRGB
205
215 $colorSpaces = [ self::SRGB_EXIF_COLOR_SPACE, '-' ];
216 $profiles = [ self::SRGB_ICC_PROFILE_DESCRIPTION ];
217
218 // we'll also add TinyRGB profile to images lacking a profile, but
219 // only if they're not low quality (which are meant to save bandwidth
220 // and we don't want to increase the filesize by adding a profile)
221 if ( isset( $params['quality'] ) && $params['quality'] > 30 ) {
222 $profiles[] = '-';
223 }
224
225 $this->swapICCProfile(
226 $params['dstPath'],
227 $colorSpaces,
228 $profiles,
229 realpath( __DIR__ ) . '/tinyrgb.icc'
230 );
231 }
232
233 return false;
234 }
235
247 public function swapICCProfile( $filepath, array $colorSpaces,
248 array $oldProfileStrings, $profileFilepath
249 ) {
250 $exiftool = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::Exiftool );
251
252 if ( !$exiftool || !is_executable( $exiftool ) ) {
253 return false;
254 }
255
256 $result = Shell::command(
257 $exiftool,
258 '-EXIF:ColorSpace',
259 '-ICC_Profile:ProfileDescription',
260 '-S',
261 '-T',
262 $filepath
263 )
264 ->includeStderr()
265 ->execute();
266
267 // Explode EXIF data into an array with [0 => Color Space, 1 => Device Model Desc]
268 $data = explode( "\t", trim( $result->getStdout() ), 3 );
269
270 if ( $result->getExitCode() !== 0 ) {
271 return false;
272 }
273
274 // Make a regex out of the source data to match it to an array of color
275 // spaces in a case-insensitive way
276 $colorSpaceRegex = '/' . preg_quote( $data[0], '/' ) . '/i';
277 if ( empty( preg_grep( $colorSpaceRegex, $colorSpaces ) ) ) {
278 // We can't establish that this file matches the color space, don't process it
279 return false;
280 }
281
282 $profileRegex = '/' . preg_quote( $data[1], '/' ) . '/i';
283 if ( empty( preg_grep( $profileRegex, $oldProfileStrings ) ) ) {
284 // We can't establish that this file has the expected ICC profile, don't process it
285 return false;
286 }
287
288 $command = Shell::command( $exiftool,
289 '-overwrite_original',
290 '-icc_profile<=' . $profileFilepath,
291 $filepath
292 );
293 $result = $command
294 ->includeStderr()
295 ->execute();
296
297 if ( $result->getExitCode() !== 0 ) {
298 $this->logErrorForExternalProcess( $result->getExitCode(),
299 $result->getStdout(),
301 );
302
303 return false;
304 }
305
306 return true;
307 }
308}
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:715
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
$command
Definition mcc.php:125
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition router.php:42