Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
50.00% covered (danger)
50.00%
84 / 168
18.75% covered (danger)
18.75%
3 / 16
CRAP
0.00% covered (danger)
0.00%
0 / 1
Image
50.00% covered (danger)
50.00%
84 / 168
18.75% covered (danger)
18.75%
3 / 16
463.12
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
 sendResponseHeaders
0.00% covered (danger)
0.00%
0 / 6
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 * 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.
7 *
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.
12 *
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
17 *
18 * @file
19 */
20
21namespace MediaWiki\ResourceLoader;
22
23use DOMDocument;
24use FileBackend;
25use InvalidArgumentException;
26use InvalidSVGException;
27use MediaWiki\Languages\LanguageFallback;
28use MediaWiki\MainConfigNames;
29use MediaWiki\MediaWikiServices;
30use MediaWiki\Shell\Shell;
31use RuntimeException;
32use SvgHandler;
33use SVGReader;
34use Wikimedia\Minify\CSSMin;
35
36/**
37 * Class encapsulating an image used in an ImageModule.
38 *
39 * @ingroup ResourceLoader
40 * @since 1.25
41 */
42class Image {
43    /**
44     * Map of allowed file extensions to their MIME types.
45     * @var array
46     */
47    private const FILE_TYPES = [
48        'svg' => 'image/svg+xml',
49        'png' => 'image/png',
50        'gif' => 'image/gif',
51        'jpg' => 'image/jpg',
52    ];
53
54    /** @var string */
55    private $name;
56    /** @var string */
57    private $module;
58    /** @var string|array */
59    private $descriptor;
60    /** @var string */
61    private $basePath;
62    /** @var array */
63    private $variants;
64    /** @var string|null */
65    private $defaultColor;
66    /** @var string */
67    private $extension;
68
69    /**
70     * @param string $name Self-name of the image as known to ImageModule.
71     * @param string $module Self-name of the module containing this image.
72     *  Used to find the image in the registry e.g. through a load.php url.
73     * @param string|array $descriptor Path to image file, or array structure containing paths
74     * @param string $basePath Directory to which paths in descriptor refer
75     * @param array $variants
76     * @param string|null $defaultColor of the base variant
77     */
78    public function __construct( $name, $module, $descriptor, $basePath, array $variants,
79        $defaultColor = null
80    ) {
81        $this->name = $name;
82        $this->module = $module;
83        $this->descriptor = $descriptor;
84        $this->basePath = $basePath;
85        $this->variants = $variants;
86        $this->defaultColor = $defaultColor;
87
88        // Expand shorthands:
89        // [ "en,de,fr" => "foo.svg" ]
90        // → [ "en" => "foo.svg", "de" => "foo.svg", "fr" => "foo.svg" ]
91        if ( is_array( $this->descriptor ) && isset( $this->descriptor['lang'] ) ) {
92            foreach ( $this->descriptor['lang'] as $langList => $_ ) {
93                if ( strpos( $langList, ',' ) !== false ) {
94                    $this->descriptor['lang'] += array_fill_keys(
95                        explode( ',', $langList ),
96                        $this->descriptor['lang'][$langList]
97                    );
98                    unset( $this->descriptor['lang'][$langList] );
99                }
100            }
101        }
102        // Remove 'deprecated' key
103        if ( is_array( $this->descriptor ) ) {
104            unset( $this->descriptor['deprecated'] );
105        }
106
107        // Ensure that all files have common extension.
108        $extensions = [];
109        $descriptor = is_array( $this->descriptor ) ? $this->descriptor : [ $this->descriptor ];
110        array_walk_recursive( $descriptor, function ( $path ) use ( &$extensions ) {
111            $extensions[] = pathinfo( $this->getLocalPath( $path ), PATHINFO_EXTENSION );
112        } );
113        $extensions = array_unique( $extensions );
114        if ( count( $extensions ) !== 1 ) {
115            throw new InvalidArgumentException(
116                "File type for different image files of '$name' not the same in module '$module'"
117            );
118        }
119        $ext = $extensions[0];
120        if ( !isset( self::FILE_TYPES[$ext] ) ) {
121            throw new InvalidArgumentException(
122                "Invalid file type for image files of '$name' (valid: svg, png, gif, jpg) in module '$module'"
123            );
124        }
125        $this->extension = $ext;
126    }
127
128    /**
129     * Get name of this image.
130     *
131     * @return string
132     */
133    public function getName() {
134        return $this->name;
135    }
136
137    /**
138     * Get name of the module this image belongs to.
139     *
140     * @return string
141     */
142    public function getModule() {
143        return $this->module;
144    }
145
146    /**
147     * Get the list of variants this image can be converted to.
148     *
149     * @return string[]
150     */
151    public function getVariants(): array {
152        return array_keys( $this->variants );
153    }
154
155    /**
156     * @internal For unit testing override
157     * @param string $lang
158     * @return string[]
159     */
160    protected function getLangFallbacks( string $lang ): array {
161        return MediaWikiServices::getInstance()
162            ->getLanguageFallback()
163            ->getAll( $lang, LanguageFallback::STRICT );
164    }
165
166    /**
167     * Get the path to image file for given context.
168     *
169     * @param Context $context Any context
170     * @return string
171     */
172    public function getPath( Context $context ) {
173        $desc = $this->descriptor;
174        if ( !is_array( $desc ) ) {
175            return $this->getLocalPath( $desc );
176        }
177        if ( isset( $desc['lang'] ) ) {
178            $contextLang = $context->getLanguage();
179            if ( isset( $desc['lang'][$contextLang] ) ) {
180                return $this->getLocalPath( $desc['lang'][$contextLang] );
181            }
182            $fallbacks = $this->getLangFallbacks( $contextLang );
183            foreach ( $fallbacks as $lang ) {
184                if ( isset( $desc['lang'][$lang] ) ) {
185                    return $this->getLocalPath( $desc['lang'][$lang] );
186                }
187            }
188        }
189        if ( isset( $desc[$context->getDirection()] ) ) {
190            return $this->getLocalPath( $desc[$context->getDirection()] );
191        }
192        if ( isset( $desc['default'] ) ) {
193            return $this->getLocalPath( $desc['default'] );
194        }
195        throw new RuntimeException( 'No matching path found' );
196    }
197
198    /**
199     * @param string|FilePath $path
200     * @return string
201     */
202    protected function getLocalPath( $path ) {
203        if ( $path instanceof FilePath ) {
204            return $path->getLocalPath();
205        }
206
207        return "{$this->basePath}/$path";
208    }
209
210    /**
211     * Get the extension of the image.
212     *
213     * @param string|null $format Format to get the extension for, 'original' or 'rasterized'
214     * @return string Extension without leading dot, e.g. 'png'
215     */
216    public function getExtension( $format = 'original' ) {
217        if ( $format === 'rasterized' && $this->extension === 'svg' ) {
218            return 'png';
219        }
220        return $this->extension;
221    }
222
223    /**
224     * Get the MIME type of the image.
225     *
226     * @param string|null $format Format to get the MIME type for, 'original' or 'rasterized'
227     * @return string
228     */
229    public function getMimeType( $format = 'original' ) {
230        $ext = $this->getExtension( $format );
231        return self::FILE_TYPES[$ext];
232    }
233
234    /**
235     * Get the load.php URL that will produce this image.
236     *
237     * @param Context $context Any context
238     * @param string $script URL to load.php
239     * @param string|null $variant Variant to get the URL for
240     * @param string $format Format to get the URL for, 'original' or 'rasterized'
241     * @return string URL
242     */
243    public function getUrl( Context $context, $script, $variant, $format ) {
244        $query = [
245            'modules' => $this->getModule(),
246            'image' => $this->getName(),
247            'variant' => $variant,
248            'format' => $format,
249            // Most images don't vary on language, but include the parameter anyway, so that version
250            // hashes are computed consistently. (T321394#9100166)
251            'lang' => $context->getLanguage(),
252            'skin' => $context->getSkin(),
253            'version' => $context->getResourceLoader()->makeVersionQuery( $context, [ $this->getModule() ] ),
254        ];
255
256        return wfAppendQuery( $script, $query );
257    }
258
259    /**
260     * Get the data: URI that will produce this image.
261     *
262     * @param Context $context Any context
263     * @param string|null $variant Variant to get the URI for
264     * @param string $format Format to get the URI for, 'original' or 'rasterized'
265     * @return string
266     */
267    public function getDataUri( Context $context, $variant, $format ) {
268        $type = $this->getMimeType( $format );
269        $contents = $this->getImageData( $context, $variant, $format );
270        return CSSMin::encodeStringAsDataURI( $contents, $type );
271    }
272
273    /**
274     * Get actual image data for this image. This can be saved to a file or sent to the browser to
275     * produce the converted image.
276     *
277     * Call getExtension() or getMimeType() with the same $format argument to learn what file type the
278     * returned data uses.
279     *
280     * @param Context $context Image context, or any context if $variant and $format
281     *     given.
282     * @param string|null|false $variant Variant to get the data for. Optional; if given, overrides the data
283     *     from $context.
284     * @param string|false $format Format to get the data for, 'original' or 'rasterized'. Optional; if
285     *     given, overrides the data from $context.
286     * @return string|false Possibly binary image data, or false on failure
287     */
288    public function getImageData( Context $context, $variant = false, $format = false ) {
289        if ( $variant === false ) {
290            $variant = $context->getVariant();
291        }
292        if ( $format === false ) {
293            $format = $context->getFormat();
294        }
295
296        $path = $this->getPath( $context );
297        if ( !file_exists( $path ) ) {
298            throw new RuntimeException( "File '$path' does not exist" );
299        }
300
301        if ( $this->getExtension() !== 'svg' ) {
302            return file_get_contents( $path );
303        }
304
305        if ( $variant && isset( $this->variants[$variant] ) ) {
306            $data = $this->variantize( $this->variants[$variant], $context );
307        } else {
308            $defaultColor = $this->defaultColor;
309            $data = $defaultColor ?
310                $this->variantize( [ 'color' => $defaultColor ], $context ) :
311                file_get_contents( $path );
312        }
313
314        if ( $format === 'rasterized' ) {
315            $data = $this->rasterize( $data );
316            if ( !$data ) {
317                $logger = $context->getResourceLoader()->getLogger();
318                $logger->error( __METHOD__ . " failed to rasterize for $path" );
319            }
320        }
321
322        return $data;
323    }
324
325    /**
326     * Send response headers (using the header() function) that are necessary to correctly serve the
327     * image data for this image, as returned by getImageData().
328     *
329     * Note that the headers are independent of the language or image variant.
330     *
331     * @param Context $context Image context
332     */
333    public function sendResponseHeaders( Context $context ): void {
334        $format = $context->getFormat();
335        $mime = $this->getMimeType( $format );
336        $filename = $this->getName() . '.' . $this->getExtension( $format );
337
338        header( 'Content-Type: ' . $mime );
339        header( 'Content-Disposition: ' .
340            FileBackend::makeContentDisposition( 'inline', $filename ) );
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( file_get_contents( $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 ( strpos( $svgConverter, 'rsvg' ) === 0 ) {
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}