Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
71.43% covered (warning)
71.43%
135 / 189
52.94% covered (warning)
52.94%
9 / 17
CRAP
0.00% covered (danger)
0.00%
0 / 1
ImageModule
71.43% covered (warning)
71.43%
135 / 189
52.94% covered (warning)
52.94%
9 / 17
167.60
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 loadFromDefinition
57.89% covered (warning)
57.89%
33 / 57
0.00% covered (danger)
0.00%
0 / 1
91.78
 getPrefix
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getSelectors
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 getImage
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 getImages
96.55% covered (success)
96.55%
28 / 29
0.00% covered (danger)
0.00%
0 / 1
8
 getGlobalVariants
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
5
 getStyles
96.88% covered (success)
96.88%
31 / 32
0.00% covered (danger)
0.00%
0 / 1
4
 getStyleDeclarations
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 getCssDeclarations
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
 supportsMaskImage
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 supportsURLLoading
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getDefinitionSummary
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
6
 getFileHashes
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 getLocalPath
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 extractLocalBasePath
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 getType
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * @license GPL-2.0-or-later
4 * @file
5 * @author Trevor Parscal
6 */
7namespace MediaWiki\ResourceLoader;
8
9use DomainException;
10use InvalidArgumentException;
11use Wikimedia\Minify\CSSMin;
12
13/**
14 * Module for generated and embedded images.
15 *
16 * @ingroup ResourceLoader
17 * @since 1.25
18 */
19class ImageModule extends Module {
20    /** @var bool */
21    private $useMaskImage;
22    /** @var array|null */
23    protected $definition;
24
25    /**
26     * Local base path, see __construct()
27     * @var string
28     */
29    protected $localBasePath = '';
30
31    /** @inheritDoc */
32    protected $origin = self::ORIGIN_CORE_SITEWIDE;
33
34    /** @var Image[][]|null */
35    protected $imageObjects = null;
36    /** @var array */
37    protected $images = [];
38    /** @var string|null */
39    protected $defaultColor = null;
40    /** @var bool */
41    protected $useDataURI = true;
42    /** @var array|null */
43    protected $globalVariants = null;
44    /** @var array */
45    protected $variants = [];
46    /** @var string|null */
47    protected $prefix = null;
48    /** @var string */
49    protected $selectorWithoutVariant = '.{prefix}-{name}';
50    /** @var string */
51    protected $selectorWithVariant = '.{prefix}-{name}-{variant}';
52
53    /**
54     * Constructs a new module from an options array.
55     *
56     * @param array $options List of options; if not given or empty, an empty module will be
57     *     constructed
58     * @param string|null $localBasePath Base path to prepend to all local paths in $options. Defaults
59     *     to $IP
60     *
61     * Below is a description for the $options array:
62     * @par Construction options:
63     * @code
64     *     [
65     *         // When set the icon will use mask-image instead of background-image for the CSS output. Using mask-image
66     *         // allows colorization of SVGs in Codex. Defaults to false for backwards compatibility.
67     *         'useMaskImage' => false,
68     *         // Base path to prepend to all local paths in $options. Defaults to $IP
69     *         'localBasePath' => [base path],
70     *         // Path to JSON file that contains any of the settings below
71     *         'data' => [file path string]
72     *         // CSS class prefix to use in all style rules
73     *         'prefix' => [CSS class prefix],
74     *         // Alternatively: Format of CSS selector to use in all style rules
75     *         'selector' => [CSS selector template, variables: {prefix} {name} {variant}],
76     *         // Alternatively: When using variants
77     *         'selectorWithoutVariant' => [CSS selector template, variables: {prefix} {name}],
78     *         'selectorWithVariant' => [CSS selector template, variables: {prefix} {name} {variant}],
79     *         // List of variants that may be used for the image files
80     *         'variants' => [
81     *             // This level of nesting can be omitted if you use the same images for every skin
82     *             [skin name (or 'default')] => [
83     *                 [variant name] => [
84     *                     'color' => [color string, e.g. '#ffff00'],
85     *                     'global' => [boolean, if true, this variant is available
86     *                                  for all images of this type],
87     *                 ],
88     *                 ...
89     *             ],
90     *             ...
91     *         ],
92     *         // List of image files and their options
93     *         'images' => [
94     *             // This level of nesting can be omitted if you use the same images for every skin
95     *             [skin name (or 'default')] => [
96     *                 [icon name] => [
97     *                     'file' => [file path string or array whose values are file path strings
98     *                                    and whose keys are 'default', 'ltr', 'rtl', a single
99     *                                    language code like 'en', or a list of language codes like
100     *                                    'en,de,ar'],
101     *                     'variants' => [array of variant name strings, variants
102     *                                    available for this image],
103     *                 ],
104     *                 ...
105     *             ],
106     *             ...
107     *         ],
108     *     ]
109     * @endcode
110     */
111    public function __construct( array $options = [], $localBasePath = null ) {
112        $this->useMaskImage = $options['useMaskImage'] ?? false;
113        $this->localBasePath = static::extractLocalBasePath( $options, $localBasePath );
114
115        $this->definition = $options;
116    }
117
118    /**
119     * Parse definition and external JSON data, if referenced.
120     */
121    protected function loadFromDefinition() {
122        if ( $this->definition === null ) {
123            return;
124        }
125
126        $options = $this->definition;
127        $this->definition = null;
128
129        if ( isset( $options['data'] ) ) {
130            $dataPath = $this->getLocalPath( $options['data'] );
131            $data = json_decode( file_get_contents( $dataPath ), true );
132            $options = array_merge( $data, $options );
133        }
134
135        // Accepted combinations:
136        // * prefix
137        // * selector
138        // * selectorWithoutVariant + selectorWithVariant
139        // * prefix + selector
140        // * prefix + selectorWithoutVariant + selectorWithVariant
141
142        $prefix = isset( $options['prefix'] ) && $options['prefix'];
143        $selector = isset( $options['selector'] ) && $options['selector'];
144        $selectorWithoutVariant = isset( $options['selectorWithoutVariant'] )
145            && $options['selectorWithoutVariant'];
146        $selectorWithVariant = isset( $options['selectorWithVariant'] )
147            && $options['selectorWithVariant'];
148
149        if ( $selectorWithoutVariant && !$selectorWithVariant ) {
150            throw new InvalidArgumentException(
151                "Given 'selectorWithoutVariant' but no 'selectorWithVariant'."
152            );
153        }
154        if ( $selectorWithVariant && !$selectorWithoutVariant ) {
155            throw new InvalidArgumentException(
156                "Given 'selectorWithVariant' but no 'selectorWithoutVariant'."
157            );
158        }
159        if ( $selector && $selectorWithVariant ) {
160            throw new InvalidArgumentException(
161                "Incompatible 'selector' and 'selectorWithVariant'+'selectorWithoutVariant' given."
162            );
163        }
164        if ( !$prefix && !$selector && !$selectorWithVariant ) {
165            throw new InvalidArgumentException(
166                "None of 'prefix', 'selector' or 'selectorWithVariant'+'selectorWithoutVariant' given."
167            );
168        }
169
170        foreach ( $options as $member => $option ) {
171            switch ( $member ) {
172                case 'images':
173                case 'variants':
174                    if ( !is_array( $option ) ) {
175                        throw new InvalidArgumentException(
176                            "Invalid list error. '$option' given, array expected."
177                        );
178                    }
179                    if ( !isset( $option['default'] ) ) {
180                        // Backwards compatibility
181                        $option = [ 'default' => $option ];
182                    }
183                    foreach ( $option as $data ) {
184                        if ( !is_array( $data ) ) {
185                            throw new InvalidArgumentException(
186                                "Invalid list error. '$data' given, array expected."
187                            );
188                        }
189                    }
190                    $this->{$member} = $option;
191                    break;
192
193                case 'useDataURI':
194                    $this->{$member} = (bool)$option;
195                    break;
196                case 'defaultColor':
197                case 'prefix':
198                case 'selectorWithoutVariant':
199                case 'selectorWithVariant':
200                    $this->{$member} = (string)$option;
201                    break;
202
203                case 'selector':
204                    $this->selectorWithoutVariant = $this->selectorWithVariant = (string)$option;
205            }
206        }
207    }
208
209    /**
210     * Get CSS class prefix used by this module.
211     * @return string
212     */
213    public function getPrefix() {
214        $this->loadFromDefinition();
215        return $this->prefix;
216    }
217
218    /**
219     * Get CSS selector templates used by this module.
220     * @return string[]
221     */
222    public function getSelectors() {
223        $this->loadFromDefinition();
224        return [
225            'selectorWithoutVariant' => $this->selectorWithoutVariant,
226            'selectorWithVariant' => $this->selectorWithVariant,
227        ];
228    }
229
230    /**
231     * Get an Image object for given image.
232     * @param string $name Image name
233     * @param Context $context
234     * @return Image|null
235     */
236    public function getImage( $name, Context $context ): ?Image {
237        $this->loadFromDefinition();
238        $images = $this->getImages( $context );
239        return $images[$name] ?? null;
240    }
241
242    /**
243     * Get Image objects for all images.
244     * @param Context $context
245     * @return Image[] Array keyed by image name
246     */
247    public function getImages( Context $context ): array {
248        $skin = $context->getSkin();
249        if ( $this->imageObjects === null ) {
250            $this->loadFromDefinition();
251            $this->imageObjects = [];
252        }
253        if ( !isset( $this->imageObjects[$skin] ) ) {
254            $this->imageObjects[$skin] = [];
255            $this->images[$skin] ??= $this->images['default'] ?? [];
256            foreach ( $this->images[$skin] as $name => $options ) {
257                $fileDescriptor = is_array( $options ) ? $options['file'] : $options;
258
259                $allowedVariants = array_merge(
260                    ( is_array( $options ) && isset( $options['variants'] ) ) ? $options['variants'] : [],
261                    $this->getGlobalVariants( $context )
262                );
263                if ( isset( $this->variants[$skin] ) ) {
264                    $variantConfig = array_intersect_key(
265                        $this->variants[$skin],
266                        array_fill_keys( $allowedVariants, true )
267                    );
268                } else {
269                    $variantConfig = [];
270                }
271
272                $image = new Image(
273                    $name,
274                    $this->getName(),
275                    $fileDescriptor,
276                    $this->localBasePath,
277                    $variantConfig,
278                    $this->defaultColor
279                );
280                $this->imageObjects[$skin][$image->getName()] = $image;
281            }
282        }
283
284        return $this->imageObjects[$skin];
285    }
286
287    /**
288     * Get list of variants in this module that are 'global', i.e., available
289     * for every image regardless of image options.
290     * @param Context $context
291     * @return string[]
292     */
293    public function getGlobalVariants( Context $context ): array {
294        $skin = $context->getSkin();
295        if ( $this->globalVariants === null ) {
296            $this->loadFromDefinition();
297            $this->globalVariants = [];
298        }
299        if ( !isset( $this->globalVariants[$skin] ) ) {
300            $this->globalVariants[$skin] = [];
301            $this->variants[$skin] ??= $this->variants['default'] ?? [];
302            foreach ( $this->variants[$skin] as $name => $config ) {
303                if ( $config['global'] ?? false ) {
304                    $this->globalVariants[$skin][] = $name;
305                }
306            }
307        }
308
309        return $this->globalVariants[$skin];
310    }
311
312    public function getStyles( Context $context ): array {
313        $this->loadFromDefinition();
314
315        // Build CSS rules
316        $rules = [];
317
318        $sources = $oldSources = $context->getResourceLoader()->getSources();
319        $this->getHookRunner()->onResourceLoaderModifyEmbeddedSourceUrls( $sources );
320        if ( array_keys( $sources ) !== array_keys( $oldSources ) ) {
321            throw new DomainException( 'ResourceLoaderModifyEmbeddedSourceUrls hook must not add or remove sources' );
322        }
323        $script = $sources[ $this->getSource() ];
324
325        $selectors = $this->getSelectors();
326
327        foreach ( $this->getImages( $context ) as $name => $image ) {
328            $declarations = $this->getStyleDeclarations( $context, $image, $script );
329            $selector = strtr(
330                $selectors['selectorWithoutVariant'],
331                [
332                    '{prefix}' => $this->getPrefix(),
333                    '{name}' => $name,
334                    '{variant}' => '',
335                ]
336            );
337            $rules[] = "$selector {\n\t$declarations\n}";
338
339            foreach ( $image->getVariants() as $variant ) {
340                $declarations = $this->getStyleDeclarations( $context, $image, $script, $variant );
341                $selector = strtr(
342                    $selectors['selectorWithVariant'],
343                    [
344                        '{prefix}' => $this->getPrefix(),
345                        '{name}' => $name,
346                        '{variant}' => $variant,
347                    ]
348                );
349                $rules[] = "$selector {\n\t$declarations\n}";
350            }
351        }
352
353        $style = implode( "\n", $rules );
354
355        return [ 'all' => $style ];
356    }
357
358    /**
359     * This method must not be used by getDefinitionSummary as doing so would cause
360     * an infinite loop (we use Image::getUrl below which calls
361     * Module:getVersionHash, which calls Module::getDefinitionSummary).
362     *
363     * @param Context $context
364     * @param Image $image Image to get the style for
365     * @param string $script URL to load.php
366     * @param string|null $variant Variant to get the style for
367     * @return string
368     */
369    private function getStyleDeclarations(
370        Context $context,
371        Image $image,
372        $script,
373        $variant = null
374    ) {
375        $imageDataUri = $this->useDataURI ? $image->getDataUri( $context, $variant, 'original' ) : false;
376        $primaryUrl = $imageDataUri ?: $image->getUrl( $context, $script, $variant, 'original' );
377        $declarations = $this->getCssDeclarations(
378            $primaryUrl
379        );
380        return implode( "\n\t", $declarations );
381    }
382
383    /**
384     * Format the CSS declaration for the image as a background-image property.
385     *
386     * @param string $primary Primary URI
387     * @return string[] CSS declarations
388     */
389    protected function getCssDeclarations( $primary ): array {
390        $primaryUrl = CSSMin::buildUrlValue( $primary );
391        if ( $this->supportsMaskImage() ) {
392            return [
393                "-webkit-mask-image: $primaryUrl;",
394                "mask-image: $primaryUrl;",
395            ];
396        }
397        return [
398            "background-image: $primaryUrl;",
399        ];
400    }
401
402    /**
403     * @return bool
404     */
405    public function supportsMaskImage() {
406        return $this->useMaskImage;
407    }
408
409    /**
410     * @return bool
411     */
412    public function supportsURLLoading() {
413        return false;
414    }
415
416    /**
417     * Get the definition summary for this module.
418     *
419     * @param Context $context
420     * @return array
421     */
422    public function getDefinitionSummary( Context $context ) {
423        $this->loadFromDefinition();
424        $summary = parent::getDefinitionSummary( $context );
425
426        $options = [];
427        foreach ( [
428            'localBasePath',
429            'images',
430            'variants',
431            'prefix',
432            'selectorWithoutVariant',
433            'selectorWithVariant',
434        ] as $member ) {
435            $options[$member] = $this->{$member};
436        }
437
438        $summary[] = [
439            'options' => $options,
440            'fileHashes' => $this->getFileHashes( $context ),
441        ];
442        return $summary;
443    }
444
445    /**
446     * Helper method for getDefinitionSummary.
447     * @param Context $context
448     * @return array
449     */
450    private function getFileHashes( Context $context ) {
451        $this->loadFromDefinition();
452        $files = [];
453        foreach ( $this->getImages( $context ) as $image ) {
454            $files[] = $image->getPath( $context );
455        }
456        $files = array_values( array_unique( $files ) );
457        return array_map( self::safeFileHash( ... ), $files );
458    }
459
460    /**
461     * @param string|FilePath $path
462     * @return string
463     */
464    protected function getLocalPath( $path ) {
465        if ( $path instanceof FilePath ) {
466            return $path->getLocalPath();
467        }
468
469        return "{$this->localBasePath}/$path";
470    }
471
472    /**
473     * Extract a local base path from module definition information.
474     *
475     * @param array $options Module definition
476     * @param string|null $localBasePath Path to use if not provided in module definition. Defaults
477     *  to $IP.
478     * @return string Local base path
479     */
480    public static function extractLocalBasePath( array $options, $localBasePath = null ) {
481        global $IP;
482
483        if ( array_key_exists( 'localBasePath', $options ) ) {
484            $localBasePath = (string)$options['localBasePath'];
485        }
486
487        return $localBasePath ?? $IP;
488    }
489
490    /**
491     * @return string
492     */
493    public function getType() {
494        return self::LOAD_STYLES;
495    }
496}