Merge "Made wl_notificationtimestamp updates able to use queues"
[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 private $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 /**
49 * Constructs a new module from an options array.
50 *
51 * @param array $options List of options; if not given or empty, an empty module will be
52 * constructed
53 * @param string $localBasePath Base path to prepend to all local paths in $options. Defaults
54 * to $IP
55 *
56 * Below is a description for the $options array:
57 * @par Construction options:
58 * @code
59 * array(
60 * // Base path to prepend to all local paths in $options. Defaults to $IP
61 * 'localBasePath' => [base path],
62 * // Path to JSON file that contains any of the settings below
63 * 'data' => [file path string]
64 * // CSS class prefix to use in all style rules
65 * 'prefix' => [CSS class prefix],
66 * // Alternatively: Format of CSS selector to use in all style rules
67 * 'selector' => [CSS selector template, variables: {prefix} {name} {variant}],
68 * // Alternatively: When using variants
69 * 'selectorWithoutVariant' => [CSS selector template, variables: {prefix} {name}],
70 * 'selectorWithVariant' => [CSS selector template, variables: {prefix} {name} {variant}],
71 * // List of variants that may be used for the image files
72 * 'variants' => array(
73 * [variant name] => array(
74 * 'color' => [color string, e.g. '#ffff00'],
75 * 'global' => [boolean, if true, this variant is available
76 * for all images of this type],
77 * ),
78 * ...
79 * ),
80 * // List of image files and their options
81 * 'images' => array(
82 * [file path string],
83 * [file path string] => array(
84 * 'name' => [image name string, defaults to file name],
85 * 'variants' => [array of variant name strings, variants
86 * available for this image],
87 * ),
88 * ...
89 * ),
90 * )
91 * @endcode
92 * @throws InvalidArgumentException
93 */
94 public function __construct( $options = array(), $localBasePath = null ) {
95 $this->localBasePath = self::extractLocalBasePath( $options, $localBasePath );
96
97 $this->definition = $options;
98 }
99
100 /**
101 * Parse definition and external JSON data, if referenced.
102 */
103 private function ensureStuffLoaded() {
104 if ( $this->definition === null ) {
105 return;
106 }
107
108 $options = $this->definition;
109 $this->definition = null;
110
111 if ( isset( $options['data'] ) ) {
112 $dataPath = $this->localBasePath . '/' . $options['data'];
113 $data = json_decode( file_get_contents( $dataPath ), true );
114 $options = array_merge( $data, $options );
115 }
116
117 // Accepted combinations:
118 // * prefix
119 // * selector
120 // * selectorWithoutVariant + selectorWithVariant
121 // * prefix + selector
122 // * prefix + selectorWithoutVariant + selectorWithVariant
123
124 $prefix = isset( $options['prefix'] ) && $options['prefix'];
125 $selector = isset( $options['selector'] ) && $options['selector'];
126 $selectorWithoutVariant = isset( $options['selectorWithoutVariant'] ) && $options['selectorWithoutVariant'];
127 $selectorWithVariant = isset( $options['selectorWithVariant'] ) && $options['selectorWithVariant'];
128
129 if ( $selectorWithoutVariant && !$selectorWithVariant ) {
130 throw new InvalidArgumentException( "Given 'selectorWithoutVariant' but no 'selectorWithVariant'." );
131 }
132 if ( $selectorWithVariant && !$selectorWithoutVariant ) {
133 throw new InvalidArgumentException( "Given 'selectorWithVariant' but no 'selectorWithoutVariant'." );
134 }
135 if ( $selector && $selectorWithVariant ) {
136 throw new InvalidArgumentException( "Incompatible 'selector' and 'selectorWithVariant'+'selectorWithoutVariant' given." );
137 }
138 if ( !$prefix && !$selector && !$selectorWithVariant ) {
139 throw new InvalidArgumentException( "None of 'prefix', 'selector' or 'selectorWithVariant'+'selectorWithoutVariant' given." );
140 }
141
142 foreach ( $options as $member => $option ) {
143 switch ( $member ) {
144 case 'images':
145 case 'variants':
146 if ( !is_array( $option ) ) {
147 throw new InvalidArgumentException(
148 "Invalid list error. '$option' given, array expected."
149 );
150 }
151 $this->{$member} = $option;
152 break;
153
154 case 'prefix':
155 case 'selectorWithoutVariant':
156 case 'selectorWithVariant':
157 $this->{$member} = (string)$option;
158 break;
159
160 case 'selector':
161 $this->selectorWithoutVariant = $this->selectorWithVariant = (string)$option;
162 }
163 }
164 }
165
166 /**
167 * Get CSS class prefix used by this module.
168 * @return string
169 */
170 public function getPrefix() {
171 $this->ensureStuffLoaded();
172 return $this->prefix;
173 }
174
175 /**
176 * Get CSS selector templates used by this module.
177 * @return string
178 */
179 public function getSelectors() {
180 $this->ensureStuffLoaded();
181 return array(
182 'selectorWithoutVariant' => $this->selectorWithoutVariant,
183 'selectorWithVariant' => $this->selectorWithVariant,
184 );
185 }
186
187 /**
188 * Get a ResourceLoaderImage object for given image.
189 * @param string $name Image name
190 * @return ResourceLoaderImage|null
191 */
192 public function getImage( $name ) {
193 $this->ensureStuffLoaded();
194 $images = $this->getImages();
195 return isset( $images[$name] ) ? $images[$name] : null;
196 }
197
198 /**
199 * Get ResourceLoaderImage objects for all images.
200 * @return ResourceLoaderImage[] Array keyed by image name
201 */
202 public function getImages() {
203 if ( !isset( $this->imageObjects ) ) {
204 $this->ensureStuffLoaded();
205 $this->imageObjects = array();
206
207 foreach ( $this->images as $name => $options ) {
208 $fileDescriptor = is_string( $options ) ? $options : $options['file'];
209
210 $allowedVariants = array_merge(
211 is_array( $options ) && isset( $options['variants'] ) ? $options['variants'] : array(),
212 $this->getGlobalVariants()
213 );
214 if ( isset( $this->variants ) ) {
215 $variantConfig = array_intersect_key(
216 $this->variants,
217 array_fill_keys( $allowedVariants, true )
218 );
219 } else {
220 $variantConfig = array();
221 }
222
223 $image = new ResourceLoaderImage(
224 $name,
225 $this->getName(),
226 $fileDescriptor,
227 $this->localBasePath,
228 $variantConfig
229 );
230 $this->imageObjects[ $image->getName() ] = $image;
231 }
232 }
233
234 return $this->imageObjects;
235 }
236
237 /**
238 * Get list of variants in this module that are 'global', i.e., available
239 * for every image regardless of image options.
240 * @return string[]
241 */
242 public function getGlobalVariants() {
243 if ( !isset( $this->globalVariants ) ) {
244 $this->ensureStuffLoaded();
245 $this->globalVariants = array();
246
247 if ( isset( $this->variants ) ) {
248 foreach ( $this->variants as $name => $config ) {
249 if ( isset( $config['global'] ) && $config['global'] ) {
250 $this->globalVariants[] = $name;
251 }
252 }
253 }
254 }
255
256 return $this->globalVariants;
257 }
258
259 /**
260 * @param ResourceLoaderContext $context
261 * @return array
262 */
263 public function getStyles( ResourceLoaderContext $context ) {
264 $this->ensureStuffLoaded();
265
266 // Build CSS rules
267 $rules = array();
268 $script = $context->getResourceLoader()->getLoadScript( $this->getSource() );
269 $selectors = $this->getSelectors();
270
271 foreach ( $this->getImages() as $name => $image ) {
272 $declarations = $this->getCssDeclarations(
273 $image->getDataUri( $context, null, 'original' ),
274 $image->getUrl( $context, $script, null, 'rasterized' )
275 );
276 $declarations = implode( "\n\t", $declarations );
277 $selector = strtr(
278 $selectors['selectorWithoutVariant'],
279 array(
280 '{prefix}' => $this->getPrefix(),
281 '{name}' => $name,
282 '{variant}' => '',
283 )
284 );
285 $rules[] = "$selector {\n\t$declarations\n}";
286
287 foreach ( $image->getVariants() as $variant ) {
288 $declarations = $this->getCssDeclarations(
289 $image->getDataUri( $context, $variant, 'original' ),
290 $image->getUrl( $context, $script, $variant, 'rasterized' )
291 );
292 $declarations = implode( "\n\t", $declarations );
293 $selector = strtr(
294 $selectors['selectorWithVariant'],
295 array(
296 '{prefix}' => $this->getPrefix(),
297 '{name}' => $name,
298 '{variant}' => $variant,
299 )
300 );
301 $rules[] = "$selector {\n\t$declarations\n}";
302 }
303 }
304
305 $style = implode( "\n", $rules );
306 return array( 'all' => $style );
307 }
308
309 /**
310 * SVG support using a transparent gradient to guarantee cross-browser
311 * compatibility (browsers able to understand gradient syntax support also SVG).
312 * http://pauginer.tumblr.com/post/36614680636/invisible-gradient-technique
313 *
314 * Keep synchronized with the .background-image-svg LESS mixin in
315 * /resources/src/mediawiki.less/mediawiki.mixins.less.
316 *
317 * @param string $primary Primary URI
318 * @param string $fallback Fallback URI
319 * @return string[] CSS declarations to use given URIs as background-image
320 */
321 protected function getCssDeclarations( $primary, $fallback ) {
322 return array(
323 "background-image: url($fallback);",
324 "background-image: -webkit-linear-gradient(transparent, transparent), url($primary);",
325 "background-image: linear-gradient(transparent, transparent), url($primary);",
326 "background-image: -o-linear-gradient(transparent, transparent), url($fallback);",
327 );
328 }
329
330 /**
331 * @return bool
332 */
333 public function supportsURLLoading() {
334 return false;
335 }
336
337 /**
338 * Get the definition summary for this module.
339 *
340 * @param ResourceLoaderContext $context
341 * @return array
342 */
343 public function getDefinitionSummary( ResourceLoaderContext $context ) {
344 $this->ensureStuffLoaded();
345 $summary = parent::getDefinitionSummary( $context );
346 foreach ( array(
347 'localBasePath',
348 'images',
349 'variants',
350 'prefix',
351 'selectorWithoutVariant',
352 'selectorWithVariant',
353 ) as $member ) {
354 $summary[$member] = $this->{$member};
355 };
356 return $summary;
357 }
358
359 /**
360 * Get the last modified timestamp of this module.
361 *
362 * @param ResourceLoaderContext $context Context in which to calculate
363 * the modified time
364 * @return int UNIX timestamp
365 */
366 public function getModifiedTime( ResourceLoaderContext $context ) {
367 $this->ensureStuffLoaded();
368 $files = array();
369 foreach ( $this->getImages() as $name => $image ) {
370 $files[] = $image->getPath( $context );
371 }
372
373 $files = array_values( array_unique( $files ) );
374 $filesMtime = max( array_map( array( __CLASS__, 'safeFilemtime' ), $files ) );
375
376 return max(
377 $filesMtime,
378 $this->getDefinitionMtime( $context )
379 );
380 }
381
382 /**
383 * Extract a local base path from module definition information.
384 *
385 * @param array $options Module definition
386 * @param string $localBasePath Path to use if not provided in module definition. Defaults
387 * to $IP
388 * @return string Local base path
389 */
390 public static function extractLocalBasePath( $options, $localBasePath = null ) {
391 global $IP;
392
393 if ( $localBasePath === null ) {
394 $localBasePath = $IP;
395 }
396
397 if ( array_key_exists( 'localBasePath', $options ) ) {
398 $localBasePath = (string)$options['localBasePath'];
399 }
400
401 return $localBasePath;
402 }
403 }