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 Self-name of the image as known to ResourceLoaderImageModule.
59 * @param string $module Self-name of the module containing this image.
60 * Used to find the image in the registry e.g. through a load.php url.
61 * @param string|array $descriptor Path to image file, or array structure containing paths
62 * @param string $basePath Directory to which paths in descriptor refer
63 * @param array $variants
64 * @param string|null $defaultColor of the base variant
65 * @throws InvalidArgumentException
67 public function __construct( $name, $module, $descriptor, $basePath, $variants,
71 $this->module
= $module;
72 $this->descriptor
= $descriptor;
73 $this->basePath
= $basePath;
74 $this->variants
= $variants;
75 $this->defaultColor
= $defaultColor;
78 // [ "en,de,fr" => "foo.svg" ]
79 // → [ "en" => "foo.svg", "de" => "foo.svg", "fr" => "foo.svg" ]
80 if ( is_array( $this->descriptor
) && isset( $this->descriptor
['lang'] ) ) {
81 foreach ( array_keys( $this->descriptor
['lang'] ) as $langList ) {
82 if ( strpos( $langList, ',' ) !== false ) {
83 $this->descriptor
['lang'] +
= array_fill_keys(
84 explode( ',', $langList ),
85 $this->descriptor
['lang'][$langList]
87 unset( $this->descriptor
['lang'][$langList] );
91 // Remove 'deprecated' key
92 if ( is_array( $this->descriptor
) ) {
93 unset( $this->descriptor
['deprecated'] );
96 // Ensure that all files have common extension.
98 $descriptor = is_array( $this->descriptor
) ?
$this->descriptor
: [ $this->descriptor
];
99 array_walk_recursive( $descriptor, function ( $path ) use ( &$extensions ) {
100 $extensions[] = pathinfo( $this->getLocalPath( $path ), PATHINFO_EXTENSION
);
102 $extensions = array_unique( $extensions );
103 if ( count( $extensions ) !== 1 ) {
104 throw new InvalidArgumentException(
105 "File type for different image files of '$name' not the same in module '$module'"
108 $ext = $extensions[0];
109 if ( !isset( self
::$fileTypes[$ext] ) ) {
110 throw new InvalidArgumentException(
111 "Invalid file type for image files of '$name' (valid: svg, png, gif, jpg) in module '$module'"
114 $this->extension
= $ext;
118 * Get name of this image.
122 public function getName() {
127 * Get name of the module this image belongs to.
131 public function getModule() {
132 return $this->module
;
136 * Get the list of variants this image can be converted to.
140 public function getVariants() {
141 return array_keys( $this->variants
);
145 * Get the path to image file for given context.
147 * @param ResourceLoaderContext $context Any context
149 * @throws MWException If no matching path is found
151 public function getPath( ResourceLoaderContext
$context ) {
152 $desc = $this->descriptor
;
153 if ( !is_array( $desc ) ) {
154 return $this->getLocalPath( $desc );
156 if ( isset( $desc['lang'] ) ) {
157 $contextLang = $context->getLanguage();
158 if ( isset( $desc['lang'][$contextLang] ) ) {
159 return $this->getLocalPath( $desc['lang'][$contextLang] );
161 $fallbacks = Language
::getFallbacksFor( $contextLang, Language
::STRICT_FALLBACKS
);
162 foreach ( $fallbacks as $lang ) {
163 if ( isset( $desc['lang'][$lang] ) ) {
164 return $this->getLocalPath( $desc['lang'][$lang] );
168 if ( isset( $desc[$context->getDirection()] ) ) {
169 return $this->getLocalPath( $desc[$context->getDirection()] );
171 if ( isset( $desc['default'] ) ) {
172 return $this->getLocalPath( $desc['default'] );
174 throw new MWException( 'No matching path found' );
179 * @param string|ResourceLoaderFilePath $path
182 protected function getLocalPath( $path ) {
183 if ( $path instanceof ResourceLoaderFilePath
) {
184 return $path->getLocalPath();
187 return "{$this->basePath}/$path";
191 * Get the extension of the image.
193 * @param string $format Format to get the extension for, 'original' or 'rasterized'
194 * @return string Extension without leading dot, e.g. 'png'
196 public function getExtension( $format = 'original' ) {
197 if ( $format === 'rasterized' && $this->extension
=== 'svg' ) {
200 return $this->extension
;
204 * Get the MIME type of the image.
206 * @param string $format Format to get the MIME type for, 'original' or 'rasterized'
209 public function getMimeType( $format = 'original' ) {
210 $ext = $this->getExtension( $format );
211 return self
::$fileTypes[$ext];
215 * Get the load.php URL that will produce this image.
217 * @param ResourceLoaderContext $context Any context
218 * @param string $script URL to load.php
219 * @param string|null $variant Variant to get the URL for
220 * @param string $format Format to get the URL for, 'original' or 'rasterized'
223 public function getUrl( ResourceLoaderContext
$context, $script, $variant, $format ) {
225 'modules' => $this->getModule(),
226 'image' => $this->getName(),
227 'variant' => $variant,
230 if ( $this->varyOnLanguage() ) {
231 $query['lang'] = $context->getLanguage();
233 // The following parameters are at the end to keep the original order of the parameters.
234 $query['skin'] = $context->getSkin();
235 $rl = $context->getResourceLoader();
236 $query['version'] = $rl->makeVersionQuery( $context, [ $this->getModule() ] );
238 return wfAppendQuery( $script, $query );
242 * Get the data: URI that will produce this image.
244 * @param ResourceLoaderContext $context Any context
245 * @param string|null $variant Variant to get the URI for
246 * @param string $format Format to get the URI for, 'original' or 'rasterized'
249 public function getDataUri( ResourceLoaderContext
$context, $variant, $format ) {
250 $type = $this->getMimeType( $format );
251 $contents = $this->getImageData( $context, $variant, $format );
252 return CSSMin
::encodeStringAsDataURI( $contents, $type );
256 * Get actual image data for this image. This can be saved to a file or sent to the browser to
257 * produce the converted image.
259 * Call getExtension() or getMimeType() with the same $format argument to learn what file type the
260 * returned data uses.
262 * @param ResourceLoaderContext $context Image context, or any context if $variant and $format
264 * @param string|null $variant Variant to get the data for. Optional; if given, overrides the data
266 * @param string $format Format to get the data for, 'original' or 'rasterized'. Optional; if
267 * given, overrides the data from $context.
268 * @return string|false Possibly binary image data, or false on failure
269 * @throws MWException If the image file doesn't exist
271 public function getImageData( ResourceLoaderContext
$context, $variant = false, $format = false ) {
272 if ( $variant === false ) {
273 $variant = $context->getVariant();
275 if ( $format === false ) {
276 $format = $context->getFormat();
279 $path = $this->getPath( $context );
280 if ( !file_exists( $path ) ) {
281 throw new MWException( "File '$path' does not exist" );
284 if ( $this->getExtension() !== 'svg' ) {
285 return file_get_contents( $path );
288 if ( $variant && isset( $this->variants
[$variant] ) ) {
289 $data = $this->variantize( $this->variants
[$variant], $context );
291 $defaultColor = $this->defaultColor
;
292 $data = $defaultColor ?
293 $this->variantize( [ 'color' => $defaultColor ], $context ) :
294 file_get_contents( $path );
297 if ( $format === 'rasterized' ) {
298 $data = $this->rasterize( $data );
300 wfDebugLog( 'ResourceLoaderImage', __METHOD__
. " failed to rasterize for $path" );
308 * Send response headers (using the header() function) that are necessary to correctly serve the
309 * image data for this image, as returned by getImageData().
311 * Note that the headers are independent of the language or image variant.
313 * @param ResourceLoaderContext $context Image context
315 public function sendResponseHeaders( ResourceLoaderContext
$context ) {
316 $format = $context->getFormat();
317 $mime = $this->getMimeType( $format );
318 $filename = $this->getName() . '.' . $this->getExtension( $format );
320 header( 'Content-Type: ' . $mime );
321 header( 'Content-Disposition: ' .
322 FileBackend
::makeContentDisposition( 'inline', $filename ) );
326 * Convert this image, which is assumed to be SVG, to given variant.
328 * @param array $variantConf Array with a 'color' key, its value will be used as fill color
329 * @param ResourceLoaderContext $context Image context
330 * @return string New SVG file data
332 protected function variantize( $variantConf, ResourceLoaderContext
$context ) {
333 $dom = new DOMDocument
;
334 $dom->loadXML( file_get_contents( $this->getPath( $context ) ) );
335 $root = $dom->documentElement
;
337 $wrapper = $dom->createElementNS( 'http://www.w3.org/2000/svg', 'g' );
338 // Reattach all direct children of the `<svg>` root node to the `<g>` wrapper
339 while ( $root->firstChild
) {
340 $node = $root->firstChild
;
341 // @phan-suppress-next-line PhanUndeclaredProperty False positive
342 if ( !$titleNode && $node->nodeType
=== XML_ELEMENT_NODE
&& $node->tagName
=== 'title' ) {
343 // Remember the first encountered `<title>` node
346 $wrapper->appendChild( $node );
349 // Reattach the `<title>` node to the `<svg>` root node rather than the `<g>` wrapper
350 $root->appendChild( $titleNode );
352 $root->appendChild( $wrapper );
353 $wrapper->setAttribute( 'fill', $variantConf['color'] );
354 return $dom->saveXML();
358 * Massage the SVG image data for converters which don't understand some path data syntax.
360 * This is necessary for rsvg and ImageMagick when compiled with rsvg support.
361 * Upstream bug is https://bugzilla.gnome.org/show_bug.cgi?id=620923, fixed 2014-11-10, so
362 * this will be needed for a while. (T76852)
364 * @param string $svg SVG image data
365 * @return string Massaged SVG image data
367 protected function massageSvgPathdata( $svg ) {
368 $dom = new DOMDocument
;
369 $dom->loadXML( $svg );
370 foreach ( $dom->getElementsByTagName( 'path' ) as $node ) {
371 $pathData = $node->getAttribute( 'd' );
372 // Make sure there is at least one space between numbers, and that leading zero is not omitted.
373 // rsvg has issues with syntax like "M-1-2" and "M.445.483" and especially "M-.445-.483".
374 $pathData = preg_replace( '/(-?)(\d*\.\d+|\d+)/', ' ${1}0$2 ', $pathData );
375 // Strip unnecessary leading zeroes for prettiness, not strictly necessary
376 $pathData = preg_replace( '/([ -])0(\d)/', '$1$2', $pathData );
377 $node->setAttribute( 'd', $pathData );
379 return $dom->saveXML();
383 * Convert passed image data, which is assumed to be SVG, to PNG.
385 * @param string $svg SVG image data
386 * @return string|bool PNG image data, or false on failure
388 protected function rasterize( $svg ) {
390 * This code should be factored out to a separate method on SvgHandler, or perhaps a separate
391 * class, with a separate set of configuration settings.
393 * This is a distinct use case from regular SVG rasterization:
394 * * We can skip many sanity and security checks (as the images come from a trusted source,
395 * rather than from the user).
396 * * We need to provide extra options to some converters to achieve acceptable quality for very
397 * small images, which might cause performance issues in the general case.
398 * * We want to directly pass image data to the converter, rather than a file path.
400 * See https://phabricator.wikimedia.org/T76473#801446 for examples of what happens with the
403 * For now, we special-case rsvg (used in WMF production) and do a messy workaround for other
407 global $wgSVGConverter, $wgSVGConverterPath;
409 $svg = $this->massageSvgPathdata( $svg );
411 // Sometimes this might be 'rsvg-secure'. Long as it's rsvg.
412 if ( strpos( $wgSVGConverter, 'rsvg' ) === 0 ) {
413 $command = 'rsvg-convert';
414 if ( $wgSVGConverterPath ) {
415 $command = Shell
::escape( "$wgSVGConverterPath/" ) . $command;
418 $process = proc_open(
420 [ 0 => [ 'pipe', 'r' ], 1 => [ 'pipe', 'w' ] ],
424 if ( is_resource( $process ) ) {
425 fwrite( $pipes[0], $svg );
427 $png = stream_get_contents( $pipes[1] );
429 proc_close( $process );
431 return $png ?
: false;
436 // Write input to and read output from a temporary file
437 $tempFilenameSvg = tempnam( wfTempDir(), 'ResourceLoaderImage' );
438 $tempFilenamePng = tempnam( wfTempDir(), 'ResourceLoaderImage' );
440 file_put_contents( $tempFilenameSvg, $svg );
442 $svgReader = new SVGReader( $tempFilenameSvg );
443 $metadata = $svgReader->getMetadata();
444 if ( !isset( $metadata['width'] ) ||
!isset( $metadata['height'] ) ) {
445 unlink( $tempFilenameSvg );
449 $handler = new SvgHandler
;
450 $res = $handler->rasterize(
456 unlink( $tempFilenameSvg );
459 if ( $res === true ) {
460 $png = file_get_contents( $tempFilenamePng );
461 unlink( $tempFilenamePng );
464 return $png ?
: false;
469 * Check if the image depends on the language.
473 private function varyOnLanguage() {
474 return is_array( $this->descriptor
) && (
475 isset( $this->descriptor
['ltr'] ) ||
476 isset( $this->descriptor
['rtl'] ) ||
477 isset( $this->descriptor
['lang'] ) );