MediaWiki REL1_31
ResourceLoaderClientHtml.php
Go to the documentation of this file.
1<?php
21use Wikimedia\WrappedStringList;
22
29
31 private $context;
32
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
62 public function __construct( ResourceLoaderContext $context, array $options = [] ) {
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
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 ) {
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}
getContext()
Allows changing specific properties of a context object, without changing the main one.
WebRequest clone which takes values from a provided array.
Bootstrap a ResourceLoader client on an HTML page.
setModules(array $modules)
Ensure one or more modules are loaded.
getLoad( $modules, $only, array $extraQuery=[])
setModuleScripts(array $modules)
Ensure the scripts of one or more modules are loaded.
__construct(ResourceLoaderContext $context, array $options=[])
getHeadHtml()
The order of elements in the head is as follows:
setConfig(array $vars)
Set mw.config variables.
setExemptStates(array $states)
Set state of special modules that are handled by the caller manually.
static makeContext(ResourceLoaderContext $mainContext, $group, $type, array $extraQuery=[])
static makeLoad(ResourceLoaderContext $mainContext, array $modules, $only, array $extraQuery=[])
Explicily load or embed modules on a page.
setModuleStyles(array $modules)
Ensure the styles of one or more modules are loaded.
Object passed around to modules which contains information about the state of a specific loader reque...
Dynamic JavaScript and CSS resource loading system.
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.
static makeConfigSetScript(array $configuration)
Returns JS code which will set the MediaWiki configuration array to the given value.
static makeInlineScript( $script)
Returns an HTML script tag that runs given JS code after startup and base modules.
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
this hook is for auditing only $req
Definition hooks.txt:990
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition hooks.txt:2228
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
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
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:302
$source