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