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
21 * @author Trevor Parscal
25 * Resource loader module for generated and embedded images.
29 class ResourceLoaderImageModule
extends ResourceLoaderModule
{
31 protected $definition = null;
34 * Local base path, see __construct()
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';
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
56 * @param string $localBasePath Base path to prepend to all local paths in $options. Defaults
59 * Below is a description for the $options array:
60 * @par Construction options:
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],
86 * // List of image files and their options
88 * [theme name] => array(
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],
101 * @throws InvalidArgumentException
103 public function __construct( $options = array(), $localBasePath = null ) {
104 $this->localBasePath
= self
::extractLocalBasePath( $options, $localBasePath );
106 $this->definition
= $options;
110 * Parse definition and external JSON data, if referenced.
112 protected function loadFromDefinition() {
113 if ( $this->definition
=== null ) {
117 $options = $this->definition
;
118 $this->definition
= null;
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 );
126 // Accepted combinations:
129 // * selectorWithoutVariant + selectorWithVariant
130 // * prefix + selector
131 // * prefix + selectorWithoutVariant + selectorWithVariant
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'];
138 if ( $selectorWithoutVariant && !$selectorWithVariant ) {
139 throw new InvalidArgumentException( "Given 'selectorWithoutVariant' but no 'selectorWithVariant'." );
141 if ( $selectorWithVariant && !$selectorWithoutVariant ) {
142 throw new InvalidArgumentException( "Given 'selectorWithVariant' but no 'selectorWithoutVariant'." );
144 if ( $selector && $selectorWithVariant ) {
145 throw new InvalidArgumentException( "Incompatible 'selector' and 'selectorWithVariant'+'selectorWithoutVariant' given." );
147 if ( !$prefix && !$selector && !$selectorWithVariant ) {
148 throw new InvalidArgumentException( "None of 'prefix', 'selector' or 'selectorWithVariant'+'selectorWithoutVariant' given." );
151 foreach ( $options as $member => $option ) {
155 if ( !is_array( $option ) ) {
156 throw new InvalidArgumentException(
157 "Invalid list error. '$option' given, array expected."
160 if ( !isset( $option['default'] ) ) {
161 // Backwards compatibility
162 $option = array( 'default' => $option );
164 foreach ( $option as $skin => $data ) {
165 if ( !is_array( $option ) ) {
166 throw new InvalidArgumentException(
167 "Invalid list error. '$option' given, array expected."
171 $this->{$member} = $option;
175 $this->isPositionDefined
= true;
177 case 'selectorWithoutVariant':
178 case 'selectorWithVariant':
179 $this->{$member} = (string)$option;
183 $this->selectorWithoutVariant
= $this->selectorWithVariant
= (string)$option;
189 * Get CSS class prefix used by this module.
192 public function getPrefix() {
193 $this->loadFromDefinition();
194 return $this->prefix
;
198 * Get CSS selector templates used by this module.
201 public function getSelectors() {
202 $this->loadFromDefinition();
204 'selectorWithoutVariant' => $this->selectorWithoutVariant
,
205 'selectorWithVariant' => $this->selectorWithVariant
,
210 * Get a ResourceLoaderImage object for given image.
211 * @param string $name Image name
212 * @return ResourceLoaderImage|null
214 public function getImage( $name, ResourceLoaderContext
$context ) {
215 $this->loadFromDefinition();
216 $images = $this->getImages( $context );
217 return isset( $images[$name] ) ?
$images[$name] : null;
221 * Get ResourceLoaderImage objects for all images.
222 * @return ResourceLoaderImage[] Array keyed by image name
224 public function getImages( ResourceLoaderContext
$context ) {
225 $skin = $context->getSkin();
226 if ( !isset( $this->imageObjects
) ) {
227 $this->loadFromDefinition();
228 $this->imageObjects
= array();
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' ] :
237 foreach ( $this->images
[ $skin ] as $name => $options ) {
238 $fileDescriptor = is_string( $options ) ?
$options : $options['file'];
240 $allowedVariants = array_merge(
241 is_array( $options ) && isset( $options['variants'] ) ?
$options['variants'] : array(),
242 $this->getGlobalVariants( $context )
244 if ( isset( $this->variants
[ $skin ] ) ) {
245 $variantConfig = array_intersect_key(
246 $this->variants
[ $skin ],
247 array_fill_keys( $allowedVariants, true )
250 $variantConfig = array();
253 $image = new ResourceLoaderImage(
257 $this->localBasePath
,
260 $this->imageObjects
[ $skin ][ $image->getName() ] = $image;
264 return $this->imageObjects
[ $skin ];
268 * Get list of variants in this module that are 'global', i.e., available
269 * for every image regardless of image options.
272 public function getGlobalVariants( ResourceLoaderContext
$context ) {
273 $skin = $context->getSkin();
274 if ( !isset( $this->globalVariants
) ) {
275 $this->loadFromDefinition();
276 $this->globalVariants
= array();
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' ] :
285 foreach ( $this->variants
[ $skin ] as $name => $config ) {
286 if ( isset( $config['global'] ) && $config['global'] ) {
287 $this->globalVariants
[ $skin ][] = $name;
292 return $this->globalVariants
[ $skin ];
296 * @param ResourceLoaderContext $context
299 public function getStyles( ResourceLoaderContext
$context ) {
300 $this->loadFromDefinition();
304 $script = $context->getResourceLoader()->getLoadScript( $this->getSource() );
305 $selectors = $this->getSelectors();
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' )
312 $declarations = implode( "\n\t", $declarations );
314 $selectors['selectorWithoutVariant'],
316 '{prefix}' => $this->getPrefix(),
321 $rules[] = "$selector {\n\t$declarations\n}";
323 foreach ( $image->getVariants() as $variant ) {
324 $declarations = $this->getCssDeclarations(
325 $image->getDataUri( $context, $variant, 'original' ),
326 $image->getUrl( $context, $script, $variant, 'rasterized' )
328 $declarations = implode( "\n\t", $declarations );
330 $selectors['selectorWithVariant'],
332 '{prefix}' => $this->getPrefix(),
334 '{variant}' => $variant,
337 $rules[] = "$selector {\n\t$declarations\n}";
341 $style = implode( "\n", $rules );
342 return array( 'all' => $style );
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
350 * Keep synchronized with the .background-image-svg LESS mixin in
351 * /resources/src/mediawiki.less/mediawiki.mixins.less.
353 * @param string $primary Primary URI
354 * @param string $fallback Fallback URI
355 * @return string[] CSS declarations to use given URIs as background-image
357 protected function getCssDeclarations( $primary, $fallback ) {
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);",
369 public function supportsURLLoading() {
374 * Get the definition summary for this module.
376 * @param ResourceLoaderContext $context
379 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
380 $this->loadFromDefinition();
381 $summary = parent
::getDefinitionSummary( $context );
387 'selectorWithoutVariant',
388 'selectorWithVariant',
390 $summary[$member] = $this->{$member};
396 * Get the last modified timestamp of this module.
398 * @param ResourceLoaderContext $context Context in which to calculate
400 * @return int UNIX timestamp
402 public function getModifiedTime( ResourceLoaderContext
$context ) {
403 $this->loadFromDefinition();
405 foreach ( $this->getImages( $context ) as $name => $image ) {
406 $files[] = $image->getPath( $context );
409 $files = array_values( array_unique( $files ) );
410 $filesMtime = max( array_map( array( __CLASS__
, 'safeFilemtime' ), $files ) );
414 $this->getDefinitionMtime( $context )
419 * Extract a local base path from module definition information.
421 * @param array $options Module definition
422 * @param string $localBasePath Path to use if not provided in module definition. Defaults
424 * @return string Local base path
426 public static function extractLocalBasePath( $options, $localBasePath = null ) {
429 if ( $localBasePath === null ) {
430 $localBasePath = $IP;
433 if ( array_key_exists( 'localBasePath', $options ) ) {
434 $localBasePath = (string)$options['localBasePath'];
437 return $localBasePath;
443 public function getPosition() {
444 $this->loadFromDefinition();
445 return $this->position
;
448 public function isPositionDefault() {
449 $this->loadFromDefinition();
450 return parent
::isPositionDefault();