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.
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.
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
19 * @author Trevor Parscal
23 * Module for generated and embedded images.
25 * @ingroup ResourceLoader
28 class ResourceLoaderImageModule
extends ResourceLoaderModule
{
30 /** @var array|null */
31 protected $definition = null;
34 * Local base path, see __construct()
37 protected $localBasePath = '';
39 protected $origin = self
::ORIGIN_CORE_SITEWIDE
;
41 /** @var ResourceLoaderImage[][]|null */
42 protected $imageObjects = null;
44 protected $images = [];
45 /** @var string|null */
46 protected $defaultColor = null;
47 protected $useDataURI = true;
48 /** @var array|null */
49 protected $globalVariants = null;
51 protected $variants = [];
52 /** @var string|null */
53 protected $prefix = null;
54 protected $selectorWithoutVariant = '.{prefix}-{name}';
55 protected $selectorWithVariant = '.{prefix}-{name}-{variant}';
56 protected $targets = [ 'desktop', 'mobile' ];
59 * Constructs a new module from an options array.
61 * @param array $options List of options; if not given or empty, an empty module will be
63 * @param string|null $localBasePath Base path to prepend to all local paths in $options. Defaults
66 * Below is a description for the $options array:
67 * @par Construction options:
70 * // Base path to prepend to all local paths in $options. Defaults to $IP
71 * 'localBasePath' => [base path],
72 * // Path to JSON file that contains any of the settings below
73 * 'data' => [file path string]
74 * // CSS class prefix to use in all style rules
75 * 'prefix' => [CSS class prefix],
76 * // Alternatively: Format of CSS selector to use in all style rules
77 * 'selector' => [CSS selector template, variables: {prefix} {name} {variant}],
78 * // Alternatively: When using variants
79 * 'selectorWithoutVariant' => [CSS selector template, variables: {prefix} {name}],
80 * 'selectorWithVariant' => [CSS selector template, variables: {prefix} {name} {variant}],
81 * // List of variants that may be used for the image files
83 * // This level of nesting can be omitted if you use the same images for every skin
84 * [skin name (or 'default')] => [
86 * 'color' => [color string, e.g. '#ffff00'],
87 * 'global' => [boolean, if true, this variant is available
88 * for all images of this type],
94 * // List of image files and their options
96 * // This level of nesting can be omitted if you use the same images for every skin
97 * [skin name (or 'default')] => [
99 * 'file' => [file path string or array whose values are file path strings
100 * and whose keys are 'default', 'ltr', 'rtl', a single
101 * language code like 'en', or a list of language codes like
103 * 'variants' => [array of variant name strings, variants
104 * available for this image],
112 * @throws InvalidArgumentException
114 public function __construct( $options = [], $localBasePath = null ) {
115 $this->localBasePath
= static::extractLocalBasePath( $options, $localBasePath );
117 $this->definition
= $options;
121 * Parse definition and external JSON data, if referenced.
123 protected function loadFromDefinition() {
124 if ( $this->definition
=== null ) {
128 $options = $this->definition
;
129 $this->definition
= null;
131 if ( isset( $options['data'] ) ) {
132 $dataPath = $this->getLocalPath( $options['data'] );
133 $data = json_decode( file_get_contents( $dataPath ), true );
134 $options = array_merge( $data, $options );
137 // Accepted combinations:
140 // * selectorWithoutVariant + selectorWithVariant
141 // * prefix + selector
142 // * prefix + selectorWithoutVariant + selectorWithVariant
144 $prefix = isset( $options['prefix'] ) && $options['prefix'];
145 $selector = isset( $options['selector'] ) && $options['selector'];
146 $selectorWithoutVariant = isset( $options['selectorWithoutVariant'] )
147 && $options['selectorWithoutVariant'];
148 $selectorWithVariant = isset( $options['selectorWithVariant'] )
149 && $options['selectorWithVariant'];
151 if ( $selectorWithoutVariant && !$selectorWithVariant ) {
152 throw new InvalidArgumentException(
153 "Given 'selectorWithoutVariant' but no 'selectorWithVariant'."
156 if ( $selectorWithVariant && !$selectorWithoutVariant ) {
157 throw new InvalidArgumentException(
158 "Given 'selectorWithVariant' but no 'selectorWithoutVariant'."
161 if ( $selector && $selectorWithVariant ) {
162 throw new InvalidArgumentException(
163 "Incompatible 'selector' and 'selectorWithVariant'+'selectorWithoutVariant' given."
166 if ( !$prefix && !$selector && !$selectorWithVariant ) {
167 throw new InvalidArgumentException(
168 "None of 'prefix', 'selector' or 'selectorWithVariant'+'selectorWithoutVariant' given."
172 foreach ( $options as $member => $option ) {
176 if ( !is_array( $option ) ) {
177 throw new InvalidArgumentException(
178 "Invalid list error. '$option' given, array expected."
181 if ( !isset( $option['default'] ) ) {
182 // Backwards compatibility
183 $option = [ 'default' => $option ];
185 foreach ( $option as $skin => $data ) {
186 if ( !is_array( $data ) ) {
187 throw new InvalidArgumentException(
188 "Invalid list error. '$data' given, array expected."
192 $this->{$member} = $option;
196 $this->{$member} = (bool)$option;
200 case 'selectorWithoutVariant':
201 case 'selectorWithVariant':
202 $this->{$member} = (string)$option;
206 $this->selectorWithoutVariant
= $this->selectorWithVariant
= (string)$option;
212 * Get CSS class prefix used by this module.
215 public function getPrefix() {
216 $this->loadFromDefinition();
217 return $this->prefix
;
221 * Get CSS selector templates used by this module.
224 public function getSelectors() {
225 $this->loadFromDefinition();
227 'selectorWithoutVariant' => $this->selectorWithoutVariant
,
228 'selectorWithVariant' => $this->selectorWithVariant
,
233 * Get a ResourceLoaderImage object for given image.
234 * @param string $name Image name
235 * @param ResourceLoaderContext $context
236 * @return ResourceLoaderImage|null
238 public function getImage( $name, ResourceLoaderContext
$context ) {
239 $this->loadFromDefinition();
240 $images = $this->getImages( $context );
241 return $images[$name] ??
null;
245 * Get ResourceLoaderImage objects for all images.
246 * @param ResourceLoaderContext $context
247 * @return ResourceLoaderImage[] Array keyed by image name
249 public function getImages( ResourceLoaderContext
$context ) {
250 $skin = $context->getSkin();
251 if ( $this->imageObjects
=== null ) {
252 $this->loadFromDefinition();
253 $this->imageObjects
= [];
255 if ( !isset( $this->imageObjects
[$skin] ) ) {
256 $this->imageObjects
[$skin] = [];
257 if ( !isset( $this->images
[$skin] ) ) {
258 $this->images
[$skin] = $this->images
['default'] ??
[];
260 foreach ( $this->images
[$skin] as $name => $options ) {
261 $fileDescriptor = is_array( $options ) ?
$options['file'] : $options;
263 $allowedVariants = array_merge(
264 ( is_array( $options ) && isset( $options['variants'] ) ) ?
$options['variants'] : [],
265 $this->getGlobalVariants( $context )
267 if ( isset( $this->variants
[$skin] ) ) {
268 $variantConfig = array_intersect_key(
269 $this->variants
[$skin],
270 array_fill_keys( $allowedVariants, true )
276 $image = new ResourceLoaderImage(
280 $this->localBasePath
,
284 $this->imageObjects
[$skin][$image->getName()] = $image;
288 return $this->imageObjects
[$skin];
292 * Get list of variants in this module that are 'global', i.e., available
293 * for every image regardless of image options.
294 * @param ResourceLoaderContext $context
297 public function getGlobalVariants( ResourceLoaderContext
$context ) {
298 $skin = $context->getSkin();
299 if ( $this->globalVariants
=== null ) {
300 $this->loadFromDefinition();
301 $this->globalVariants
= [];
303 if ( !isset( $this->globalVariants
[$skin] ) ) {
304 $this->globalVariants
[$skin] = [];
305 if ( !isset( $this->variants
[$skin] ) ) {
306 $this->variants
[$skin] = $this->variants
['default'] ??
[];
308 foreach ( $this->variants
[$skin] as $name => $config ) {
309 if ( isset( $config['global'] ) && $config['global'] ) {
310 $this->globalVariants
[$skin][] = $name;
315 return $this->globalVariants
[$skin];
319 * @param ResourceLoaderContext $context
322 public function getStyles( ResourceLoaderContext
$context ) {
323 $this->loadFromDefinition();
327 $script = $context->getResourceLoader()->getLoadScript( $this->getSource() );
328 $selectors = $this->getSelectors();
330 foreach ( $this->getImages( $context ) as $name => $image ) {
331 $declarations = $this->getStyleDeclarations( $context, $image, $script );
333 $selectors['selectorWithoutVariant'],
335 '{prefix}' => $this->getPrefix(),
340 $rules[] = "$selector {\n\t$declarations\n}";
342 foreach ( $image->getVariants() as $variant ) {
343 $declarations = $this->getStyleDeclarations( $context, $image, $script, $variant );
345 $selectors['selectorWithVariant'],
347 '{prefix}' => $this->getPrefix(),
349 '{variant}' => $variant,
352 $rules[] = "$selector {\n\t$declarations\n}";
356 $style = implode( "\n", $rules );
357 return [ 'all' => $style ];
361 * @param ResourceLoaderContext $context
362 * @param ResourceLoaderImage $image Image to get the style for
363 * @param string $script URL to load.php
364 * @param string|null $variant Variant to get the style for
367 private function getStyleDeclarations(
368 ResourceLoaderContext
$context,
369 ResourceLoaderImage
$image,
373 $imageDataUri = $this->useDataURI ?
$image->getDataUri( $context, $variant, 'original' ) : false;
374 $primaryUrl = $imageDataUri ?
: $image->getUrl( $context, $script, $variant, 'original' );
375 $declarations = $this->getCssDeclarations(
377 $image->getUrl( $context, $script, $variant, 'rasterized' )
379 return implode( "\n\t", $declarations );
383 * SVG support using a transparent gradient to guarantee cross-browser
384 * compatibility (browsers able to understand gradient syntax support also SVG).
385 * http://pauginer.tumblr.com/post/36614680636/invisible-gradient-technique
387 * Keep synchronized with the .background-image-svg LESS mixin in
388 * /resources/src/mediawiki.less/mediawiki.mixins.less.
390 * @param string $primary Primary URI
391 * @param string $fallback Fallback URI
392 * @return string[] CSS declarations to use given URIs as background-image
394 protected function getCssDeclarations( $primary, $fallback ) {
395 $primaryUrl = CSSMin
::buildUrlValue( $primary );
396 $fallbackUrl = CSSMin
::buildUrlValue( $fallback );
398 "background-image: $fallbackUrl;",
399 "background-image: linear-gradient(transparent, transparent), $primaryUrl;",
406 public function supportsURLLoading() {
411 * Get the definition summary for this module.
413 * @param ResourceLoaderContext $context
416 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
417 $this->loadFromDefinition();
418 $summary = parent
::getDefinitionSummary( $context );
426 'selectorWithoutVariant',
427 'selectorWithVariant',
429 $options[$member] = $this->{$member};
433 'options' => $options,
434 'fileHashes' => $this->getFileHashes( $context ),
440 * Helper method for getDefinitionSummary.
441 * @param ResourceLoaderContext $context
444 private function getFileHashes( ResourceLoaderContext
$context ) {
445 $this->loadFromDefinition();
447 foreach ( $this->getImages( $context ) as $name => $image ) {
448 $files[] = $image->getPath( $context );
450 $files = array_values( array_unique( $files ) );
451 return array_map( [ __CLASS__
, 'safeFileHash' ], $files );
455 * @param string|ResourceLoaderFilePath $path
458 protected function getLocalPath( $path ) {
459 if ( $path instanceof ResourceLoaderFilePath
) {
460 return $path->getLocalPath();
463 return "{$this->localBasePath}/$path";
467 * Extract a local base path from module definition information.
469 * @param array $options Module definition
470 * @param string|null $localBasePath Path to use if not provided in module definition. Defaults
472 * @return string Local base path
474 public static function extractLocalBasePath( $options, $localBasePath = null ) {
477 if ( $localBasePath === null ) {
478 $localBasePath = $IP;
481 if ( array_key_exists( 'localBasePath', $options ) ) {
482 $localBasePath = (string)$options['localBasePath'];
485 return $localBasePath;
491 public function getType() {
492 return self
::LOAD_STYLES
;