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