MediaWiki  1.29.1
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  $group = $module->getGroup();
153 
154  if ( $group === 'private' ) {
155  // Embed via mw.loader.implement per T36907.
156  $data['embed']['general'][] = $name;
157  // Avoid duplicate request from mw.loader
158  $data['states'][$name] = 'loading';
159  } else {
160  // Load via mw.loader.load()
161  $data['general'][] = $name;
162  }
163  }
164 
165  foreach ( $this->moduleStyles as $name ) {
166  $module = $rl->getModule( $name );
167  if ( !$module ) {
168  continue;
169  }
170 
171  if ( $module->getType() !== ResourceLoaderModule::LOAD_STYLES ) {
172  $logger = $rl->getLogger();
173  $logger->warning( 'Unexpected general module "{module}" in styles queue.', [
174  'module' => $name,
175  ] );
176  } else {
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 
182  $group = $module->getGroup();
184  if ( $module->isKnownEmpty( $context ) ) {
185  // Avoid needless request for empty module
186  $data['states'][$name] = 'ready';
187  } else {
188  if ( $group === 'private' ) {
189  // Embed via style element
190  $data['embed']['styles'][] = $name;
191  // Avoid duplicate request from mw.loader
192  $data['states'][$name] = 'ready';
193  } else {
194  // Load from load.php?only=styles via <link rel=stylesheet>
195  $data['styles'][] = $name;
196  }
197  }
198  }
199 
200  foreach ( $this->moduleScripts as $name ) {
201  $module = $rl->getModule( $name );
202  if ( !$module ) {
203  continue;
204  }
205 
206  $group = $module->getGroup();
208  if ( $module->isKnownEmpty( $context ) ) {
209  // Avoid needless request for empty module
210  $data['states'][$name] = 'ready';
211  } else {
212  // Load from load.php?only=scripts via <script src></script>
213  $data['scripts'][] = $name;
214 
215  // Avoid duplicate request from mw.loader
216  $data['states'][$name] = 'loading';
217  }
218  }
219 
220  return $data;
221  }
222 
226  public function getDocumentAttributes() {
227  return [ 'class' => 'client-nojs' ];
228  }
229 
244  public function getHeadHtml() {
245  $data = $this->getData();
246  $chunks = [];
247 
248  // Change "client-nojs" class to client-js. This allows easy toggling of UI components.
249  // This happens synchronously on every page view to avoid flashes of wrong content.
250  // See also #getDocumentAttributes() and /resources/src/startup.js.
251  $chunks[] = Html::inlineScript(
252  'document.documentElement.className = document.documentElement.className'
253  . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );'
254  );
255 
256  // Inline RLQ: Set page variables
257  if ( $this->config ) {
258  $chunks[] = ResourceLoader::makeInlineScript(
259  ResourceLoader::makeConfigSetScript( $this->config )
260  );
261  }
262 
263  // Inline RLQ: Initial module states
264  $states = array_merge( $this->exemptStates, $data['states'] );
265  if ( $states ) {
266  $chunks[] = ResourceLoader::makeInlineScript(
267  ResourceLoader::makeLoaderStateScript( $states )
268  );
269  }
270 
271  // Inline RLQ: Embedded modules
272  if ( $data['embed']['general'] ) {
273  $chunks[] = $this->getLoad(
274  $data['embed']['general'],
276  );
277  }
278 
279  // Inline RLQ: Load general modules
280  if ( $data['general'] ) {
281  $chunks[] = ResourceLoader::makeInlineScript(
282  Xml::encodeJsCall( 'mw.loader.load', [ $data['general'] ] )
283  );
284  }
285 
286  // Inline RLQ: Load only=scripts
287  if ( $data['scripts'] ) {
288  $chunks[] = $this->getLoad(
289  $data['scripts'],
291  );
292  }
293 
294  // External stylesheets
295  if ( $data['styles'] ) {
296  $chunks[] = $this->getLoad(
297  $data['styles'],
299  );
300  }
301 
302  // Inline stylesheets (embedded only=styles)
303  if ( $data['embed']['styles'] ) {
304  $chunks[] = $this->getLoad(
305  $data['embed']['styles'],
307  );
308  }
309 
310  // Async scripts. Once the startup is loaded, inline RLQ scripts will run.
311  // Pass-through a custom target from OutputPage (T143066).
312  $startupQuery = $this->target ? [ 'target' => $this->target ] : [];
313  $chunks[] = $this->getLoad(
314  'startup',
316  $startupQuery
317  );
318 
319  return WrappedStringList::join( "\n", $chunks );
320  }
321 
325  public function getBodyHtml() {
326  return '';
327  }
328 
329  private function getContext( $group, $type ) {
330  return self::makeContext( $this->context, $group, $type );
331  }
332 
333  private function getLoad( $modules, $only, array $extraQuery = [] ) {
334  return self::makeLoad( $this->context, (array)$modules, $only, $extraQuery );
335  }
336 
337  private static function makeContext( ResourceLoaderContext $mainContext, $group, $type,
338  array $extraQuery = []
339  ) {
340  // Create new ResourceLoaderContext so that $extraQuery may trigger isRaw().
341  $req = new FauxRequest( array_merge( $mainContext->getRequest()->getValues(), $extraQuery ) );
342  // Set 'only' if not combined
343  $req->setVal( 'only', $type === ResourceLoaderModule::TYPE_COMBINED ? null : $type );
344  // Remove user parameter in most cases
345  if ( $group !== 'user' && $group !== 'private' ) {
346  $req->setVal( 'user', null );
347  }
348  $context = new ResourceLoaderContext( $mainContext->getResourceLoader(), $req );
349  // Allow caller to setVersion() and setModules()
351  }
352 
362  public static function makeLoad( ResourceLoaderContext $mainContext, array $modules, $only,
363  array $extraQuery = []
364  ) {
365  $rl = $mainContext->getResourceLoader();
366  $chunks = [];
367 
368  // Sort module names so requests are more uniform
369  sort( $modules );
370 
371  if ( $mainContext->getDebug() && count( $modules ) > 1 ) {
372 
373  $chunks = [];
374  // Recursively call us for every item
375  foreach ( $modules as $name ) {
376  $chunks[] = self::makeLoad( $mainContext, [ $name ], $only, $extraQuery );
377  }
378  return new WrappedStringList( "\n", $chunks );
379  }
380 
381  // Create keyed-by-source and then keyed-by-group list of module objects from modules list
382  $sortedModules = [];
383  foreach ( $modules as $name ) {
384  $module = $rl->getModule( $name );
385  if ( !$module ) {
386  $rl->getLogger()->warning( 'Unknown module "{module}"', [ 'module' => $name ] );
387  continue;
388  }
389  $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
390  }
391 
392  foreach ( $sortedModules as $source => $groups ) {
393  foreach ( $groups as $group => $grpModules ) {
394  $context = self::makeContext( $mainContext, $group, $only, $extraQuery );
395  $context->setModules( array_keys( $grpModules ) );
396 
397  if ( $group === 'private' ) {
398  // Decide whether to use style or script element
399  if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
400  $chunks[] = Html::inlineStyle(
401  $rl->makeModuleResponse( $context, $grpModules )
402  );
403  } else {
404  $chunks[] = ResourceLoader::makeInlineScript(
405  $rl->makeModuleResponse( $context, $grpModules )
406  );
407  }
408  continue;
409  }
410 
411  // See if we have one or more raw modules
412  $isRaw = false;
413  foreach ( $grpModules as $key => $module ) {
414  $isRaw |= $module->isRaw();
415  }
416 
417  // Special handling for the user group; because users might change their stuff
418  // on-wiki like user pages, or user preferences; we need to find the highest
419  // timestamp of these user-changeable modules so we can ensure cache misses on change
420  // This should NOT be done for the site group (T29564) because anons get that too
421  // and we shouldn't be putting timestamps in CDN-cached HTML
422  if ( $group === 'user' ) {
423  // Must setModules() before makeVersionQuery()
424  $context->setVersion( $rl->makeVersionQuery( $context ) );
425  }
426 
427  $url = $rl->createLoaderURL( $source, $context, $extraQuery );
428 
429  // Decide whether to use 'style' or 'script' element
430  if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
431  $chunk = Html::linkedStyle( $url );
432  } else {
433  if ( $context->getRaw() || $isRaw ) {
434  $chunk = Html::element( 'script', [
435  // In SpecialJavaScriptTest, QUnit must load synchronous
436  'async' => !isset( $extraQuery['sync'] ),
437  'src' => $url
438  ] );
439  } else {
440  $chunk = ResourceLoader::makeInlineScript(
441  Xml::encodeJsCall( 'mw.loader.load', [ $url ] )
442  );
443  }
444  }
445 
446  if ( $group == 'noscript' ) {
447  $chunks[] = Html::rawElement( 'noscript', [], $chunk );
448  } else {
449  $chunks[] = $chunk;
450  }
451  }
452  }
453 
454  return new WrappedStringList( "\n", $chunks );
455  }
456 }
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:337
ResourceLoaderClientHtml\getContext
getContext( $group, $type)
Definition: ResourceLoaderClientHtml.php:329
ResourceLoaderContext\getResourceLoader
getResourceLoader()
Definition: ResourceLoaderContext.php:149
captcha-old.count
count
Definition: captcha-old.py:225
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:226
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:990
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:304
$type
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Definition: hooks.txt:2536
ResourceLoaderClientHtml\$moduleScripts
array $moduleScripts
Definition: ResourceLoaderClientHtml.php:49
Html\inlineScript
static inlineScript( $contents)
Output a "<script>" tag with the given contents.
Definition: Html.php:583
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:645
ResourceLoaderClientHtml\$config
array $config
Definition: ResourceLoaderClientHtml.php:40
ResourceLoaderContext\getRequest
getRequest()
Definition: ResourceLoaderContext.php:156
ResourceLoaderContext\getDebug
getDebug()
Definition: ResourceLoaderContext.php:261
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:2179
ResourceLoaderClientHtml\getLoad
getLoad( $modules, $only, array $extraQuery=[])
Definition: ResourceLoaderClientHtml.php:333
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:325
$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:615
ResourceLoaderClientHtml\makeLoad
static makeLoad(ResourceLoaderContext $mainContext, array $modules, $only, array $extraQuery=[])
Explicily load or embed modules on a page.
Definition: ResourceLoaderClientHtml.php:362
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:644
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:45
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:284
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:244