summaryrefslogtreecommitdiff
path: root/includes/resourceloader/ResourceLoaderImageModule.php
blob: 8de87f2ef5222e73a8877e25796e30db4581d9ff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
<?php
/**
 * Resource loader module for generated and embedded images.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @author Trevor Parscal
 */

/**
 * Resource loader module for generated and embedded images.
 *
 * @since 1.25
 */
class ResourceLoaderImageModule extends ResourceLoaderModule {

	protected $definition = null;

	/**
	 * Local base path, see __construct()
	 * @var string
	 */
	protected $localBasePath = '';

	protected $origin = self::ORIGIN_CORE_SITEWIDE;

	protected $images = array();
	protected $variants = array();
	protected $prefix = null;
	protected $selectorWithoutVariant = '.{prefix}-{name}';
	protected $selectorWithVariant = '.{prefix}-{name}-{variant}';
	protected $targets = array( 'desktop', 'mobile' );

	/** @var string Position on the page to load this module at */
	protected $position = 'bottom';

	/**
	 * Constructs a new module from an options array.
	 *
	 * @param array $options List of options; if not given or empty, an empty module will be
	 *     constructed
	 * @param string $localBasePath Base path to prepend to all local paths in $options. Defaults
	 *     to $IP
	 *
	 * Below is a description for the $options array:
	 * @par Construction options:
	 * @code
	 *     array(
	 *         // Base path to prepend to all local paths in $options. Defaults to $IP
	 *         'localBasePath' => [base path],
	 *         // Path to JSON file that contains any of the settings below
	 *         'data' => [file path string]
	 *         // CSS class prefix to use in all style rules
	 *         'prefix' => [CSS class prefix],
	 *         // Alternatively: Format of CSS selector to use in all style rules
	 *         'selector' => [CSS selector template, variables: {prefix} {name} {variant}],
	 *         // Alternatively: When using variants
	 *         'selectorWithoutVariant' => [CSS selector template, variables: {prefix} {name}],
	 *         'selectorWithVariant' => [CSS selector template, variables: {prefix} {name} {variant}],
	 *         // List of variants that may be used for the image files
	 *         'variants' => array(
	 *             [theme name] => array(
	 *                 [variant name] => array(
	 *                     'color' => [color string, e.g. '#ffff00'],
	 *                     'global' => [boolean, if true, this variant is available
	 *                                  for all images of this type],
	 *                 ),
	 *                 ...
	 *             ),
	 *             ...
	 *         ),
	 *         // List of image files and their options
	 *         'images' => array(
	 *             [theme name] => array(
	 *                 [icon name] => array(
	 *                     'file' => [file path string or array whose values are file path strings
	 *                                    and whose keys are 'default', 'ltr', 'rtl', a single
	 *                                    language code like 'en', or a list of language codes like
	 *                                    'en,de,ar'],
	 *                     'variants' => [array of variant name strings, variants
	 *                                    available for this image],
	 *                 ),
	 *                 ...
	 *             ),
	 *             ...
	 *         ),
	 *     )
	 * @endcode
	 * @throws InvalidArgumentException
	 */
	public function __construct( $options = array(), $localBasePath = null ) {
		$this->localBasePath = self::extractLocalBasePath( $options, $localBasePath );

		$this->definition = $options;
	}

