3 * Class encapsulating an image used in a ResourceLoaderImageModule.
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.
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.
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
23 use MediaWiki\Shell\Shell
;
26 * Class encapsulating an image used in a ResourceLoaderImageModule.
30 class ResourceLoaderImage
{
33 * Map of allowed file extensions to their MIME types.
36 protected static $fileTypes = [
37 'svg' => 'image/svg+xml',
44 * @param string $name Image name
45 * @param string $module Module name
46 * @param string|array $descriptor Path to image file, or array structure containing paths
47 * @param string $basePath Directory to which paths in descriptor refer
48 * @param array $variants
49 * @param string|null $defaultColor of the base variant
50 * @throws InvalidArgumentException
52 public function __construct( $name, $module, $descriptor, $basePath, $variants,
56 $this->module
= $module;
57 $this->descriptor
= $descriptor;
58 $this->basePath
= $basePath;
59 $this->variants
= $variants;
60 $this->defaultColor
= $defaultColor;
63 // [ "en,de,fr" => "foo.svg" ]
64 // → [ "en" => "foo.svg", "de" => "foo.svg", "fr" => "foo.svg" ]
65 if ( is_array( $this->descriptor
) && isset( $this->descriptor
['lang'] ) ) {
66 foreach ( array_keys( $this->descriptor
['lang'] ) as $langList ) {
67 if ( strpos( $langList, ',' ) !== false ) {
68 $this->descriptor
['lang'] +
= array_fill_keys(
69 explode( ',', $langList ),
70 $this->descriptor
['lang'][$langList]
72 unset( $this->descriptor
['lang'][$langList] );
76 // Remove 'deprecated' key
77 if ( is_array( $this->descriptor
) ) {
78 unset( $this->descriptor
['deprecated'] );
81 // Ensure that all files have common extension.
83 $descriptor = (array)$this->descriptor
;
84 array_walk_recursive( $descriptor, function ( $path ) use ( &$extensions ) {
85 $extensions[] = pathinfo( $path, PATHINFO_EXTENSION
);
87 $extensions = array_unique( $extensions );
88 if ( count( $extensions ) !== 1 ) {
89 throw new InvalidArgumentException(
90 "File type for different image files of '$name' not the same in module '$module'"
93 $ext = $extensions[0];
94 if ( !isset( self
::$fileTypes[$ext] ) ) {
95 throw new InvalidArgumentException(
96 "Invalid file type for image files of '$name' (valid: svg, png, gif, jpg) in module '$module'"
99 $this->extension
= $ext;
103 * Get name of this image.
107 public function getName() {
112 * Get name of the module this image belongs to.
116 public function getModule() {
117 return $this->module
;
121 * Get the list of variants this image can be converted to.
125 public function getVariants() {
126 return array_keys( $this->variants
);
130 * Get the path to image file for given context.
132 * @param ResourceLoaderContext $context Any context
135 public function getPath( ResourceLoaderContext
$context ) {
136 $desc = $this->descriptor
;
137 if ( is_string( $desc ) ) {
138 return $this->basePath
. '/' . $desc;
140 if ( isset( $desc['lang'] ) ) {
141 $contextLang = $context->getLanguage();
142 if ( isset( $desc['lang'][$contextLang] ) ) {
143 return $this->basePath
. '/' . $desc['lang'][$contextLang];
145 $fallbacks = Language
::getFallbacksFor( $contextLang, Language
::STRICT_FALLBACKS
);
146 foreach ( $fallbacks as $lang ) {
147 if ( isset( $desc['lang'][$lang] ) ) {
148 return $this->basePath
. '/' . $desc['lang'][$lang];
152 if ( isset( $desc[$context->getDirection()] ) ) {
153 return $this->basePath
. '/' . $desc[$context->getDirection()];
155 return $this->basePath
. '/' . $desc['default'];
159 * Get the extension of the image.
161 * @param string $format Format to get the extension for, 'original' or 'rasterized'
162 * @return string Extension without leading dot, e.g. 'png'
164 public function getExtension( $format = 'original' ) {
165 if ( $format === 'rasterized' && $this->extension
=== 'svg' ) {
168 return $this->extension
;
172 * Get the MIME type of the image.
174 * @param string $format Format to get the MIME type for, 'original' or 'rasterized'
177 public function getMimeType( $format = 'original' ) {
178 $ext = $this->getExtension( $format );
179 return self
::$fileTypes[$ext];
183 * Get the load.php URL that will produce this image.
185 * @param ResourceLoaderContext $context Any context
186 * @param string $script URL to load.php
187 * @param string|null $variant Variant to get the URL for
188 * @param string $format Format to get the URL for, 'original' or 'rasterized'
191 public function getUrl( ResourceLoaderContext
$context, $script, $variant, $format ) {
193 'modules' => $this->getModule(),
194 'image' => $this->getName(),
195 'variant' => $variant,
197 'lang' => $context->getLanguage(),
198 'skin' => $context->getSkin(),
199 'version' => $context->getVersion(),
202 return wfAppendQuery( $script, $query );
206 * Get the data: URI that will produce this image.
208 * @param ResourceLoaderContext $context Any context
209 * @param string|null $variant Variant to get the URI for
210 * @param string $format Format to get the URI for, 'original' or 'rasterized'
213 public function getDataUri( ResourceLoaderContext
$context, $variant, $format ) {
214 $type = $this->getMimeType( $format );
215 $contents = $this->getImageData( $context, $variant, $format );
216 return CSSMin
::encodeStringAsDataURI( $contents, $type );
220 * Get actual image data for this image. This can be saved to a file or sent to the browser to
221 * produce the converted image.
223 * Call getExtension() or getMimeType() with the same $format argument to learn what file type the
224 * returned data uses.
226 * @param ResourceLoaderContext $context Image context, or any context if $variant and $format
228 * @param string|null $variant Variant to get the data for. Optional; if given, overrides the data
230 * @param string $format Format to get the data for, 'original' or 'rasterized'. Optional; if
231 * given, overrides the data from $context.
232 * @return string|false Possibly binary image data, or false on failure
233 * @throws MWException If the image file doesn't exist
235 public function getImageData( ResourceLoaderContext
$context, $variant = false, $format = false ) {
236 if ( $variant === false ) {
237 $variant = $context->getVariant();
239 if ( $format === false ) {
240 $format = $context->getFormat();
243 $path = $this->getPath( $context );
244 if ( !file_exists( $path ) ) {
245 throw new MWException( "File '$path' does not exist" );
248 if ( $this->getExtension() !== 'svg' ) {
249 return file_get_contents( $path );
252 if ( $variant && isset( $this->variants
[$variant] ) ) {
253 $data = $this->variantize( $this->variants
[$variant], $context );
255 $defaultColor = $this->defaultColor
;
256 $data = $defaultColor ?
257 $this->variantize( [ 'color' => $defaultColor ], $context ) :
258 file_get_contents( $path );
261 if ( $format === 'rasterized' ) {
262 $data = $this->rasterize( $data );
264 wfDebugLog( 'ResourceLoaderImage', __METHOD__
. " failed to rasterize for $path" );
272 * Send response headers (using the header() function) that are necessary to correctly serve the
273 * image data for this image, as returned by getImageData().
275 * Note that the headers are independent of the language or image variant.
277 * @param ResourceLoaderContext $context Image context
279 public function sendResponseHeaders( ResourceLoaderContext
$context ) {
280 $format = $context->getFormat();
281 $mime = $this->getMimeType( $format );
282 $filename = $this->getName() . '.' . $this->getExtension( $format );
284 header( 'Content-Type: ' . $mime );
285 header( 'Content-Disposition: ' .
286 FileBackend
::makeContentDisposition( 'inline', $filename ) );
290 * Convert this image, which is assumed to be SVG, to given variant.
292 * @param array $variantConf Array with a 'color' key, its value will be used as fill color
293 * @param ResourceLoaderContext $context Image context
294 * @return string New SVG file data
296 protected function variantize( $variantConf, ResourceLoaderContext
$context ) {
297 $dom = new DOMDocument
;
298 $dom->loadXML( file_get_contents( $this->getPath( $context ) ) );
299 $root = $dom->documentElement
;
301 $wrapper = $dom->createElementNS( 'http://www.w3.org/2000/svg', 'g' );
302 // Reattach all direct children of the `<svg>` root node to the `<g>` wrapper
303 while ( $root->firstChild
) {
304 $node = $root->firstChild
;
305 if ( !$titleNode && $node->nodeType
=== XML_ELEMENT_NODE
&& $node->tagName
=== 'title' ) {
306 // Remember the first encountered `<title>` node
309 $wrapper->appendChild( $node );
312 // Reattach the `<title>` node to the `<svg>` root node rather than the `<g>` wrapper
313 $root->appendChild( $titleNode );
315 $root->appendChild( $wrapper );
316 $wrapper->setAttribute( 'fill', $variantConf['color'] );
317 return $dom->saveXML();
321 * Massage the SVG image data for converters which don't understand some path data syntax.
323 * This is necessary for rsvg and ImageMagick when compiled with rsvg support.
324 * Upstream bug is https://bugzilla.gnome.org/show_bug.cgi?id=620923, fixed 2014-11-10, so
325 * this will be needed for a while. (T76852)
327 * @param string $svg SVG image data
328 * @return string Massaged SVG image data
330 protected function massageSvgPathdata( $svg ) {
331 $dom = new DOMDocument
;
332 $dom->loadXML( $svg );
333 foreach ( $dom->getElementsByTagName( 'path' ) as $node ) {
334 $pathData = $node->getAttribute( 'd' );
335 // Make sure there is at least one space between numbers, and that leading zero is not omitted.
336 // rsvg has issues with syntax like "M-1-2" and "M.445.483" and especially "M-.445-.483".
337 $pathData = preg_replace( '/(-?)(\d*\.\d+|\d+)/', ' ${1}0$2 ', $pathData );
338 // Strip unnecessary leading zeroes for prettiness, not strictly necessary
339 $pathData = preg_replace( '/([ -])0(\d)/', '$1$2', $pathData );
340 $node->setAttribute( 'd', $pathData );
342 return $dom->saveXML();
346 * Convert passed image data, which is assumed to be SVG, to PNG.
348 * @param string $svg SVG image data
349 * @return string|bool PNG image data, or false on failure
351 protected function rasterize( $svg ) {
353 * This code should be factored out to a separate method on SvgHandler, or perhaps a separate
354 * class, with a separate set of configuration settings.
356 * This is a distinct use case from regular SVG rasterization:
357 * * We can skip many sanity and security checks (as the images come from a trusted source,
358 * rather than from the user).
359 * * We need to provide extra options to some converters to achieve acceptable quality for very
360 * small images, which might cause performance issues in the general case.
361 * * We want to directly pass image data to the converter, rather than a file path.
363 * See https://phabricator.wikimedia.org/T76473#801446 for examples of what happens with the
366 * For now, we special-case rsvg (used in WMF production) and do a messy workaround for other
370 global $wgSVGConverter, $wgSVGConverterPath;
372 $svg = $this->massageSvgPathdata( $svg );
374 // Sometimes this might be 'rsvg-secure'. Long as it's rsvg.
375 if ( strpos( $wgSVGConverter, 'rsvg' ) === 0 ) {
376 $command = 'rsvg-convert';
377 if ( $wgSVGConverterPath ) {
378 $command = Shell
::escape( "$wgSVGConverterPath/" ) . $command;
381 $process = proc_open(
383 [ 0 => [ 'pipe', 'r' ], 1 => [ 'pipe', 'w' ] ],
387 if ( is_resource( $process ) ) {
388 fwrite( $pipes[0], $svg );
390 $png = stream_get_contents( $pipes[1] );
392 proc_close( $process );
394 return $png ?
: false;
399 // Write input to and read output from a temporary file
400 $tempFilenameSvg = tempnam( wfTempDir(), 'ResourceLoaderImage' );
401 $tempFilenamePng = tempnam( wfTempDir(), 'ResourceLoaderImage' );
403 file_put_contents( $tempFilenameSvg, $svg );
405 $metadata = SVGMetadataExtractor
::getMetadata( $tempFilenameSvg );
406 if ( !isset( $metadata['width'] ) ||
!isset( $metadata['height'] ) ) {
407 unlink( $tempFilenameSvg );
411 $handler = new SvgHandler
;
412 $res = $handler->rasterize(
418 unlink( $tempFilenameSvg );
421 if ( $res === true ) {
422 $png = file_get_contents( $tempFilenamePng );
423 unlink( $tempFilenamePng );
426 return $png ?
: false;