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 private $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 * [variant name] => array(
77 * 'color' => [color string, e.g. '#ffff00'],
78 * 'global' => [boolean, if true, this variant is available
79 * for all images of this type],
83 * // List of image files and their options
86 * [file path string] => array(
87 * 'name' => [image name string, defaults to file name],
88 * 'variants' => [array of variant name strings, variants
89 * available for this image],
95 * @throws InvalidArgumentException
97 public function __construct( $options = array(), $localBasePath = null ) {
98 $this->localBasePath
= self
::extractLocalBasePath( $options, $localBasePath );
100 $this->definition
= $options;
104 * Parse definition and external JSON data, if referenced.
106 private function loadFromDefinition() {
107 if ( $this->definition
=== null ) {
111 $options = $this->definition
;
112 $this->definition
= null;
114 if ( isset( $options['data'] ) ) {
115 $dataPath = $this->localBasePath
. '/' . $options['data'];
116 $data = json_decode( file_get_contents( $dataPath ), true );
117 $options = array_merge( $data, $options );
120 // Accepted combinations:
123 // * selectorWithoutVariant + selectorWithVariant
124 // * prefix + selector
125 // * prefix + selectorWithoutVariant + selectorWithVariant
127 $prefix = isset( $options['prefix'] ) && $options['prefix'];
128 $selector = isset( $options['selector'] ) && $options['selector'];
129 $selectorWithoutVariant = isset( $options['selectorWithoutVariant'] ) && $options['selectorWithoutVariant'];
130 $selectorWithVariant = isset( $options['selectorWithVariant'] ) && $options['selectorWithVariant'];
132 if ( $selectorWithoutVariant && !$selectorWithVariant ) {
133 throw new InvalidArgumentException( "Given 'selectorWithoutVariant' but no 'selectorWithVariant'." );
135 if ( $selectorWithVariant && !$selectorWithoutVariant ) {
136 throw new InvalidArgumentException( "Given 'selectorWithVariant' but no 'selectorWithoutVariant'." );
138 if ( $selector && $selectorWithVariant ) {
139 throw new InvalidArgumentException( "Incompatible 'selector' and 'selectorWithVariant'+'selectorWithoutVariant' given." );
141 if ( !$prefix && !$selector && !$selectorWithVariant ) {
142 throw new InvalidArgumentException( "None of 'prefix', 'selector' or 'selectorWithVariant'+'selectorWithoutVariant' given." );
145 foreach ( $options as $member => $option ) {
149 if ( !is_array( $option ) ) {
150 throw new InvalidArgumentException(
151 "Invalid list error. '$option' given, array expected."
154 $this->{$member} = $option;
158 $this->isPositionDefined
= true;
160 case 'selectorWithoutVariant':
161 case 'selectorWithVariant':
162 $this->{$member} = (string)$option;
166 $this->selectorWithoutVariant
= $this->selectorWithVariant
= (string)$option;
172 * Get CSS class prefix used by this module.
175 public function getPrefix() {
176 $this->loadFromDefinition();
177 return $this->prefix
;
181 * Get CSS selector templates used by this module.
184 public function getSelectors() {
185 $this->loadFromDefinition();
187 'selectorWithoutVariant' => $this->selectorWithoutVariant
,
188 'selectorWithVariant' => $this->selectorWithVariant
,
193 * Get a ResourceLoaderImage object for given image.
194 * @param string $name Image name
195 * @return ResourceLoaderImage|null
197 public function getImage( $name ) {
198 $this->loadFromDefinition();
199 $images = $this->getImages();
200 return isset( $images[$name] ) ?
$images[$name] : null;
204 * Get ResourceLoaderImage objects for all images.
205 * @return ResourceLoaderImage[] Array keyed by image name
207 public function getImages() {
208 if ( !isset( $this->imageObjects
) ) {
209 $this->loadFromDefinition();
210 $this->imageObjects
= array();
212 foreach ( $this->images
as $name => $options ) {
213 $fileDescriptor = is_string( $options ) ?
$options : $options['file'];
215 $allowedVariants = array_merge(
216 is_array( $options ) && isset( $options['variants'] ) ?
$options['variants'] : array(),
217 $this->getGlobalVariants()
219 if ( isset( $this->variants
) ) {
220 $variantConfig = array_intersect_key(
222 array_fill_keys( $allowedVariants, true )
225 $variantConfig = array();
228 $image = new ResourceLoaderImage(
232 $this->localBasePath
,
235 $this->imageObjects
[ $image->getName() ] = $image;
239 return $this->imageObjects
;
243 * Get list of variants in this module that are 'global', i.e., available
244 * for every image regardless of image options.
247 public function getGlobalVariants() {
248 if ( !isset( $this->globalVariants
) ) {
249 $this->loadFromDefinition();
250 $this->globalVariants
= array();
252 if ( isset( $this->variants
) ) {
253 foreach ( $this->variants
as $name => $config ) {
254 if ( isset( $config['global'] ) && $config['global'] ) {
255 $this->globalVariants
[] = $name;
261 return $this->globalVariants
;
265 * @param ResourceLoaderContext $context
268 public function getStyles( ResourceLoaderContext
$context ) {
269 $this->loadFromDefinition();
273 $script = $context->getResourceLoader()->getLoadScript( $this->getSource() );
274 $selectors = $this->getSelectors();
276 foreach ( $this->getImages() as $name => $image ) {
277 $declarations = $this->getCssDeclarations(
278 $image->getDataUri( $context, null, 'original' ),
279 $image->getUrl( $context, $script, null, 'rasterized' )
281 $declarations = implode( "\n\t", $declarations );
283 $selectors['selectorWithoutVariant'],
285 '{prefix}' => $this->getPrefix(),
290 $rules[] = "$selector {\n\t$declarations\n}";
292 foreach ( $image->getVariants() as $variant ) {
293 $declarations = $this->getCssDeclarations(
294 $image->getDataUri( $context, $variant, 'original' ),
295 $image->getUrl( $context, $script, $variant, 'rasterized' )
297 $declarations = implode( "\n\t", $declarations );
299 $selectors['selectorWithVariant'],
301 '{prefix}' => $this->getPrefix(),
303 '{variant}' => $variant,
306 $rules[] = "$selector {\n\t$declarations\n}";
310 $style = implode( "\n", $rules );
311 return array( 'all' => $style );
315 * SVG support using a transparent gradient to guarantee cross-browser
316 * compatibility (browsers able to understand gradient syntax support also SVG).
317 * http://pauginer.tumblr.com/post/36614680636/invisible-gradient-technique
319 * Keep synchronized with the .background-image-svg LESS mixin in
320 * /resources/src/mediawiki.less/mediawiki.mixins.less.
322 * @param string $primary Primary URI
323 * @param string $fallback Fallback URI
324 * @return string[] CSS declarations to use given URIs as background-image
326 protected function getCssDeclarations( $primary, $fallback ) {
328 "background-image: url($fallback);",
329 "background-image: -webkit-linear-gradient(transparent, transparent), url($primary);",
330 "background-image: linear-gradient(transparent, transparent), url($primary);",
331 "background-image: -o-linear-gradient(transparent, transparent), url($fallback);",
338 public function supportsURLLoading() {
343 * Get the definition summary for this module.
345 * @param ResourceLoaderContext $context
348 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
349 $this->loadFromDefinition();
350 $summary = parent
::getDefinitionSummary( $context );
356 'selectorWithoutVariant',
357 'selectorWithVariant',
359 $summary[$member] = $this->{$member};
365 * Get the last modified timestamp of this module.
367 * @param ResourceLoaderContext $context Context in which to calculate
369 * @return int UNIX timestamp
371 public function getModifiedTime( ResourceLoaderContext
$context ) {
372 $this->loadFromDefinition();
374 foreach ( $this->getImages() as $name => $image ) {
375 $files[] = $image->getPath( $context );
378 $files = array_values( array_unique( $files ) );
379 $filesMtime = max( array_map( array( __CLASS__
, 'safeFilemtime' ), $files ) );
383 $this->getDefinitionMtime( $context )
388 * Extract a local base path from module definition information.
390 * @param array $options Module definition
391 * @param string $localBasePath Path to use if not provided in module definition. Defaults
393 * @return string Local base path
395 public static function extractLocalBasePath( $options, $localBasePath = null ) {
398 if ( $localBasePath === null ) {
399 $localBasePath = $IP;
402 if ( array_key_exists( 'localBasePath', $options ) ) {
403 $localBasePath = (string)$options['localBasePath'];
406 return $localBasePath;
412 public function getPosition() {
413 $this->loadFromDefinition();
414 return $this->position
;
417 public function isPositionDefault() {
418 $this->loadFromDefinition();
419 return parent
::isPositionDefault();