MediaWiki  master
JpegHandler.php
Go to the documentation of this file.
1 <?php
26 
37  private const SRGB_EXIF_COLOR_SPACE = 'sRGB';
38  private const SRGB_ICC_PROFILE_DESCRIPTION = 'sRGB IEC61966-2.1';
39 
40  public function normaliseParams( $image, &$params ) {
41  if ( !parent::normaliseParams( $image, $params ) ) {
42  return false;
43  }
44  if ( isset( $params['quality'] ) && !self::validateQuality( $params['quality'] ) ) {
45  return false;
46  }
47  return true;
48  }
49 
50  public function validateParam( $name, $value ) {
51  if ( $name === 'quality' ) {
52  return self::validateQuality( $value );
53  } else {
54  return parent::validateParam( $name, $value );
55  }
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( '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  $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  } else {
171  return parent::rotate( $file, $params );
172  }
173  }
174 
175  public function supportsBucketing() {
176  return true;
177  }
178 
179  public function sanitizeParamsForBucketing( $params ) {
180  $params = parent::sanitizeParamsForBucketing( $params );
181 
182  // Quality needs to be cleared for bucketing. Buckets need to be default quality
183  unset( $params['quality'] );
184 
185  return $params;
186  }
187 
191  protected function transformImageMagick( $image, $params ) {
192  $useTinyRGBForJPGThumbnails = MediaWikiServices::getInstance()
193  ->getMainConfig()->get( 'UseTinyRGBForJPGThumbnails' );
194 
195  $ret = parent::transformImageMagick( $image, $params );
196 
197  if ( $ret ) {
198  return $ret;
199  }
200 
201  if ( $useTinyRGBForJPGThumbnails ) {
202  // T100976 If the profile embedded in the JPG is sRGB, swap it for the smaller
203  // (and free) TinyRGB
204 
214  $colorSpaces = [ self::SRGB_EXIF_COLOR_SPACE, '-' ];
215  $profiles = [ self::SRGB_ICC_PROFILE_DESCRIPTION ];
216 
217  // we'll also add TinyRGB profile to images lacking a profile, but
218  // only if they're not low quality (which are meant to save bandwidth
219  // and we don't want to increase the filesize by adding a profile)
220  if ( isset( $params['quality'] ) && $params['quality'] > 30 ) {
221  $profiles[] = '-';
222  }
223 
224  $this->swapICCProfile(
225  $params['dstPath'],
226  $colorSpaces,
227  $profiles,
228  realpath( __DIR__ ) . '/tinyrgb.icc'
229  );
230  }
231 
232  return false;
233  }
234 
246  public function swapICCProfile( $filepath, array $colorSpaces,
247  array $oldProfileStrings, $profileFilepath
248  ) {
249  $exiftool = MediaWikiServices::getInstance()->getMainConfig()->get( 'Exiftool' );
250 
251  if ( !$exiftool || !is_executable( $exiftool ) ) {
252  return false;
253  }
254 
255  $result = Shell::command(
256  $exiftool,
257  '-EXIF:ColorSpace',
258  '-ICC_Profile:ProfileDescription',
259  '-S',
260  '-T',
261  $filepath
262  )
263  ->includeStderr()
264  ->execute();
265 
266  // Explode EXIF data into an array with [0 => Color Space, 1 => Device Model Desc]
267  $data = explode( "\t", trim( $result->getStdout() ) );
268 
269  if ( $result->getExitCode() !== 0 ) {
270  return false;
271  }
272 
273  // Make a regex out of the source data to match it to an array of color
274  // spaces in a case-insensitive way
275  $colorSpaceRegex = '/' . preg_quote( $data[0], '/' ) . '/i';
276  if ( empty( preg_grep( $colorSpaceRegex, $colorSpaces ) ) ) {
277  // We can't establish that this file matches the color space, don't process it
278  return false;
279  }
280 
281  $profileRegex = '/' . preg_quote( $data[1], '/' ) . '/i';
282  if ( empty( preg_grep( $profileRegex, $oldProfileStrings ) ) ) {
283  // We can't establish that this file has the expected ICC profile, don't process it
284  return false;
285  }
286 
287  $command = Shell::command( $exiftool,
288  '-overwrite_original',
289  '-icc_profile<=' . $profileFilepath,
290  $filepath
291  );
292  $result = $command
293  ->includeStderr()
294  ->execute();
295 
296  if ( $result->getExitCode() !== 0 ) {
297  $this->logErrorForExternalProcess( $result->getExitCode(),
298  $result->getStdout(),
299  $command
300  );
301 
302  return false;
303  }
304 
305  return true;
306  }
307 }
ExifBitmapHandler
Stuff specific to JPEG and (built-in) TIFF handler.
Definition: ExifBitmapHandler.php:34
MediaWiki\Shell\Shell
Executes shell commands.
Definition: Shell.php:45
MediaTransformError
Basic media transform error class.
Definition: MediaTransformError.php:31
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:203
JpegHandler\SRGB_EXIF_COLOR_SPACE
const SRGB_EXIF_COLOR_SPACE
Definition: JpegHandler.php:37
$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)
Stability: stableto override
Definition: JpegHandler.php:96
$res
$res
Definition: testCompression.php:57
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:50
JpegHandler\supportsBucketing
supportsBucketing()
Returns whether or not this handler supports the chained generation of thumbnails according to bucket...
Definition: JpegHandler.php:175
MWException
MediaWiki exception.
Definition: MWException.php:29
JpegHandler\getSizeAndMetadata
getSizeAndMetadata( $state, $filename)
Get image size information and metadata array.
Definition: JpegHandler.php:104
Exif\version
static version()
#-
Definition: Exif.php:590
JpegHandler\SRGB_ICC_PROFILE_DESCRIPTION
const SRGB_ICC_PROFILE_DESCRIPTION
Definition: JpegHandler.php:38
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:894
JpegHandler\normaliseParams
normaliseParams( $image, &$params)
Definition: JpegHandler.php:40
JpegHandler\swapICCProfile
swapICCProfile( $filepath, array $colorSpaces, array $oldProfileStrings, $profileFilepath)
Swaps an embedded ICC profile for another, if found.
Definition: JpegHandler.php:246
JpegHandler\sanitizeParamsForBucketing
sanitizeParamsForBucketing( $params)
Returns a normalised params array for which parameters have been cleaned up for bucketing purposes....
Definition: JpegHandler.php:179
JpegHandler
JPEG specific handler.
Definition: JpegHandler.php:36
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:185
JpegHandler\rotate
rotate( $file, $params)
Definition: JpegHandler.php:144
$command
$command
Definition: mcc.php:125
ExifBitmapHandler\applyExifRotation
applyExifRotation( $info, $metadata)
Definition: ExifBitmapHandler.php:158
MediaHandler\logErrorForExternalProcess
logErrorForExternalProcess( $retval, $err, $cmd)
Log an error that occurred in an external process.
Definition: MediaHandler.php:1008
JpegHandler\validateQuality
static validateQuality( $value)
Validate and normalize quality value to be between 1 and 100 (inclusive).
Definition: JpegHandler.php:62
ExifBitmapHandler\BROKEN_FILE
const BROKEN_FILE
Error extracting metadata.
Definition: ExifBitmapHandler.php:36
BitmapMetadataHandler\Jpeg
static Jpeg( $filename)
Main entry point for jpeg's.
Definition: BitmapMetadataHandler.php:164
JpegHandler\makeParamString
makeParamString( $params)
Merge a parameter array into a string appropriate for inclusion in filenames.Array of parameters that...
Definition: JpegHandler.php:66
JpegHandler\transformImageMagick
transformImageMagick( $image, $params)
Transform an image using ImageMagick.Stability: stableto overrideFile associated with this thumbnail ...
Definition: JpegHandler.php:191
JpegHandler\parseParamString
parseParamString( $str)
Parse a param string made with makeParamString back into an array.The parameter string without file n...
Definition: JpegHandler.php:75