Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
50.87% covered (warning)
50.87%
88 / 173
23.53% covered (danger)
23.53%
4 / 17
CRAP
0.00% covered (danger)
0.00%
0 / 1
Image
50.87% covered (warning)
50.87%
88 / 173
23.53% covered (danger)
23.53%
4 / 17
486.99
0.00% covered (danger)
0.00%
0 / 1
 __construct
81.25% covered (warning)
81.25%
26 / 32
0.00% covered (danger)
0.00%
0 / 1
9.53
 getName
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getModule
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getVariants
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getLangFallbacks
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 getPath
93.75% covered (success)
93.75%
15 / 16
0.00% covered (danger)
0.00%
0 / 1
8.02
 getLocalPath
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 getExtension
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 getMimeType
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 getUrl
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
2
 getDataUri
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 getImageData
71.43% covered (warning)
71.43%
15 / 21
0.00% covered (danger)
0.00%
0 / 1
12.33
 readFile
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 sendResponseHeaders
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 variantize
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
6
 massageSvgPathdata
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
 rasterize
0.00% covered (danger)
0.00%
0 / 43
0.00% covered (danger)
0.00%
0 / 1
90
1<?php
2/**
3 * @license GPL-2.0-or-later
4 * @file
5 */
6
7namespace MediaWiki\ResourceLoader;
8
9use DOMDocument;
10use InvalidArgumentException;
11use MediaWiki\Language\LanguageFallbackMode;
12use MediaWiki\MainConfigNames;
13use MediaWiki\Media\InvalidSVGException;
14use MediaWiki\Media\SvgHandler;
15use MediaWiki\Media\SVGReader;
16use MediaWiki\MediaWikiServices;
17use MediaWiki\Shell\Shell;
18use RuntimeException;
19use Wikimedia\FileBackend\FileBackend;
20use Wikimedia\Http\HttpHeader;
21use Wikimedia\Minify\CSSMin;
22
23/**
24 * Class encapsulating an image used in an ImageModule.
25 *
26 * @ingroup ResourceLoader
27 * @since 1.25
28 */
29class Image {
30    /**
31     * Map of allowed file extensions to their MIME types.
32     */
33    private const FILE_TYPES = [
34        'svg' => 'image/svg+xml',
35        'png' => 'image/png',
36        'gif' => 'image/gif',
37        'jpg' => 'image/jpg',
38    ];
39
40    /** @var string */
41    private $name;
42    /** @var string */
43    private $module;
44    /** @var string|array */
45    private $descriptor;
46    /** @var string */
47    private $basePath;
48    /** @var array */
49    private $variants;
50    /** @var string|null */
51    private $defaultColor;
52    /** @var string */
53    private $extension;
54
55    /**
56     * @param string $name Self-name of the image as known to ImageModule.
57     * @param string $module Self-name of the module containing this image.
58     *  Used to find the image in the registry e.g. through a load.php url.
59     * @param string|array $descriptor Path to image file, or array structure containing paths
60     * @param string $basePath Directory to which paths in descriptor refer
61     * @param array $variants
62     * @param string|null $defaultColor of the base variant
63     */
64    public function __construct( $name, $module, $descriptor, $basePath, array $variants,
65        $defaultColor = null
66    ) {
67        $this->name = $name;
68        $this->module = $module;
69        $this->descriptor = $descriptor;
70        $this->basePath = $basePath;
71        $this->variants = $variants;
72        $this->defaultColor = $defaultColor;
73
74        // Expand shorthands:
75        // [ "en,de,fr" => "foo.svg" ]
76        // → [ "en" => "foo.svg", "de" => "foo.svg", "fr" => "foo.svg" ]
77        if ( is_array( $this->descriptor ) && isset( $this->descriptor['lang'] ) ) {
78            foreach ( $this->descriptor['lang'] as $langList => $_ ) {
79                if ( str_contains( $langList, ',' ) ) {
80                    $this->descriptor['lang'] += array_fill_keys(
81                        explode( ',', $langList ),
82                        $this->descriptor['lang'][$langList]
83                    );
84                    unset( $this->descriptor['lang'][$langList] );
85                }
86            }
87        }
88        // Remove 'deprecated' key
89        if ( is_array( $this->descriptor ) ) {
90            unset( $this->descriptor['deprecated'] );
91        }
92
93        // Ensure that all files have common extension.
94        $extensions = [];
95        $descriptor = is_array( $this->descriptor ) ? $this->descriptor : [ $this->descriptor ];
96        array_walk_recursive( $descriptor, function ( $path ) use ( &$extensions ) {
97            $extensions[] = pathinfo( $this->getLocalPath( $path ), PATHINFO_EXTENSION );
98        } );
99        $extensions = array_unique( $extensions );
100        if ( count( $extensions ) !== 1 ) {
101            throw new InvalidArgumentException(
102                "File type for different image files of '$name' not the same in module '$module'"
103            );
104        }
105        $ext = $extensions[0];
106        if ( !isset( self::FILE_TYPES[$ext] ) ) {
107            throw new InvalidArgumentException(
108                "Invalid file type for image files of '$name' (valid: svg, png, gif, jpg) in module '$module'"
109            );
110        }
111        $this->extension = $ext;
112    }
113
114    /**
115     * Get name of this image.
116     *
117     * @return string
118     */
119    public function getName() {
120        return $this->name;
121    }
122
123    /**
124     * Get name of the module this image belongs to.
125     *
126     * @return string
127     */
128    public function getModule() {
129        return $this->module;
130    }
131
132    /**
133     * Get the list of variants this image can be converted to.
134     *
135     * @return string[]
136     */
137    public function getVariants(): array {
138        return array_keys( $this->variants );
139    }
140
141    /**
142     * @internal For unit testing override
143     * @param string $lang
144     * @return string[]
145     */
146    protected function getLangFallbacks( string $lang ): array {
147        return MediaWikiServices::getInstance()
148            ->getLanguageFallback()
149            ->getAll( $lang, LanguageFallbackMode::STRICT );
150    }
151
152    /**
153     * Get the path to image file for given context.
154     *
155     * @param Context $context Any context
156     * @return string
157     */
158    public function getPath( Context $context ) {
159        $desc = $this->descriptor;
160        if ( !is_array( $desc ) ) {
161            return $this->getLocalPath( $desc );
162        }
163        if ( isset( $desc['lang'] ) ) {
164            $contextLang = $context->getLanguage();
165            if ( isset( $desc['lang'][$contextLang] ) ) {
166                return $this->getLocalPath( $desc['lang'][$contextLang] );
167            }
168            $fallbacks = $this->getLangFallbacks( $contextLang );
169            foreach ( $fallbacks as $lang ) {
170                if ( isset( $desc['lang'][$lang] ) ) {
171                    return $this->getLocalPath( $desc['lang'][$lang] );
172                }
173            }
174        }
175        if ( isset( $desc[$context->getDirection()] ) ) {
176            return $this->getLocalPath( $desc[$context->getDirection()] );
177        }
178        if ( isset( $desc['default'] ) ) {
179            return $this->getLocalPath( $desc['default'] );
180        }
181        throw new RuntimeException( 'No matching path found' );
182    }
183
184    /**
185     * @param string|FilePath $path
186     * @return string
187     */
188    protected function getLocalPath( $path ) {
189        if ( $path instanceof FilePath ) {
190            return $path->getLocalPath();
191        }
192
193        return "{$this->basePath}/$path";
194    }
195
196    /**
197     * Get the extension of the image.
198     *
199     * @param string|null $format Format to get the extension for, 'original' or 'rasterized'
200     * @return string Extension without leading dot, e.g. 'png'
201     */
202    public function getExtension( $format = 'original' ) {
203        if ( $format === 'rasterized' && $this->extension === 'svg' ) {
204            return 'png';
205        }
206        return $this->extension;
207    }
208
209    /**
210     * Get the MIME type of the image.
211     *
212     * @param string|null $format Format to get the MIME type for, 'original' or 'rasterized'
213     * @return string
214     */
215    public function getMimeType( $format = 'original' ) {
216        $ext = $this->getExtension( $format );
217        return self::FILE_TYPES[$ext];
218    }
219
220    /**
221     * Get the load.php URL that will produce this image.
222     *
223     * @param Context $context Any context
224     * @param string $script URL to load.php
225     * @param string|null $variant Variant to get the URL for
226     * @param string $format Format to get the URL for, 'original' or 'rasterized'
227     * @return string URL
228     */
229    public function getUrl( Context $context, $script, $variant, $format ) {
230        $query = [
231            'modules' => $this->getModule(),
232            'image' => $this->getName(),
233            'variant' => $variant,
234            'format' => $format,
235            // Most images don't vary on language, but include the parameter anyway, so that version
236            // hashes are computed consistently. (T321394#9100166)
237            'lang' => $context->getLanguage(),
238            'skin' => $context->getSkin(),
239            'version' => $context->getResourceLoader()->makeVersionQuery( $context, [ $this->getModule() ] ),
240        ];
241
242        return wfAppendQuery( $script, $query );
243    }
244
245    /**
246     * Get the data: URI that will produce this image.
247     *
248     * @param Context $context Any context
249     * @param string|null $variant Variant to get the URI for
250     * @param string $format Format to get the URI for, 'original' or 'rasterized'
251     * @return string
252     */
253    public function getDataUri( Context $context, $variant, $format ) {
254        $type = $this->getMimeType( $format );
255        $contents = $this->getImageData( $context, $variant, $format );
256        return CSSMin::encodeStringAsDataURI( $contents, $type );
257    }
258
259    /**
260     * Get actual image data for this image. This can be saved to a file or sent to the browser to
261     * produce the converted image.
262     *
263     * Call getExtension() or getMimeType() with the same $format argument to learn what file type the
264     * returned data uses.
265     *
266     * @param Context $context Image context, or any context if $variant and $format
267     *     given.
268     * @param string|null|false $variant Variant to get the data for. Optional; if given, overrides the data
269     *     from $context.
270     * @param string|false $format Format to get the data for, 'original' or 'rasterized'. Optional; if
271     *     given, overrides the data from $context.
272     * @return string|false Possibly binary image data, or false on failure
273     */
274    public function getImageData( Context $context, $variant = false, $format = false ) {
275        if ( $variant === false ) {
276            $variant = $context->getVariant();
277        }
278        if ( $format === false ) {
279            $format = $context->getFormat();
280        }
281
282        $path = $this->getPath( $context );
283        if ( !file_exists( $path ) ) {
284            throw new RuntimeException( "File '$path' does not exist" );
285        }
286
287        if ( $this->getExtension() !== 'svg' ) {
288            return $this->readFile( $path );
289        }
290
291        if ( $variant && isset( $this->variants[$variant] ) ) {
292            $data = $this->variantize( $this->variants[$variant], $context );
293        } else {
294            $defaultColor = $this->defaultColor;
295            $data = $defaultColor ?
296                $this->variantize( [ 'color' => $defaultColor ], $context ) :
297                $this->readFile( $path );
298        }
299
300        if ( $format === 'rasterized' ) {
301            $data = $this->rasterize( $data );
302            if ( !$data ) {
303                $logger = $context->getResourceLoader()->getLogger();
304                $logger->error( __METHOD__ . " failed to rasterize for $path" );
305            }
306        }
307
308        return $data;
309    }
310
311    /**
312     * @param string $path
313     * @return string
314     * @throws RuntimeException if the file cannot be read or is empty
315     */
316    private function readFile( string $path ): string {
317        $content = file_get_contents( $path );
318        if ( $content === false || $content === '' ) {
319            throw new RuntimeException( "File '$path' could not be read or is empty" );
320        }
321        return $content;
322    }
323
324    /**
325     * Send response headers (using the header() function) that are necessary to correctly serve the
326     * image data for this image, as returned by getImageData().
327     *
328     * Note that the headers are independent of the language or image variant.
329     *
330     * @param Context $context Image context
331     */
332    public function sendResponseHeaders( Context $context ): void {
333        $format = $context->getFormat();
334        $mime = $this->getMimeType( $format );
335        $filename = $this->getName() . '.' . $this->getExtension( $format );
336
337        HttpHeader::send( 'Content-Type: ' . $mime );
338        HttpHeader::send( 'Content-Disposition: ' .
339            FileBackend::makeContentDisposition( 'inline', $filename ) );
340        HttpHeader::send( 'Access-Control-Allow-Origin: *' );
341    }
342
343    /**
344     * Convert this image, which is assumed to be SVG, to given variant.
345     *
346     * @param array $variantConf Array with a 'color' key, its value will be used as fill color
347     * @param Context $context Image context
348     * @return string New SVG file data
349     */
350    protected function variantize( array $variantConf, Context $context ) {
351        $dom = new DOMDocument;
352        $dom->loadXML( $this->readFile( $this->getPath( $context ) ) );
353        $root = $dom->documentElement;
354        $titleNode = null;
355        $wrapper = $dom->createElementNS( 'http://www.w3.org/2000/svg', 'g' );
356        // Reattach all direct children of the `<svg>` root node to the `<g>` wrapper
357        while ( $root->firstChild ) {
358            $node = $root->firstChild;
359            '@phan-var \DOMElement $node'; /** @var \DOMElement $node */
360            if ( !$titleNode && $node->nodeType === XML_ELEMENT_NODE && $node->tagName === 'title' ) {
361                // Remember the first encountered `<title>` node
362                $titleNode = $node;
363            }
364            $wrapper->appendChild( $node );
365        }
366        if ( $titleNode ) {
367            // Reattach the `<title>` node to the `<svg>` root node rather than the `<g>` wrapper
368            $root->appendChild( $titleNode );
369        }
370        $root->appendChild( $wrapper );
371        $wrapper->setAttribute( 'fill', $variantConf['color'] );
372        return $dom->saveXML();
373    }
374
375    /**
376     * Massage the SVG image data for converters which don't understand some path data syntax.
377     *
378     * This is necessary for rsvg and ImageMagick when compiled with rsvg support.
379     * Upstream bug is https://bugzilla.gnome.org/show_bug.cgi?id=620923, fixed 2014-11-10, so
380     * this will be needed for a while. (T76852)
381     *
382     * @param string $svg SVG image data
383     * @return string Massaged SVG image data
384     */
385    protected function massageSvgPathdata( $svg ) {
386        $dom = new DOMDocument;
387        $dom->loadXML( $svg );
388        foreach ( $dom->getElementsByTagName( 'path' ) as $node ) {
389            $pathData = $node->getAttribute( 'd' );
390            // Make sure there is at least one space between numbers, and that leading zero is not omitted.
391            // rsvg has issues with syntax like "M-1-2" and "M.445.483" and especially "M-.445-.483".
392            $pathData = preg_replace( '/(-?)(\d*\.\d+|\d+)/', ' ${1}0$2 ', $pathData );
393            // Strip unnecessary leading zeroes for prettiness, not strictly necessary
394            $pathData = preg_replace( '/([ -])0(\d)/', '$1$2', $pathData );
395            $node->setAttribute( 'd', $pathData );
396        }
397        return $dom->saveXML();
398    }
399
400    /**
401     * Convert passed image data, which is assumed to be SVG, to PNG.
402     *
403     * @param string $svg SVG image data
404     * @return string|bool PNG image data, or false on failure
405     */
406    protected function rasterize( $svg ) {
407        $svgConverter = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::SVGConverter );
408        $svgConverterPath = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::SVGConverterPath );
409        // This code should be factored out to a separate method on SvgHandler, or perhaps a separate
410        // class, with a separate set of configuration settings.
411        //
412        // This is a distinct use case from regular SVG rasterization:
413        // * We can skip many checks (as the images come from a trusted source,
414        //   rather than from the user).
415        // * We need to provide extra options to some converters to achieve acceptable quality for very
416        //   small images, which might cause performance issues in the general case.
417        // * We want to directly pass image data to the converter, rather than a file path.
418        //
419        // See https://phabricator.wikimedia.org/T76473#801446 for examples of what happens with the
420        // default settings.
421        //
422        // For now, we special-case rsvg (used in WMF production) and do a messy workaround for other
423        // converters.
424
425        $svg = $this->massageSvgPathdata( $svg );
426
427        // Sometimes this might be 'rsvg-secure'. Long as it's rsvg.
428        if ( str_starts_with( $svgConverter, 'rsvg' ) ) {
429            $command = 'rsvg-convert';
430            if ( $svgConverterPath ) {
431                $command = Shell::escape( "{$svgConverterPath}/" ) . $command;
432            }
433
434            $process = proc_open(
435                $command,
436                [ 0 => [ 'pipe', 'r' ], 1 => [ 'pipe', 'w' ] ],
437                $pipes
438            );
439
440            if ( $process ) {
441                fwrite( $pipes[0], $svg );
442                fclose( $pipes[0] );
443                $png = stream_get_contents( $pipes[1] );
444                fclose( $pipes[1] );
445                proc_close( $process );
446
447                return $png ?: false;
448            }
449            return false;
450
451        }
452        // Write input to and read output from a temporary file
453        $tempFilenameSvg = tempnam( wfTempDir(), 'ResourceLoaderImage' );
454        $tempFilenamePng = tempnam( wfTempDir(), 'ResourceLoaderImage' );
455
456        file_put_contents( $tempFilenameSvg, $svg );
457
458        try {
459            $svgReader = new SVGReader( $tempFilenameSvg );
460        } catch ( InvalidSVGException $e ) {
461            // XXX Can this ever happen?
462            throw new RuntimeException( 'Invalid SVG', 0, $e );
463        }
464        $metadata = $svgReader->getMetadata();
465        if ( !isset( $metadata['width'] ) || !isset( $metadata['height'] ) ) {
466            unlink( $tempFilenameSvg );
467            return false;
468        }
469
470        $handler = new SvgHandler;
471        $res = $handler->rasterize(
472            $tempFilenameSvg,
473            $tempFilenamePng,
474            $metadata['width'],
475            $metadata['height']
476        );
477        unlink( $tempFilenameSvg );
478
479        if ( $res === true ) {
480            $png = file_get_contents( $tempFilenamePng );
481            unlink( $tempFilenamePng );
482            return $png;
483        }
484
485        return false;
486    }
487}