MediaWiki  REL1_31
ResourceLoaderClientHtml.php
Go to the documentation of this file.
1 <?php
21 use Wikimedia\WrappedStringList;
22 
29 
31  private $context;
32 
34  private $resourceLoader;
35 
37  private $options;
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 
63  $this->context = $context;
64  $this->resourceLoader = $context->getResourceLoader();
65  $this->options = $options;
66  }
67 
73  public function setConfig( array $vars ) {
74  foreach ( $vars as $key => $value ) {
75  $this->config[$key] = $value;
76  }
77  }
78 
84  public function setModules( array $modules ) {
85  $this->modules = $modules;
86  }
87 
94  public function setModuleStyles( array $modules ) {
95  $this->moduleStyles = $modules;
96  }
97 
104  public function setModuleScripts( array $modules ) {
105  $this->moduleScripts = $modules;
106  }
107 
115  public function setExemptStates( array $states ) {
116  $this->exemptStates = $states;
117  }
118 
122  private function getData() {
123  if ( $this->data ) {
124  // @codeCoverageIgnoreStart
125  return $this->data;
126  // @codeCoverageIgnoreEnd
127  }
128 
129  $rl = $this->resourceLoader;
130  $data = [
131  'states' => [
132  // moduleName => state
133  ],
134  'general' => [],
135  'styles' => [],
136  'scripts' => [],
137  // Embedding for private modules
138  'embed' => [
139  'styles' => [],
140  'general' => [],
141  ],
142 
143  ];
144 
145  foreach ( $this->modules as $name ) {
146  $module = $rl->getModule( $name );
147  if ( !$module ) {
148  continue;
149  }
150 
151  $context = $this->getContext( $module->getGroup(), ResourceLoaderModule::TYPE_COMBINED );
152  if ( $module->isKnownEmpty( $context ) ) {
153  // Avoid needless request or embed for empty module
154  $data['states'][$name] = 'ready';
155  continue;
156  }
157 
158  if ( $module->shouldEmbedModule( $this->context ) ) {
159  // Embed via mw.loader.implement per T36907.
160  $data['embed']['general'][] = $name;
161  // Avoid duplicate request from mw.loader
162  $data['states'][$name] = 'loading';
163  } else {
164  // Load via mw.loader.load()
165  $data['general'][] = $name;
166  }
167  }
168 
169  foreach ( $this->moduleStyles as $name ) {
170  $module = $rl->getModule( $name );
171  if ( !$module ) {
172  continue;
173  }
174 
175  if ( $module->getType() !== ResourceLoaderModule::LOAD_STYLES ) {
176  $logger = $rl->getLogger();
177  $logger->error( 'Unexpected general module "{module}" in styles queue.', [
178  'module' => $name,
179  ] );
180  continue;
181  }
182 
183  // Stylesheet doesn't trigger mw.loader callback.
184  // Set "ready" state to allow script modules to depend on this module (T87871).
185  // And to avoid duplicate requests at run-time from mw.loader.
186  $data['states'][$name] = 'ready';
187 
188  $group = $module->getGroup();
190  // Avoid needless request for empty module
191  if ( !$module->isKnownEmpty( $context ) ) {
192  if ( $module->shouldEmbedModule( $this->context ) ) {
193  // Embed via style element
194  $data['embed']['styles'][] = $name;
195  } else {
196  // Load from load.php?only=styles via <link rel=stylesheet>
197  $data['styles'][] = $name;
198  }
199  }
200  }
201 
202  foreach ( $this->moduleScripts as $name ) {
203  $module = $rl->getModule( $name );
204  if ( !$module ) {
205  continue;
206  }
207 
208  $group = $module->getGroup();
210  if ( $module->isKnownEmpty( $context ) ) {
211  // Avoid needless request for empty module
212  $data['states'][$name] = 'ready';
213  } else {
214  // Load from load.php?only=scripts via <script src></script>
215  $data['scripts'][] = $name;
216 
217  // Avoid duplicate request from mw.loader
218  $data['states'][$name] = 'loading';
219  }
220  }
221 
222  return $data;
223  }
224 
228  public function getDocumentAttributes() {
229  return [ 'class' => 'client-nojs' ];
230  }
231 
246  public function getHeadHtml() {
247  $data = $this->getData();
248  $chunks = [];
249 
250  // Change "client-nojs" class to client-js. This allows easy toggling of UI components.
251  // This happens synchronously on every page view to avoid flashes of wrong content.
252  // See also #getDocumentAttributes() and /resources/src/startup.js.
253  $chunks[] = Html::inlineScript(
254  'document.documentElement.className = document.documentElement.className'
255  . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );'
256  );
257 
258  // Inline RLQ: Set page variables
259  if ( $this->config ) {
261  ResourceLoader::makeConfigSetScript( $this->config )
262  );
263  }
264 
265  // Inline RLQ: Initial module states
266  $states = array_merge( $this->exemptStates, $data['states'] );
267  if ( $states ) {
270  );
271  }
272 
273  // Inline RLQ: Embedded modules
274  if ( $data['embed']['general'] ) {
275  $chunks[] = $this->getLoad(
276  $data['embed']['general'],
278  );
279  }
280 
281  // Inline RLQ: Load general modules
282  if ( $data['general'] ) {
284  Xml::encodeJsCall( 'mw.loader.load', [ $data['general'] ] )
285  );
286  }
287 
288  // Inline RLQ: Load only=scripts
289  if ( $data['scripts'] ) {
290  $chunks[] = $this->getLoad(
291  $data['scripts'],
293  );
294  }
295 
296  // External stylesheets
297  if ( $data['styles'] ) {
298  $chunks[] = $this->getLoad(
299  $data['styles'],
301  );
302  }
303 
304  // Inline stylesheets (embedded only=styles)
305  if ( $data['embed']['styles'] ) {
306  $chunks[] = $this->getLoad(
307  $data['embed']['styles'],
309  );
310  }
311 
312  // Async scripts. Once the startup is loaded, inline RLQ scripts will run.
313  // Pass-through a custom 'target' from OutputPage (T143066).
314  $startupQuery = isset( $this->options['target'] )
315  ? [ 'target' => (string)$this->options['target'] ]
316  : [];
317  $chunks[] = $this->getLoad(
318  'startup',
320  $startupQuery
321  );
322 
323  return WrappedStringList::join( "\n", $chunks );
324  }
325 
329  public function getBodyHtml() {
330  return '';
331  }
332 
333  private function getContext( $group, $type ) {
334  return self::makeContext( $this->context, $group, $type );
335  }
336 
337  private function getLoad( $modules, $only, array $extraQuery = [] ) {
338  return self::makeLoad( $this->context, (array)$modules, $only, $extraQuery );
339  }
340 
341  private static function makeContext( ResourceLoaderContext $mainContext, $group, $type,
342  array $extraQuery = []
343  ) {
344  // Create new ResourceLoaderContext so that $extraQuery may trigger isRaw().
345  $req = new FauxRequest( array_merge( $mainContext->getRequest()->getValues(), $extraQuery ) );
346  // Set 'only' if not combined
347  $req->setVal( 'only', $type === ResourceLoaderModule::TYPE_COMBINED ? null : $type );
348  // Remove user parameter in most cases
349  if ( $group !== 'user' && $group !== 'private' ) {
350  $req->setVal( 'user', null );
351  }
352  $context = new ResourceLoaderContext( $mainContext->getResourceLoader(), $req );
353  // Allow caller to setVersion() and setModules()
355  }
356 
366  public static function makeLoad( ResourceLoaderContext $mainContext, array $modules, $only,
367  array $extraQuery = []
368  ) {
369  $rl = $mainContext->getResourceLoader();
370  $chunks = [];
371 
372  // Sort module names so requests are more uniform
373  sort( $modules );
374 
375  if ( $mainContext->getDebug() && count( $modules ) > 1 ) {
376  $chunks = [];
377  // Recursively call us for every item
378  foreach ( $modules as $name ) {
379  $chunks[] = self::makeLoad( $mainContext, [ $name ], $only, $extraQuery );
380  }
381  return new WrappedStringList( "\n", $chunks );
382  }
383 
384  // Create keyed-by-source and then keyed-by-group list of module objects from modules list
385  $sortedModules = [];
386  foreach ( $modules as $name ) {
387  $module = $rl->getModule( $name );
388  if ( !$module ) {
389  $rl->getLogger()->warning( 'Unknown module "{module}"', [ 'module' => $name ] );
390  continue;
391  }
392  $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
393  }
394 
395  foreach ( $sortedModules as $source => $groups ) {
396  foreach ( $groups as $group => $grpModules ) {
397  $context = self::makeContext( $mainContext, $group, $only, $extraQuery );
398 
399  // Separate sets of linked and embedded modules while preserving order
400  $moduleSets = [];
401  $idx = -1;
402  foreach ( $grpModules as $name => $module ) {
403  $shouldEmbed = $module->shouldEmbedModule( $context );
404  if ( !$moduleSets || $moduleSets[$idx][0] !== $shouldEmbed ) {
405  $moduleSets[++$idx] = [ $shouldEmbed, [] ];
406  }
407  $moduleSets[$idx][1][$name] = $module;
408  }
409 
410  // Link/embed each set
411  foreach ( $moduleSets as list( $embed, $moduleSet ) ) {
412  $context->setModules( array_keys( $moduleSet ) );
413  if ( $embed ) {
414  // Decide whether to use style or script element
415  if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
416  $chunks[] = Html::inlineStyle(
417  $rl->makeModuleResponse( $context, $moduleSet )
418  );
419  } else {
421  $rl->makeModuleResponse( $context, $moduleSet )
422  );
423  }
424  } else {
425  // See if we have one or more raw modules
426  $isRaw = false;
427  foreach ( $moduleSet as $key => $module ) {
428  $isRaw |= $module->isRaw();
429  }
430 
431  // Special handling for the user group; because users might change their stuff
432  // on-wiki like user pages, or user preferences; we need to find the highest
433  // timestamp of these user-changeable modules so we can ensure cache misses on change
434  // This should NOT be done for the site group (T29564) because anons get that too
435  // and we shouldn't be putting timestamps in CDN-cached HTML
436  if ( $group === 'user' ) {
437  // Must setModules() before makeVersionQuery()
438  $context->setVersion( $rl->makeVersionQuery( $context ) );
439  }
440 
441  $url = $rl->createLoaderURL( $source, $context, $extraQuery );
442 
443  // Decide whether to use 'style' or 'script' element
444  if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
445  $chunk = Html::linkedStyle( $url );
446  } else {
447  if ( $context->getRaw() || $isRaw ) {
448  $chunk = Html::element( 'script', [
449  // In SpecialJavaScriptTest, QUnit must load synchronous
450  'async' => !isset( $extraQuery['sync'] ),
451  'src' => $url
452  ] );
453  } else {
455  Xml::encodeJsCall( 'mw.loader.load', [ $url ] )
456  );
457  }
458  }
459 
460  if ( $group == 'noscript' ) {
461  $chunks[] = Html::rawElement( 'noscript', [], $chunk );
462  } else {
463  $chunks[] = $chunk;
464  }
465  }
466  }
467  }
468  }
469 
470  return new WrappedStringList( "\n", $chunks );
471  }
472 }
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
ResourceLoader\makeConfigSetScript
static makeConfigSetScript(array $configuration)
Returns JS code which will set the MediaWiki configuration array to the given value.
Definition: ResourceLoader.php:1522
use
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Definition: APACHE-LICENSE-2.0.txt:10
ResourceLoaderModule\TYPE_COMBINED
const TYPE_COMBINED
Definition: ResourceLoaderModule.php:39
array
the array() calling protocol came about after MediaWiki 1.4rc1.
ResourceLoaderClientHtml\makeContext
static makeContext(ResourceLoaderContext $mainContext, $group, $type, array $extraQuery=[])
Definition: ResourceLoaderClientHtml.php:341
ResourceLoaderClientHtml\getContext
getContext( $group, $type)
Definition: ResourceLoaderClientHtml.php:333
ResourceLoaderContext\getResourceLoader
getResourceLoader()
Definition: ResourceLoaderContext.php:148
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:181
ResourceLoaderClientHtml\setModuleScripts
setModuleScripts(array $modules)
Ensure the scripts of one or more modules are loaded.
Definition: ResourceLoaderClientHtml.php:104
ResourceLoaderClientHtml\getData
getData()
Definition: ResourceLoaderClientHtml.php:122
ResourceLoaderClientHtml\getDocumentAttributes
getDocumentAttributes()
Definition: ResourceLoaderClientHtml.php:228
ResourceLoaderClientHtml\setExemptStates
setExemptStates(array $states)
Set state of special modules that are handled by the caller manually.
Definition: ResourceLoaderClientHtml.php:115
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
ResourceLoaderClientHtml\$options
array $options
Definition: ResourceLoaderClientHtml.php:37
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:37
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:73
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:678
ResourceLoaderClientHtml\$config
array $config
Definition: ResourceLoaderClientHtml.php:40
ResourceLoaderContext\getRequest
getRequest()
Definition: ResourceLoaderContext.php:155
ResourceLoader\makeLoaderStateScript
static makeLoaderStateScript( $name, $state=null)
Returns a JS call to mw.loader.state, which sets the state of a module or modules to a given value.
Definition: ResourceLoader.php:1314
ResourceLoaderContext\getDebug
getDebug()
Definition: ResourceLoaderContext.php:261
ResourceLoaderClientHtml\$data
array $data
Definition: ResourceLoaderClientHtml.php:55
ResourceLoaderModule\TYPE_SCRIPTS
const TYPE_SCRIPTS
Definition: ResourceLoaderModule.php:37
ResourceLoaderClientHtml\getLoad
getLoad( $modules, $only, array $extraQuery=[])
Definition: ResourceLoaderClientHtml.php:337
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
Html\inlineStyle
static inlineStyle( $contents, $media='all', $attribs=[])
Output a "<style>" tag with the given contents for the given media type (if any).
Definition: Html.php:597
ResourceLoaderClientHtml\getBodyHtml
getBodyHtml()
Definition: ResourceLoaderClientHtml.php:329
$value
$value
Definition: styleTest.css.php:45
options
We ve cleaned up the code here by removing clumps of infrequently used code and moving them off somewhere else It s much easier for someone working with this code to see what s _really_ going and make changes or fix bugs In we can take all the code that deals with the little used title reversing options(say) and put it in one place. Instead of having little title-reversing if-blocks spread all over the codebase in showAnArticle
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:43
$req
this hook is for auditing only $req
Definition: hooks.txt:990
ResourceLoaderClientHtml\makeLoad
static makeLoad(ResourceLoaderContext $mainContext, array $modules, $only, array $extraQuery=[])
Explicily load or embed modules on a page.
Definition: ResourceLoaderClientHtml.php:366
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
ResourceLoader
Dynamic JavaScript and CSS resource loading system.
Definition: ResourceLoader.php:38
ResourceLoaderClientHtml\setModules
setModules(array $modules)
Ensure one or more modules are loaded.
Definition: ResourceLoaderClientHtml.php:84
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:626
ResourceLoaderClientHtml\setModuleStyles
setModuleStyles(array $modules)
Ensure the styles of one or more modules are loaded.
Definition: ResourceLoaderClientHtml.php:94
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:22
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:38
$vars
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition: hooks.txt:2228
Html\element
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:231
ResourceLoaderClientHtml\__construct
__construct(ResourceLoaderContext $context, array $options=[])
Definition: ResourceLoaderClientHtml.php:62
ResourceLoaderContext\getRaw
getRaw()
Definition: ResourceLoaderContext.php:284
ResourceLoader\makeInlineScript
static makeInlineScript( $script)
Returns an HTML script tag that runs given JS code after startup and base modules.
Definition: ResourceLoader.php:1506
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:18
ResourceLoaderClientHtml\getHeadHtml
getHeadHtml()
The order of elements in the head is as follows:
Definition: ResourceLoaderClientHtml.php:246
$type
$type
Definition: testCompression.php:48