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