	/**
	 * Parse definition and external JSON data, if referenced.
	 */
	protected function loadFromDefinition() {
		if ( $this->definition === null ) {
			return;
		}

		$options = $this->definition;
		$this->definition = null;

		if ( isset( $options['data'] ) ) {
			$dataPath = $this->localBasePath . '/' . $options['data'];
			$data = json_decode( file_get_contents( $dataPath ), true );
			$options = array_merge( $data, $options );
		}

		// Accepted combinations:
		// * prefix
		// * selector
		// * selectorWithoutVariant + selectorWithVariant
		// * prefix + selector
		// * prefix + selectorWithoutVariant + selectorWithVariant

		$prefix = isset( $options['prefix'] ) && $options['prefix'];
		$selector = isset( $options['selector'] ) && $options['selector'];
		$selectorWithoutVariant = isset( $options['selectorWithoutVariant'] )
			&& $options['selectorWithoutVariant'];
		$selectorWithVariant = isset( $options['selectorWithVariant'] )
			&& $options['selectorWithVariant'];

		if ( $selectorWithoutVariant && !$selectorWithVariant ) {
			throw new InvalidArgumentException(
				"Given 'selectorWithoutVariant' but no 'selectorWithVariant'."
			);
		}
		if ( $selectorWithVariant && !$selectorWithoutVariant ) {
			throw new InvalidArgumentException(
				"Given 'selectorWithVariant' but no 'selectorWithoutVariant'."
			);
		}
		if ( $selector && $selectorWithVariant ) {
			throw new InvalidArgumentException(
				"Incompatible 'selector' and 'selectorWithVariant'+'selectorWithoutVariant' given."
			);
		}
		if ( !$prefix && !$selector && !$selectorWithVariant ) {
			throw new InvalidArgumentException(
				"None of 'prefix', 'selector' or 'selectorWithVariant'+'selectorWithoutVariant' given."
			);
		}

		foreach ( $options as $member => $option ) {
			switch ( $member ) {
				case 'images':
				case 'variants':
					if ( !is_array( $option ) ) {
						throw new InvalidArgumentException(
							"Invalid list error. '$option' given, array expected."
						);
					}
					if ( !isset( $option['default'] ) ) {
						// Backwards compatibility
						$option = array( 'default' => $option );
					}
					foreach ( $option as $skin => $data ) {
						if ( !is_array( $option ) ) {
							throw new InvalidArgumentException(
								"Invalid list error. '$option' given, array expected."
							);
						}
					}
					$this->{$member} = $option;
					break;

				case 'position':
					$this->isPositionDefined = true;
				case 'prefix':
				case 'selectorWithoutVariant':
				case 'selectorWithVariant':
					$this->{$member} = (string)$option;
					break;

				case 'selector':
					$this->selectorWithoutVariant = $this->selectorWithVariant = (string)$option;
			}
		}
	}

	/**
	 * Get CSS class prefix used by this module.
	 * @return string
	 */
	public function getPrefix() {
		$this->loadFromDefinition();
		return $this->prefix;
	}

	/**
	 * Get CSS selector templates used by this module.
	 * @return string
	 */
	public function getSelectors() {
		$this->loadFromDefinition();
		return array(
			'selectorWithoutVariant' => $this->selectorWithoutVariant,
			'selectorWithVariant' => $this->selectorWithVariant,
		);
	}

	/**
	 * Get a ResourceLoaderImage object for given image.
	 * @param string $name Image name
	 * @param ResourceLoaderContext $context
	 * @return ResourceLoaderImage|null
	 */
	public function getImage( $name, ResourceLoaderContext $context ) {
		$this->loadFromDefinition();
		$images = $this->getImages( $context );
		return isset( $images[$name] ) ? $images[$name] : null;
	}

	/**
	 * Get ResourceLoaderImage objects for all images.
	 * @param ResourceLoaderContext $context
	 * @return ResourceLoaderImage[] Array keyed by image name
	 */
	public function getImages( ResourceLoaderContext $context ) {
		$skin = $context->getSkin();
		if ( !isset( $this->imageObjects ) ) {
			$this->loadFromDefinition();
			$this->imageObjects = array();
		}
		if ( !isset( $this->imageObjects[$skin] ) ) {
			$this->imageObjects[$skin] = array();
			if ( !isset( $this->images[$skin] ) ) {
				$this->images[$skin] = isset( $this->images['default'] ) ?
					$this->images['default'] :
					array();
			}
			foreach ( $this->images[$skin] as $name => $options ) {
				$fileDescriptor = is_string( $options ) ? $options : $options['file'];

				$allowedVariants = array_merge(
					is_array( $options ) && isset( $options['variants'] ) ? $options['variants'] : array(),
					$this->getGlobalVariants( $context )
				);
				if ( isset( $this->variants[$skin] ) ) {
					$variantConfig = array_intersect_key(
						$this->variants[$skin],
						array_fill_keys( $allowedVariants, true )
					);
				} else {
					$variantConfig = array();
				}

				$image = new ResourceLoaderImage(
					$name,
					$this->getName(),
					$fileDescriptor,
					$this->localBasePath,
					$variantConfig
				);
				$this->imageObjects[$skin][$image->getName()] = $image;
			}
		}

		return $this->imageObjects[$skin];
	}

	/**
	 * Get list of variants in this module that are 'global', i.e., available
	 * for every image regardless of image options.
	 * @param ResourceLoaderContext $context
	 * @return string[]
	 */
	public function getGlobalVariants( ResourceLoaderContext $context ) {
		$skin = $context->getSkin();
		if ( !isset( $this->globalVariants ) ) {
			$this->loadFromDefinition();
			$this->globalVariants = array();
		}
		if ( !isset( $this->globalVariants[$skin] ) ) {
			$this->globalVariants[$skin] = array();
			if ( !isset( $this->variants[$skin] ) ) {
				$this->variants[$skin] = isset( $this->variants['default'] ) ?
					$this->variants['default'] :
					array();
			}
			foreach ( $this->variants[$skin] as $name => $config ) {
				if ( isset( $config['global'] ) && $config['global'] ) {
					$this->globalVariants[$skin][] = $name;
				}
			}
		}

		return $this->globalVariants[$skin];
	}

