3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 use Wikimedia\WrappedString
;
22 use Wikimedia\WrappedStringList
;
25 * Load and configure a ResourceLoader client on an HTML page.
27 * @ingroup ResourceLoader
30 class ResourceLoaderClientHtml
{
32 /** @var ResourceLoaderContext */
35 /** @var ResourceLoader */
36 private $resourceLoader;
45 private $modules = [];
48 private $moduleStyles = [];
51 private $exemptStates = [];
57 * @param ResourceLoaderContext $context
58 * @param array $options [optional] Array of options
59 * - 'target': Parameter for modules=startup request, see ResourceLoaderStartUpModule.
60 * - 'safemode': Parameter for modules=startup request, see ResourceLoaderStartUpModule.
61 * - 'nonce': From OutputPage::getCSPNonce().
63 public function __construct( ResourceLoaderContext
$context, array $options = [] ) {
64 $this->context
= $context;
65 $this->resourceLoader
= $context->getResourceLoader();
66 $this->options
= $options +
[
74 * Set mw.config variables.
76 * @param array $vars Array of key/value pairs
78 public function setConfig( array $vars ) {
79 foreach ( $vars as $key => $value ) {
80 $this->config
[$key] = $value;
85 * Ensure one or more modules are loaded.
87 * @param array $modules Array of module names
89 public function setModules( array $modules ) {
90 $this->modules
= $modules;
94 * Ensure the styles of one or more modules are loaded.
96 * @param array $modules Array of module names
98 public function setModuleStyles( array $modules ) {
99 $this->moduleStyles
= $modules;
103 * Set state of special modules that are handled by the caller manually.
105 * See OutputPage::buildExemptModules() for use cases.
107 * @param array $states Module state keyed by module name
109 public function setExemptStates( array $states ) {
110 $this->exemptStates
= $states;
116 private function getData() {
118 // @codeCoverageIgnoreStart
120 // @codeCoverageIgnoreEnd
123 $rl = $this->resourceLoader
;
126 // moduleName => state
130 // Embedding for private modules
135 // Deprecations for style-only modules
136 'styleDeprecations' => [],
139 foreach ( $this->modules
as $name ) {
140 $module = $rl->getModule( $name );
145 $group = $module->getGroup();
146 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_COMBINED
);
147 $shouldEmbed = $module->shouldEmbedModule( $this->context
);
149 if ( ( $group === 'user' ||
$shouldEmbed ) && $module->isKnownEmpty( $context ) ) {
150 // This is a user-specific or embedded module, which means its output
151 // can be specific to the current page or user. As such, we can optimise
152 // the way we load it based on the current version of the module.
153 // Avoid needless embed for empty module, preset ready state.
154 $data['states'][$name] = 'ready';
155 } elseif ( $group === 'user' ||
$shouldEmbed ) {
156 // - For group=user: We need to provide a pre-generated load.php
157 // url to the client that has the 'user' and 'version' parameters
158 // filled in. Without this, the client would wrongly use the static
159 // version hash, per T64602.
160 // - For shouldEmbed=true: Embed via mw.loader.implement, per T36907.
161 $data['embed']['general'][] = $name;
162 // Avoid duplicate request from mw.loader
163 $data['states'][$name] = 'loading';
165 // Load via mw.loader.load()
166 $data['general'][] = $name;
170 foreach ( $this->moduleStyles
as $name ) {
171 $module = $rl->getModule( $name );
176 if ( $module->getType() !== ResourceLoaderModule
::LOAD_STYLES
) {
177 $logger = $rl->getLogger();
178 $logger->error( 'Unexpected general module "{module}" in styles queue.', [
184 // Stylesheet doesn't trigger mw.loader callback.
185 // Set "ready" state to allow script modules to depend on this module (T87871).
186 // And to avoid duplicate requests at run-time from mw.loader.
187 $data['states'][$name] = 'ready';
189 $group = $module->getGroup();
190 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_STYLES
);
191 if ( $module->shouldEmbedModule( $this->context
) ) {
192 // Avoid needless embed for private embeds we know are empty.
193 // (Set "ready" state directly instead, which we do a few lines above.)
194 if ( !$module->isKnownEmpty( $context ) ) {
195 // Embed via <style> element
196 $data['embed']['styles'][] = $name;
198 // For other style modules, always request them, regardless of whether they are
199 // currently known to be empty. Because:
200 // 1. Those modules are requested in batch, so there is no extra request overhead
201 // or extra HTML element to be avoided.
202 // 2. Checking isKnownEmpty for those can be expensive and slow down page view
203 // generation (T230260).
204 // 3. We don't want cached HTML to vary on the current state of a module.
205 // If the module becomes non-empty a few minutes later, it should start working
206 // on cached HTML without requiring a purge.
208 // But, user-specific modules:
209 // * ... are used on page views not publicly cached.
210 // * ... are in their own group and thus a require a request we can avoid
211 // * ... have known-empty status preloaded by ResourceLoader.
212 } elseif ( $group !== 'user' ||
!$module->isKnownEmpty( $context ) ) {
213 // Load from load.php?only=styles via <link rel=stylesheet>
214 $data['styles'][] = $name;
216 $deprecation = $module->getDeprecationInformation();
217 if ( $deprecation ) {
218 $data['styleDeprecations'][] = $deprecation;
226 * @return array Attribute key-value pairs for the HTML document element
228 public function getDocumentAttributes() {
229 return [ 'class' => 'client-nojs' ];
233 * The order of elements in the head is as follows:
236 * - Async external script-src.
239 * - Script execution may be blocked on preceeding stylesheets.
240 * - Async scripts are not blocked on stylesheets.
241 * - Inline scripts can't be asynchronous.
242 * - For styles, earlier is better.
244 * @param string|null $nojsClass Class name that caller uses on HTML document element
245 * @return string|WrappedStringList HTML
247 public function getHeadHtml( $nojsClass = null ) {
248 $nonce = $this->options
['nonce'];
249 $data = $this->getData();
252 // Change "client-nojs" class to client-js. This allows easy toggling of UI components.
253 // This must happen synchronously on every page view to avoid flashes of wrong content.
254 // See also startup/startup.js.
255 $nojsClass = $nojsClass ??
$this->getDocumentAttributes()['class'];
256 $jsClass = preg_replace( '/(^|\s)client-nojs(\s|$)/', '$1client-js$2', $nojsClass );
257 $jsClassJson = ResourceLoader
::encodeJsonForScript( $jsClass );
258 $script = <<<JAVASCRIPT
259 document.documentElement.className = {$jsClassJson};
262 // Inline script: Declare mw.config variables for this page.
263 if ( $this->config
) {
264 $confJson = ResourceLoader
::encodeJsonForScript( $this->config
);
265 $script .= <<<JAVASCRIPT
266 RLCONF = {$confJson};
270 // Inline script: Declare initial module states for this page.
271 $states = array_merge( $this->exemptStates
, $data['states'] );
273 $stateJson = ResourceLoader
::encodeJsonForScript( $states );
274 $script .= <<<JAVASCRIPT
275 RLSTATE = {$stateJson};
279 // Inline script: Declare general modules to load on this page.
280 if ( $data['general'] ) {
281 $pageModulesJson = ResourceLoader
::encodeJsonForScript( $data['general'] );
282 $script .= <<<JAVASCRIPT
283 RLPAGEMODULES = {$pageModulesJson};
287 if ( !$this->context
->getDebug() ) {
288 $script = ResourceLoader
::filter( 'minify-js', $script, [ 'cache' => false ] );
291 $chunks[] = Html
::inlineScript( $script, $nonce );
293 // Inline RLQ: Embedded modules
294 if ( $data['embed']['general'] ) {
295 $chunks[] = $this->getLoad(
296 $data['embed']['general'],
297 ResourceLoaderModule
::TYPE_COMBINED
,
302 // External stylesheets (only=styles)
303 if ( $data['styles'] ) {
304 $chunks[] = $this->getLoad(
306 ResourceLoaderModule
::TYPE_STYLES
,
311 // Inline stylesheets (embedded only=styles)
312 if ( $data['embed']['styles'] ) {
313 $chunks[] = $this->getLoad(
314 $data['embed']['styles'],
315 ResourceLoaderModule
::TYPE_STYLES
,
320 // Async scripts. Once the startup is loaded, inline RLQ scripts will run.
321 // Pass-through a custom 'target' from OutputPage (T143066).
322 $startupQuery = [ 'raw' => '1' ];
323 foreach ( [ 'target', 'safemode' ] as $param ) {
324 if ( $this->options
[$param] !== null ) {
325 $startupQuery[$param] = (string)$this->options
[$param];
328 $chunks[] = $this->getLoad(
330 ResourceLoaderModule
::TYPE_SCRIPTS
,
335 return WrappedString
::join( "\n", $chunks );
339 * @return string|WrappedStringList HTML
341 public function getBodyHtml() {
342 $data = $this->getData();
345 // Deprecations for only=styles modules
346 if ( $data['styleDeprecations'] ) {
347 $chunks[] = ResourceLoader
::makeInlineScript(
348 implode( '', $data['styleDeprecations'] ),
349 $this->options
['nonce']
353 return WrappedString
::join( "\n", $chunks );
356 private function getContext( $group, $type ) {
357 return self
::makeContext( $this->context
, $group, $type );
360 private function getLoad( $modules, $only, $nonce, array $extraQuery = [] ) {
361 return self
::makeLoad( $this->context
, (array)$modules, $only, $extraQuery, $nonce );
364 private static function makeContext( ResourceLoaderContext
$mainContext, $group, $type,
365 array $extraQuery = []
367 // Create new ResourceLoaderContext so that $extraQuery is supported (eg. for 'sync=1').
368 $req = new FauxRequest( array_merge( $mainContext->getRequest()->getValues(), $extraQuery ) );
369 // Set 'only' if not combined
370 $req->setVal( 'only', $type === ResourceLoaderModule
::TYPE_COMBINED ?
null : $type );
371 // Remove user parameter in most cases
372 if ( $group !== 'user' && $group !== 'private' ) {
373 $req->setVal( 'user', null );
375 $context = new ResourceLoaderContext( $mainContext->getResourceLoader(), $req );
376 // Allow caller to setVersion() and setModules()
377 $ret = new DerivativeResourceLoaderContext( $context );
378 $ret->setContentOverrideCallback( $mainContext->getContentOverrideCallback() );
383 * Explicily load or embed modules on a page.
385 * @param ResourceLoaderContext $mainContext
386 * @param array $modules One or more module names
387 * @param string $only ResourceLoaderModule TYPE_ class constant
388 * @param array $extraQuery [optional] Array with extra query parameters for the request
389 * @param string|null $nonce [optional] Content-Security-Policy nonce
390 * (from OutputPage::getCSPNonce)
391 * @return string|WrappedStringList HTML
393 public static function makeLoad( ResourceLoaderContext
$mainContext, array $modules, $only,
394 array $extraQuery = [], $nonce = null
396 $rl = $mainContext->getResourceLoader();
399 // Sort module names so requests are more uniform
402 if ( $mainContext->getDebug() && count( $modules ) > 1 ) {
404 // Recursively call us for every item
405 foreach ( $modules as $name ) {
406 $chunks[] = self
::makeLoad( $mainContext, [ $name ], $only, $extraQuery, $nonce );
408 return new WrappedStringList( "\n", $chunks );
411 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
413 foreach ( $modules as $name ) {
414 $module = $rl->getModule( $name );
416 $rl->getLogger()->warning( 'Unknown module "{module}"', [ 'module' => $name ] );
419 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
422 foreach ( $sortedModules as $source => $groups ) {
423 foreach ( $groups as $group => $grpModules ) {
424 $context = self
::makeContext( $mainContext, $group, $only, $extraQuery );
426 // Separate sets of linked and embedded modules while preserving order
429 foreach ( $grpModules as $name => $module ) {
430 $shouldEmbed = $module->shouldEmbedModule( $context );
431 if ( !$moduleSets ||
$moduleSets[$idx][0] !== $shouldEmbed ) {
432 $moduleSets[++
$idx] = [ $shouldEmbed, [] ];
434 $moduleSets[$idx][1][$name] = $module;
437 // Link/embed each set
438 foreach ( $moduleSets as list( $embed, $moduleSet ) ) {
439 $context->setModules( array_keys( $moduleSet ) );
441 // Decide whether to use style or script element
442 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
443 $chunks[] = Html
::inlineStyle(
444 $rl->makeModuleResponse( $context, $moduleSet )
447 $chunks[] = ResourceLoader
::makeInlineScript(
448 $rl->makeModuleResponse( $context, $moduleSet ),
453 // Special handling for the user group; because users might change their stuff
454 // on-wiki like user pages, or user preferences; we need to find the highest
455 // timestamp of these user-changeable modules so we can ensure cache misses on change
456 // This should NOT be done for the site group (T29564) because anons get that too
457 // and we shouldn't be putting timestamps in CDN-cached HTML
458 if ( $group === 'user' ) {
459 // Must setModules() before makeVersionQuery()
460 $context->setVersion( $rl->makeVersionQuery( $context ) );
463 $url = $rl->createLoaderURL( $source, $context, $extraQuery );
465 // Decide whether to use 'style' or 'script' element
466 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
467 $chunk = Html
::linkedStyle( $url );
468 } elseif ( $context->getRaw() ) {
469 // This request is asking for the module to be delivered standalone,
470 // (aka "raw") without communicating to any mw.loader client.
472 // - startup (naturally because this is what will define mw.loader)
473 // - html5shiv (loads synchronously in old IE before the async startup module arrives)
474 // - QUnit (needed in SpecialJavaScriptTest before async startup)
475 $chunk = Html
::element( 'script', [
476 // The 'sync' option is only supported in combination with 'raw'.
477 'async' => !isset( $extraQuery['sync'] ),
481 $chunk = ResourceLoader
::makeInlineScript(
482 'mw.loader.load(' . ResourceLoader
::encodeJsonForScript( $url ) . ');',
487 if ( $group == 'noscript' ) {
488 $chunks[] = Html
::rawElement( 'noscript', [], $chunk );
497 return new WrappedStringList( "\n", $chunks );