Debian Codegraph @

includes/ResourceLoader/ImageModule.php

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