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