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 protected $definition = null;
34 * Local base path, see __construct()
37 protected $localBasePath = '';
39 protected $origin = self
::ORIGIN_CORE_SITEWIDE
;
41 protected $images = [];
42 protected $defaultColor = null;
43 protected $useDataURI = true;
44 protected $variants = [];
45 protected $prefix = null;
46 protected $selectorWithoutVariant = '.{prefix}-{name}';
47 protected $selectorWithVariant = '.{prefix}-{name}-{variant}';
48 protected $targets = [ 'desktop', 'mobile' ];
51 * Constructs a new module from an options array.
53 * @param array $options List of options; if not given or empty, an empty module will be
55 * @param string $localBasePath Base path to prepend to all local paths in $options. Defaults
58 * Below is a description for the $options array:
59 * @par Construction options:
62 * // Base path to prepend to all local paths in $options. Defaults to $IP
63 * 'localBasePath' => [base path],
64 * // Path to JSON file that contains any of the settings below
65 * 'data' => [file path string]
66 * // CSS class prefix to use in all style rules
67 * 'prefix' => [CSS class prefix],
68 * // Alternatively: Format of CSS selector to use in all style rules
69 * 'selector' => [CSS selector template, variables: {prefix} {name} {variant}],
70 * // Alternatively: When using variants
71 * 'selectorWithoutVariant' => [CSS selector template, variables: {prefix} {name}],
72 * 'selectorWithVariant' => [CSS selector template, variables: {prefix} {name} {variant}],
73 * // List of variants that may be used for the image files
75 * // This level of nesting can be omitted if you use the same images for every skin
76 * [skin name (or 'default')] => [
78 * 'color' => [color string, e.g. '#ffff00'],
79 * 'global' => [boolean, if true, this variant is available
80 * for all images of this type],
86 * // List of image files and their options
88 * // This level of nesting can be omitted if you use the same images for every skin
89 * [skin name (or 'default')] => [
91 * 'file' => [file path string or array whose values are file path strings
92 * and whose keys are 'default', 'ltr', 'rtl', a single
93 * language code like 'en', or a list of language codes like
95 * 'variants' => [array of variant name strings, variants
96 * available for this image],
104 * @throws InvalidArgumentException
106 public function __construct( $options = [], $localBasePath = null ) {
107 $this->localBasePath
= self
::extractLocalBasePath( $options, $localBasePath );
109 $this->definition
= $options;
113 * Parse definition and external JSON data, if referenced.
115 protected function loadFromDefinition() {
116 if ( $this->definition
=== null ) {
120 $options = $this->definition
;
121 $this->definition
= null;
123 if ( isset( $options['data'] ) ) {
124 $dataPath = $this->localBasePath
. '/' . $options['data'];
125 $data = json_decode( file_get_contents( $dataPath ), true );
126 $options = array_merge( $data, $options );
129 // Accepted combinations:
132 // * selectorWithoutVariant + selectorWithVariant
133 // * prefix + selector
134 // * prefix + selectorWithoutVariant + selectorWithVariant
136 $prefix = isset( $options['prefix'] ) && $options['prefix'];
137 $selector = isset( $options['selector'] ) && $options['selector'];
138 $selectorWithoutVariant = isset( $options['selectorWithoutVariant'] )
139 && $options['selectorWithoutVariant'];
140 $selectorWithVariant = isset( $options['selectorWithVariant'] )
141 && $options['selectorWithVariant'];
143 if ( $selectorWithoutVariant && !$selectorWithVariant ) {
144 throw new InvalidArgumentException(
145 "Given 'selectorWithoutVariant' but no 'selectorWithVariant'."
148 if ( $selectorWithVariant && !$selectorWithoutVariant ) {
149 throw new InvalidArgumentException(
150 "Given 'selectorWithVariant' but no 'selectorWithoutVariant'."
153 if ( $selector && $selectorWithVariant ) {
154 throw new InvalidArgumentException(
155 "Incompatible 'selector' and 'selectorWithVariant'+'selectorWithoutVariant' given."
158 if ( !$prefix && !$selector && !$selectorWithVariant ) {
159 throw new InvalidArgumentException(
160 "None of 'prefix', 'selector' or 'selectorWithVariant'+'selectorWithoutVariant' given."
164 foreach ( $options as $member => $option ) {
168 if ( !is_array( $option ) ) {
169 throw new InvalidArgumentException(
170 "Invalid list error. '$option' given, array expected."
173 if ( !isset( $option['default'] ) ) {
174 // Backwards compatibility
175 $option = [ 'default' => $option ];
177 foreach ( $option as $skin => $data ) {
178 if ( !is_array( $option ) ) {
179 throw new InvalidArgumentException(
180 "Invalid list error. '$option' given, array expected."
184 $this->{$member} = $option;
188 $this->{$member} = (bool)$option;
192 case 'selectorWithoutVariant':
193 case 'selectorWithVariant':
194 $this->{$member} = (string)$option;
198 $this->selectorWithoutVariant
= $this->selectorWithVariant
= (string)$option;
204 * Get CSS class prefix used by this module.
207 public function getPrefix() {
208 $this->loadFromDefinition();
209 return $this->prefix
;
213 * Get CSS selector templates used by this module.
216 public function getSelectors() {
217 $this->loadFromDefinition();
219 'selectorWithoutVariant' => $this->selectorWithoutVariant
,
220 'selectorWithVariant' => $this->selectorWithVariant
,
225 * Get a ResourceLoaderImage object for given image.
226 * @param string $name Image name
227 * @param ResourceLoaderContext $context
228 * @return ResourceLoaderImage|null
230 public function getImage( $name, ResourceLoaderContext
$context ) {
231 $this->loadFromDefinition();
232 $images = $this->getImages( $context );
233 return $images[$name] ??
null;
237 * Get ResourceLoaderImage objects for all images.
238 * @param ResourceLoaderContext $context
239 * @return ResourceLoaderImage[] Array keyed by image name
241 public function getImages( ResourceLoaderContext
$context ) {
242 $skin = $context->getSkin();
243 if ( !isset( $this->imageObjects
) ) {
244 $this->loadFromDefinition();
245 $this->imageObjects
= [];
247 if ( !isset( $this->imageObjects
[$skin] ) ) {
248 $this->imageObjects
[$skin] = [];
249 if ( !isset( $this->images
[$skin] ) ) {
250 $this->images
[$skin] = $this->images
['default'] ??
[];
252 foreach ( $this->images
[$skin] as $name => $options ) {
253 $fileDescriptor = is_string( $options ) ?
$options : $options['file'];
255 $allowedVariants = array_merge(
256 ( is_array( $options ) && isset( $options['variants'] ) ) ?
$options['variants'] : [],
257 $this->getGlobalVariants( $context )
259 if ( isset( $this->variants
[$skin] ) ) {
260 $variantConfig = array_intersect_key(
261 $this->variants
[$skin],
262 array_fill_keys( $allowedVariants, true )
268 $image = new ResourceLoaderImage(
272 $this->localBasePath
,
276 $this->imageObjects
[$skin][$image->getName()] = $image;
280 return $this->imageObjects
[$skin];
284 * Get list of variants in this module that are 'global', i.e., available
285 * for every image regardless of image options.
286 * @param ResourceLoaderContext $context
289 public function getGlobalVariants( ResourceLoaderContext
$context ) {
290 $skin = $context->getSkin();
291 if ( !isset( $this->globalVariants
) ) {
292 $this->loadFromDefinition();
293 $this->globalVariants
= [];
295 if ( !isset( $this->globalVariants
[$skin] ) ) {
296 $this->globalVariants
[$skin] = [];
297 if ( !isset( $this->variants
[$skin] ) ) {
298 $this->variants
[$skin] = $this->variants
['default'] ??
[];
300 foreach ( $this->variants
[$skin] as $name => $config ) {
301 if ( isset( $config['global'] ) && $config['global'] ) {
302 $this->globalVariants
[$skin][] = $name;
307 return $this->globalVariants
[$skin];
311 * @param ResourceLoaderContext $context
314 public function getStyles( ResourceLoaderContext
$context ) {
315 $this->loadFromDefinition();
319 $script = $context->getResourceLoader()->getLoadScript( $this->getSource() );
320 $selectors = $this->getSelectors();
322 foreach ( $this->getImages( $context ) as $name => $image ) {
323 $declarations = $this->getStyleDeclarations( $context, $image, $script );
325 $selectors['selectorWithoutVariant'],
327 '{prefix}' => $this->getPrefix(),
332 $rules[] = "$selector {\n\t$declarations\n}";
334 foreach ( $image->getVariants() as $variant ) {
335 $declarations = $this->getStyleDeclarations( $context, $image, $script, $variant );
337 $selectors['selectorWithVariant'],
339 '{prefix}' => $this->getPrefix(),
341 '{variant}' => $variant,
344 $rules[] = "$selector {\n\t$declarations\n}";
348 $style = implode( "\n", $rules );
349 return [ 'all' => $style ];
353 * @param ResourceLoaderContext $context
354 * @param ResourceLoaderImage $image Image to get the style for
355 * @param string $script URL to load.php
356 * @param string|null $variant Variant to get the style for
359 private function getStyleDeclarations(
360 ResourceLoaderContext
$context,
361 ResourceLoaderImage
$image,
365 $imageDataUri = $this->useDataURI ?
$image->getDataUri( $context, $variant, 'original' ) : false;
366 $primaryUrl = $imageDataUri ?
: $image->getUrl( $context, $script, $variant, 'original' );
367 $declarations = $this->getCssDeclarations(
369 $image->getUrl( $context, $script, $variant, 'rasterized' )
371 return implode( "\n\t", $declarations );
375 * SVG support using a transparent gradient to guarantee cross-browser
376 * compatibility (browsers able to understand gradient syntax support also SVG).
377 * http://pauginer.tumblr.com/post/36614680636/invisible-gradient-technique
379 * Keep synchronized with the .background-image-svg LESS mixin in
380 * /resources/src/mediawiki.less/mediawiki.mixins.less.
382 * @param string $primary Primary URI
383 * @param string $fallback Fallback URI
384 * @return string[] CSS declarations to use given URIs as background-image
386 protected function getCssDeclarations( $primary, $fallback ) {
387 $primaryUrl = CSSMin
::buildUrlValue( $primary );
388 $fallbackUrl = CSSMin
::buildUrlValue( $fallback );
390 "background-image: $fallbackUrl;",
391 "background-image: linear-gradient(transparent, transparent), $primaryUrl;",
398 public function supportsURLLoading() {
403 * Get the definition summary for this module.
405 * @param ResourceLoaderContext $context
408 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
409 $this->loadFromDefinition();
410 $summary = parent
::getDefinitionSummary( $context );
418 'selectorWithoutVariant',
419 'selectorWithVariant',
421 $options[$member] = $this->{$member};
425 'options' => $options,
426 'fileHashes' => $this->getFileHashes( $context ),
432 * Helper method for getDefinitionSummary.
433 * @param ResourceLoaderContext $context
436 private function getFileHashes( ResourceLoaderContext
$context ) {
437 $this->loadFromDefinition();
439 foreach ( $this->getImages( $context ) as $name => $image ) {
440 $files[] = $image->getPath( $context );
442 $files = array_values( array_unique( $files ) );
443 return array_map( [ __CLASS__
, 'safeFileHash' ], $files );
447 * Extract a local base path from module definition information.
449 * @param array $options Module definition
450 * @param string $localBasePath Path to use if not provided in module definition. Defaults
452 * @return string Local base path
454 public static function extractLocalBasePath( $options, $localBasePath = null ) {
457 if ( $localBasePath === null ) {
458 $localBasePath = $IP;
461 if ( array_key_exists( 'localBasePath', $options ) ) {
462 $localBasePath = (string)$options['localBasePath'];
465 return $localBasePath;
471 public function getType() {
472 return self
::LOAD_STYLES
;