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.
29 class ResourceLoaderClientHtml
{
31 /** @var ResourceLoaderContext */
34 /** @var ResourceLoader */
35 private $resourceLoader;
44 private $modules = [];
47 private $moduleStyles = [];
50 private $exemptStates = [];
56 * @param ResourceLoaderContext $context
57 * @param array $options [optional] Array of options
58 * - 'target': Parameter for modules=startup request, see ResourceLoaderStartUpModule.
59 * - 'safemode': Parameter for modules=startup request, see ResourceLoaderStartUpModule.
60 * - 'nonce': From OutputPage::getCSPNonce().
62 public function __construct( ResourceLoaderContext
$context, array $options = [] ) {
63 $this->context
= $context;
64 $this->resourceLoader
= $context->getResourceLoader();
65 $this->options
= $options +
[
73 * Set mw.config variables.
75 * @param array $vars Array of key/value pairs
77 public function setConfig( array $vars ) {
78 foreach ( $vars as $key => $value ) {
79 $this->config
[$key] = $value;
84 * Ensure one or more modules are loaded.
86 * @param array $modules Array of module names
88 public function setModules( array $modules ) {
89 $this->modules
= $modules;
93 * Ensure the styles of one or more modules are loaded.
95 * @param array $modules Array of module names
97 public function setModuleStyles( array $modules ) {
98 $this->moduleStyles
= $modules;
102 * Set state of special modules that are handled by the caller manually.
104 * See OutputPage::buildExemptModules() for use cases.
106 * @param array $states Module state keyed by module name
108 public function setExemptStates( array $states ) {
109 $this->exemptStates
= $states;
115 private function getData() {
117 // @codeCoverageIgnoreStart
119 // @codeCoverageIgnoreEnd
122 $rl = $this->resourceLoader
;
125 // moduleName => state
129 // Embedding for private modules
134 // Deprecations for style-only modules
135 'styleDeprecations' => [],
138 foreach ( $this->modules
as $name ) {
139 $module = $rl->getModule( $name );
144 $group = $module->getGroup();
145 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_COMBINED
);
146 $shouldEmbed = $module->shouldEmbedModule( $this->context
);
148 if ( ( $group === 'user' ||
$shouldEmbed ) && $module->isKnownEmpty( $context ) ) {
149 // This is a user-specific or embedded module, which means its output
150 // can be specific to the current page or user. As such, we can optimise
151 // the way we load it based on the current version of the module.
152 // Avoid needless embed for empty module, preset ready state.
153 $data['states'][$name] = 'ready';
154 } elseif ( $group === 'user' ||
$shouldEmbed ) {
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';
164 // Load via mw.loader.load()
165 $data['general'][] = $name;
169 foreach ( $this->moduleStyles
as $name ) {
170 $module = $rl->getModule( $name );
175 if ( $module->getType() !== ResourceLoaderModule
::LOAD_STYLES
) {
176 $logger = $rl->getLogger();
177 $logger->error( 'Unexpected general module "{module}" in styles queue.', [
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';
188 $group = $module->getGroup();
189 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_STYLES
);
190 if ( $module->shouldEmbedModule( $this->context
) ) {
191 // Avoid needless embed for private embeds we know are empty.
192 // (Set "ready" state directly instead, which we do a few lines above.)
193 if ( !$module->isKnownEmpty( $context ) ) {
194 // Embed via <style> element
195 $data['embed']['styles'][] = $name;
197 // For other style modules, always request them, regardless of whether they are
198 // currently known to be empty. Because:
199 // 1. Those modules are requested in batch, so there is no extra request overhead
200 // or extra HTML element to be avoided.
201 // 2. Checking isKnownEmpty for those can be expensive and slow down page view
202 // generation (T230260).
203 // 3. We don't want cached HTML to vary on the current state of a module.
204 // If the module becomes non-empty a few minutes later, it should start working
205 // on cached HTML without requiring a purge.
207 // But, user-specific modules:
208 // * ... are used on page views not publicly cached.
209 // * ... are in their own group and thus a require a request we can avoid
210 // * ... have known-empty status preloaded by ResourceLoader.
211 } elseif ( $group !== 'user' ||
!$module->isKnownEmpty( $context ) ) {
212 // Load from load.php?only=styles via <link rel=stylesheet>
213 $data['styles'][] = $name;
215 $deprecation = $module->getDeprecationInformation();
216 if ( $deprecation ) {
217 $data['styleDeprecations'][] = $deprecation;
225 * @return array Attribute key-value pairs for the HTML document element
227 public function getDocumentAttributes() {
228 return [ 'class' => 'client-nojs' ];
232 * The order of elements in the head is as follows:
235 * - Async external script-src.
238 * - Script execution may be blocked on preceeding stylesheets.
239 * - Async scripts are not blocked on stylesheets.
240 * - Inline scripts can't be asynchronous.
241 * - For styles, earlier is better.
243 * @return string|WrappedStringList HTML
245 public function getHeadHtml() {
246 $nonce = $this->options
['nonce'];
247 $data = $this->getData();
250 // Change "client-nojs" class to client-js. This allows easy toggling of UI components.
251 // This must happen synchronously on every page view to avoid flashes of wrong content.
252 // See also #getDocumentAttributes() and /resources/src/startup.js.
253 $script = <<<'JAVASCRIPT'
254 document.documentElement.className = document.documentElement.className
255 .replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );
258 // Inline script: Declare mw.config variables for this page.
259 if ( $this->config
) {
260 $confJson = ResourceLoader
::encodeJsonForScript( $this->config
);
261 $script .= <<<JAVASCRIPT
262 RLCONF = {$confJson};
266 // Inline script: Declare initial module states for this page.
267 $states = array_merge( $this->exemptStates
, $data['states'] );
269 $stateJson = ResourceLoader
::encodeJsonForScript( $states );
270 $script .= <<<JAVASCRIPT
271 RLSTATE = {$stateJson};
275 // Inline script: Declare general modules to load on this page.
276 if ( $data['general'] ) {
277 $pageModulesJson = ResourceLoader
::encodeJsonForScript( $data['general'] );
278 $script .= <<<JAVASCRIPT
279 RLPAGEMODULES = {$pageModulesJson};
283 if ( !$this->context
->getDebug() ) {
284 $script = ResourceLoader
::filter( 'minify-js', $script, [ 'cache' => false ] );
287 $chunks[] = Html
::inlineScript( $script, $nonce );
289 // Inline RLQ: Embedded modules
290 if ( $data['embed']['general'] ) {
291 $chunks[] = $this->getLoad(
292 $data['embed']['general'],
293 ResourceLoaderModule
::TYPE_COMBINED
,
298 // External stylesheets (only=styles)
299 if ( $data['styles'] ) {
300 $chunks[] = $this->getLoad(
302 ResourceLoaderModule
::TYPE_STYLES
,
307 // Inline stylesheets (embedded only=styles)
308 if ( $data['embed']['styles'] ) {
309 $chunks[] = $this->getLoad(
310 $data['embed']['styles'],
311 ResourceLoaderModule
::TYPE_STYLES
,
316 // Async scripts. Once the startup is loaded, inline RLQ scripts will run.
317 // Pass-through a custom 'target' from OutputPage (T143066).
318 $startupQuery = [ 'raw' => '1' ];
319 foreach ( [ 'target', 'safemode' ] as $param ) {
320 if ( $this->options
[$param] !== null ) {
321 $startupQuery[$param] = (string)$this->options
[$param];
324 $chunks[] = $this->getLoad(
326 ResourceLoaderModule
::TYPE_SCRIPTS
,
331 return WrappedString
::join( "\n", $chunks );
335 * @return string|WrappedStringList HTML
337 public function getBodyHtml() {
338 $data = $this->getData();
341 // Deprecations for only=styles modules
342 if ( $data['styleDeprecations'] ) {
343 $chunks[] = ResourceLoader
::makeInlineScript(
344 implode( '', $data['styleDeprecations'] ),
345 $this->options
['nonce']
349 return WrappedString
::join( "\n", $chunks );
352 private function getContext( $group, $type ) {
353 return self
::makeContext( $this->context
, $group, $type );
356 private function getLoad( $modules, $only, $nonce, array $extraQuery = [] ) {
357 return self
::makeLoad( $this->context
, (array)$modules, $only, $extraQuery, $nonce );
360 private static function makeContext( ResourceLoaderContext
$mainContext, $group, $type,
361 array $extraQuery = []
363 // Create new ResourceLoaderContext so that $extraQuery is supported (eg. for 'sync=1').
364 $req = new FauxRequest( array_merge( $mainContext->getRequest()->getValues(), $extraQuery ) );
365 // Set 'only' if not combined
366 $req->setVal( 'only', $type === ResourceLoaderModule
::TYPE_COMBINED ?
null : $type );
367 // Remove user parameter in most cases
368 if ( $group !== 'user' && $group !== 'private' ) {
369 $req->setVal( 'user', null );
371 $context = new ResourceLoaderContext( $mainContext->getResourceLoader(), $req );
372 // Allow caller to setVersion() and setModules()
373 $ret = new DerivativeResourceLoaderContext( $context );
374 $ret->setContentOverrideCallback( $mainContext->getContentOverrideCallback() );
379 * Explicily load or embed modules on a page.
381 * @param ResourceLoaderContext $mainContext
382 * @param array $modules One or more module names
383 * @param string $only ResourceLoaderModule TYPE_ class constant
384 * @param array $extraQuery [optional] Array with extra query parameters for the request
385 * @param string|null $nonce [optional] Content-Security-Policy nonce
386 * (from OutputPage::getCSPNonce)
387 * @return string|WrappedStringList HTML
389 public static function makeLoad( ResourceLoaderContext
$mainContext, array $modules, $only,
390 array $extraQuery = [], $nonce = null
392 $rl = $mainContext->getResourceLoader();
395 // Sort module names so requests are more uniform
398 if ( $mainContext->getDebug() && count( $modules ) > 1 ) {
400 // Recursively call us for every item
401 foreach ( $modules as $name ) {
402 $chunks[] = self
::makeLoad( $mainContext, [ $name ], $only, $extraQuery, $nonce );
404 return new WrappedStringList( "\n", $chunks );
407 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
409 foreach ( $modules as $name ) {
410 $module = $rl->getModule( $name );
412 $rl->getLogger()->warning( 'Unknown module "{module}"', [ 'module' => $name ] );
415 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
418 foreach ( $sortedModules as $source => $groups ) {
419 foreach ( $groups as $group => $grpModules ) {
420 $context = self
::makeContext( $mainContext, $group, $only, $extraQuery );
422 // Separate sets of linked and embedded modules while preserving order
425 foreach ( $grpModules as $name => $module ) {
426 $shouldEmbed = $module->shouldEmbedModule( $context );
427 if ( !$moduleSets ||
$moduleSets[$idx][0] !== $shouldEmbed ) {
428 $moduleSets[++
$idx] = [ $shouldEmbed, [] ];
430 $moduleSets[$idx][1][$name] = $module;
433 // Link/embed each set
434 foreach ( $moduleSets as list( $embed, $moduleSet ) ) {
435 $context->setModules( array_keys( $moduleSet ) );
437 // Decide whether to use style or script element
438 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
439 $chunks[] = Html
::inlineStyle(
440 $rl->makeModuleResponse( $context, $moduleSet )
443 $chunks[] = ResourceLoader
::makeInlineScript(
444 $rl->makeModuleResponse( $context, $moduleSet ),
449 // Special handling for the user group; because users might change their stuff
450 // on-wiki like user pages, or user preferences; we need to find the highest
451 // timestamp of these user-changeable modules so we can ensure cache misses on change
452 // This should NOT be done for the site group (T29564) because anons get that too
453 // and we shouldn't be putting timestamps in CDN-cached HTML
454 if ( $group === 'user' ) {
455 // Must setModules() before makeVersionQuery()
456 $context->setVersion( $rl->makeVersionQuery( $context ) );
459 $url = $rl->createLoaderURL( $source, $context, $extraQuery );
461 // Decide whether to use 'style' or 'script' element
462 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
463 $chunk = Html
::linkedStyle( $url );
464 } elseif ( $context->getRaw() ) {
465 // This request is asking for the module to be delivered standalone,
466 // (aka "raw") without communicating to any mw.loader client.
468 // - startup (naturally because this is what will define mw.loader)
469 // - html5shiv (loads synchronously in old IE before the async startup module arrives)
470 // - QUnit (needed in SpecialJavaScriptTest before async startup)
471 $chunk = Html
::element( 'script', [
472 // The 'sync' option is only supported in combination with 'raw'.
473 'async' => !isset( $extraQuery['sync'] ),
477 $chunk = ResourceLoader
::makeInlineScript(
478 Xml
::encodeJsCall( 'mw.loader.load', [ $url ] ),
483 if ( $group == 'noscript' ) {
484 $chunks[] = Html
::rawElement( 'noscript', [], $chunk );
493 return new WrappedStringList( "\n", $chunks );