MediaWiki  1.28.1
ResourceLoaderImageModule.php
Go to the documentation of this file.
1 <?php
30 
31  protected $definition = null;
32 
37  protected $localBasePath = '';
38 
39  protected $origin = self::ORIGIN_CORE_SITEWIDE;
40 
41  protected $images = [];
42  protected $variants = [];
43  protected $prefix = null;
44  protected $selectorWithoutVariant = '.{prefix}-{name}';
45  protected $selectorWithVariant = '.{prefix}-{name}-{variant}';
46  protected $targets = [ 'desktop', 'mobile' ];
47 
49  protected $position = 'bottom';
50 
105  public function __construct( $options = [], $localBasePath = null ) {
106  $this->localBasePath = self::extractLocalBasePath( $options, $localBasePath );
107 
108  $this->definition = $options;
109  }
110 
114  protected function loadFromDefinition() {
115  if ( $this->definition === null ) {
116  return;
117  }
118 
120  $this->definition = null;
121 
122  if ( isset( $options['data'] ) ) {
123  $dataPath = $this->localBasePath . '/' . $options['data'];
124  $data = json_decode( file_get_contents( $dataPath ), true );
125  $options = array_merge( $data, $options );
126  }
127 
128  // Accepted combinations:
129  // * prefix
130  // * selector
131  // * selectorWithoutVariant + selectorWithVariant
132  // * prefix + selector
133  // * prefix + selectorWithoutVariant + selectorWithVariant
134 
135  $prefix = isset( $options['prefix'] ) && $options['prefix'];
136  $selector = isset( $options['selector'] ) && $options['selector'];
137  $selectorWithoutVariant = isset( $options['selectorWithoutVariant'] )
138  && $options['selectorWithoutVariant'];
139  $selectorWithVariant = isset( $options['selectorWithVariant'] )
140  && $options['selectorWithVariant'];
141 
143  throw new InvalidArgumentException(
144  "Given 'selectorWithoutVariant' but no 'selectorWithVariant'."
145  );
146  }
148  throw new InvalidArgumentException(
149  "Given 'selectorWithVariant' but no 'selectorWithoutVariant'."
150  );
151  }
152  if ( $selector && $selectorWithVariant ) {
153  throw new InvalidArgumentException(
154  "Incompatible 'selector' and 'selectorWithVariant'+'selectorWithoutVariant' given."
155  );
156  }
157  if ( !$prefix && !$selector && !$selectorWithVariant ) {
158  throw new InvalidArgumentException(
159  "None of 'prefix', 'selector' or 'selectorWithVariant'+'selectorWithoutVariant' given."
160  );
161  }
162 
163  foreach ( $options as $member => $option ) {
164  switch ( $member ) {
165  case 'images':
166  case 'variants':
167  if ( !is_array( $option ) ) {
168  throw new InvalidArgumentException(
169  "Invalid list error. '$option' given, array expected."
170  );
171  }
172  if ( !isset( $option['default'] ) ) {
173  // Backwards compatibility
174  $option = [ 'default' => $option ];
175  }
176  foreach ( $option as $skin => $data ) {
177  if ( !is_array( $option ) ) {
178  throw new InvalidArgumentException(
179  "Invalid list error. '$option' given, array expected."
180  );
181  }
182  }
183  $this->{$member} = $option;
184  break;
185 
186  case 'position':
187  case 'prefix':
188  case 'selectorWithoutVariant':
189  case 'selectorWithVariant':
190  $this->{$member} = (string)$option;
191  break;
192 
193  case 'selector':
194  $this->selectorWithoutVariant = $this->selectorWithVariant = (string)$option;
195  }
196  }
197  }
198 
203  public function getPrefix() {
204  $this->loadFromDefinition();
205  return $this->prefix;
206  }
207 
212  public function getSelectors() {
213  $this->loadFromDefinition();
214  return [
215  'selectorWithoutVariant' => $this->selectorWithoutVariant,
216  'selectorWithVariant' => $this->selectorWithVariant,
217  ];
218  }
219 
227  $this->loadFromDefinition();
228  $images = $this->getImages( $context );
229  return isset( $images[$name] ) ? $images[$name] : null;
230  }
231 
238  $skin = $context->getSkin();
239  if ( !isset( $this->imageObjects ) ) {
240  $this->loadFromDefinition();
241  $this->imageObjects = [];
242  }
243  if ( !isset( $this->imageObjects[$skin] ) ) {
244  $this->imageObjects[$skin] = [];
245  if ( !isset( $this->images[$skin] ) ) {
246  $this->images[$skin] = isset( $this->images['default'] ) ?
247  $this->images['default'] :
248  [];
249  }
250  foreach ( $this->images[$skin] as $name => $options ) {
251  $fileDescriptor = is_string( $options ) ? $options : $options['file'];
252 
253  $allowedVariants = array_merge(
254  is_array( $options ) && isset( $options['variants'] ) ? $options['variants'] : [],
255  $this->getGlobalVariants( $context )
256  );
257  if ( isset( $this->variants[$skin] ) ) {
258  $variantConfig = array_intersect_key(
259  $this->variants[$skin],
260  array_fill_keys( $allowedVariants, true )
261  );
262  } else {
263  $variantConfig = [];
264  }
265 
267  $name,
268  $this->getName(),
269  $fileDescriptor,
270  $this->localBasePath,
271  $variantConfig
272  );
273  $this->imageObjects[$skin][$image->getName()] = $image;
274  }
275  }
276 
277  return $this->imageObjects[$skin];
278  }
279 
287  $skin = $context->getSkin();
288  if ( !isset( $this->globalVariants ) ) {
289  $this->loadFromDefinition();
290  $this->globalVariants = [];
291  }
292  if ( !isset( $this->globalVariants[$skin] ) ) {
293  $this->globalVariants[$skin] = [];
294  if ( !isset( $this->variants[$skin] ) ) {
295  $this->variants[$skin] = isset( $this->variants['default'] ) ?
296  $this->variants['default'] :
297  [];
298  }
299  foreach ( $this->variants[$skin] as $name => $config ) {
300  if ( isset( $config['global'] ) && $config['global'] ) {
301  $this->globalVariants[$skin][] = $name;
302  }
303  }
304  }
305 
306  return $this->globalVariants[$skin];
307  }
308 
314  $this->loadFromDefinition();
315 
316  // Build CSS rules
317  $rules = [];
318  $script = $context->getResourceLoader()->getLoadScript( $this->getSource() );
319  $selectors = $this->getSelectors();
320 
321  foreach ( $this->getImages( $context ) as $name => $image ) {
322  $declarations = $this->getCssDeclarations(
323  $image->getDataUri( $context, null, 'original' ),
324  $image->getUrl( $context, $script, null, 'rasterized' )
325  );
326  $declarations = implode( "\n\t", $declarations );
327  $selector = strtr(
328  $selectors['selectorWithoutVariant'],
329  [
330  '{prefix}' => $this->getPrefix(),
331  '{name}' => $name,
332  '{variant}' => '',
333  ]
334  );
335  $rules[] = "$selector {\n\t$declarations\n}";
336 
337  foreach ( $image->getVariants() as $variant ) {
338  $declarations = $this->getCssDeclarations(
339  $image->getDataUri( $context, $variant, 'original' ),
340  $image->getUrl( $context, $script, $variant, 'rasterized' )
341  );
342  $declarations = implode( "\n\t", $declarations );
343  $selector = strtr(
344  $selectors['selectorWithVariant'],
345  [
346  '{prefix}' => $this->getPrefix(),
347  '{name}' => $name,
348  '{variant}' => $variant,
349  ]
350  );
351  $rules[] = "$selector {\n\t$declarations\n}";
352  }
353  }
354 
355  $style = implode( "\n", $rules );
356  return [ 'all' => $style ];
357  }
358 
371  protected function getCssDeclarations( $primary, $fallback ) {
372  return [
373  "background-image: url($fallback);",
374  "background-image: linear-gradient(transparent, transparent), url($primary);",
375  // Do not serve SVG to Opera 12, bad rendering with border-radius or background-size (T87504)
376  "background-image: -o-linear-gradient(transparent, transparent), url($fallback);",
377  ];
378  }
379 
383  public function supportsURLLoading() {
384  return false;
385  }
386 
394  $this->loadFromDefinition();
395  $summary = parent::getDefinitionSummary( $context );
396 
397  $options = [];
398  foreach ( [
399  'localBasePath',
400  'images',
401  'variants',
402  'prefix',
403  'selectorWithoutVariant',
404  'selectorWithVariant',
405  ] as $member ) {
406  $options[$member] = $this->{$member};
407  };
408 
409  $summary[] = [
410  'options' => $options,
411  'fileHashes' => $this->getFileHashes( $context ),
412  ];
413  return $summary;
414  }
415 
420  $this->loadFromDefinition();
421  $files = [];
422  foreach ( $this->getImages( $context ) as $name => $image ) {
423  $files[] = $image->getPath( $context );
424  }
425  $files = array_values( array_unique( $files ) );
426  return array_map( [ __CLASS__, 'safeFileHash' ], $files );
427  }
428 
437  public static function extractLocalBasePath( $options, $localBasePath = null ) {
438  global $IP;
439 
440  if ( $localBasePath === null ) {
442  }
443 
444  if ( array_key_exists( 'localBasePath', $options ) ) {
445  $localBasePath = (string)$options['localBasePath'];
446  }
447 
448  return $localBasePath;
449  }
450 
454  public function getPosition() {
455  $this->loadFromDefinition();
456  return $this->position;
457  }
458 
462  public function getType() {
463  return self::LOAD_STYLES;
464  }
465 }
getImages(ResourceLoaderContext $context)
Get ResourceLoaderImage objects for all images.
Class encapsulating an image used in a ResourceLoaderImageModule.
$context
Definition: load.php:50
ResourceLoader module for generated and embedded images.
Abstraction for ResourceLoader modules, with name registration and maxage functionality.
getImage($name, ResourceLoaderContext $context)
Get a ResourceLoaderImage object for given image.
$IP
Definition: WebStart.php:58
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:177
$files
getCssDeclarations($primary, $fallback)
SVG support using a transparent gradient to guarantee cross-browser compatibility (browsers able to u...
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
getFileHashes(ResourceLoaderContext $context)
Helper method for getDefinitionSummary.
$selector
getGlobalVariants(ResourceLoaderContext $context)
Get list of variants in this module that are 'global', i.e., available for every image regardless of ...
getSource()
Get the origin of this module.
getDefinitionSummary(ResourceLoaderContext $context)
Get the definition summary for this module.
getStyles(ResourceLoaderContext $context)
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition: hooks.txt:1046
getPrefix()
Get CSS class prefix used by this module.
$summary
string $localBasePath
Local base path, see __construct()
getSelectors()
Get CSS selector templates used by this module.
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:1936
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
__construct($options=[], $localBasePath=null)
Constructs a new module from an options array.
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
$fallback
Definition: MessagesAb.php:11
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub 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:802
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
static extractLocalBasePath($options, $localBasePath=null)
Extract a local base path from module definition information.
string $position
Position on the page to load this module at.
getName()
Get this module's name.
loadFromDefinition()
Parse definition and external JSON data, if referenced.
Object passed around to modules which contains information about the state of a specific loader reque...