Merge "Move MWTimestamp::getHumanTimestamp() to Language"
[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 /** @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 * [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],
80 * ),
81 * ...
82 * ),
83 * // List of image files and their options
84 * 'images' => array(
85 * [file path string],
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],
90 * ),
91 * ...
92 * ),
93 * )
94 * @endcode
95 * @throws InvalidArgumentException
96 */
97 public function __construct( $options = array(), $localBasePath = null ) {
98 $this->localBasePath = self::extractLocalBasePath( $options, $localBasePath );
99
100 $this->definition = $options;
101 }
102
103 /**
104 * Parse definition and external JSON data, if referenced.
105 */
106 private function loadFromDefinition() {
107 if ( $this->definition === null ) {
108 return;
109 }
110
111 $options = $this->definition;
112 $this->definition = null;
113
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 );
118 }
119
120 // Accepted combinations:
121 // * prefix
122 // * selector
123 // * selectorWithoutVariant + selectorWithVariant
124 // * prefix + selector
125 // * prefix + selectorWithoutVariant + selectorWithVariant
126
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'];
131
132 if ( $selectorWithoutVariant && !$selectorWithVariant ) {
133 throw new InvalidArgumentException( "Given 'selectorWithoutVariant' but no 'selectorWithVariant'." );
134 }
135 if ( $selectorWithVariant && !$selectorWithoutVariant ) {
136 throw new InvalidArgumentException( "Given 'selectorWithVariant' but no 'selectorWithoutVariant'." );
137 }
138 if ( $selector && $selectorWithVariant ) {
139 throw new InvalidArgumentException( "Incompatible 'selector' and 'selectorWithVariant'+'selectorWithoutVariant' given." );
140 }
141 if ( !$prefix && !$selector && !$selectorWithVariant ) {
142 throw new InvalidArgumentException( "None of 'prefix', 'selector' or 'selectorWithVariant'+'selectorWithoutVariant' given." );
143 }
144
145 foreach ( $options as $member => $option ) {
146 switch ( $member ) {
147 case 'images':
148 case 'variants':
149 if ( !is_array( $option ) ) {
150 throw new InvalidArgumentException(
151 "Invalid list error. '$option' given, array expected."
152 );
153 }
154 $this->{$member} = $option;
155 break;
156
157 case 'position':
158 $this->isPositionDefined = true;
159 case 'prefix':
160 case 'selectorWithoutVariant':
161 case 'selectorWithVariant':
162 $this->{$member} = (string)$option;
163 break;
164
165 case 'selector':
166 $this->selectorWithoutVariant = $this->selectorWithVariant = (string)$option;
167 }
168 }
169 }
170
171 /**
172 * Get CSS class prefix used by this module.
173 * @return string
174 */
175 public function getPrefix() {
176 $this->loadFromDefinition();
177 return $this->prefix;
178 }
179
180 /**
181 * Get CSS selector templates used by this module.
182 * @return string
183 */
184 public function getSelectors() {
185 $this->loadFromDefinition();
186 return array(
187 'selectorWithoutVariant' => $this->selectorWithoutVariant,
188 'selectorWithVariant' => $this->selectorWithVariant,
189 );
190 }
191
192 /**
193 * Get a ResourceLoaderImage object for given image.
194 * @param string $name Image name
195 * @return ResourceLoaderImage|null
196 */
197 public function getImage( $name ) {
198 $this->loadFromDefinition();
199 $images = $this->getImages();
200 return isset( $images[$name] ) ? $images[$name] : null;
201 }
202
203 /**
204 * Get ResourceLoaderImage objects for all images.
205 * @return ResourceLoaderImage[] Array keyed by image name
206 */
207 public function getImages() {
208 if ( !isset( $this->imageObjects ) ) {
209 $this->loadFromDefinition();
210 $this->imageObjects = array();
211
212 foreach ( $this->images as $name => $options ) {
213 $fileDescriptor = is_string( $options ) ? $options : $options['file'];
214
215 $allowedVariants = array_merge(
216 is_array( $options ) && isset( $options['variants'] ) ? $options['variants'] : array(),
217 $this->getGlobalVariants()
218 );
219 if ( isset( $this->variants ) ) {
220 $variantConfig = array_intersect_key(
221 $this->variants,
222 array_fill_keys( $allowedVariants, true )
223 );
224 } else {
225 $variantConfig = array();
226 }
227
228 $image = new ResourceLoaderImage(
229 $name,
230 $this->getName(),
231 $fileDescriptor,
232 $this->localBasePath,
233 $variantConfig
234 );
235 $this->imageObjects[ $image->getName() ] = $image;
236 }
237 }
238
239 return $this->imageObjects;
240 }
241
242 /**
243 * Get list of variants in this module that are 'global', i.e., available
244 * for every image regardless of image options.
245 * @return string[]
246 */
247 public function getGlobalVariants() {
248 if ( !isset( $this->globalVariants ) ) {
249 $this->loadFromDefinition();
250 $this->globalVariants = array();
251
252 if ( isset( $this->variants ) ) {
253 foreach ( $this->variants as $name => $config ) {
254 if ( isset( $config['global'] ) && $config['global'] ) {
255 $this->globalVariants[] = $name;
256 }
257 }
258 }
259 }
260
261 return $this->globalVariants;
262 }
263
264 /**
265 * @param ResourceLoaderContext $context
266 * @return array
267 */
268 public function getStyles( ResourceLoaderContext $context ) {
269 $this->loadFromDefinition();
270
271 // Build CSS rules
272 $rules = array();
273 $script = $context->getResourceLoader()->getLoadScript( $this->getSource() );
274 $selectors = $this->getSelectors();
275
276 foreach ( $this->getImages() as $name => $image ) {
277 $declarations = $this->getCssDeclarations(
278 $image->getDataUri( $context, null, 'original' ),
279 $image->getUrl( $context, $script, null, 'rasterized' )
280 );
281 $declarations = implode( "\n\t", $declarations );
282 $selector = strtr(
283 $selectors['selectorWithoutVariant'],
284 array(
285 '{prefix}' => $this->getPrefix(),
286 '{name}' => $name,
287 '{variant}' => '',
288 )
289 );
290 $rules[] = "$selector {\n\t$declarations\n}";
291
292 foreach ( $image->getVariants() as $variant ) {
293 $declarations = $this->getCssDeclarations(
294 $image->getDataUri( $context, $variant, 'original' ),
295 $image->getUrl( $context, $script, $variant, 'rasterized' )
296 );
297 $declarations = implode( "\n\t", $declarations );
298 $selector = strtr(
299 $selectors['selectorWithVariant'],
300 array(
301 '{prefix}' => $this->getPrefix(),
302 '{name}' => $name,
303 '{variant}' => $variant,
304 )
305 );
306 $rules[] = "$selector {\n\t$declarations\n}";
307 }
308 }
309
310 $style = implode( "\n", $rules );
311 return array( 'all' => $style );
312 }
313
314 /**
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
318 *
319 * Keep synchronized with the .background-image-svg LESS mixin in
320 * /resources/src/mediawiki.less/mediawiki.mixins.less.
321 *
322 * @param string $primary Primary URI
323 * @param string $fallback Fallback URI
324 * @return string[] CSS declarations to use given URIs as background-image
325 */
326 protected function getCssDeclarations( $primary, $fallback ) {
327 return array(
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);",
332 );
333 }
334
335 /**
336 * @return bool
337 */
338 public function supportsURLLoading() {
339 return false;
340 }
341
342 /**
343 * Get the definition summary for this module.
344 *
345 * @param ResourceLoaderContext $context
346 * @return array
347 */
348 public function getDefinitionSummary( ResourceLoaderContext $context ) {
349 $this->loadFromDefinition();
350 $summary = parent::getDefinitionSummary( $context );
351 foreach ( array(
352 'localBasePath',
353 'images',
354 'variants',
355 'prefix',
356 'selectorWithoutVariant',
357 'selectorWithVariant',
358 ) as $member ) {
359 $summary[$member] = $this->{$member};
360 };
361 return $summary;
362 }
363
364 /**
365 * Get the last modified timestamp of this module.
366 *
367 * @param ResourceLoaderContext $context Context in which to calculate
368 * the modified time
369 * @return int UNIX timestamp
370 */
371 public function getModifiedTime( ResourceLoaderContext $context ) {
372 $this->loadFromDefinition();
373 $files = array();
374 foreach ( $this->getImages() as $name => $image ) {
375 $files[] = $image->getPath( $context );
376 }
377
378 $files = array_values( array_unique( $files ) );
379 $filesMtime = max( array_map( array( __CLASS__, 'safeFilemtime' ), $files ) );
380
381 return max(
382 $filesMtime,
383 $this->getDefinitionMtime( $context )
384 );
385 }
386
387 /**
388 * Extract a local base path from module definition information.
389 *
390 * @param array $options Module definition
391 * @param string $localBasePath Path to use if not provided in module definition. Defaults
392 * to $IP
393 * @return string Local base path
394 */
395 public static function extractLocalBasePath( $options, $localBasePath = null ) {
396 global $IP;
397
398 if ( $localBasePath === null ) {
399 $localBasePath = $IP;
400 }
401
402 if ( array_key_exists( 'localBasePath', $options ) ) {
403 $localBasePath = (string)$options['localBasePath'];
404 }
405
406 return $localBasePath;
407 }
408
409 /**
410 * @return string
411 */
412 public function getPosition() {
413 $this->loadFromDefinition();
414 return $this->position;
415 }
416
417 public function isPositionDefault() {
418 $this->loadFromDefinition();
419 return parent::isPositionDefault();
420 }
421 }