MediaWiki  1.33.0
ResourceLoaderClientHtml.php
Go to the documentation of this file.
1 <?php
21 use Wikimedia\WrappedString;
22 use Wikimedia\WrappedStringList;
23 
30 
32  private $context;
33 
35  private $resourceLoader;
36 
38  private $options;
39 
41  private $config = [];
42 
44  private $modules = [];
45 
47  private $moduleStyles = [];
48 
50  private $exemptStates = [];
51 
53  private $data;
54 
63  $this->context = $context;
64  $this->resourceLoader = $context->getResourceLoader();
65  $this->options = $options + [
66  'target' => null,
67  'safemode' => null,
68  'nonce' => null,
69  ];
70  }
71 
77  public function setConfig( array $vars ) {
78  foreach ( $vars as $key => $value ) {
79  $this->config[$key] = $value;
80  }
81  }
82 
88  public function setModules( array $modules ) {
89  $this->modules = $modules;
90  }
91 
97  public function setModuleStyles( array $modules ) {
98  $this->moduleStyles = $modules;
99  }
100 
108  public function setExemptStates( array $states ) {
109  $this->exemptStates = $states;
110  }
111 
115  private function getData() {
116  if ( $this->data ) {
117  // @codeCoverageIgnoreStart
118  return $this->data;
119  // @codeCoverageIgnoreEnd
120  }
121 
122  $rl = $this->resourceLoader;
123  $data = [
124  'states' => [
125  // moduleName => state
126  ],
127  'general' => [],
128  'styles' => [],
129  // Embedding for private modules
130  'embed' => [
131  'styles' => [],
132  'general' => [],
133  ],
134  // Deprecations for style-only modules
135  'styleDeprecations' => [],
136  ];
137 
138  foreach ( $this->modules as $name ) {
139  $module = $rl->getModule( $name );
140  if ( !$module ) {
141  continue;
142  }
143 
144  $group = $module->getGroup();
146  if ( $module->isKnownEmpty( $context ) ) {
147  // Avoid needless request or embed for empty module
148  $data['states'][$name] = 'ready';
149  continue;
150  }
151 
152  if ( $group === 'user' || $module->shouldEmbedModule( $this->context ) ) {
153  // Call makeLoad() to decide how to load these, instead of
154  // loading via mw.loader.load().
155  // - For group=user: We need to provide a pre-generated load.php
156  // url to the client that has the 'user' and 'version' parameters
157  // filled in. Without this, the client would wrongly use the static
158  // version hash, per T64602.
159  // - For shouldEmbed=true: 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  $deprecation = $module->getDeprecationInformation();
201  if ( $deprecation ) {
202  $data['styleDeprecations'][] = $deprecation;
203  }
204  }
205 
206  return $data;
207  }
208 
212  public function getDocumentAttributes() {
213  return [ 'class' => 'client-nojs' ];
214  }
215 
230  public function getHeadHtml() {
231  $nonce = $this->options['nonce'];
232  $data = $this->getData();
233  $chunks = [];
234 
235  // Change "client-nojs" class to client-js. This allows easy toggling of UI components.
236  // This happens synchronously on every page view to avoid flashes of wrong content.
237  // See also #getDocumentAttributes() and /resources/src/startup.js.
238  $chunks[] = Html::inlineScript(
239  'document.documentElement.className = document.documentElement.className'
240  . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );',
241  $nonce
242  );
243 
244  // Inline RLQ: Set page variables
245  if ( $this->config ) {
246  $chunks[] = ResourceLoader::makeInlineScript(
247  ResourceLoader::makeConfigSetScript( $this->config ),
248  $nonce
249  );
250  }
251 
252  // Inline RLQ: Initial module states
253  $states = array_merge( $this->exemptStates, $data['states'] );
254  if ( $states ) {
255  $chunks[] = ResourceLoader::makeInlineScript(
256  ResourceLoader::makeLoaderStateScript( $states ),
257  $nonce
258  );
259  }
260 
261  // Inline RLQ: Embedded modules
262  if ( $data['embed']['general'] ) {
263  $chunks[] = $this->getLoad(
264  $data['embed']['general'],
266  $nonce
267  );
268  }
269 
270  // Inline RLQ: Load general modules
271  if ( $data['general'] ) {
272  $chunks[] = ResourceLoader::makeInlineScript(
273  'RLPAGEMODULES='
274  . ResourceLoader::encodeJsonForScript( $data['general'] )
275  . ';'
276  . 'mw.loader.load(RLPAGEMODULES);',
277  $nonce
278  );
279  }
280 
281  // External stylesheets (only=styles)
282  if ( $data['styles'] ) {
283  $chunks[] = $this->getLoad(
284  $data['styles'],
286  $nonce
287  );
288  }
289 
290  // Inline stylesheets (embedded only=styles)
291  if ( $data['embed']['styles'] ) {
292  $chunks[] = $this->getLoad(
293  $data['embed']['styles'],
295  $nonce
296  );
297  }
298 
299  // Async scripts. Once the startup is loaded, inline RLQ scripts will run.
300  // Pass-through a custom 'target' from OutputPage (T143066).
301  $startupQuery = [];
302  foreach ( [ 'target', 'safemode' ] as $param ) {
303  if ( $this->options[$param] !== null ) {
304  $startupQuery[$param] = (string)$this->options[$param];
305  }
306  }
307  $chunks[] = $this->getLoad(
308  'startup',
310  $nonce,
311  $startupQuery
312  );
313 
314  return WrappedString::join( "\n", $chunks );
315  }
316 
320  public function getBodyHtml() {
321  $data = $this->getData();
322  $chunks = [];
323 
324  // Deprecations for only=styles modules
325  if ( $data['styleDeprecations'] ) {
326  $chunks[] = ResourceLoader::makeInlineScript(
327  implode( '', $data['styleDeprecations'] ),
328  $this->options['nonce']
329  );
330  }
331 
332  return WrappedString::join( "\n", $chunks );
333  }
334 
335  private function getContext( $group, $type ) {
336  return self::makeContext( $this->context, $group, $type );
337  }
338 
339  private function getLoad( $modules, $only, $nonce, array $extraQuery = [] ) {
340  return self::makeLoad( $this->context, (array)$modules, $only, $extraQuery, $nonce );
341  }
342 
343  private static function makeContext( ResourceLoaderContext $mainContext, $group, $type,
344  array $extraQuery = []
345  ) {
346  // Create new ResourceLoaderContext so that $extraQuery may trigger isRaw().
347  $req = new FauxRequest( array_merge( $mainContext->getRequest()->getValues(), $extraQuery ) );
348  // Set 'only' if not combined
349  $req->setVal( 'only', $type === ResourceLoaderModule::TYPE_COMBINED ? null : $type );
350  // Remove user parameter in most cases
351  if ( $group !== 'user' && $group !== 'private' ) {
352  $req->setVal( 'user', null );
353  }
354  $context = new ResourceLoaderContext( $mainContext->getResourceLoader(), $req );
355  // Allow caller to setVersion() and setModules()
357  $ret->setContentOverrideCallback( $mainContext->getContentOverrideCallback() );
358  return $ret;
359  }
360 
372  public static function makeLoad( ResourceLoaderContext $mainContext, array $modules, $only,
373  array $extraQuery = [], $nonce = null
374  ) {
375  $rl = $mainContext->getResourceLoader();
376  $chunks = [];
377 
378  // Sort module names so requests are more uniform
379  sort( $modules );
380 
381  if ( $mainContext->getDebug() && count( $modules ) > 1 ) {
382  $chunks = [];
383  // Recursively call us for every item
384  foreach ( $modules as $name ) {
385  $chunks[] = self::makeLoad( $mainContext, [ $name ], $only, $extraQuery, $nonce );
386  }
387  return new WrappedStringList( "\n", $chunks );
388  }
389 
390  // Create keyed-by-source and then keyed-by-group list of module objects from modules list
391  $sortedModules = [];
392  foreach ( $modules as $name ) {
393  $module = $rl->getModule( $name );
394  if ( !$module ) {
395  $rl->getLogger()->warning( 'Unknown module "{module}"', [ 'module' => $name ] );
396  continue;
397  }
398  $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
399  }
400 
401  foreach ( $sortedModules as $source => $groups ) {
402  foreach ( $groups as $group => $grpModules ) {
403  $context = self::makeContext( $mainContext, $group, $only, $extraQuery );
404 
405  // Separate sets of linked and embedded modules while preserving order
406  $moduleSets = [];
407  $idx = -1;
408  foreach ( $grpModules as $name => $module ) {
409  $shouldEmbed = $module->shouldEmbedModule( $context );
410  if ( !$moduleSets || $moduleSets[$idx][0] !== $shouldEmbed ) {
411  $moduleSets[++$idx] = [ $shouldEmbed, [] ];
412  }
413  $moduleSets[$idx][1][$name] = $module;
414  }
415 
416  // Link/embed each set
417  foreach ( $moduleSets as list( $embed, $moduleSet ) ) {
418  $context->setModules( array_keys( $moduleSet ) );
419  if ( $embed ) {
420  // Decide whether to use style or script element
421  if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
422  $chunks[] = Html::inlineStyle(
423  $rl->makeModuleResponse( $context, $moduleSet )
424  );
425  } else {
426  $chunks[] = ResourceLoader::makeInlineScript(
427  $rl->makeModuleResponse( $context, $moduleSet ),
428  $nonce
429  );
430  }
431  } else {
432  // See if we have one or more raw modules
433  $isRaw = false;
434  foreach ( $moduleSet as $key => $module ) {
435  $isRaw |= $module->isRaw();
436  }
437 
438  // Special handling for the user group; because users might change their stuff
439  // on-wiki like user pages, or user preferences; we need to find the highest
440  // timestamp of these user-changeable modules so we can ensure cache misses on change
441  // This should NOT be done for the site group (T29564) because anons get that too
442  // and we shouldn't be putting timestamps in CDN-cached HTML
443  if ( $group === 'user' ) {
444  // Must setModules() before makeVersionQuery()
445  $context->setVersion( $rl->makeVersionQuery( $context ) );
446  }
447 
448  $url = $rl->createLoaderURL( $source, $context, $extraQuery );
449 
450  // Decide whether to use 'style' or 'script' element
451  if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
452  $chunk = Html::linkedStyle( $url );
453  } elseif ( $context->getRaw() || $isRaw ) {
454  $chunk = Html::element( 'script', [
455  // In SpecialJavaScriptTest, QUnit must load synchronous
456  'async' => !isset( $extraQuery['sync'] ),
457  'src' => $url
458  ] );
459  } else {
460  $chunk = ResourceLoader::makeInlineScript(
461  Xml::encodeJsCall( 'mw.loader.load', [ $url ] ),
462  $nonce
463  );
464  }
465 
466  if ( $group == 'noscript' ) {
467  $chunks[] = Html::rawElement( 'noscript', [], $chunk );
468  } else {
469  $chunks[] = $chunk;
470  }
471  }
472  }
473  }
474  }
475 
476  return new WrappedStringList( "\n", $chunks );
477  }
478 }
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
Load and configure a ResourceLoader client on an HTML page.
Definition: ResourceLoaderClientHtml.php:29
ResourceLoaderModule\TYPE_COMBINED
const TYPE_COMBINED
Definition: ResourceLoaderModule.php:39
ResourceLoaderClientHtml\makeContext
static makeContext(ResourceLoaderContext $mainContext, $group, $type, array $extraQuery=[])
Definition: ResourceLoaderClientHtml.php:343
ResourceLoaderClientHtml\getContext
getContext( $group, $type)
Definition: ResourceLoaderClientHtml.php:335
ResourceLoaderContext\getResourceLoader
getResourceLoader()
Definition: ResourceLoaderContext.php:130
captcha-old.count
count
Definition: captcha-old.py:249
ResourceLoaderClientHtml\getData
getData()
Definition: ResourceLoaderClientHtml.php:115
ResourceLoaderClientHtml\getDocumentAttributes
getDocumentAttributes()
Definition: ResourceLoaderClientHtml.php:212
ResourceLoaderContext\getContentOverrideCallback
getContentOverrideCallback()
Return the replaced-content mapping callback.
Definition: ResourceLoaderContext.php:345
$req
this hook is for auditing only $req
Definition: hooks.txt:979
ResourceLoaderClientHtml\setExemptStates
setExemptStates(array $states)
Set state of special modules that are handled by the caller manually.
Definition: ResourceLoaderClientHtml.php:108
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
ResourceLoaderClientHtml\$options
array $options
Definition: ResourceLoaderClientHtml.php:38
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:32
ResourceLoaderClientHtml\$resourceLoader
ResourceLoader $resourceLoader
Definition: ResourceLoaderClientHtml.php:35
ResourceLoaderClientHtml\setConfig
setConfig(array $vars)
Set mw.config variables.
Definition: ResourceLoaderClientHtml.php:77
ResourceLoaderClientHtml\$modules
array $modules
Definition: ResourceLoaderClientHtml.php:44
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:41
ResourceLoaderContext\getRequest
getRequest()
Definition: ResourceLoaderContext.php:144
ResourceLoaderContext\getDebug
getDebug()
Definition: ResourceLoaderContext.php:250
ResourceLoaderClientHtml\$data
array $data
Definition: ResourceLoaderClientHtml.php:53
ResourceLoaderModule\TYPE_SCRIPTS
const TYPE_SCRIPTS
Definition: ResourceLoaderModule.php:37
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
$vars
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition: hooks.txt:2220
array
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
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:175
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:50
ResourceLoaderClientHtml\$moduleStyles
array $moduleStyles
Definition: ResourceLoaderClientHtml.php:47
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
ResourceLoaderClientHtml\getBodyHtml
getBodyHtml()
Definition: ResourceLoaderClientHtml.php:320
$value
$value
Definition: styleTest.css.php:49
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
$ret
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 & $ret
Definition: hooks.txt:1985
ResourceLoaderClientHtml\makeLoad
static makeLoad(ResourceLoaderContext $mainContext, array $modules, $only, array $extraQuery=[], $nonce=null)
Explicily load or embed modules on a page.
Definition: ResourceLoaderClientHtml.php:372
ResourceLoaderClientHtml\setModules
setModules(array $modules)
Ensure one or more modules are loaded.
Definition: ResourceLoaderClientHtml.php:88
ResourceLoaderClientHtml\setModuleStyles
setModuleStyles(array $modules)
Ensure the styles of one or more modules are loaded.
Definition: ResourceLoaderClientHtml.php:97
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
$source
$source
Definition: mwdoc-filter.php:46
ResourceLoaderModule\TYPE_STYLES
const TYPE_STYLES
Definition: ResourceLoaderModule.php:38
ResourceLoaderClientHtml\getLoad
getLoad( $modules, $only, $nonce, array $extraQuery=[])
Definition: ResourceLoaderClientHtml.php:339
options
Using a hook running we can avoid having all this option specific stuff in our mainline code Using the function 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
ResourceLoaderClientHtml\__construct
__construct(ResourceLoaderContext $context, array $options=[])
Definition: ResourceLoaderClientHtml.php:62
ResourceLoaderContext\getRaw
getRaw()
Definition: ResourceLoaderContext.php:273
ResourceLoaderClientHtml\getHeadHtml
getHeadHtml()
The order of elements in the head is as follows:
Definition: ResourceLoaderClientHtml.php:230
$type
$type
Definition: testCompression.php:48