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