MediaWiki  1.30.0
ResourceLoaderClientHtml.php
Go to the documentation of this file.
1 <?php
21 use WrappedString\WrappedStringList;
22 
29 
31  private $context;
32 
34  private $resourceLoader;
35 
37  private $target;
38 
40  private $config = [];
41 
43  private $modules = [];
44 
46  private $moduleStyles = [];
47 
49  private $moduleScripts = [];
50 
52  private $exemptStates = [];
53 
55  private $data;
56 
61  public function __construct( ResourceLoaderContext $context, $target = null ) {
62  $this->context = $context;
63  $this->resourceLoader = $context->getResourceLoader();
64  $this->target = $target;
65  }
66 
72  public function setConfig( array $vars ) {
73  foreach ( $vars as $key => $value ) {
74  $this->config[$key] = $value;
75  }
76  }
77 
83  public function setModules( array $modules ) {
84  $this->modules = $modules;
85  }
86 
93  public function setModuleStyles( array $modules ) {
94  $this->moduleStyles = $modules;
95  }
96 
103  public function setModuleScripts( array $modules ) {
104  $this->moduleScripts = $modules;
105  }
106 
114  public function setExemptStates( array $states ) {
115  $this->exemptStates = $states;
116  }
117 
121  private function getData() {
122  if ( $this->data ) {
123  // @codeCoverageIgnoreStart
124  return $this->data;
125  // @codeCoverageIgnoreEnd
126  }
127 
128  $rl = $this->resourceLoader;
129  $data = [
130  'states' => [
131  // moduleName => state
132  ],
133  'general' => [],
134  'styles' => [
135  // moduleName
136  ],
137  'scripts' => [],
138  // Embedding for private modules
139  'embed' => [
140  'styles' => [],
141  'general' => [],
142  ],
143 
144  ];
145 
146  foreach ( $this->modules as $name ) {
147  $module = $rl->getModule( $name );
148  if ( !$module ) {
149  continue;
150  }
151 
152  if ( $module->shouldEmbedModule( $this->context ) ) {
153  // Embed via mw.loader.implement per T36907.
154  $data['embed']['general'][] = $name;
155  // Avoid duplicate request from mw.loader
156  $data['states'][$name] = 'loading';
157  } else {
158  // Load via mw.loader.load()
159  $data['general'][] = $name;
160  }
161  }
162 
163  foreach ( $this->moduleStyles as $name ) {
164  $module = $rl->getModule( $name );
165  if ( !$module ) {
166  continue;
167  }
168 
169  if ( $module->getType() !== ResourceLoaderModule::LOAD_STYLES ) {
170  $logger = $rl->getLogger();
171  $logger->error( 'Unexpected general module "{module}" in styles queue.', [
172  'module' => $name,
173  ] );
174  continue;
175  }
176 
177  // Stylesheet doesn't trigger mw.loader callback.
178  // Set "ready" state to allow dependencies and avoid duplicate requests. (T87871)
179  $data['states'][$name] = 'ready';
180 
181  $group = $module->getGroup();
183  if ( $module->isKnownEmpty( $context ) ) {
184  // Avoid needless request for empty module
185  $data['states'][$name] = 'ready';
186  } else {
187  if ( $module->shouldEmbedModule( $this->context ) ) {
188  // Embed via style element
189  $data['embed']['styles'][] = $name;
190  // Avoid duplicate request from mw.loader
191  $data['states'][$name] = 'ready';
192  } else {
193  // Load from load.php?only=styles via <link rel=stylesheet>
194  $data['styles'][] = $name;
195  }
196  }
197  }
198 
199  foreach ( $this->moduleScripts as $name ) {
200  $module = $rl->getModule( $name );
201  if ( !$module ) {
202  continue;
203  }
204 
205  $group = $module->getGroup();
207  if ( $module->isKnownEmpty( $context ) ) {
208  // Avoid needless request for empty module
209  $data['states'][$name] = 'ready';
210  } else {
211  // Load from load.php?only=scripts via <script src></script>
212  $data['scripts'][] = $name;
213 
214  // Avoid duplicate request from mw.loader
215  $data['states'][$name] = 'loading';
216  }
217  }
218 
219  return $data;
220  }
221 
225  public function getDocumentAttributes() {
226  return [ 'class' => 'client-nojs' ];
227  }
228 
243  public function getHeadHtml() {
244  $data = $this->getData();
245  $chunks = [];
246 
247  // Change "client-nojs" class to client-js. This allows easy toggling of UI components.
248  // This happens synchronously on every page view to avoid flashes of wrong content.
249  // See also #getDocumentAttributes() and /resources/src/startup.js.
250  $chunks[] = Html::inlineScript(
251  'document.documentElement.className = document.documentElement.className'
252  . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );'
253  );
254 
255  // Inline RLQ: Set page variables
256  if ( $this->config ) {
257  $chunks[] = ResourceLoader::makeInlineScript(
258  ResourceLoader::makeConfigSetScript( $this->config )
259  );
260  }
261 
262  // Inline RLQ: Initial module states
263  $states = array_merge( $this->exemptStates, $data['states'] );
264  if ( $states ) {
265  $chunks[] = ResourceLoader::makeInlineScript(
266  ResourceLoader::makeLoaderStateScript( $states )
267  );
268  }
269 
270  // Inline RLQ: Embedded modules
271  if ( $data['embed']['general'] ) {
272  $chunks[] = $this->getLoad(
273  $data['embed']['general'],
275  );
276  }
277 
278  // Inline RLQ: Load general modules
279  if ( $data['general'] ) {
280  $chunks[] = ResourceLoader::makeInlineScript(
281  Xml::encodeJsCall( 'mw.loader.load', [ $data['general'] ] )
282  );
283  }
284 
285  // Inline RLQ: Load only=scripts
286  if ( $data['scripts'] ) {
287  $chunks[] = $this->getLoad(
288  $data['scripts'],
290  );
291  }
292 
293  // External stylesheets
294  if ( $data['styles'] ) {
295  $chunks[] = $this->getLoad(
296  $data['styles'],
298  );
299  }
300 
301  // Inline stylesheets (embedded only=styles)
302  if ( $data['embed']['styles'] ) {
303  $chunks[] = $this->getLoad(
304  $data['embed']['styles'],
306  );
307  }
308 
309  // Async scripts. Once the startup is loaded, inline RLQ scripts will run.
310  // Pass-through a custom target from OutputPage (T143066).
311  $startupQuery = $this->target ? [ 'target' => $this->target ] : [];
312  $chunks[] = $this->getLoad(
313  'startup',
315  $startupQuery
316  );
317 
318  return WrappedStringList::join( "\n", $chunks );
319  }
320 
324  public function getBodyHtml() {
325  return '';
326  }
327 
328  private function getContext( $group, $type ) {
329  return self::makeContext( $this->context, $group, $type );
330  }
331 
332  private function getLoad( $modules, $only, array $extraQuery = [] ) {
333  return self::makeLoad( $this->context, (array)$modules, $only, $extraQuery );
334  }
335 
336  private static function makeContext( ResourceLoaderContext $mainContext, $group, $type,
337  array $extraQuery = []
338  ) {
339  // Create new ResourceLoaderContext so that $extraQuery may trigger isRaw().
340  $req = new FauxRequest( array_merge( $mainContext->getRequest()->getValues(), $extraQuery ) );
341  // Set 'only' if not combined
342  $req->setVal( 'only', $type === ResourceLoaderModule::TYPE_COMBINED ? null : $type );
343  // Remove user parameter in most cases
344  if ( $group !== 'user' && $group !== 'private' ) {
345  $req->setVal( 'user', null );
346  }
347  $context = new ResourceLoaderContext( $mainContext->getResourceLoader(), $req );
348  // Allow caller to setVersion() and setModules()
350  }
351 
361  public static function makeLoad( ResourceLoaderContext $mainContext, array $modules, $only,
362  array $extraQuery = []
363  ) {
364  $rl = $mainContext->getResourceLoader();
365  $chunks = [];
366 
367  // Sort module names so requests are more uniform
368  sort( $modules );
369 
370  if ( $mainContext->getDebug() && count( $modules ) > 1 ) {
371  $chunks = [];
372  // Recursively call us for every item
373  foreach ( $modules as $name ) {
374  $chunks[] = self::makeLoad( $mainContext, [ $name ], $only, $extraQuery );
375  }
376  return new WrappedStringList( "\n", $chunks );
377  }
378 
379  // Create keyed-by-source and then keyed-by-group list of module objects from modules list
380  $sortedModules = [];
381  foreach ( $modules as $name ) {
382  $module = $rl->getModule( $name );
383  if ( !$module ) {
384  $rl->getLogger()->warning( 'Unknown module "{module}"', [ 'module' => $name ] );
385  continue;
386  }
387  $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
388  }
389 
390  foreach ( $sortedModules as $source => $groups ) {
391  foreach ( $groups as $group => $grpModules ) {
392  $context = self::makeContext( $mainContext, $group, $only, $extraQuery );
393 
394  // Separate sets of linked and embedded modules while preserving order
395  $moduleSets = [];
396  $idx = -1;
397  foreach ( $grpModules as $name => $module ) {
398  $shouldEmbed = $module->shouldEmbedModule( $context );
399  if ( !$moduleSets || $moduleSets[$idx][0] !== $shouldEmbed ) {
400  $moduleSets[++$idx] = [ $shouldEmbed, [] ];
401  }
402  $moduleSets[$idx][1][$name] = $module;
403  }
404 
405  // Link/embed each set
406  foreach ( $moduleSets as list( $embed, $moduleSet ) ) {
407  $context->setModules( array_keys( $moduleSet ) );
408  if ( $embed ) {
409  // Decide whether to use style or script element
410  if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
411  $chunks[] = Html::inlineStyle(
412  $rl->makeModuleResponse( $context, $moduleSet )
413  );
414  } else {
415  $chunks[] = ResourceLoader::makeInlineScript(
416  $rl->makeModuleResponse( $context, $moduleSet )
417  );
418  }
419  } else {
420  // See if we have one or more raw modules
421  $isRaw = false;
422  foreach ( $moduleSet as $key => $module ) {
423  $isRaw |= $module->isRaw();
424  }
425 
426  // Special handling for the user group; because users might change their stuff
427  // on-wiki like user pages, or user preferences; we need to find the highest
428  // timestamp of these user-changeable modules so we can ensure cache misses on change
429  // This should NOT be done for the site group (T29564) because anons get that too
430  // and we shouldn't be putting timestamps in CDN-cached HTML
431  if ( $group === 'user' ) {
432  // Must setModules() before makeVersionQuery()
433  $context->setVersion( $rl->makeVersionQuery( $context ) );
434  }
435 
436  $url = $rl->createLoaderURL( $source, $context, $extraQuery );
437 
438  // Decide whether to use 'style' or 'script' element
439  if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
440  $chunk = Html::linkedStyle( $url );
441  } else {
442  if ( $context->getRaw() || $isRaw ) {
443  $chunk = Html::element( 'script', [
444  // In SpecialJavaScriptTest, QUnit must load synchronous
445  'async' => !isset( $extraQuery['sync'] ),
446  'src' => $url
447  ] );
448  } else {
449  $chunk = ResourceLoader::makeInlineScript(
450  Xml::encodeJsCall( 'mw.loader.load', [ $url ] )
451  );
452  }
453  }
454 
455  if ( $group == 'noscript' ) {
456  $chunks[] = Html::rawElement( 'noscript', [], $chunk );
457  } else {
458  $chunks[] = $chunk;
459  }
460  }
461  }
462  }
463  }
464 
465  return new WrappedStringList( "\n", $chunks );
466  }
467 }
ResourceLoaderContext
Object passed around to modules which contains information about the state of a specific loader reque...
Definition: ResourceLoaderContext.php:32
FauxRequest
WebRequest clone which takes values from a provided array.
Definition: FauxRequest.php:33
ResourceLoaderClientHtml
Bootstrap a ResourceLoader client on an HTML page.
Definition: ResourceLoaderClientHtml.php:28
ResourceLoaderModule\TYPE_COMBINED
const TYPE_COMBINED
Definition: ResourceLoaderModule.php:38
ResourceLoaderClientHtml\__construct
__construct(ResourceLoaderContext $context, $target=null)
Definition: ResourceLoaderClientHtml.php:61
ResourceLoaderClientHtml\makeContext
static makeContext(ResourceLoaderContext $mainContext, $group, $type, array $extraQuery=[])
Definition: ResourceLoaderClientHtml.php:336
ResourceLoaderClientHtml\getContext
getContext( $group, $type)
Definition: ResourceLoaderClientHtml.php:328
ResourceLoaderContext\getResourceLoader
getResourceLoader()
Definition: ResourceLoaderContext.php:149
captcha-old.count
count
Definition: captcha-old.py:249
ResourceLoaderClientHtml\setModuleScripts
setModuleScripts(array $modules)
Ensure the scripts of one or more modules are loaded.
Definition: ResourceLoaderClientHtml.php:103
ResourceLoaderClientHtml\getData
getData()
Definition: ResourceLoaderClientHtml.php:121
ResourceLoaderClientHtml\getDocumentAttributes
getDocumentAttributes()
Definition: ResourceLoaderClientHtml.php:225
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
$req
this hook is for auditing only $req
Definition: hooks.txt:988
ResourceLoaderClientHtml\setExemptStates
setExemptStates(array $states)
Set state of special modules that are handled by the caller manually.
Definition: ResourceLoaderClientHtml.php:114
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
ResourceLoaderClientHtml\$moduleScripts
array $moduleScripts
Definition: ResourceLoaderClientHtml.php:49
Html\inlineScript
static inlineScript( $contents)
Output a "<script>" tag with the given contents.
Definition: Html.php:562
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
ResourceLoaderClientHtml\$context
ResourceLoaderContext $context
Definition: ResourceLoaderClientHtml.php:31
ResourceLoaderClientHtml\$resourceLoader
ResourceLoader $resourceLoader
Definition: ResourceLoaderClientHtml.php:34
ResourceLoaderClientHtml\setConfig
setConfig(array $vars)
Set mw.config variables.
Definition: ResourceLoaderClientHtml.php:72
ResourceLoaderClientHtml\$modules
array $modules
Definition: ResourceLoaderClientHtml.php:43
Xml\encodeJsCall
static encodeJsCall( $name, $args, $pretty=false)
Create a call to a JavaScript function.
Definition: Xml.php:677
ResourceLoaderClientHtml\$config
array $config
Definition: ResourceLoaderClientHtml.php:40
ResourceLoaderContext\getRequest
getRequest()
Definition: ResourceLoaderContext.php:156
ResourceLoaderContext\getDebug
getDebug()
Definition: ResourceLoaderContext.php:263
ResourceLoaderClientHtml\$data
array $data
Definition: ResourceLoaderClientHtml.php:55
ResourceLoaderModule\TYPE_SCRIPTS
const TYPE_SCRIPTS
Definition: ResourceLoaderModule.php:36
$vars
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition: hooks.txt:2198
ResourceLoaderClientHtml\getLoad
getLoad( $modules, $only, array $extraQuery=[])
Definition: ResourceLoaderClientHtml.php:332
list
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
ResourceLoaderClientHtml\$exemptStates
array $exemptStates
Definition: ResourceLoaderClientHtml.php:52
ResourceLoaderClientHtml\$moduleStyles
array $moduleStyles
Definition: ResourceLoaderClientHtml.php:46
ResourceLoaderClientHtml\$target
string null $target
Definition: ResourceLoaderClientHtml.php:37
ResourceLoaderClientHtml\getBodyHtml
getBodyHtml()
Definition: ResourceLoaderClientHtml.php:324
$value
$value
Definition: styleTest.css.php:45
DerivativeResourceLoaderContext
Allows changing specific properties of a context object, without changing the main one.
Definition: DerivativeResourceLoaderContext.php:30
ResourceLoaderModule\LOAD_STYLES
const LOAD_STYLES
Definition: ResourceLoaderModule.php:42
Html\inlineStyle
static inlineStyle( $contents, $media='all')
Output a "<style>" tag with the given contents for the given media type (if any).
Definition: Html.php:594
ResourceLoaderClientHtml\makeLoad
static makeLoad(ResourceLoaderContext $mainContext, array $modules, $only, array $extraQuery=[])
Explicily load or embed modules on a page.
Definition: ResourceLoaderClientHtml.php:361
ResourceLoaderClientHtml\setModules
setModules(array $modules)
Ensure one or more modules are loaded.
Definition: ResourceLoaderClientHtml.php:83
Html\linkedStyle
static linkedStyle( $url, $media='all')
Output a "<link rel=stylesheet>" linking to the given URL for the given media type (if any).
Definition: Html.php:623
ResourceLoaderClientHtml\setModuleStyles
setModuleStyles(array $modules)
Ensure the styles of one or more modules are loaded.
Definition: ResourceLoaderClientHtml.php:93
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
Html\rawElement
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:209
$source
$source
Definition: mwdoc-filter.php:46
ResourceLoaderModule\TYPE_STYLES
const TYPE_STYLES
Definition: ResourceLoaderModule.php:37
Html\element
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:231
ResourceLoaderContext\getRaw
getRaw()
Definition: ResourceLoaderContext.php:286
data
and how to run hooks for an and one after Each event has a preferably in CamelCase For ArticleDelete hook A clump of code and data that should be run when an event happens This can be either a function and a chunk of data
Definition: hooks.txt:6
array
the array() calling protocol came about after MediaWiki 1.4rc1.
ResourceLoaderClientHtml\getHeadHtml
getHeadHtml()
The order of elements in the head is as follows:
Definition: ResourceLoaderClientHtml.php:243
$type
$type
Definition: testCompression.php:48