	/**
	 * @param ResourceLoaderContext $context
	 * @return array
	 */
	public function getStyles( ResourceLoaderContext $context ) {
		$this->loadFromDefinition();

		// Build CSS rules
		$rules = array();
		$script = $context->getResourceLoader()->getLoadScript( $this->getSource() );
		$selectors = $this->getSelectors();

		foreach ( $this->getImages( $context ) as $name => $image ) {
			$declarations = $this->getCssDeclarations(
				$image->getDataUri( $context, null, 'original' ),
				$image->getUrl( $context, $script, null, 'rasterized' )
			);
			$declarations = implode( "\n\t", $declarations );
			$selector = strtr(
				$selectors['selectorWithoutVariant'],
				array(
					'{prefix}' => $this->getPrefix(),
					'{name}' => $name,
					'{variant}' => '',
				)
			);
			$rules[] = "$selector {\n\t$declarations\n}";

			foreach ( $image->getVariants() as $variant ) {
				$declarations = $this->getCssDeclarations(
					$image->getDataUri( $context, $variant, 'original' ),
					$image->getUrl( $context, $script, $variant, 'rasterized' )
				);
				$declarations = implode( "\n\t", $declarations );
				$selector = strtr(
					$selectors['selectorWithVariant'],
					array(
						'{prefix}' => $this->getPrefix(),
						'{name}' => $name,
						'{variant}' => $variant,
					)
				);
				$rules[] = "$selector {\n\t$declarations\n}";
			}
		}

		$style = implode( "\n", $rules );
		return array( 'all' => $style );
	}

	/**
	 * SVG support using a transparent gradient to guarantee cross-browser
	 * compatibility (browsers able to understand gradient syntax support also SVG).
	 * http://pauginer.tumblr.com/post/36614680636/invisible-gradient-technique
	 *
	 * Keep synchronized with the .background-image-svg LESS mixin in
	 * /resources/src/mediawiki.less/mediawiki.mixins.less.
	 *
	 * @param string $primary Primary URI
	 * @param string $fallback Fallback URI
	 * @return string[] CSS declarations to use given URIs as background-image
	 */
	protected function getCssDeclarations( $primary, $fallback ) {
		return array(
			"background-image: url($fallback);",
			"background-image: -webkit-linear-gradient(transparent, transparent), url($primary);",
			"background-image: linear-gradient(transparent, transparent), url($primary);",
			"background-image: -o-linear-gradient(transparent, transparent), url($fallback);",
		);
	}

	/**
	 * @return bool
	 */
	public function supportsURLLoading() {
		return false;
	}

	/**
	 * Get the definition summary for this module.
	 *
	 * @param ResourceLoaderContext $context
	 * @return array
	 */
	public function getDefinitionSummary( ResourceLoaderContext $context ) {
		$this->loadFromDefinition();
		$summary = parent::getDefinitionSummary( $context );
		foreach ( array(
			'localBasePath',
			'images',
			'variants',
			'prefix',
			'selectorWithoutVariant',
			'selectorWithVariant',
		) as $member ) {
			$summary[$member] = $this->{$member};
		};
		return $summary;
	}

	/**
	 * Get the last modified timestamp of this module.
	 *
	 * @param ResourceLoaderContext $context Context in which to calculate
	 *     the modified time
	 * @return int UNIX timestamp
	 */
	public function getModifiedTime( ResourceLoaderContext $context ) {
		$this->loadFromDefinition();
		$files = array();
		foreach ( $this->getImages( $context ) as $name => $image ) {
			$files[] = $image->getPath( $context );
		}

		$files = array_values( array_unique( $files ) );
		$filesMtime = max( array_map( array( __CLASS__, 'safeFilemtime' ), $files ) );

		return $filesMtime;
	}

	/**
	 * Extract a local base path from module definition information.
	 *
	 * @param array $options Module definition
	 * @param string $localBasePath Path to use if not provided in module definition. Defaults
	 *     to $IP
	 * @return string Local base path
	 */
	public static function extractLocalBasePath( $options, $localBasePath = null ) {
		global $IP;

		if ( $localBasePath === null ) {
			$localBasePath = $IP;
		}

		if ( array_key_exists( 'localBasePath', $options ) ) {
			$localBasePath = (string)$options['localBasePath'];
		}

		return $localBasePath;
	}

	/**
	 * @return string
	 */
	public function getPosition() {
		$this->loadFromDefinition();
		return $this->position;
	}

	public function isPositionDefault() {
		$this->loadFromDefinition();
		return parent::isPositionDefault();
	}
}