6474b7d6f95bdc56b5d1d6576ae3c3bb81de314b
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 use MediaWiki\Shell\Shell
;
24 * Class encapsulating an image used in a ResourceLoaderImageModule.
26 * @ingroup ResourceLoader
29 class ResourceLoaderImage
{
32 * Map of allowed file extensions to their MIME types.
35 protected static $fileTypes = [
36 'svg' => 'image/svg+xml',
46 /** @var string|array */
52 /** @var string|null */
53 private $defaultColor;
58 * @param string $name Image name
59 * @param string $module Module name
60 * @param string|array $descriptor Path to image file, or array structure containing paths
61 * @param string $basePath Directory to which paths in descriptor refer
62 * @param array $variants
63 * @param string|null $defaultColor of the base variant
64 * @throws InvalidArgumentException
66 public function __construct( $name, $module, $descriptor, $basePath, $variants,
70 $this->module
= $module;
71 $this->descriptor
= $descriptor;
72 $this->basePath
= $basePath;
73 $this->variants
= $variants;
74 $this->defaultColor
= $defaultColor;
77 // [ "en,de,fr" => "foo.svg" ]
78 // → [ "en" => "foo.svg", "de" => "foo.svg", "fr" => "foo.svg" ]
79 if ( is_array( $this->descriptor
) && isset( $this->descriptor
['lang'] ) ) {
80 foreach ( array_keys( $this->descriptor
['lang'] ) as $langList ) {
81 if ( strpos( $langList, ',' ) !== false ) {
82 $this->descriptor
['lang'] +
= array_fill_keys(
83 explode( ',', $langList ),
84 $this->descriptor
['lang'][$langList]
86 unset( $this->descriptor
['lang'][$langList] );
90 // Remove 'deprecated' key
91 if ( is_array( $this->descriptor
) ) {
92 unset( $this->descriptor
['deprecated'] );
95 // Ensure that all files have common extension.
97 $descriptor = is_array( $this->descriptor
) ?
$this->descriptor
: [ $this->descriptor
];
98 array_walk_recursive( $descriptor, function ( $path ) use ( &$extensions ) {
99 $extensions[] = pathinfo( $this->getLocalPath( $path ), PATHINFO_EXTENSION
);
101 $extensions = array_unique( $extensions );
102 if ( count( $extensions ) !== 1 ) {
103 throw new InvalidArgumentException(
104 "File type for different image files of '$name' not the same in module '$module'"
107 $ext = $extensions[0];
108 if ( !isset( self
::$fileTypes[$ext] ) ) {
109 throw new InvalidArgumentException(
110 "Invalid file type for image files of '$name' (valid: svg, png, gif, jpg) in module '$module'"
113 $this->extension
= $ext;
117 * Get name of this image.
121 public function getName() {
126 * Get name of the module this image belongs to.
130 public function getModule() {
131 return $this->module
;
135 * Get the list of variants this image can be converted to.
139 public function getVariants() {
140 return array_keys( $this->variants
);
144 * Get the path to image file for given context.
146 * @param ResourceLoaderContext $context Any context
148 * @throws MWException If no matching path is found
150 public function getPath( ResourceLoaderContext
$context ) {
151 $desc = $this->descriptor
;
152 if ( !is_array( $desc ) ) {
153 return $this->getLocalPath( $desc );
155 if ( isset( $desc['lang'] ) ) {
156 $contextLang = $context->getLanguage();
157 if ( isset( $desc['lang'][$contextLang] ) ) {
158 return $this->getLocalPath( $desc['lang'][$contextLang] );
160 $fallbacks = Language
::getFallbacksFor( $contextLang, Language
::STRICT_FALLBACKS
);
161 foreach ( $fallbacks as $lang ) {
162 if ( isset( $desc['lang'][$lang] ) ) {
163 return $this->getLocalPath( $desc['lang'][$lang] );
167 if ( isset( $desc[$context->getDirection()] ) ) {
168 return $this->getLocalPath( $desc[$context->getDirection()] );
170 if ( isset( $desc['default'] ) ) {
171 return $this->getLocalPath( $desc['default'] );
173 throw new MWException( 'No matching path found' );
178 * @param string|ResourceLoaderFilePath $path
181 protected function getLocalPath( $path ) {
182 if ( $path instanceof ResourceLoaderFilePath
) {
183 return $path->getLocalPath();
186 return "{$this->basePath}/$path";
190 * Get the extension of the image.
192 * @param string $format Format to get the extension for, 'original' or 'rasterized'
193 * @return string Extension without leading dot, e.g. 'png'
195 public function getExtension( $format = 'original' ) {
196 if ( $format === 'rasterized' && $this->extension
=== 'svg' ) {
199 return $this->extension
;
203 * Get the MIME type of the image.
205 * @param string $format Format to get the MIME type for, 'original' or 'rasterized'
208 public function getMimeType( $format = 'original' ) {
209 $ext = $this->getExtension( $format );
210 return self
::$fileTypes[$ext];
214 * Get the load.php URL that will produce this image.
216 * @param ResourceLoaderContext $context Any context
217 * @param string $script URL to load.php
218 * @param string|null $variant Variant to get the URL for
219 * @param string $format Format to get the URL for, 'original' or 'rasterized'
222 public function getUrl( ResourceLoaderContext
$context, $script, $variant, $format ) {
224 'modules' => $this->getModule(),
225 'image' => $this->getName(),
226 'variant' => $variant,
229 if ( $this->varyOnLanguage() ) {
230 $query['lang'] = $context->getLanguage();
232 // The following parameters are at the end to keep the original order of the parameters.
233 $query['skin'] = $context->getSkin();
234 $query['version'] = $context->getVersion();
236 return wfAppendQuery( $script, $query );
240 * Get the data: URI that will produce this image.
242 * @param ResourceLoaderContext $context Any context
243 * @param string|null $variant Variant to get the URI for
244 * @param string $format Format to get the URI for, 'original' or 'rasterized'
247 public function getDataUri( ResourceLoaderContext
$context, $variant, $format ) {
248 $type = $this->getMimeType( $format );
249 $contents = $this->getImageData( $context, $variant, $format );
250 return CSSMin
::encodeStringAsDataURI( $contents, $type );
254 * Get actual image data for this image. This can be saved to a file or sent to the browser to
255 * produce the converted image.
257 * Call getExtension() or getMimeType() with the same $format argument to learn what file type the
258 * returned data uses.
260 * @param ResourceLoaderContext $context Image context, or any context if $variant and $format
262 * @param string|null $variant Variant to get the data for. Optional; if given, overrides the data
264 * @param string $format Format to get the data for, 'original' or 'rasterized'. Optional; if
265 * given, overrides the data from $context.
266 * @return string|false Possibly binary image data, or false on failure
267 * @throws MWException If the image file doesn't exist
269 public function getImageData( ResourceLoaderContext
$context, $variant = false, $format = false ) {
270 if ( $variant === false ) {
271 $variant = $context->getVariant();
273 if ( $format === false ) {
274 $format = $context->getFormat();
277 $path = $this->getPath( $context );
278 if ( !file_exists( $path ) ) {
279 throw new MWException( "File '$path' does not exist" );
282 if ( $this->getExtension() !== 'svg' ) {
283 return file_get_contents( $path );
286 if ( $variant && isset( $this->variants
[$variant] ) ) {
287 $data = $this->variantize( $this->variants
[$variant], $context );
289 $defaultColor = $this->defaultColor
;
290 $data = $defaultColor ?
291 $this->variantize( [ 'color' => $defaultColor ], $context ) :
292 file_get_contents( $path );
295 if ( $format === 'rasterized' ) {
296 $data = $this->rasterize( $data );
298 wfDebugLog( 'ResourceLoaderImage', __METHOD__
. " failed to rasterize for $path" );
306 * Send response headers (using the header() function) that are necessary to correctly serve the
307 * image data for this image, as returned by getImageData().
309 * Note that the headers are independent of the language or image variant.
311 * @param ResourceLoaderContext $context Image context
313 public function sendResponseHeaders( ResourceLoaderContext
$context ) {
314 $format = $context->getFormat();
315 $mime = $this->getMimeType( $format );
316 $filename = $this->getName() . '.' . $this->getExtension( $format );
318 header( 'Content-Type: ' . $mime );
319 header( 'Content-Disposition: ' .
320 FileBackend
::makeContentDisposition( 'inline', $filename ) );
324 * Convert this image, which is assumed to be SVG, to given variant.
326 * @param array $variantConf Array with a 'color' key, its value will be used as fill color
327 * @param ResourceLoaderContext $context Image context
328 * @return string New SVG file data
330 protected function variantize( $variantConf, ResourceLoaderContext
$context ) {
331 $dom = new DOMDocument
;
332 $dom->loadXML( file_get_contents( $this->getPath( $context ) ) );
333 $root = $dom->documentElement
;
335 $wrapper = $dom->createElementNS( 'http://www.w3.org/2000/svg', 'g' );
336 // Reattach all direct children of the `<svg>` root node to the `<g>` wrapper
337 while ( $root->firstChild
) {
338 $node = $root->firstChild
;
339 if ( !$titleNode && $node->nodeType
=== XML_ELEMENT_NODE
&& $node->tagName
=== 'title' ) {
340 // Remember the first encountered `<title>` node
343 $wrapper->appendChild( $node );
346 // Reattach the `<title>` node to the `<svg>` root node rather than the `<g>` wrapper
347 $root->appendChild( $titleNode );
349 $root->appendChild( $wrapper );
350 $wrapper->setAttribute( 'fill', $variantConf['color'] );
351 return $dom->saveXML();
355 * Massage the SVG image data for converters which don't understand some path data syntax.
357 * This is necessary for rsvg and ImageMagick when compiled with rsvg support.
358 * Upstream bug is https://bugzilla.gnome.org/show_bug.cgi?id=620923, fixed 2014-11-10, so
359 * this will be needed for a while. (T76852)
361 * @param string $svg SVG image data
362 * @return string Massaged SVG image data
364 protected function massageSvgPathdata( $svg ) {
365 $dom = new DOMDocument
;
366 $dom->loadXML( $svg );
367 foreach ( $dom->getElementsByTagName( 'path' ) as $node ) {
368 $pathData = $node->getAttribute( 'd' );
369 // Make sure there is at least one space between numbers, and that leading zero is not omitted.
370 // rsvg has issues with syntax like "M-1-2" and "M.445.483" and especially "M-.445-.483".
371 $pathData = preg_replace( '/(-?)(\d*\.\d+|\d+)/', ' ${1}0$2 ', $pathData );
372 // Strip unnecessary leading zeroes for prettiness, not strictly necessary
373 $pathData = preg_replace( '/([ -])0(\d)/', '$1$2', $pathData );
374 $node->setAttribute( 'd', $pathData );
376 return $dom->saveXML();
380 * Convert passed image data, which is assumed to be SVG, to PNG.
382 * @param string $svg SVG image data
383 * @return string|bool PNG image data, or false on failure
385 protected function rasterize( $svg ) {
387 * This code should be factored out to a separate method on SvgHandler, or perhaps a separate
388 * class, with a separate set of configuration settings.
390 * This is a distinct use case from regular SVG rasterization:
391 * * We can skip many sanity and security checks (as the images come from a trusted source,
392 * rather than from the user).
393 * * We need to provide extra options to some converters to achieve acceptable quality for very
394 * small images, which might cause performance issues in the general case.
395 * * We want to directly pass image data to the converter, rather than a file path.
397 * See https://phabricator.wikimedia.org/T76473#801446 for examples of what happens with the
400 * For now, we special-case rsvg (used in WMF production) and do a messy workaround for other
404 global $wgSVGConverter, $wgSVGConverterPath;
406 $svg = $this->massageSvgPathdata( $svg );
408 // Sometimes this might be 'rsvg-secure'. Long as it's rsvg.
409 if ( strpos( $wgSVGConverter, 'rsvg' ) === 0 ) {
410 $command = 'rsvg-convert';
411 if ( $wgSVGConverterPath ) {
412 $command = Shell
::escape( "$wgSVGConverterPath/" ) . $command;
415 $process = proc_open(
417 [ 0 => [ 'pipe', 'r' ], 1 => [ 'pipe', 'w' ] ],
421 if ( is_resource( $process ) ) {
422 fwrite( $pipes[0], $svg );
424 $png = stream_get_contents( $pipes[1] );
426 proc_close( $process );
428 return $png ?
: false;
433 // Write input to and read output from a temporary file
434 $tempFilenameSvg = tempnam( wfTempDir(), 'ResourceLoaderImage' );
435 $tempFilenamePng = tempnam( wfTempDir(), 'ResourceLoaderImage' );
437 file_put_contents( $tempFilenameSvg, $svg );
439 $svgReader = new SVGReader( $tempFilenameSvg );
440 $metadata = $svgReader->getMetadata();
441 if ( !isset( $metadata['width'] ) ||
!isset( $metadata['height'] ) ) {
442 unlink( $tempFilenameSvg );
446 $handler = new SvgHandler
;
447 $res = $handler->rasterize(
453 unlink( $tempFilenameSvg );
456 if ( $res === true ) {
457 $png = file_get_contents( $tempFilenamePng );
458 unlink( $tempFilenamePng );
461 return $png ?
: false;
466 * Check if the image depends on the language.
470 private function varyOnLanguage() {
471 return is_array( $this->descriptor
) && (
472 isset( $this->descriptor
['ltr'] ) ||
473 isset( $this->descriptor
['rtl'] ) ||
474 isset( $this->descriptor
['lang'] ) );