3 * ResourceLoader module for generated and embedded images.
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
21 * @author Trevor Parscal
25 * ResourceLoader module for generated and embedded images.
29 class ResourceLoaderImageModule
extends ResourceLoaderModule
{
31 /** @var array|null */
32 protected $definition = null;
35 * Local base path, see __construct()
38 protected $localBasePath = '';
40 protected $origin = self
::ORIGIN_CORE_SITEWIDE
;
42 /** @var ResourceLoaderImage[]|null */
43 protected $imageObjects = null;
45 protected $images = [];
46 /** @var string|null */
47 protected $defaultColor = null;
48 protected $useDataURI = true;
49 /** @var array|null */
50 protected $globalVariants = null;
52 protected $variants = [];
53 /** @var string|null */
54 protected $prefix = null;
55 protected $selectorWithoutVariant = '.{prefix}-{name}';
56 protected $selectorWithVariant = '.{prefix}-{name}-{variant}';
57 protected $targets = [ 'desktop', 'mobile' ];
60 * Constructs a new module from an options array.
62 * @param array $options List of options; if not given or empty, an empty module will be
64 * @param string|null $localBasePath Base path to prepend to all local paths in $options. Defaults
67 * Below is a description for the $options array:
68 * @par Construction options:
71 * // Base path to prepend to all local paths in $options. Defaults to $IP
72 * 'localBasePath' => [base path],
73 * // Path to JSON file that contains any of the settings below
74 * 'data' => [file path string]
75 * // CSS class prefix to use in all style rules
76 * 'prefix' => [CSS class prefix],
77 * // Alternatively: Format of CSS selector to use in all style rules
78 * 'selector' => [CSS selector template, variables: {prefix} {name} {variant}],
79 * // Alternatively: When using variants
80 * 'selectorWithoutVariant' => [CSS selector template, variables: {prefix} {name}],
81 * 'selectorWithVariant' => [CSS selector template, variables: {prefix} {name} {variant}],
82 * // List of variants that may be used for the image files
84 * // This level of nesting can be omitted if you use the same images for every skin
85 * [skin name (or 'default')] => [
87 * 'color' => [color string, e.g. '#ffff00'],
88 * 'global' => [boolean, if true, this variant is available
89 * for all images of this type],
95 * // List of image files and their options
97 * // This level of nesting can be omitted if you use the same images for every skin
98 * [skin name (or 'default')] => [
100 * 'file' => [file path string or array whose values are file path strings
101 * and whose keys are 'default', 'ltr', 'rtl', a single
102 * language code like 'en', or a list of language codes like
104 * 'variants' => [array of variant name strings, variants
105 * available for this image],
113 * @throws InvalidArgumentException
115 public function __construct( $options = [], $localBasePath = null ) {
116 $this->localBasePath
= self
::extractLocalBasePath( $options, $localBasePath );
118 $this->definition
= $options;
122 * Parse definition and external JSON data, if referenced.
124 protected function loadFromDefinition() {
125 if ( $this->definition
=== null ) {
129 $options = $this->definition
;
130 $this->definition
= null;
132 if ( isset( $options['data'] ) ) {
133 $dataPath = $this->localBasePath
. '/' . $options['data'];
134 $data = json_decode( file_get_contents( $dataPath ), true );
135 $options = array_merge( $data, $options );
138 // Accepted combinations:
141 // * selectorWithoutVariant + selectorWithVariant
142 // * prefix + selector
143 // * prefix + selectorWithoutVariant + selectorWithVariant
145 $prefix = isset( $options['prefix'] ) && $options['prefix'];
146 $selector = isset( $options['selector'] ) && $options['selector'];
147 $selectorWithoutVariant = isset( $options['selectorWithoutVariant'] )
148 && $options['selectorWithoutVariant'];
149 $selectorWithVariant = isset( $options['selectorWithVariant'] )
150 && $options['selectorWithVariant'];
152 if ( $selectorWithoutVariant && !$selectorWithVariant ) {
153 throw new InvalidArgumentException(
154 "Given 'selectorWithoutVariant' but no 'selectorWithVariant'."
157 if ( $selectorWithVariant && !$selectorWithoutVariant ) {
158 throw new InvalidArgumentException(
159 "Given 'selectorWithVariant' but no 'selectorWithoutVariant'."
162 if ( $selector && $selectorWithVariant ) {
163 throw new InvalidArgumentException(
164 "Incompatible 'selector' and 'selectorWithVariant'+'selectorWithoutVariant' given."
167 if ( !$prefix && !$selector && !$selectorWithVariant ) {
168 throw new InvalidArgumentException(
169 "None of 'prefix', 'selector' or 'selectorWithVariant'+'selectorWithoutVariant' given."
173 foreach ( $options as $member => $option ) {
177 if ( !is_array( $option ) ) {
178 throw new InvalidArgumentException(
179 "Invalid list error. '$option' given, array expected."
182 if ( !isset( $option['default'] ) ) {
183 // Backwards compatibility
184 $option = [ 'default' => $option ];
186 foreach ( $option as $skin => $data ) {
187 if ( !is_array( $option ) ) {
188 throw new InvalidArgumentException(
189 "Invalid list error. '$option' given, array expected."
193 $this->{$member} = $option;
197 $this->{$member} = (bool)$option;
201 case 'selectorWithoutVariant':
202 case 'selectorWithVariant':
203 $this->{$member} = (string)$option;
207 $this->selectorWithoutVariant
= $this->selectorWithVariant
= (string)$option;
213 * Get CSS class prefix used by this module.
216 public function getPrefix() {
217 $this->loadFromDefinition();
218 return $this->prefix
;
222 * Get CSS selector templates used by this module.
225 public function getSelectors() {
226 $this->loadFromDefinition();
228 'selectorWithoutVariant' => $this->selectorWithoutVariant
,
229 'selectorWithVariant' => $this->selectorWithVariant
,
234 * Get a ResourceLoaderImage object for given image.
235 * @param string $name Image name
236 * @param ResourceLoaderContext $context
237 * @return ResourceLoaderImage|null
239 public function getImage( $name, ResourceLoaderContext
$context ) {
240 $this->loadFromDefinition();
241 $images = $this->getImages( $context );
242 return $images[$name] ??
null;
246 * Get ResourceLoaderImage objects for all images.
247 * @param ResourceLoaderContext $context
248 * @return ResourceLoaderImage[] Array keyed by image name
250 public function getImages( ResourceLoaderContext
$context ) {
251 $skin = $context->getSkin();
252 if ( $this->imageObjects
=== null ) {
253 $this->loadFromDefinition();
254 $this->imageObjects
= [];
256 if ( !isset( $this->imageObjects
[$skin] ) ) {
257 $this->imageObjects
[$skin] = [];
258 if ( !isset( $this->images
[$skin] ) ) {
259 $this->images
[$skin] = $this->images
['default'] ??
[];
261 foreach ( $this->images
[$skin] as $name => $options ) {
262 $fileDescriptor = is_string( $options ) ?
$options : $options['file'];
264 $allowedVariants = array_merge(
265 ( is_array( $options ) && isset( $options['variants'] ) ) ?
$options['variants'] : [],
266 $this->getGlobalVariants( $context )
268 if ( isset( $this->variants
[$skin] ) ) {
269 $variantConfig = array_intersect_key(
270 $this->variants
[$skin],
271 array_fill_keys( $allowedVariants, true )
277 $image = new ResourceLoaderImage(
281 $this->localBasePath
,
285 $this->imageObjects
[$skin][$image->getName()] = $image;
289 return $this->imageObjects
[$skin];
293 * Get list of variants in this module that are 'global', i.e., available
294 * for every image regardless of image options.
295 * @param ResourceLoaderContext $context
298 public function getGlobalVariants( ResourceLoaderContext
$context ) {
299 $skin = $context->getSkin();
300 if ( $this->globalVariants
=== null ) {
301 $this->loadFromDefinition();
302 $this->globalVariants
= [];
304 if ( !isset( $this->globalVariants
[$skin] ) ) {
305 $this->globalVariants
[$skin] = [];
306 if ( !isset( $this->variants
[$skin] ) ) {
307 $this->variants
[$skin] = $this->variants
['default'] ??
[];
309 foreach ( $this->variants
[$skin] as $name => $config ) {
310 if ( isset( $config['global'] ) && $config['global'] ) {
311 $this->globalVariants
[$skin][] = $name;
316 return $this->globalVariants
[$skin];
320 * @param ResourceLoaderContext $context
323 public function getStyles( ResourceLoaderContext
$context ) {
324 $this->loadFromDefinition();
328 $script = $context->getResourceLoader()->getLoadScript( $this->getSource() );
329 $selectors = $this->getSelectors();
331 foreach ( $this->getImages( $context ) as $name => $image ) {
332 $declarations = $this->getStyleDeclarations( $context, $image, $script );
334 $selectors['selectorWithoutVariant'],
336 '{prefix}' => $this->getPrefix(),
341 $rules[] = "$selector {\n\t$declarations\n}";
343 foreach ( $image->getVariants() as $variant ) {
344 $declarations = $this->getStyleDeclarations( $context, $image, $script, $variant );
346 $selectors['selectorWithVariant'],
348 '{prefix}' => $this->getPrefix(),
350 '{variant}' => $variant,
353 $rules[] = "$selector {\n\t$declarations\n}";
357 $style = implode( "\n", $rules );
358 return [ 'all' => $style ];
362 * @param ResourceLoaderContext $context
363 * @param ResourceLoaderImage $image Image to get the style for
364 * @param string $script URL to load.php
365 * @param string|null $variant Variant to get the style for
368 private function getStyleDeclarations(
369 ResourceLoaderContext
$context,
370 ResourceLoaderImage
$image,
374 $imageDataUri = $this->useDataURI ?
$image->getDataUri( $context, $variant, 'original' ) : false;
375 $primaryUrl = $imageDataUri ?
: $image->getUrl( $context, $script, $variant, 'original' );
376 $declarations = $this->getCssDeclarations(
378 $image->getUrl( $context, $script, $variant, 'rasterized' )
380 return implode( "\n\t", $declarations );
384 * SVG support using a transparent gradient to guarantee cross-browser
385 * compatibility (browsers able to understand gradient syntax support also SVG).
386 * http://pauginer.tumblr.com/post/36614680636/invisible-gradient-technique
388 * Keep synchronized with the .background-image-svg LESS mixin in
389 * /resources/src/mediawiki.less/mediawiki.mixins.less.
391 * @param string $primary Primary URI
392 * @param string $fallback Fallback URI
393 * @return string[] CSS declarations to use given URIs as background-image
395 protected function getCssDeclarations( $primary, $fallback ) {
396 $primaryUrl = CSSMin
::buildUrlValue( $primary );
397 $fallbackUrl = CSSMin
::buildUrlValue( $fallback );
399 "background-image: $fallbackUrl;",
400 "background-image: linear-gradient(transparent, transparent), $primaryUrl;",
407 public function supportsURLLoading() {
412 * Get the definition summary for this module.
414 * @param ResourceLoaderContext $context
417 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
418 $this->loadFromDefinition();
419 $summary = parent
::getDefinitionSummary( $context );
427 'selectorWithoutVariant',
428 'selectorWithVariant',
430 $options[$member] = $this->{$member};
434 'options' => $options,
435 'fileHashes' => $this->getFileHashes( $context ),
441 * Helper method for getDefinitionSummary.
442 * @param ResourceLoaderContext $context
445 private function getFileHashes( ResourceLoaderContext
$context ) {
446 $this->loadFromDefinition();
448 foreach ( $this->getImages( $context ) as $name => $image ) {
449 $files[] = $image->getPath( $context );
451 $files = array_values( array_unique( $files ) );
452 return array_map( [ __CLASS__
, 'safeFileHash' ], $files );
456 * Extract a local base path from module definition information.
458 * @param array $options Module definition
459 * @param string|null $localBasePath Path to use if not provided in module definition. Defaults
461 * @return string Local base path
463 public static function extractLocalBasePath( $options, $localBasePath = null ) {
466 if ( $localBasePath === null ) {
467 $localBasePath = $IP;
470 if ( array_key_exists( 'localBasePath', $options ) ) {
471 $localBasePath = (string)$options['localBasePath'];
474 return $localBasePath;
480 public function getType() {
481 return self
::LOAD_STYLES
;