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 $variants = [];
43 protected $prefix = null;
44 protected $selectorWithoutVariant = '.{prefix}-{name}';
45 protected $selectorWithVariant = '.{prefix}-{name}-{variant}';
46 protected $targets = [ 'desktop', 'mobile' ];
49 * Constructs a new module from an options array.
51 * @param array $options List of options; if not given or empty, an empty module will be
53 * @param string $localBasePath Base path to prepend to all local paths in $options. Defaults
56 * Below is a description for the $options array:
57 * @par Construction options:
60 * // Base path to prepend to all local paths in $options. Defaults to $IP
61 * 'localBasePath' => [base path],
62 * // Path to JSON file that contains any of the settings below
63 * 'data' => [file path string]
64 * // CSS class prefix to use in all style rules
65 * 'prefix' => [CSS class prefix],
66 * // Alternatively: Format of CSS selector to use in all style rules
67 * 'selector' => [CSS selector template, variables: {prefix} {name} {variant}],
68 * // Alternatively: When using variants
69 * 'selectorWithoutVariant' => [CSS selector template, variables: {prefix} {name}],
70 * 'selectorWithVariant' => [CSS selector template, variables: {prefix} {name} {variant}],
71 * // List of variants that may be used for the image files
75 * 'color' => [color string, e.g. '#ffff00'],
76 * 'global' => [boolean, if true, this variant is available
77 * for all images of this type],
83 * // List of image files and their options
87 * 'file' => [file path string or array whose values are file path strings
88 * and whose keys are 'default', 'ltr', 'rtl', a single
89 * language code like 'en', or a list of language codes like
91 * 'variants' => [array of variant name strings, variants
92 * available for this image],
100 * @throws InvalidArgumentException
102 public function __construct( $options = [], $localBasePath = null ) {
103 $this->localBasePath
= self
::extractLocalBasePath( $options, $localBasePath );
105 $this->definition
= $options;
109 * Parse definition and external JSON data, if referenced.
111 protected function loadFromDefinition() {
112 if ( $this->definition
=== null ) {
116 $options = $this->definition
;
117 $this->definition
= null;
119 if ( isset( $options['data'] ) ) {
120 $dataPath = $this->localBasePath
. '/' . $options['data'];
121 $data = json_decode( file_get_contents( $dataPath ), true );
122 $options = array_merge( $data, $options );
125 // Accepted combinations:
128 // * selectorWithoutVariant + selectorWithVariant
129 // * prefix + selector
130 // * prefix + selectorWithoutVariant + selectorWithVariant
132 $prefix = isset( $options['prefix'] ) && $options['prefix'];
133 $selector = isset( $options['selector'] ) && $options['selector'];
134 $selectorWithoutVariant = isset( $options['selectorWithoutVariant'] )
135 && $options['selectorWithoutVariant'];
136 $selectorWithVariant = isset( $options['selectorWithVariant'] )
137 && $options['selectorWithVariant'];
139 if ( $selectorWithoutVariant && !$selectorWithVariant ) {
140 throw new InvalidArgumentException(
141 "Given 'selectorWithoutVariant' but no 'selectorWithVariant'."
144 if ( $selectorWithVariant && !$selectorWithoutVariant ) {
145 throw new InvalidArgumentException(
146 "Given 'selectorWithVariant' but no 'selectorWithoutVariant'."
149 if ( $selector && $selectorWithVariant ) {
150 throw new InvalidArgumentException(
151 "Incompatible 'selector' and 'selectorWithVariant'+'selectorWithoutVariant' given."
154 if ( !$prefix && !$selector && !$selectorWithVariant ) {
155 throw new InvalidArgumentException(
156 "None of 'prefix', 'selector' or 'selectorWithVariant'+'selectorWithoutVariant' given."
160 foreach ( $options as $member => $option ) {
164 if ( !is_array( $option ) ) {
165 throw new InvalidArgumentException(
166 "Invalid list error. '$option' given, array expected."
169 if ( !isset( $option['default'] ) ) {
170 // Backwards compatibility
171 $option = [ 'default' => $option ];
173 foreach ( $option as $skin => $data ) {
174 if ( !is_array( $option ) ) {
175 throw new InvalidArgumentException(
176 "Invalid list error. '$option' given, array expected."
180 $this->{$member} = $option;
184 case 'selectorWithoutVariant':
185 case 'selectorWithVariant':
186 $this->{$member} = (string)$option;
190 $this->selectorWithoutVariant
= $this->selectorWithVariant
= (string)$option;
196 * Get CSS class prefix used by this module.
199 public function getPrefix() {
200 $this->loadFromDefinition();
201 return $this->prefix
;
205 * Get CSS selector templates used by this module.
208 public function getSelectors() {
209 $this->loadFromDefinition();
211 'selectorWithoutVariant' => $this->selectorWithoutVariant
,
212 'selectorWithVariant' => $this->selectorWithVariant
,
217 * Get a ResourceLoaderImage object for given image.
218 * @param string $name Image name
219 * @param ResourceLoaderContext $context
220 * @return ResourceLoaderImage|null
222 public function getImage( $name, ResourceLoaderContext
$context ) {
223 $this->loadFromDefinition();
224 $images = $this->getImages( $context );
225 return isset( $images[$name] ) ?
$images[$name] : null;
229 * Get ResourceLoaderImage objects for all images.
230 * @param ResourceLoaderContext $context
231 * @return ResourceLoaderImage[] Array keyed by image name
233 public function getImages( ResourceLoaderContext
$context ) {
234 $skin = $context->getSkin();
235 if ( !isset( $this->imageObjects
) ) {
236 $this->loadFromDefinition();
237 $this->imageObjects
= [];
239 if ( !isset( $this->imageObjects
[$skin] ) ) {
240 $this->imageObjects
[$skin] = [];
241 if ( !isset( $this->images
[$skin] ) ) {
242 $this->images
[$skin] = isset( $this->images
['default'] ) ?
243 $this->images
['default'] :
246 foreach ( $this->images
[$skin] as $name => $options ) {
247 $fileDescriptor = is_string( $options ) ?
$options : $options['file'];
249 $allowedVariants = array_merge(
250 is_array( $options ) && isset( $options['variants'] ) ?
$options['variants'] : [],
251 $this->getGlobalVariants( $context )
253 if ( isset( $this->variants
[$skin] ) ) {
254 $variantConfig = array_intersect_key(
255 $this->variants
[$skin],
256 array_fill_keys( $allowedVariants, true )
262 $image = new ResourceLoaderImage(
266 $this->localBasePath
,
269 $this->imageObjects
[$skin][$image->getName()] = $image;
273 return $this->imageObjects
[$skin];
277 * Get list of variants in this module that are 'global', i.e., available
278 * for every image regardless of image options.
279 * @param ResourceLoaderContext $context
282 public function getGlobalVariants( ResourceLoaderContext
$context ) {
283 $skin = $context->getSkin();
284 if ( !isset( $this->globalVariants
) ) {
285 $this->loadFromDefinition();
286 $this->globalVariants
= [];
288 if ( !isset( $this->globalVariants
[$skin] ) ) {
289 $this->globalVariants
[$skin] = [];
290 if ( !isset( $this->variants
[$skin] ) ) {
291 $this->variants
[$skin] = isset( $this->variants
['default'] ) ?
292 $this->variants
['default'] :
295 foreach ( $this->variants
[$skin] as $name => $config ) {
296 if ( isset( $config['global'] ) && $config['global'] ) {
297 $this->globalVariants
[$skin][] = $name;
302 return $this->globalVariants
[$skin];
306 * @param ResourceLoaderContext $context
309 public function getStyles( ResourceLoaderContext
$context ) {
310 $this->loadFromDefinition();
314 $script = $context->getResourceLoader()->getLoadScript( $this->getSource() );
315 $selectors = $this->getSelectors();
317 foreach ( $this->getImages( $context ) as $name => $image ) {
318 $declarations = $this->getCssDeclarations(
319 $image->getDataUri( $context, null, 'original' ),
320 $image->getUrl( $context, $script, null, 'rasterized' )
322 $declarations = implode( "\n\t", $declarations );
324 $selectors['selectorWithoutVariant'],
326 '{prefix}' => $this->getPrefix(),
331 $rules[] = "$selector {\n\t$declarations\n}";
333 foreach ( $image->getVariants() as $variant ) {
334 $declarations = $this->getCssDeclarations(
335 $image->getDataUri( $context, $variant, 'original' ),
336 $image->getUrl( $context, $script, $variant, 'rasterized' )
338 $declarations = implode( "\n\t", $declarations );
340 $selectors['selectorWithVariant'],
342 '{prefix}' => $this->getPrefix(),
344 '{variant}' => $variant,
347 $rules[] = "$selector {\n\t$declarations\n}";
351 $style = implode( "\n", $rules );
352 return [ 'all' => $style ];
356 * SVG support using a transparent gradient to guarantee cross-browser
357 * compatibility (browsers able to understand gradient syntax support also SVG).
358 * http://pauginer.tumblr.com/post/36614680636/invisible-gradient-technique
360 * Keep synchronized with the .background-image-svg LESS mixin in
361 * /resources/src/mediawiki.less/mediawiki.mixins.less.
363 * @param string $primary Primary URI
364 * @param string $fallback Fallback URI
365 * @return string[] CSS declarations to use given URIs as background-image
367 protected function getCssDeclarations( $primary, $fallback ) {
369 "background-image: url($fallback);",
370 "background-image: linear-gradient(transparent, transparent), url($primary);",
371 // Do not serve SVG to Opera 12, bad rendering with border-radius or background-size (T87504)
372 "background-image: -o-linear-gradient(transparent, transparent), url($fallback);",
379 public function supportsURLLoading() {
384 * Get the definition summary for this module.
386 * @param ResourceLoaderContext $context
389 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
390 $this->loadFromDefinition();
391 $summary = parent
::getDefinitionSummary( $context );
399 'selectorWithoutVariant',
400 'selectorWithVariant',
402 $options[$member] = $this->{$member};
406 'options' => $options,
407 'fileHashes' => $this->getFileHashes( $context ),
413 * Helper method for getDefinitionSummary.
415 protected function getFileHashes( ResourceLoaderContext
$context ) {
416 $this->loadFromDefinition();
418 foreach ( $this->getImages( $context ) as $name => $image ) {
419 $files[] = $image->getPath( $context );
421 $files = array_values( array_unique( $files ) );
422 return array_map( [ __CLASS__
, 'safeFileHash' ], $files );
426 * Extract a local base path from module definition information.
428 * @param array $options Module definition
429 * @param string $localBasePath Path to use if not provided in module definition. Defaults
431 * @return string Local base path
433 public static function extractLocalBasePath( $options, $localBasePath = null ) {
436 if ( $localBasePath === null ) {
437 $localBasePath = $IP;
440 if ( array_key_exists( 'localBasePath', $options ) ) {
441 $localBasePath = (string)$options['localBasePath'];
444 return $localBasePath;
450 public function getType() {
451 return self
::LOAD_STYLES
;