MediaWiki REL1_33
JpegHandler.php
Go to the documentation of this file.
1<?php
25
36 const SRGB_EXIF_COLOR_SPACE = 'sRGB';
37 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' ) {
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() . "\n" );
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 );
153 ->includeStderr()
154 ->execute();
155 if ( $result->getExitCode() !== 0 ) {
156 $this->logErrorForExternalProcess( $result->getExitCode(),
157 $result->getStdout(),
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
175 $params = parent::sanitizeParamsForBucketing( $params );
176
177 // Quality needs to be cleared for bucketing. Buckets need to be default quality
178 if ( isset( $params['quality'] ) ) {
179 unset( $params['quality'] );
180 }
181
182 return $params;
183 }
184
188 protected function transformImageMagick( $image, $params ) {
190
191 $ret = parent::transformImageMagick( $image, $params );
192
193 if ( $ret ) {
194 return $ret;
195 }
196
198 // T100976 If the profile embedded in the JPG is sRGB, swap it for the smaller
199 // (and free) TinyRGB
200
210 $colorSpaces = [ self::SRGB_EXIF_COLOR_SPACE, '-' ];
212
213 // we'll also add TinyRGB profile to images lacking a profile, but
214 // only if they're not low quality (which are meant to save bandwith
215 // and we don't want to increase the filesize by adding a profile)
216 if ( isset( $params['quality'] ) && $params['quality'] > 30 ) {
217 $profiles[] = '-';
218 }
219
220 $this->swapICCProfile(
221 $params['dstPath'],
222 $colorSpaces,
223 $profiles,
224 realpath( __DIR__ ) . '/tinyrgb.icc'
225 );
226 }
227
228 return false;
229 }
230
242 public function swapICCProfile( $filepath, array $colorSpaces,
243 array $oldProfileStrings, $profileFilepath
244 ) {
245 global $wgExiftool;
246
247 if ( !$wgExiftool || !is_executable( $wgExiftool ) ) {
248 return false;
249 }
250
251 $result = Shell::command(
253 '-EXIF:ColorSpace',
254 '-ICC_Profile:ProfileDescription',
255 '-S',
256 '-T',
257 $filepath
258 )
259 ->includeStderr()
260 ->execute();
261
262 // Explode EXIF data into an array with [0 => Color Space, 1 => Device Model Desc]
263 $data = explode( "\t", trim( $result->getStdout() ) );
264
265 if ( $result->getExitCode() !== 0 ) {
266 return false;
267 }
268
269 // Make a regex out of the source data to match it to an array of color
270 // spaces in a case-insensitive way
271 $colorSpaceRegex = '/' . preg_quote( $data[0], '/' ) . '/i';
272 if ( empty( preg_grep( $colorSpaceRegex, $colorSpaces ) ) ) {
273 // We can't establish that this file matches the color space, don't process it
274 return false;
275 }
276
277 $profileRegex = '/' . preg_quote( $data[1], '/' ) . '/i';
278 if ( empty( preg_grep( $profileRegex, $oldProfileStrings ) ) ) {
279 // We can't establish that this file has the expected ICC profile, don't process it
280 return false;
281 }
282
283 $command = Shell::command( $wgExiftool,
284 '-overwrite_original',
285 '-icc_profile<=' . $profileFilepath,
286 $filepath
287 );
289 ->includeStderr()
290 ->execute();
291
292 if ( $result->getExitCode() !== 0 ) {
293 $this->logErrorForExternalProcess( $result->getExitCode(),
294 $result->getStdout(),
296 );
297
298 return false;
299 }
300
301 return true;
302 }
303}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
serialize()
$wgUseTinyRGBForJPGThumbnails
When this variable is true and JPGs use the sRGB ICC profile, swaps it for the more lightweight (and ...
$wgJpegTran
used for lossless jpeg rotation
$wgExiftool
Path to exiftool binary.
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
$command
Definition cdb.php:65
static Jpeg( $filename)
Main entry point for jpeg's.
Stuff specific to JPEG and (built-in) TIFF handler.
getRotation( $file)
On supporting image formats, try to read out the low-level orientation of the file and return the ang...
static version()
#-
Definition Exif.php:581
JPEG specific handler.
makeParamString( $params)
Merge a parameter array into a string appropriate for inclusion in filenames.
validateParam( $name, $value)
Validate a thumbnail parameter at parse time.
const SRGB_ICC_PROFILE_DESCRIPTION
getScriptParams( $params)
getMetadata( $image, $filename)
Get handler-specific metadata which will be saved in the img_metadata field.
swapICCProfile( $filepath, array $colorSpaces, array $oldProfileStrings, $profileFilepath)
Swaps an embedded ICC profile for another, if found.
static validateQuality( $value)
Validate and normalize quality value to be between 1 and 100 (inclusive).
supportsBucketing()
Returns whether or not this handler supports the chained generation of thumbnails according to bucket...
rotate( $file, $params)
const SRGB_EXIF_COLOR_SPACE
parseParamString( $str)
Parse a param string made with makeParamString back into an array.
sanitizeParamsForBucketing( $params)
Returns a normalised params array for which parameters have been cleaned up for bucketing purposes.
normaliseParams( $image, &$params)
transformImageMagick( $image, $params)
@inheritDoc
MediaWiki exception.
logErrorForExternalProcess( $retval, $err, $cmd)
Log an error that occurred in an external process.
Basic media transform error class.
Executes shell commands.
Definition Shell.php:44
$res
Definition database.txt:21
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check $image
Definition hooks.txt:886
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition hooks.txt:1991
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition hooks.txt:2003
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:271
returning false will NOT prevent logging $e
Definition hooks.txt:2175
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Definition router.php:42
$params