Made wfIsBadImage() use APC
[mediawiki.git] / includes / resourceloader / ResourceLoaderImageModule.php
blob8de87f2ef5222e73a8877e25796e30db4581d9ff
1 <?php
2 /**
3 * Resource loader module for generated and embedded images.
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.
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.
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
20 * @file
21 * @author Trevor Parscal
24 /**
25 * Resource loader module for generated and embedded images.
27 * @since 1.25
29 class ResourceLoaderImageModule extends ResourceLoaderModule {
31 protected $definition = null;
33 /**
34 * Local base path, see __construct()
35 * @var string
37 protected $localBasePath = '';
39 protected $origin = self::ORIGIN_CORE_SITEWIDE;
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' );
48 /** @var string Position on the page to load this module at */
49 protected $position = 'bottom';
51 /**
52 * Constructs a new module from an options array.
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
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 * ),
102 * @endcode
103 * @throws InvalidArgumentException
105 public function __construct( $options = array(), $localBasePath = null ) {
106 $this->localBasePath = self::extractLocalBasePath( $options, $localBasePath );
108 $this->definition = $options;
112 * Parse definition and external JSON data, if referenced.
114 protected function loadFromDefinition() {
115 if ( $this->definition === null ) {
116 return;
119 $options = $this->definition;
120 $this->definition = null;
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 );
128 // Accepted combinations:
129 // * prefix
130 // * selector
131 // * selectorWithoutVariant + selectorWithVariant
132 // * prefix + selector
133 // * prefix + selectorWithoutVariant + selectorWithVariant
135 $prefix = isset( $options['prefix'] ) && $options['prefix'];
136 $selector = isset( $options['selector'] ) && $options['selector'];
137 $selectorWithoutVariant = isset( $options['selectorWithoutVariant'] )
138 && $options['selectorWithoutVariant'];
139 $selectorWithVariant = isset( $options['selectorWithVariant'] )
140 && $options['selectorWithVariant'];
142 if ( $selectorWithoutVariant && !$selectorWithVariant ) {
143 throw new InvalidArgumentException(
144 "Given 'selectorWithoutVariant' but no 'selectorWithVariant'."
147 if ( $selectorWithVariant && !$selectorWithoutVariant ) {
148 throw new InvalidArgumentException(
149 "Given 'selectorWithVariant' but no 'selectorWithoutVariant'."
152 if ( $selector && $selectorWithVariant ) {
153 throw new InvalidArgumentException(
154 "Incompatible 'selector' and 'selectorWithVariant'+'selectorWithoutVariant' given."
157 if ( !$prefix && !$selector && !$selectorWithVariant ) {
158 throw new InvalidArgumentException(
159 "None of 'prefix', 'selector' or 'selectorWithVariant'+'selectorWithoutVariant' given."
163 foreach ( $options as $member => $option ) {
164 switch ( $member ) {
165 case 'images':
166 case 'variants':
167 if ( !is_array( $option ) ) {
168 throw new InvalidArgumentException(
169 "Invalid list error. '$option' given, array expected."
172 if ( !isset( $option['default'] ) ) {
173 // Backwards compatibility
174 $option = array( 'default' => $option );
176 foreach ( $option as $skin => $data ) {
177 if ( !is_array( $option ) ) {
178 throw new InvalidArgumentException(
179 "Invalid list error. '$option' given, array expected."
183 $this->{$member} = $option;
184 break;
186 case 'position':
187 $this->isPositionDefined = true;
188 case 'prefix':
189 case 'selectorWithoutVariant':
190 case 'selectorWithVariant':
191 $this->{$member} = (string)$option;
192 break;
194 case 'selector':
195 $this->selectorWithoutVariant = $this->selectorWithVariant = (string)$option;
201 * Get CSS class prefix used by this module.
202 * @return string
204 public function getPrefix() {
205 $this->loadFromDefinition();
206 return $this->prefix;
210 * Get CSS selector templates used by this module.
211 * @return string
213 public function getSelectors() {
214 $this->loadFromDefinition();
215 return array(
216 'selectorWithoutVariant' => $this->selectorWithoutVariant,
217 'selectorWithVariant' => $this->selectorWithVariant,
222 * Get a ResourceLoaderImage object for given image.
223 * @param string $name Image name
224 * @param ResourceLoaderContext $context
225 * @return ResourceLoaderImage|null
227 public function getImage( $name, ResourceLoaderContext $context ) {
228 $this->loadFromDefinition();
229 $images = $this->getImages( $context );
230 return isset( $images[$name] ) ? $images[$name] : null;
234 * Get ResourceLoaderImage objects for all images.
235 * @param ResourceLoaderContext $context
236 * @return ResourceLoaderImage[] Array keyed by image name
238 public function getImages( ResourceLoaderContext $context ) {
239 $skin = $context->getSkin();
240 if ( !isset( $this->imageObjects ) ) {
241 $this->loadFromDefinition();
242 $this->imageObjects = array();
244 if ( !isset( $this->imageObjects[$skin] ) ) {
245 $this->imageObjects[$skin] = array();
246 if ( !isset( $this->images[$skin] ) ) {
247 $this->images[$skin] = isset( $this->images['default'] ) ?
248 $this->images['default'] :
249 array();
251 foreach ( $this->images[$skin] as $name => $options ) {
252 $fileDescriptor = is_string( $options ) ? $options : $options['file'];
254 $allowedVariants = array_merge(
255 is_array( $options ) && isset( $options['variants'] ) ? $options['variants'] : array(),
256 $this->getGlobalVariants( $context )
258 if ( isset( $this->variants[$skin] ) ) {
259 $variantConfig = array_intersect_key(
260 $this->variants[$skin],
261 array_fill_keys( $allowedVariants, true )
263 } else {
264 $variantConfig = array();
267 $image = new ResourceLoaderImage(
268 $name,
269 $this->getName(),
270 $fileDescriptor,
271 $this->localBasePath,
272 $variantConfig
274 $this->imageObjects[$skin][$image->getName()] = $image;
278 return $this->imageObjects[$skin];
282 * Get list of variants in this module that are 'global', i.e., available
283 * for every image regardless of image options.
284 * @param ResourceLoaderContext $context
285 * @return string[]
287 public function getGlobalVariants( ResourceLoaderContext $context ) {
288 $skin = $context->getSkin();
289 if ( !isset( $this->globalVariants ) ) {
290 $this->loadFromDefinition();
291 $this->globalVariants = array();
293 if ( !isset( $this->globalVariants[$skin] ) ) {
294 $this->globalVariants[$skin] = array();
295 if ( !isset( $this->variants[$skin] ) ) {
296 $this->variants[$skin] = isset( $this->variants['default'] ) ?
297 $this->variants['default'] :
298 array();
300 foreach ( $this->variants[$skin] as $name => $config ) {
301 if ( isset( $config['global'] ) && $config['global'] ) {
302 $this->globalVariants[$skin][] = $name;
307 return $this->globalVariants[$skin];
311 * @param ResourceLoaderContext $context
312 * @return array
314 public function getStyles( ResourceLoaderContext $context ) {
315 $this->loadFromDefinition();
317 // Build CSS rules
318 $rules = array();
319 $script = $context->getResourceLoader()->getLoadScript( $this->getSource() );
320 $selectors = $this->getSelectors();
322 foreach ( $this->getImages( $context ) as $name => $image ) {
323 $declarations = $this->getCssDeclarations(
324 $image->getDataUri( $context, null, 'original' ),
325 $image->getUrl( $context, $script, null, 'rasterized' )
327 $declarations = implode( "\n\t", $declarations );
328 $selector = strtr(
329 $selectors['selectorWithoutVariant'],
330 array(
331 '{prefix}' => $this->getPrefix(),
332 '{name}' => $name,
333 '{variant}' => '',
336 $rules[] = "$selector {\n\t$declarations\n}";
338 foreach ( $image->getVariants() as $variant ) {
339 $declarations = $this->getCssDeclarations(
340 $image->getDataUri( $context, $variant, 'original' ),
341 $image->getUrl( $context, $script, $variant, 'rasterized' )
343 $declarations = implode( "\n\t", $declarations );
344 $selector = strtr(
345 $selectors['selectorWithVariant'],
346 array(
347 '{prefix}' => $this->getPrefix(),
348 '{name}' => $name,
349 '{variant}' => $variant,
352 $rules[] = "$selector {\n\t$declarations\n}";
356 $style = implode( "\n", $rules );
357 return array( 'all' => $style );
361 * SVG support using a transparent gradient to guarantee cross-browser
362 * compatibility (browsers able to understand gradient syntax support also SVG).
363 * http://pauginer.tumblr.com/post/36614680636/invisible-gradient-technique
365 * Keep synchronized with the .background-image-svg LESS mixin in
366 * /resources/src/mediawiki.less/mediawiki.mixins.less.
368 * @param string $primary Primary URI
369 * @param string $fallback Fallback URI
370 * @return string[] CSS declarations to use given URIs as background-image
372 protected function getCssDeclarations( $primary, $fallback ) {
373 return array(
374 "background-image: url($fallback);",
375 "background-image: -webkit-linear-gradient(transparent, transparent), url($primary);",
376 "background-image: linear-gradient(transparent, transparent), url($primary);",
377 "background-image: -o-linear-gradient(transparent, transparent), url($fallback);",
382 * @return bool
384 public function supportsURLLoading() {
385 return false;
389 * Get the definition summary for this module.
391 * @param ResourceLoaderContext $context
392 * @return array
394 public function getDefinitionSummary( ResourceLoaderContext $context ) {
395 $this->loadFromDefinition();
396 $summary = parent::getDefinitionSummary( $context );
397 foreach ( array(
398 'localBasePath',
399 'images',
400 'variants',
401 'prefix',
402 'selectorWithoutVariant',
403 'selectorWithVariant',
404 ) as $member ) {
405 $summary[$member] = $this->{$member};
407 return $summary;
411 * Get the last modified timestamp of this module.
413 * @param ResourceLoaderContext $context Context in which to calculate
414 * the modified time
415 * @return int UNIX timestamp
417 public function getModifiedTime( ResourceLoaderContext $context ) {
418 $this->loadFromDefinition();
419 $files = array();
420 foreach ( $this->getImages( $context ) as $name => $image ) {
421 $files[] = $image->getPath( $context );
424 $files = array_values( array_unique( $files ) );
425 $filesMtime = max( array_map( array( __CLASS__, 'safeFilemtime' ), $files ) );
427 return $filesMtime;
431 * Extract a local base path from module definition information.
433 * @param array $options Module definition
434 * @param string $localBasePath Path to use if not provided in module definition. Defaults
435 * to $IP
436 * @return string Local base path
438 public static function extractLocalBasePath( $options, $localBasePath = null ) {
439 global $IP;
441 if ( $localBasePath === null ) {
442 $localBasePath = $IP;
445 if ( array_key_exists( 'localBasePath', $options ) ) {
446 $localBasePath = (string)$options['localBasePath'];
449 return $localBasePath;
453 * @return string
455 public function getPosition() {
456 $this->loadFromDefinition();
457 return $this->position;
460 public function isPositionDefault() {
461 $this->loadFromDefinition();
462 return parent::isPositionDefault();