MediaWiki  master
JpegHandler.php
Go to the documentation of this file.
1 <?php
25 
36  private const SRGB_EXIF_COLOR_SPACE = 'sRGB';
37  private const SRGB_ICC_PROFILE_DESCRIPTION = 'sRGB IEC61966-2.1';
38 
39  public function normaliseParams( $image, &$params ) {
40  if ( !parent::normaliseParams( $image, $params ) ) {
41  return false;
42  }
43  if ( isset( $params['quality'] ) && !self::validateQuality( $params['quality'] ) ) {
44  return false;
45  }
46  return true;
47  }
48 
49  public function validateParam( $name, $value ) {
50  if ( $name === 'quality' ) {
51  return self::validateQuality( $value );
52  } else {
53  return parent::validateParam( $name, $value );
54  }
55  }
56 
61  private static function validateQuality( $value ) {
62  return $value === 'low';
63  }
64 
65  public function makeParamString( $params ) {
66  // Prepend quality as "qValue-". This has to match parseParamString() below
67  $res = parent::makeParamString( $params );
68  if ( $res && isset( $params['quality'] ) ) {
69  $res = "q{$params['quality']}-$res";
70  }
71  return $res;
72  }
73 
74  public function parseParamString( $str ) {
75  // $str contains "qlow-200px" or "200px" strings because thumb.php would strip the filename
76  // first - check if the string begins with "qlow-", and if so, treat it as quality.
77  // Pass the first portion, or the whole string if "qlow-" not found, to the parent
78  // The parsing must match the makeParamString() above
79  $res = false;
80  $m = false;
81  if ( preg_match( '/q([^-]+)-(.*)$/', $str, $m ) ) {
82  $v = $m[1];
83  if ( self::validateQuality( $v ) ) {
84  $res = parent::parseParamString( $m[2] );
85  if ( $res ) {
86  $res['quality'] = $v;
87  }
88  }
89  } else {
90  $res = parent::parseParamString( $str );
91  }
92  return $res;
93  }
94 
95  protected function getScriptParams( $params ) {
96  $res = parent::getScriptParams( $params );
97  if ( isset( $params['quality'] ) ) {
98  $res['quality'] = $params['quality'];
99  }
100  return $res;
101  }
102 
103  public function getMetadata( $image, $filename ) {
104  try {
105  $meta = BitmapMetadataHandler::Jpeg( $filename );
106  if ( !is_array( $meta ) ) {
107  // This should never happen, but doesn't hurt to be paranoid.
108  throw new MWException( 'Metadata array is not an array' );
109  }
110  $meta['MEDIAWIKI_EXIF_VERSION'] = Exif::version();
111 
112  return serialize( $meta );
113  } catch ( Exception $e ) {
114  // BitmapMetadataHandler throws an exception in certain exceptional
115  // cases like if file does not exist.
116  wfDebug( __METHOD__ . ': ' . $e->getMessage() );
117 
118  /* This used to use 0 (ExifBitmapHandler::OLD_BROKEN_FILE) for the cases
119  * * No metadata in the file
120  * * Something is broken in the file.
121  * However, if the metadata support gets expanded then you can't tell if the 0 is from
122  * a broken file, or just no props found. A broken file is likely to stay broken, but
123  * a file which had no props could have props once the metadata support is improved.
124  * Thus switch to using -1 to denote only a broken file, and use an array with only
125  * MEDIAWIKI_EXIF_VERSION to denote no props.
126  */
127 
129  }
130  }
131 
139  public function rotate( $file, $params ) {
140  global $wgJpegTran;
141 
142  $rotation = ( $params['rotation'] + $this->getRotation( $file ) ) % 360;
143 
144  if ( $wgJpegTran && is_executable( $wgJpegTran ) ) {
145  $command = Shell::command( $wgJpegTran,
146  '-rotate',
147  $rotation,
148  '-outfile',
149  $params['dstPath'],
150  $params['srcPath']
151  );
152  $result = $command
153  ->includeStderr()
154  ->execute();
155  if ( $result->getExitCode() !== 0 ) {
156  $this->logErrorForExternalProcess( $result->getExitCode(),
157  $result->getStdout(),
158  $command
159  );
160 
161  return new MediaTransformError( 'thumbnail_error', 0, 0, $result->getStdout() );
162  }
163 
164  return false;
165  } else {
166  return parent::rotate( $file, $params );
167  }
168  }
169 
170  public function supportsBucketing() {
171  return true;
172  }
173 
174  public function sanitizeParamsForBucketing( $params ) {
175  $params = parent::sanitizeParamsForBucketing( $params );
176 
177  // Quality needs to be cleared for bucketing. Buckets need to be default quality
178  unset( $params['quality'] );
179 
180  return $params;
181  }
182 
186  protected function transformImageMagick( $image, $params ) {
188 
189  $ret = parent::transformImageMagick( $image, $params );
190 
191  if ( $ret ) {
192  return $ret;
193  }
194 
196  // T100976 If the profile embedded in the JPG is sRGB, swap it for the smaller
197  // (and free) TinyRGB
198 
208  $colorSpaces = [ self::SRGB_EXIF_COLOR_SPACE, '-' ];
209  $profiles = [ self::SRGB_ICC_PROFILE_DESCRIPTION ];
210 
211  // we'll also add TinyRGB profile to images lacking a profile, but
212  // only if they're not low quality (which are meant to save bandwith
213  // and we don't want to increase the filesize by adding a profile)
214  if ( isset( $params['quality'] ) && $params['quality'] > 30 ) {
215  $profiles[] = '-';
216  }
217 
218  $this->swapICCProfile(
219  $params['dstPath'],
220  $colorSpaces,
221  $profiles,
222  realpath( __DIR__ ) . '/tinyrgb.icc'
223  );
224  }
225 
226  return false;
227  }
228 
240  public function swapICCProfile( $filepath, array $colorSpaces,
241  array $oldProfileStrings, $profileFilepath
242  ) {
243  global $wgExiftool;
244 
245  if ( !$wgExiftool || !is_executable( $wgExiftool ) ) {
246  return false;
247  }
248 
249  $result = Shell::command(
250  $wgExiftool,
251  '-EXIF:ColorSpace',
252  '-ICC_Profile:ProfileDescription',
253  '-S',
254  '-T',
255  $filepath
256  )
257  ->includeStderr()
258  ->execute();
259 
260  // Explode EXIF data into an array with [0 => Color Space, 1 => Device Model Desc]
261  $data = explode( "\t", trim( $result->getStdout() ) );
262 
263  if ( $result->getExitCode() !== 0 ) {
264  return false;
265  }
266 
267  // Make a regex out of the source data to match it to an array of color
268  // spaces in a case-insensitive way
269  $colorSpaceRegex = '/' . preg_quote( $data[0], '/' ) . '/i';
270  if ( empty( preg_grep( $colorSpaceRegex, $colorSpaces ) ) ) {
271  // We can't establish that this file matches the color space, don't process it
272  return false;
273  }
274 
275  $profileRegex = '/' . preg_quote( $data[1], '/' ) . '/i';
276  if ( empty( preg_grep( $profileRegex, $oldProfileStrings ) ) ) {
277  // We can't establish that this file has the expected ICC profile, don't process it
278  return false;
279  }
280 
281  $command = Shell::command( $wgExiftool,
282  '-overwrite_original',
283  '-icc_profile<=' . $profileFilepath,
284  $filepath
285  );
286  $result = $command
287  ->includeStderr()
288  ->execute();
289 
290  if ( $result->getExitCode() !== 0 ) {
291  $this->logErrorForExternalProcess( $result->getExitCode(),
292  $result->getStdout(),
293  $command
294  );
295 
296  return false;
297  }
298 
299  return true;
300  }
301 }
JpegHandler\getMetadata
getMetadata( $image, $filename)
Get handler-specific metadata which will be saved in the img_metadata field.
Definition: JpegHandler.php:103
ExifBitmapHandler
Stuff specific to JPEG and (built-in) TIFF handler.
Definition: ExifBitmapHandler.php:31
MediaWiki\Shell\Shell
Executes shell commands.
Definition: Shell.php:44
MediaTransformError
Basic media transform error class.
Definition: MediaTransformError.php:31
$wgExiftool
$wgExiftool
Path to exiftool binary.
Definition: DefaultSettings.php:1265
JpegHandler\SRGB_EXIF_COLOR_SPACE
const SRGB_EXIF_COLOR_SPACE
Definition: JpegHandler.php:36
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
JpegHandler\getScriptParams
getScriptParams( $params)
Stable to override Stable to override
Definition: JpegHandler.php:95
$res
$res
Definition: testCompression.php:57
serialize
serialize()
Definition: ApiMessageTrait.php:138
JpegHandler\validateParam
validateParam( $name, $value)
Validate a thumbnail parameter at parse time.Return true to accept the parameter, and false to reject...
Definition: JpegHandler.php:49
JpegHandler\supportsBucketing
supportsBucketing()
Returns whether or not this handler supports the chained generation of thumbnails according to bucket...
Definition: JpegHandler.php:170
MWException
MediaWiki exception.
Definition: MWException.php:29
Exif\version
static version()
#-
Definition: Exif.php:592
JpegHandler\SRGB_ICC_PROFILE_DESCRIPTION
const SRGB_ICC_PROFILE_DESCRIPTION
Definition: JpegHandler.php:37
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:914
JpegHandler\normaliseParams
normaliseParams( $image, &$params)
Stable to override.
Definition: JpegHandler.php:39
JpegHandler\swapICCProfile
swapICCProfile( $filepath, array $colorSpaces, array $oldProfileStrings, $profileFilepath)
Swaps an embedded ICC profile for another, if found.
Definition: JpegHandler.php:240
JpegHandler\sanitizeParamsForBucketing
sanitizeParamsForBucketing( $params)
Returns a normalised params array for which parameters have been cleaned up for bucketing purposes St...
Definition: JpegHandler.php:174
JpegHandler
JPEG specific handler.
Definition: JpegHandler.php:35
$wgJpegTran
$wgJpegTran
used for lossless jpeg rotation
Definition: DefaultSettings.php:1222
ExifBitmapHandler\getRotation
getRotation( $file)
On supporting image formats, try to read out the low-level orientation of the file and return the ang...
Definition: ExifBitmapHandler.php:207
JpegHandler\rotate
rotate( $file, $params)
Definition: JpegHandler.php:139
$command
$command
Definition: mcc.php:125
$wgUseTinyRGBForJPGThumbnails
$wgUseTinyRGBForJPGThumbnails
When this variable is true and JPGs use the sRGB ICC profile, swaps it for the more lightweight (and ...
Definition: DefaultSettings.php:1648
MediaHandler\logErrorForExternalProcess
logErrorForExternalProcess( $retval, $err, $cmd)
Log an error that occurred in an external process.
Definition: MediaHandler.php:856
JpegHandler\validateQuality
static validateQuality( $value)
Validate and normalize quality value to be between 1 and 100 (inclusive).
Definition: JpegHandler.php:61
ExifBitmapHandler\BROKEN_FILE
const BROKEN_FILE
Error extracting metadata.
Definition: ExifBitmapHandler.php:33
BitmapMetadataHandler\Jpeg
static Jpeg( $filename)
Main entry point for jpeg's.
Definition: BitmapMetadataHandler.php:163
JpegHandler\makeParamString
makeParamString( $params)
Merge a parameter array into a string appropriate for inclusion in filenames.Array of parameters that...
Definition: JpegHandler.php:65
JpegHandler\transformImageMagick
transformImageMagick( $image, $params)
Transform an image using ImageMagick Stable to override.File associated with this thumbnail Array wit...
Definition: JpegHandler.php:186
JpegHandler\parseParamString
parseParamString( $str)
Parse a param string made with makeParamString back into an array.The parameter string without file n...
Definition: JpegHandler.php:74