Don't check namespace in SpecialWantedtemplates
[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 * @param ResourceLoaderContext $context
213 * @return ResourceLoaderImage|null
214 */
215 public function getImage( $name, ResourceLoaderContext $context ) {
216 $this->loadFromDefinition();
217 $images = $this->getImages( $context );
218 return isset( $images[$name] ) ? $images[$name] : null;
219 }
220
221 /**
222 * Get ResourceLoaderImage objects for all images.
223 * @param ResourceLoaderContext $context
224 * @return ResourceLoaderImage[] Array keyed by image name
225 */
226 public function getImages( ResourceLoaderContext $context ) {
227 $skin = $context->getSkin();
228 if ( !isset( $this->imageObjects ) ) {
229 $this->loadFromDefinition();
230 $this->imageObjects = array();
231 }
232 if ( !isset( $this->imageObjects[ $skin ] ) ) {
233 $this->imageObjects[ $skin ] = array();
234 if ( !isset( $this->images[ $skin ] ) ) {
235 $this->images[ $skin ] = isset( $this->images[ 'default' ] ) ?
236 $this->images[ 'default' ] :
237 array();
238 }
239 foreach ( $this->images[ $skin ] as $name => $options ) {
240 $fileDescriptor = is_string( $options ) ? $options : $options['file'];
241
242 $allowedVariants = array_merge(
243 is_array( $options ) && isset( $options['variants'] ) ? $options['variants'] : array(),
244 $this->getGlobalVariants( $context )
245 );
246 if ( isset( $this->variants[ $skin ] ) ) {
247 $variantConfig = array_intersect_key(
248 $this->variants[ $skin ],
249 array_fill_keys( $allowedVariants, true )
250 );
251 } else {
252 $variantConfig = array();
253 }
254
255 $image = new ResourceLoaderImage(
256 $name,
257 $this->getName(),
258 $fileDescriptor,
259 $this->localBasePath,
260 $variantConfig
261 );
262 $this->imageObjects[ $skin ][ $image->getName() ] = $image;
263 }
264 }
265
266 return $this->imageObjects[ $skin ];
267 }
268
269 /**
270 * Get list of variants in this module that are 'global', i.e., available
271 * for every image regardless of image options.
272 * @param ResourceLoaderContext $context
273 * @return string[]
274 */
275 public function getGlobalVariants( ResourceLoaderContext $context ) {
276 $skin = $context->getSkin();
277 if ( !isset( $this->globalVariants ) ) {
278 $this->loadFromDefinition();
279 $this->globalVariants = array();
280 }
281 if ( !isset( $this->globalVariants[ $skin ] ) ) {
282 $this->globalVariants[ $skin ] = array();
283 if ( !isset( $this->variants[ $skin ] ) ) {
284 $this->variants[ $skin ] = isset( $this->variants[ 'default' ] ) ?
285 $this->variants[ 'default' ] :
286 array();
287 }
288 foreach ( $this->variants[ $skin ] as $name => $config ) {
289 if ( isset( $config['global'] ) && $config['global'] ) {
290 $this->globalVariants[ $skin ][] = $name;
291 }
292 }
293 }
294
295 return $this->globalVariants[ $skin ];
296 }
297
298 /**
299 * @param ResourceLoaderContext $context
300 * @return array
301 */
302 public function getStyles( ResourceLoaderContext $context ) {
303 $this->loadFromDefinition();
304
305 // Build CSS rules
306 $rules = array();
307 $script = $context->getResourceLoader()->getLoadScript( $this->getSource() );
308 $selectors = $this->getSelectors();
309
310 foreach ( $this->getImages( $context ) as $name => $image ) {
311 $declarations = $this->getCssDeclarations(
312 $image->getDataUri( $context, null, 'original' ),
313 $image->getUrl( $context, $script, null, 'rasterized' )
314 );
315 $declarations = implode( "\n\t", $declarations );
316 $selector = strtr(
317 $selectors['selectorWithoutVariant'],
318 array(
319 '{prefix}' => $this->getPrefix(),
320 '{name}' => $name,
321 '{variant}' => '',
322 )
323 );
324 $rules[] = "$selector {\n\t$declarations\n}";
325
326 foreach ( $image->getVariants() as $variant ) {
327 $declarations = $this->getCssDeclarations(
328 $image->getDataUri( $context, $variant, 'original' ),
329 $image->getUrl( $context, $script, $variant, 'rasterized' )
330 );
331 $declarations = implode( "\n\t", $declarations );
332 $selector = strtr(
333 $selectors['selectorWithVariant'],
334 array(
335 '{prefix}' => $this->getPrefix(),
336 '{name}' => $name,
337 '{variant}' => $variant,
338 )
339 );
340 $rules[] = "$selector {\n\t$declarations\n}";
341 }
342 }
343
344 $style = implode( "\n", $rules );
345 return array( 'all' => $style );
346 }
347
348 /**
349 * SVG support using a transparent gradient to guarantee cross-browser
350 * compatibility (browsers able to understand gradient syntax support also SVG).
351 * http://pauginer.tumblr.com/post/36614680636/invisible-gradient-technique
352 *
353 * Keep synchronized with the .background-image-svg LESS mixin in
354 * /resources/src/mediawiki.less/mediawiki.mixins.less.
355 *
356 * @param string $primary Primary URI
357 * @param string $fallback Fallback URI
358 * @return string[] CSS declarations to use given URIs as background-image
359 */
360 protected function getCssDeclarations( $primary, $fallback ) {
361 return array(
362 "background-image: url($fallback);",
363 "background-image: -webkit-linear-gradient(transparent, transparent), url($primary);",
364 "background-image: linear-gradient(transparent, transparent), url($primary);",
365 "background-image: -o-linear-gradient(transparent, transparent), url($fallback);",
366 );
367 }
368
369 /**
370 * @return bool
371 */
372 public function supportsURLLoading() {
373 return false;
374 }
375
376 /**
377 * Get the definition summary for this module.
378 *
379 * @param ResourceLoaderContext $context
380 * @return array
381 */
382 public function getDefinitionSummary( ResourceLoaderContext $context ) {
383 $this->loadFromDefinition();
384 $summary = parent::getDefinitionSummary( $context );
385 foreach ( array(
386 'localBasePath',
387 'images',
388 'variants',
389 'prefix',
390 'selectorWithoutVariant',
391 'selectorWithVariant',
392 ) as $member ) {
393 $summary[$member] = $this->{$member};
394 };
395 return $summary;
396 }
397
398 /**
399 * Get the last modified timestamp of this module.
400 *
401 * @param ResourceLoaderContext $context Context in which to calculate
402 * the modified time
403 * @return int UNIX timestamp
404 */
405 public function getModifiedTime( ResourceLoaderContext $context ) {
406 $this->loadFromDefinition();
407 $files = array();
408 foreach ( $this->getImages( $context ) as $name => $image ) {
409 $files[] = $image->getPath( $context );
410 }
411
412 $files = array_values( array_unique( $files ) );
413 $filesMtime = max( array_map( array( __CLASS__, 'safeFilemtime' ), $files ) );
414
415 return $filesMtime;
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 }