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