MediaWiki  1.33.0
ResourceLoaderImageModule.php
Go to the documentation of this file.
1 <?php
30 
32  protected $definition = null;
33 
38  protected $localBasePath = '';
39 
41 
43  protected $imageObjects = null;
45  protected $images = [];
47  protected $defaultColor = null;
48  protected $useDataURI = true;
50  protected $globalVariants = null;
52  protected $variants = [];
54  protected $prefix = null;
55  protected $selectorWithoutVariant = '.{prefix}-{name}';
56  protected $selectorWithVariant = '.{prefix}-{name}-{variant}';
57  protected $targets = [ 'desktop', 'mobile' ];
58 
115  public function __construct( $options = [], $localBasePath = null ) {
116  $this->localBasePath = self::extractLocalBasePath( $options, $localBasePath );
117 
118  $this->definition = $options;
119  }
120 
124  protected function loadFromDefinition() {
125  if ( $this->definition === null ) {
126  return;
127  }
128 
130  $this->definition = null;
131 
132  if ( isset( $options['data'] ) ) {
133  $dataPath = $this->localBasePath . '/' . $options['data'];
134  $data = json_decode( file_get_contents( $dataPath ), true );
135  $options = array_merge( $data, $options );
136  }
137 
138  // Accepted combinations:
139  // * prefix
140  // * selector
141  // * selectorWithoutVariant + selectorWithVariant
142  // * prefix + selector
143  // * prefix + selectorWithoutVariant + selectorWithVariant
144 
145  $prefix = isset( $options['prefix'] ) && $options['prefix'];
146  $selector = isset( $options['selector'] ) && $options['selector'];
147  $selectorWithoutVariant = isset( $options['selectorWithoutVariant'] )
148  && $options['selectorWithoutVariant'];
149  $selectorWithVariant = isset( $options['selectorWithVariant'] )
150  && $options['selectorWithVariant'];
151 
153  throw new InvalidArgumentException(
154  "Given 'selectorWithoutVariant' but no 'selectorWithVariant'."
155  );
156  }
158  throw new InvalidArgumentException(
159  "Given 'selectorWithVariant' but no 'selectorWithoutVariant'."
160  );
161  }
162  if ( $selector && $selectorWithVariant ) {
163  throw new InvalidArgumentException(
164  "Incompatible 'selector' and 'selectorWithVariant'+'selectorWithoutVariant' given."
165  );
166  }
167  if ( !$prefix && !$selector && !$selectorWithVariant ) {
168  throw new InvalidArgumentException(
169  "None of 'prefix', 'selector' or 'selectorWithVariant'+'selectorWithoutVariant' given."
170  );
171  }
172 
173  foreach ( $options as $member => $option ) {
174  switch ( $member ) {
175  case 'images':
176  case 'variants':
177  if ( !is_array( $option ) ) {
178  throw new InvalidArgumentException(
179  "Invalid list error. '$option' given, array expected."
180  );
181  }
182  if ( !isset( $option['default'] ) ) {
183  // Backwards compatibility
184  $option = [ 'default' => $option ];
185  }
186  foreach ( $option as $skin => $data ) {
187  if ( !is_array( $data ) ) {
188  throw new InvalidArgumentException(
189  "Invalid list error. '$data' given, array expected."
190  );
191  }
192  }
193  $this->{$member} = $option;
194  break;
195 
196  case 'useDataURI':
197  $this->{$member} = (bool)$option;
198  break;
199  case 'defaultColor':
200  case 'prefix':
201  case 'selectorWithoutVariant':
202  case 'selectorWithVariant':
203  $this->{$member} = (string)$option;
204  break;
205 
206  case 'selector':
207  $this->selectorWithoutVariant = $this->selectorWithVariant = (string)$option;
208  }
209  }
210  }
211 
216  public function getPrefix() {
217  $this->loadFromDefinition();
218  return $this->prefix;
219  }
220 
225  public function getSelectors() {
226  $this->loadFromDefinition();
227  return [
228  'selectorWithoutVariant' => $this->selectorWithoutVariant,
229  'selectorWithVariant' => $this->selectorWithVariant,
230  ];
231  }
232 
240  $this->loadFromDefinition();
241  $images = $this->getImages( $context );
242  return $images[$name] ?? null;
243  }
244 
251  $skin = $context->getSkin();
252  if ( $this->imageObjects === null ) {
253  $this->loadFromDefinition();
254  $this->imageObjects = [];
255  }
256  if ( !isset( $this->imageObjects[$skin] ) ) {
257  $this->imageObjects[$skin] = [];
258  if ( !isset( $this->images[$skin] ) ) {
259  $this->images[$skin] = $this->images['default'] ?? [];
260  }
261  foreach ( $this->images[$skin] as $name => $options ) {
262  $fileDescriptor = is_string( $options ) ? $options : $options['file'];
263 
264  $allowedVariants = array_merge(
265  ( is_array( $options ) && isset( $options['variants'] ) ) ? $options['variants'] : [],
266  $this->getGlobalVariants( $context )
267  );
268  if ( isset( $this->variants[$skin] ) ) {
269  $variantConfig = array_intersect_key(
270  $this->variants[$skin],
271  array_fill_keys( $allowedVariants, true )
272  );
273  } else {
274  $variantConfig = [];
275  }
276 
278  $name,
279  $this->getName(),
280  $fileDescriptor,
281  $this->localBasePath,
282  $variantConfig,
283  $this->defaultColor
284  );
285  $this->imageObjects[$skin][$image->getName()] = $image;
286  }
287  }
288 
289  return $this->imageObjects[$skin];
290  }
291 
299  $skin = $context->getSkin();
300  if ( $this->globalVariants === null ) {
301  $this->loadFromDefinition();
302  $this->globalVariants = [];
303  }
304  if ( !isset( $this->globalVariants[$skin] ) ) {
305  $this->globalVariants[$skin] = [];
306  if ( !isset( $this->variants[$skin] ) ) {
307  $this->variants[$skin] = $this->variants['default'] ?? [];
308  }
309  foreach ( $this->variants[$skin] as $name => $config ) {
310  if ( isset( $config['global'] ) && $config['global'] ) {
311  $this->globalVariants[$skin][] = $name;
312  }
313  }
314  }
315 
316  return $this->globalVariants[$skin];
317  }
318 
324  $this->loadFromDefinition();
325 
326  // Build CSS rules
327  $rules = [];
328  $script = $context->getResourceLoader()->getLoadScript( $this->getSource() );
329  $selectors = $this->getSelectors();
330 
331  foreach ( $this->getImages( $context ) as $name => $image ) {
332  $declarations = $this->getStyleDeclarations( $context, $image, $script );
333  $selector = strtr(
334  $selectors['selectorWithoutVariant'],
335  [
336  '{prefix}' => $this->getPrefix(),
337  '{name}' => $name,
338  '{variant}' => '',
339  ]
340  );
341  $rules[] = "$selector {\n\t$declarations\n}";
342 
343  foreach ( $image->getVariants() as $variant ) {
344  $declarations = $this->getStyleDeclarations( $context, $image, $script, $variant );
345  $selector = strtr(
346  $selectors['selectorWithVariant'],
347  [
348  '{prefix}' => $this->getPrefix(),
349  '{name}' => $name,
350  '{variant}' => $variant,
351  ]
352  );
353  $rules[] = "$selector {\n\t$declarations\n}";
354  }
355  }
356 
357  $style = implode( "\n", $rules );
358  return [ 'all' => $style ];
359  }
360 
368  private function getStyleDeclarations(
371  $script,
372  $variant = null
373  ) {
374  $imageDataUri = $this->useDataURI ? $image->getDataUri( $context, $variant, 'original' ) : false;
375  $primaryUrl = $imageDataUri ?: $image->getUrl( $context, $script, $variant, 'original' );
376  $declarations = $this->getCssDeclarations(
377  $primaryUrl,
378  $image->getUrl( $context, $script, $variant, 'rasterized' )
379  );
380  return implode( "\n\t", $declarations );
381  }
382 
395  protected function getCssDeclarations( $primary, $fallback ) {
396  $primaryUrl = CSSMin::buildUrlValue( $primary );
397  $fallbackUrl = CSSMin::buildUrlValue( $fallback );
398  return [
399  "background-image: $fallbackUrl;",
400  "background-image: linear-gradient(transparent, transparent), $primaryUrl;",
401  ];
402  }
403 
407  public function supportsURLLoading() {
408  return false;
409  }
410 
418  $this->loadFromDefinition();
419  $summary = parent::getDefinitionSummary( $context );
420 
421  $options = [];
422  foreach ( [
423  'localBasePath',
424  'images',
425  'variants',
426  'prefix',
427  'selectorWithoutVariant',
428  'selectorWithVariant',
429  ] as $member ) {
430  $options[$member] = $this->{$member};
431  }
432 
433  $summary[] = [
434  'options' => $options,
435  'fileHashes' => $this->getFileHashes( $context ),
436  ];
437  return $summary;
438  }
439 
446  $this->loadFromDefinition();
447  $files = [];
448  foreach ( $this->getImages( $context ) as $name => $image ) {
449  $files[] = $image->getPath( $context );
450  }
451  $files = array_values( array_unique( $files ) );
452  return array_map( [ __CLASS__, 'safeFileHash' ], $files );
453  }
454 
463  public static function extractLocalBasePath( $options, $localBasePath = null ) {
464  global $IP;
465 
466  if ( $localBasePath === null ) {
468  }
469 
470  if ( array_key_exists( 'localBasePath', $options ) ) {
471  $localBasePath = (string)$options['localBasePath'];
472  }
473 
474  return $localBasePath;
475  }
476 
480  public function getType() {
481  return self::LOAD_STYLES;
482  }
483 }
ResourceLoaderImageModule\$globalVariants
array null $globalVariants
Definition: ResourceLoaderImageModule.php:50
ResourceLoaderContext
Object passed around to modules which contains information about the state of a specific loader reque...
Definition: ResourceLoaderContext.php:32
ResourceLoaderImageModule\$variants
array $variants
Definition: ResourceLoaderImageModule.php:52
ResourceLoaderImageModule\$images
array $images
Definition: ResourceLoaderImageModule.php:45
ResourceLoaderImageModule\getType
getType()
Definition: ResourceLoaderImageModule.php:480
$context
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition: hooks.txt:2636
ResourceLoaderImageModule\extractLocalBasePath
static extractLocalBasePath( $options, $localBasePath=null)
Extract a local base path from module definition information.
Definition: ResourceLoaderImageModule.php:463
ResourceLoaderImageModule\$useDataURI
$useDataURI
Definition: ResourceLoaderImageModule.php:48
ResourceLoaderModule\ORIGIN_CORE_SITEWIDE
const ORIGIN_CORE_SITEWIDE
Definition: ResourceLoaderModule.php:48
$fallback
$fallback
Definition: MessagesAb.php:11
ResourceLoaderImageModule\$targets
$targets
Definition: ResourceLoaderImageModule.php:57
ResourceLoaderImageModule\getGlobalVariants
getGlobalVariants(ResourceLoaderContext $context)
Get list of variants in this module that are 'global', i.e., available for every image regardless of ...
Definition: ResourceLoaderImageModule.php:298
ResourceLoaderImageModule\getStyles
getStyles(ResourceLoaderContext $context)
Definition: ResourceLoaderImageModule.php:323
ResourceLoaderImageModule\__construct
__construct( $options=[], $localBasePath=null)
Constructs a new module from an options array.
Definition: ResourceLoaderImageModule.php:115
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
ResourceLoaderImageModule\$prefix
string null $prefix
Definition: ResourceLoaderImageModule.php:54
ResourceLoaderImageModule\$localBasePath
string $localBasePath
Local base path, see __construct()
Definition: ResourceLoaderImageModule.php:38
ResourceLoaderImageModule\getPrefix
getPrefix()
Get CSS class prefix used by this module.
Definition: ResourceLoaderImageModule.php:216
$data
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
Definition: generatePhpCharToUpperMappings.php:13
ResourceLoaderImageModule\supportsURLLoading
supportsURLLoading()
Definition: ResourceLoaderImageModule.php:407
ResourceLoaderImageModule\$selectorWithVariant
$selectorWithVariant
Definition: ResourceLoaderImageModule.php:56
ResourceLoaderImageModule\$origin
$origin
Definition: ResourceLoaderImageModule.php:40
$IP
$IP
Definition: update.php:3
$image
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check $image
Definition: hooks.txt:780
array
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
string
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
Definition: hooks.txt:175
ResourceLoaderImageModule\$selectorWithoutVariant
$selectorWithoutVariant
Definition: ResourceLoaderImageModule.php:55
ResourceLoaderImageModule\$imageObjects
ResourceLoaderImage[] null $imageObjects
Definition: ResourceLoaderImageModule.php:43
ResourceLoaderImage
Class encapsulating an image used in a ResourceLoaderImageModule.
Definition: ResourceLoaderImage.php:30
$selector
$selector
Definition: styleTest.css.php:47
ResourceLoaderImageModule\getCssDeclarations
getCssDeclarations( $primary, $fallback)
SVG support using a transparent gradient to guarantee cross-browser compatibility (browsers able to u...
Definition: ResourceLoaderImageModule.php:395
ResourceLoaderModule\$name
$name
Definition: ResourceLoaderModule.php:69
ResourceLoaderModule\LOAD_STYLES
const LOAD_STYLES
Definition: ResourceLoaderModule.php:43
ResourceLoaderImageModule\getFileHashes
getFileHashes(ResourceLoaderContext $context)
Helper method for getDefinitionSummary.
Definition: ResourceLoaderImageModule.php:445
ResourceLoaderModule
Abstraction for ResourceLoader modules, with name registration and maxage functionality.
Definition: ResourceLoaderModule.php:35
ResourceLoaderImageModule\getStyleDeclarations
getStyleDeclarations(ResourceLoaderContext $context, ResourceLoaderImage $image, $script, $variant=null)
Definition: ResourceLoaderImageModule.php:368
ResourceLoaderModule\$config
Config $config
Definition: ResourceLoaderModule.php:84
$options
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1985
ResourceLoaderImageModule\getImages
getImages(ResourceLoaderContext $context)
Get ResourceLoaderImage objects for all images.
Definition: ResourceLoaderImageModule.php:250
ResourceLoaderImageModule\$definition
array null $definition
Definition: ResourceLoaderImageModule.php:32
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
$skin
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned $skin
Definition: hooks.txt:1985
ResourceLoaderImageModule\loadFromDefinition
loadFromDefinition()
Parse definition and external JSON data, if referenced.
Definition: ResourceLoaderImageModule.php:124
ResourceLoaderImageModule\getDefinitionSummary
getDefinitionSummary(ResourceLoaderContext $context)
Get the definition summary for this module.
Definition: ResourceLoaderImageModule.php:417
ResourceLoaderModule\getSource
getSource()
Get the source of this module.
Definition: ResourceLoaderModule.php:336
ResourceLoaderImageModule\$defaultColor
string null $defaultColor
Definition: ResourceLoaderImageModule.php:47
definition
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for and distribution as defined by Sections through of this document Licensor shall mean the copyright owner or entity authorized by the copyright owner that is granting the License Legal Entity shall mean the union of the acting entity and all other entities that control are controlled by or are under common control with that entity For the purposes of this definition control direct or to cause the direction or management of such whether by contract or including but not limited to software source documentation and configuration files Object form shall mean any form resulting from mechanical transformation or translation of a Source including but not limited to compiled object generated and conversions to other media types Work shall mean the work of whether in Source or Object made available under the as indicated by a copyright notice that is included in or attached to the whether in Source or Object that is based or other modifications as a an original work of authorship For the purposes of this Derivative Works shall not include works that remain separable or merely the Work and Derivative Works thereof Contribution shall mean any work of including the original version of the Work and any modifications or additions to that Work or Derivative Works that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner For the purposes of this definition
Definition: APACHE-LICENSE-2.0.txt:49
ResourceLoaderImageModule\getImage
getImage( $name, ResourceLoaderContext $context)
Get a ResourceLoaderImage object for given image.
Definition: ResourceLoaderImageModule.php:239
ResourceLoaderImageModule
ResourceLoader module for generated and embedded images.
Definition: ResourceLoaderImageModule.php:29
ResourceLoaderModule\getName
getName()
Get this module's name.
Definition: ResourceLoaderModule.php:102
ResourceLoaderImageModule\getSelectors
getSelectors()
Get CSS selector templates used by this module.
Definition: ResourceLoaderImageModule.php:225