Merge "Align "What's this" vertically"
[lhc/web/wiklou.git] / includes / media / Jpeg.php
1 <?php
2 /**
3 * Handler for JPEG images.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Media
22 */
23
24 /**
25 * JPEG specific handler.
26 * Inherits most stuff from BitmapHandler, just here to do the metadata handler differently.
27 *
28 * Metadata stuff common to Jpeg and built-in Tiff (not PagedTiffHandler) is
29 * in ExifBitmapHandler.
30 *
31 * @ingroup Media
32 */
33 class JpegHandler extends ExifBitmapHandler {
34 const SRGB_EXIF_COLOR_SPACE = 'sRGB';
35 const SRGB_ICC_PROFILE_DESCRIPTION = 'sRGB IEC61966-2.1';
36
37 function normaliseParams( $image, &$params ) {
38 if ( !parent::normaliseParams( $image, $params ) ) {
39 return false;
40 }
41 if ( isset( $params['quality'] ) && !self::validateQuality( $params['quality'] ) ) {
42 return false;
43 }
44 return true;
45 }
46
47 public function validateParam( $name, $value ) {
48 if ( $name === 'quality' ) {
49 return self::validateQuality( $value );
50 } else {
51 return parent::validateParam( $name, $value );
52 }
53 }
54
55 /** Validate and normalize quality value to be between 1 and 100 (inclusive).
56 * @param int $value Quality value, will be converted to integer or 0 if invalid
57 * @return bool True if the value is valid
58 */
59 private static function validateQuality( $value ) {
60 return $value === 'low';
61 }
62
63 public function makeParamString( $params ) {
64 // Prepend quality as "qValue-". This has to match parseParamString() below
65 $res = parent::makeParamString( $params );
66 if ( $res && isset( $params['quality'] ) ) {
67 $res = "q{$params['quality']}-$res";
68 }
69 return $res;
70 }
71
72 public function parseParamString( $str ) {
73 // $str contains "qlow-200px" or "200px" strings because thumb.php would strip the filename
74 // first - check if the string begins with "qlow-", and if so, treat it as quality.
75 // Pass the first portion, or the whole string if "qlow-" not found, to the parent
76 // The parsing must match the makeParamString() above
77 $res = false;
78 $m = false;
79 if ( preg_match( '/q([^-]+)-(.*)$/', $str, $m ) ) {
80 $v = $m[1];
81 if ( self::validateQuality( $v ) ) {
82 $res = parent::parseParamString( $m[2] );
83 if ( $res ) {
84 $res['quality'] = $v;
85 }
86 }
87 } else {
88 $res = parent::parseParamString( $str );
89 }
90 return $res;
91 }
92
93 function getScriptParams( $params ) {
94 $res = parent::getScriptParams( $params );
95 if ( isset( $params['quality'] ) ) {
96 $res['quality'] = $params['quality'];
97 }
98 return $res;
99 }
100
101 function getMetadata( $image, $filename ) {
102 try {
103 $meta = BitmapMetadataHandler::Jpeg( $filename );
104 if ( !is_array( $meta ) ) {
105 // This should never happen, but doesn't hurt to be paranoid.
106 throw new MWException( 'Metadata array is not an array' );
107 }
108 $meta['MEDIAWIKI_EXIF_VERSION'] = Exif::version();
109
110 return serialize( $meta );
111 } catch ( Exception $e ) {
112 // BitmapMetadataHandler throws an exception in certain exceptional
113 // cases like if file does not exist.
114 wfDebug( __METHOD__ . ': ' . $e->getMessage() . "\n" );
115
116 /* This used to use 0 (ExifBitmapHandler::OLD_BROKEN_FILE) for the cases
117 * * No metadata in the file
118 * * Something is broken in the file.
119 * However, if the metadata support gets expanded then you can't tell if the 0 is from
120 * a broken file, or just no props found. A broken file is likely to stay broken, but
121 * a file which had no props could have props once the metadata support is improved.
122 * Thus switch to using -1 to denote only a broken file, and use an array with only
123 * MEDIAWIKI_EXIF_VERSION to denote no props.
124 */
125
126 return ExifBitmapHandler::BROKEN_FILE;
127 }
128 }
129
130 /**
131 * @param File $file
132 * @param array $params Rotate parameters.
133 * 'rotation' clockwise rotation in degrees, allowed are multiples of 90
134 * @since 1.21
135 * @return bool|MediaTransformError
136 */
137 public function rotate( $file, $params ) {
138 global $wgJpegTran;
139
140 $rotation = ( $params['rotation'] + $this->getRotation( $file ) ) % 360;
141
142 if ( $wgJpegTran && is_executable( $wgJpegTran ) ) {
143 $cmd = wfEscapeShellArg( $wgJpegTran ) .
144 " -rotate " . wfEscapeShellArg( $rotation ) .
145 " -outfile " . wfEscapeShellArg( $params['dstPath'] ) .
146 " " . wfEscapeShellArg( $params['srcPath'] );
147 wfDebug( __METHOD__ . ": running jpgtran: $cmd\n" );
148 $retval = 0;
149 $err = wfShellExecWithStderr( $cmd, $retval );
150 if ( $retval !== 0 ) {
151 $this->logErrorForExternalProcess( $retval, $err, $cmd );
152
153 return new MediaTransformError( 'thumbnail_error', 0, 0, $err );
154 }
155
156 return false;
157 } else {
158 return parent::rotate( $file, $params );
159 }
160 }
161
162 public function supportsBucketing() {
163 return true;
164 }
165
166 public function sanitizeParamsForBucketing( $params ) {
167 $params = parent::sanitizeParamsForBucketing( $params );
168
169 // Quality needs to be cleared for bucketing. Buckets need to be default quality
170 if ( isset( $params['quality'] ) ) {
171 unset( $params['quality'] );
172 }
173
174 return $params;
175 }
176
177 /**
178 * @inheritDoc
179 */
180 protected function transformImageMagick( $image, $params ) {
181 global $wgUseTinyRGBForJPGThumbnails;
182
183 $ret = parent::transformImageMagick( $image, $params );
184
185 if ( $ret ) {
186 return $ret;
187 }
188
189 if ( $wgUseTinyRGBForJPGThumbnails ) {
190 // T100976 If the profile embedded in the JPG is sRGB, swap it for the smaller
191 // (and free) TinyRGB
192
193 /**
194 * We'll want to replace the color profile for JPGs:
195 * * in the sRGB color space, or with the sRGB profile
196 * (other profiles will be left untouched)
197 * * without color space or profile, in which case browsers
198 * should assume sRGB, but don't always do (e.g. on wide-gamut
199 * monitors (unless it's meant for low bandwith)
200 * @see https://phabricator.wikimedia.org/T134498
201 */
202 $colorSpaces = [ self::SRGB_EXIF_COLOR_SPACE, '-' ];
203 $profiles = [ self::SRGB_ICC_PROFILE_DESCRIPTION ];
204
205 // we'll also add TinyRGB profile to images lacking a profile, but
206 // only if they're not low quality (which are meant to save bandwith
207 // and we don't want to increase the filesize by adding a profile)
208 if ( isset( $params['quality'] ) && $params['quality'] > 30 ) {
209 $profiles[] = '-';
210 }
211
212 $this->swapICCProfile(
213 $params['dstPath'],
214 $colorSpaces,
215 $profiles,
216 realpath( __DIR__ ) . '/tinyrgb.icc'
217 );
218 }
219
220 return false;
221 }
222
223 /**
224 * Swaps an embedded ICC profile for another, if found.
225 * Depends on exiftool, no-op if not installed.
226 * @param string $filepath File to be manipulated (will be overwritten)
227 * @param array $colorSpaces Only process files with this/these Color Space(s)
228 * @param array $oldProfileStrings Exact name(s) of color profile to look for
229 * (the one that will be replaced)
230 * @param string $profileFilepath ICC profile file to apply to the file
231 * @since 1.26
232 * @return bool
233 */
234 public function swapICCProfile( $filepath, array $colorSpaces,
235 array $oldProfileStrings, $profileFilepath
236 ) {
237 global $wgExiftool;
238
239 if ( !$wgExiftool || !is_executable( $wgExiftool ) ) {
240 return false;
241 }
242
243 $cmd = wfEscapeShellArg( $wgExiftool,
244 '-EXIF:ColorSpace',
245 '-ICC_Profile:ProfileDescription',
246 '-S',
247 '-T',
248 $filepath
249 );
250
251 $output = wfShellExecWithStderr( $cmd, $retval );
252
253 // Explode EXIF data into an array with [0 => Color Space, 1 => Device Model Desc]
254 $data = explode( "\t", trim( $output ) );
255
256 if ( $retval !== 0 ) {
257 return false;
258 }
259
260 // Make a regex out of the source data to match it to an array of color
261 // spaces in a case-insensitive way
262 $colorSpaceRegex = '/'.preg_quote( $data[0], '/' ).'/i';
263 if ( empty( preg_grep( $colorSpaceRegex, $colorSpaces ) ) ) {
264 // We can't establish that this file matches the color space, don't process it
265 return false;
266 }
267
268 $profileRegex = '/'.preg_quote( $data[1], '/' ).'/i';
269 if ( empty( preg_grep( $profileRegex, $oldProfileStrings ) ) ) {
270 // We can't establish that this file has the expected ICC profile, don't process it
271 return false;
272 }
273
274 $cmd = wfEscapeShellArg( $wgExiftool,
275 '-overwrite_original',
276 '-icc_profile<=' . $profileFilepath,
277 $filepath
278 );
279
280 $output = wfShellExecWithStderr( $cmd, $retval );
281
282 if ( $retval !== 0 ) {
283 $this->logErrorForExternalProcess( $retval, $output, $cmd );
284
285 return false;
286 }
287
288 return true;
289 }
290 }