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
24 * Class encapsulating an image used in a ResourceLoaderImageModule.
28 class ResourceLoaderImage
{
31 * Map of allowed file extensions to their MIME types.
34 protected static $fileTypes = array(
35 'svg' => 'image/svg+xml',
42 * @param string $name Image name
43 * @param string $module Module name
44 * @param string|array $descriptor Path to image file, or array structure containing paths
45 * @param string $basePath Directory to which paths in descriptor refer
46 * @param array $variants
47 * @throws InvalidArgumentException
49 public function __construct( $name, $module, $descriptor, $basePath, $variants ) {
51 $this->module
= $module;
52 $this->descriptor
= $descriptor;
53 $this->basePath
= $basePath;
54 $this->variants
= $variants;
57 // array( "en,de,fr" => "foo.svg" ) → array( "en" => "foo.svg", "de" => "foo.svg", "fr" => "foo.svg" )
58 if ( is_array( $this->descriptor
) && isset( $this->descriptor
['lang'] ) ) {
59 foreach ( array_keys( $this->descriptor
['lang'] ) as $langList ) {
60 if ( strpos( $langList, ',' ) !== false ) {
61 $this->descriptor
['lang'] +
= array_fill_keys(
62 explode( ',', $langList ),
63 $this->descriptor
['lang'][ $langList ]
65 unset( $this->descriptor
['lang'][ $langList ] );
70 // Ensure that all files have common extension.
71 $extensions = array();
72 $descriptor = (array)$descriptor;
73 array_walk_recursive( $descriptor, function ( $path ) use ( &$extensions ) {
74 $extensions[] = pathinfo( $path, PATHINFO_EXTENSION
);
76 $extensions = array_unique( $extensions );
77 if ( count( $extensions ) !== 1 ) {
78 throw new InvalidArgumentException( "File type for different image files of '$name' not the same" );
80 $ext = $extensions[0];
81 if ( !isset( self
::$fileTypes[$ext] ) ) {
82 throw new InvalidArgumentException( "Invalid file type for image files of '$name' (valid: svg, png, gif, jpg)" );
84 $this->extension
= $ext;
88 * Get name of this image.
92 public function getName() {
97 * Get name of the module this image belongs to.
101 public function getModule() {
102 return $this->module
;
106 * Get the list of variants this image can be converted to.
110 public function getVariants() {
111 return array_keys( $this->variants
);
115 * Get the path to image file for given context.
117 * @param ResourceLoaderContext $context Any context
120 public function getPath( ResourceLoaderContext
$context ) {
121 $desc = $this->descriptor
;
122 if ( is_string( $desc ) ) {
123 return $this->basePath
. '/' . $desc;
124 } elseif ( isset( $desc['lang'][ $context->getLanguage() ] ) ) {
125 return $this->basePath
. '/' . $desc['lang'][ $context->getLanguage() ];
126 } elseif ( isset( $desc[ $context->getDirection() ] ) ) {
127 return $this->basePath
. '/' . $desc[ $context->getDirection() ];
129 return $this->basePath
. '/' . $desc['default'];
134 * Get the extension of the image.
136 * @param string $format Format to get the extension for, 'original' or 'rasterized'
137 * @return string Extension without leading dot, e.g. 'png'
139 public function getExtension( $format = 'original' ) {
140 if ( $format === 'rasterized' && $this->extension
=== 'svg' ) {
143 return $this->extension
;
148 * Get the MIME type of the image.
150 * @param string $format Format to get the MIME type for, 'original' or 'rasterized'
153 public function getMimeType( $format = 'original' ) {
154 $ext = $this->getExtension( $format );
155 return self
::$fileTypes[$ext];
159 * Get the load.php URL that will produce this image.
161 * @param ResourceLoaderContext $context Any context
162 * @param string $script URL to load.php
163 * @param string|null $variant Variant to get the URL for
164 * @param string $format Format to get the URL for, 'original' or 'rasterized'
167 public function getUrl( ResourceLoaderContext
$context, $script, $variant, $format ) {
169 'modules' => $this->getModule(),
170 'image' => $this->getName(),
171 'variant' => $variant,
173 'lang' => $context->getLanguage(),
174 'version' => $context->getVersion(),
177 return wfExpandUrl( wfAppendQuery( $script, $query ), PROTO_RELATIVE
);
181 * Get the data: URI that will produce this image.
183 * @param ResourceLoaderContext $context Any context
184 * @param string|null $variant Variant to get the URI for
185 * @param string $format Format to get the URI for, 'original' or 'rasterized'
188 public function getDataUri( ResourceLoaderContext
$context, $variant, $format ) {
189 $type = $this->getMimeType( $format );
190 $contents = $this->getImageData( $context, $variant, $format );
191 return CSSMin
::encodeStringAsDataURI( $contents, $type );
195 * Get actual image data for this image. This can be saved to a file or sent to the browser to
196 * produce the converted image.
198 * Call getExtension() or getMimeType() with the same $format argument to learn what file type the
199 * returned data uses.
201 * @param ResourceLoaderContext $context Image context, or any context if $variant and $format
203 * @param string|null $variant Variant to get the data for. Optional; if given, overrides the data
205 * @param string $format Format to get the data for, 'original' or 'rasterized'. Optional; if
206 * given, overrides the data from $context.
207 * @return string|false Possibly binary image data, or false on failure
208 * @throws MWException If the image file doesn't exist
210 public function getImageData( ResourceLoaderContext
$context, $variant = false, $format = false ) {
211 if ( $variant === false ) {
212 $variant = $context->getVariant();
214 if ( $format === false ) {
215 $format = $context->getFormat();
218 $path = $this->getPath( $context );
219 if ( !file_exists( $path ) ) {
220 throw new MWException( "File '$path' does not exist" );
223 if ( $this->getExtension() !== 'svg' ) {
224 return file_get_contents( $path );
227 if ( $variant && isset( $this->variants
[$variant] ) ) {
228 $data = $this->variantize( $this->variants
[$variant], $context );
230 $data = file_get_contents( $path );
233 if ( $format === 'rasterized' ) {
234 $data = $this->rasterize( $data );
236 wfDebugLog( 'ResourceLoaderImage', __METHOD__
. " failed to rasterize for $path" );
244 * Send response headers (using the header() function) that are necessary to correctly serve the
245 * image data for this image, as returned by getImageData().
247 * Note that the headers are independent of the language or image variant.
249 * @param ResourceLoaderContext $context Image context
251 public function sendResponseHeaders( ResourceLoaderContext
$context ) {
252 $format = $context->getFormat();
253 $mime = $this->getMimeType( $format );
254 $filename = $this->getName() . '.' . $this->getExtension( $format );
256 header( 'Content-Type: ' . $mime );
257 header( 'Content-Disposition: ' .
258 FileBackend
::makeContentDisposition( 'inline', $filename ) );
262 * Convert this image, which is assumed to be SVG, to given variant.
264 * @param array $variantConf Array with a 'color' key, its value will be used as fill color
265 * @param ResourceLoaderContext $context Image context
266 * @return string New SVG file data
268 protected function variantize( $variantConf, ResourceLoaderContext
$context ) {
269 $dom = new DomDocument
;
270 $dom->load( $this->getPath( $context ) );
271 $root = $dom->documentElement
;
272 $wrapper = $dom->createElement( 'g' );
273 while ( $root->firstChild
) {
274 $wrapper->appendChild( $root->firstChild
);
276 $root->appendChild( $wrapper );
277 $wrapper->setAttribute( 'fill', $variantConf['color'] );
278 return $dom->saveXml();
282 * Massage the SVG image data for converters which don't understand some path data syntax.
284 * This is necessary for rsvg and ImageMagick when compiled with rsvg support.
285 * Upstream bug is https://bugzilla.gnome.org/show_bug.cgi?id=620923, fixed 2014-11-10, so
286 * this will be needed for a while. (T76852)
288 * @param string $svg SVG image data
289 * @return string Massaged SVG image data
291 protected function massageSvgPathdata( $svg ) {
292 $dom = new DomDocument
;
293 $dom->loadXml( $svg );
294 foreach ( $dom->getElementsByTagName( 'path' ) as $node ) {
295 $pathData = $node->getAttribute( 'd' );
296 // Make sure there is at least one space between numbers, and that leading zero is not omitted.
297 // rsvg has issues with syntax like "M-1-2" and "M.445.483" and especially "M-.445-.483".
298 $pathData = preg_replace( '/(-?)(\d*\.\d+|\d+)/', ' ${1}0$2 ', $pathData );
299 // Strip unnecessary leading zeroes for prettiness, not strictly necessary
300 $pathData = preg_replace( '/([ -])0(\d)/', '$1$2', $pathData );
301 $node->setAttribute( 'd', $pathData );
303 return $dom->saveXml();
307 * Convert passed image data, which is assumed to be SVG, to PNG.
309 * @param string $svg SVG image data
310 * @return string|bool PNG image data, or false on failure
312 protected function rasterize( $svg ) {
313 // This code should be factored out to a separate method on SvgHandler, or perhaps a separate
314 // class, with a separate set of configuration settings.
316 // This is a distinct use case from regular SVG rasterization:
317 // * We can skip many sanity and security checks (as the images come from a trusted source,
318 // rather than from the user).
319 // * We need to provide extra options to some converters to achieve acceptable quality for very
320 // small images, which might cause performance issues in the general case.
321 // * We want to directly pass image data to the converter, rather than a file path.
323 // See https://phabricator.wikimedia.org/T76473#801446 for examples of what happens with the
326 // For now, we special-case rsvg (used in WMF production) and do a messy workaround for other
329 global $wgSVGConverter, $wgSVGConverterPath;
331 $svg = $this->massageSvgPathdata( $svg );
333 // Sometimes this might be 'rsvg-secure'. Long as it's rsvg.
334 if ( strpos( $wgSVGConverter, 'rsvg' ) === 0 ) {
335 $command = 'rsvg-convert';
336 if ( $wgSVGConverterPath ) {
337 $command = wfEscapeShellArg( "$wgSVGConverterPath/" ) . $command;
340 $process = proc_open(
342 array( 0 => array( 'pipe', 'r' ), 1 => array( 'pipe', 'w' ) ),
346 if ( is_resource( $process ) ) {
347 fwrite( $pipes[0], $svg );
349 $png = stream_get_contents( $pipes[1] );
351 proc_close( $process );
353 return $png ?
: false;
358 // Write input to and read output from a temporary file
359 $tempFilenameSvg = tempnam( wfTempDir(), 'ResourceLoaderImage' );
360 $tempFilenamePng = tempnam( wfTempDir(), 'ResourceLoaderImage' );
362 file_put_contents( $tempFilenameSvg, $svg );
364 $metadata = SVGMetadataExtractor
::getMetadata( $tempFilenameSvg );
365 if ( !isset( $metadata['width'] ) ||
!isset( $metadata['height'] ) ) {
366 unlink( $tempFilenameSvg );
370 $handler = new SvgHandler
;
371 $res = $handler->rasterize(
377 unlink( $tempFilenameSvg );
380 if ( $res === true ) {
381 $png = file_get_contents( $tempFilenamePng );
382 unlink( $tempFilenamePng );
385 return $png ?
: false;