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 if ( $module->isKnownEmpty( $context ) ) {
147 // Avoid needless request or embed for empty module
148 $data['states'][$name] = 'ready';
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';
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 // 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;
196 // Load from load.php?only=styles via <link rel=stylesheet>
197 $data['styles'][] = $name;
200 $deprecation = $module->getDeprecationInformation();
201 if ( $deprecation ) {
202 $data['styleDeprecations'][] = $deprecation;
210 * @return array Attribute key-value pairs for the HTML document element
212 public function getDocumentAttributes() {
213 return [ 'class' => 'client-nojs' ];
217 * The order of elements in the head is as follows:
220 * - Async external script-src.
223 * - Script execution may be blocked on preceeding stylesheets.
224 * - Async scripts are not blocked on stylesheets.
225 * - Inline scripts can't be asynchronous.
226 * - For styles, earlier is better.
228 * @return string|WrappedStringList HTML
230 public function getHeadHtml() {
231 $nonce = $this->options
['nonce'];
232 $data = $this->getData();
235 // Change "client-nojs" class to client-js. This allows easy toggling of UI components.
236 // This must happen synchronously on every page view to avoid flashes of wrong content.
237 // See also #getDocumentAttributes() and /resources/src/startup.js.
238 $script = <<<'JAVASCRIPT'
239 document.documentElement.className = document.documentElement.className
240 .replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );
243 // Inline script: Declare mw.config variables for this page.
244 if ( $this->config
) {
245 $confJson = ResourceLoader
::encodeJsonForScript( $this->config
);
246 $script .= <<<JAVASCRIPT
247 RLCONF = {$confJson};
251 // Inline script: Declare initial module states for this page.
252 $states = array_merge( $this->exemptStates
, $data['states'] );
254 $stateJson = ResourceLoader
::encodeJsonForScript( $states );
255 $script .= <<<JAVASCRIPT
256 RLSTATE = {$stateJson};
260 // Inline script: Declare general modules to load on this page.
261 if ( $data['general'] ) {
262 $pageModulesJson = ResourceLoader
::encodeJsonForScript( $data['general'] );
263 $script .= <<<JAVASCRIPT
264 RLPAGEMODULES = {$pageModulesJson};
268 if ( !$this->context
->getDebug() ) {
269 $script = ResourceLoader
::filter( 'minify-js', $script, [ 'cache' => false ] );
272 $chunks[] = Html
::inlineScript( $script, $nonce );
274 // Inline RLQ: Embedded modules
275 if ( $data['embed']['general'] ) {
276 $chunks[] = $this->getLoad(
277 $data['embed']['general'],
278 ResourceLoaderModule
::TYPE_COMBINED
,
283 // External stylesheets (only=styles)
284 if ( $data['styles'] ) {
285 $chunks[] = $this->getLoad(
287 ResourceLoaderModule
::TYPE_STYLES
,
292 // Inline stylesheets (embedded only=styles)
293 if ( $data['embed']['styles'] ) {
294 $chunks[] = $this->getLoad(
295 $data['embed']['styles'],
296 ResourceLoaderModule
::TYPE_STYLES
,
301 // Async scripts. Once the startup is loaded, inline RLQ scripts will run.
302 // Pass-through a custom 'target' from OutputPage (T143066).
303 $startupQuery = [ 'raw' => '1' ];
304 foreach ( [ 'target', 'safemode' ] as $param ) {
305 if ( $this->options
[$param] !== null ) {
306 $startupQuery[$param] = (string)$this->options
[$param];
309 $chunks[] = $this->getLoad(
311 ResourceLoaderModule
::TYPE_SCRIPTS
,
316 return WrappedString
::join( "\n", $chunks );
320 * @return string|WrappedStringList HTML
322 public function getBodyHtml() {
323 $data = $this->getData();
326 // Deprecations for only=styles modules
327 if ( $data['styleDeprecations'] ) {
328 $chunks[] = ResourceLoader
::makeInlineScript(
329 implode( '', $data['styleDeprecations'] ),
330 $this->options
['nonce']
334 return WrappedString
::join( "\n", $chunks );
337 private function getContext( $group, $type ) {
338 return self
::makeContext( $this->context
, $group, $type );
341 private function getLoad( $modules, $only, $nonce, array $extraQuery = [] ) {
342 return self
::makeLoad( $this->context
, (array)$modules, $only, $extraQuery, $nonce );
345 private static function makeContext( ResourceLoaderContext
$mainContext, $group, $type,
346 array $extraQuery = []
348 // Create new ResourceLoaderContext so that $extraQuery is supported (eg. for 'sync=1').
349 $req = new FauxRequest( array_merge( $mainContext->getRequest()->getValues(), $extraQuery ) );
350 // Set 'only' if not combined
351 $req->setVal( 'only', $type === ResourceLoaderModule
::TYPE_COMBINED ?
null : $type );
352 // Remove user parameter in most cases
353 if ( $group !== 'user' && $group !== 'private' ) {
354 $req->setVal( 'user', null );
356 $context = new ResourceLoaderContext( $mainContext->getResourceLoader(), $req );
357 // Allow caller to setVersion() and setModules()
358 $ret = new DerivativeResourceLoaderContext( $context );
359 $ret->setContentOverrideCallback( $mainContext->getContentOverrideCallback() );
364 * Explicily load or embed modules on a page.
366 * @param ResourceLoaderContext $mainContext
367 * @param array $modules One or more module names
368 * @param string $only ResourceLoaderModule TYPE_ class constant
369 * @param array $extraQuery [optional] Array with extra query parameters for the request
370 * @param string|null $nonce [optional] Content-Security-Policy nonce
371 * (from OutputPage::getCSPNonce)
372 * @return string|WrappedStringList HTML
374 public static function makeLoad( ResourceLoaderContext
$mainContext, array $modules, $only,
375 array $extraQuery = [], $nonce = null
377 $rl = $mainContext->getResourceLoader();
380 // Sort module names so requests are more uniform
383 if ( $mainContext->getDebug() && count( $modules ) > 1 ) {
385 // Recursively call us for every item
386 foreach ( $modules as $name ) {
387 $chunks[] = self
::makeLoad( $mainContext, [ $name ], $only, $extraQuery, $nonce );
389 return new WrappedStringList( "\n", $chunks );
392 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
394 foreach ( $modules as $name ) {
395 $module = $rl->getModule( $name );
397 $rl->getLogger()->warning( 'Unknown module "{module}"', [ 'module' => $name ] );
400 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
403 foreach ( $sortedModules as $source => $groups ) {
404 foreach ( $groups as $group => $grpModules ) {
405 $context = self
::makeContext( $mainContext, $group, $only, $extraQuery );
407 // Separate sets of linked and embedded modules while preserving order
410 foreach ( $grpModules as $name => $module ) {
411 $shouldEmbed = $module->shouldEmbedModule( $context );
412 if ( !$moduleSets ||
$moduleSets[$idx][0] !== $shouldEmbed ) {
413 $moduleSets[++
$idx] = [ $shouldEmbed, [] ];
415 $moduleSets[$idx][1][$name] = $module;
418 // Link/embed each set
419 foreach ( $moduleSets as list( $embed, $moduleSet ) ) {
420 $context->setModules( array_keys( $moduleSet ) );
422 // Decide whether to use style or script element
423 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
424 $chunks[] = Html
::inlineStyle(
425 $rl->makeModuleResponse( $context, $moduleSet )
428 $chunks[] = ResourceLoader
::makeInlineScript(
429 $rl->makeModuleResponse( $context, $moduleSet ),
434 // Special handling for the user group; because users might change their stuff
435 // on-wiki like user pages, or user preferences; we need to find the highest
436 // timestamp of these user-changeable modules so we can ensure cache misses on change
437 // This should NOT be done for the site group (T29564) because anons get that too
438 // and we shouldn't be putting timestamps in CDN-cached HTML
439 if ( $group === 'user' ) {
440 // Must setModules() before makeVersionQuery()
441 $context->setVersion( $rl->makeVersionQuery( $context ) );
444 $url = $rl->createLoaderURL( $source, $context, $extraQuery );
446 // Decide whether to use 'style' or 'script' element
447 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
448 $chunk = Html
::linkedStyle( $url );
449 } elseif ( $context->getRaw() ) {
450 // This request is asking for the module to be delivered standalone,
451 // (aka "raw") without communicating to any mw.loader client.
453 // - startup (naturally because this is what will define mw.loader)
454 // - html5shiv (loads synchronously in old IE before the async startup module arrives)
455 // - QUnit (needed in SpecialJavaScriptTest before async startup)
456 $chunk = Html
::element( 'script', [
457 // The 'sync' option is only supported in combination with 'raw'.
458 'async' => !isset( $extraQuery['sync'] ),
462 $chunk = ResourceLoader
::makeInlineScript(
463 Xml
::encodeJsCall( 'mw.loader.load', [ $url ] ),
468 if ( $group == 'noscript' ) {
469 $chunks[] = Html
::rawElement( 'noscript', [], $chunk );
478 return new WrappedStringList( "\n", $chunks );