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