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