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