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 * Bootstrap 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 $moduleScripts = [];
53 private $exemptStates = [];
59 * @param ResourceLoaderContext $context
60 * @param array $options [optional] Array of options
61 * - 'target': Parameter for modules=startup request, see ResourceLoaderStartUpModule.
62 * - 'safemode': Parameter for modules=startup request, see ResourceLoaderStartUpModule.
63 * - 'nonce': From OutputPage::getCSPNonce().
65 public function __construct( ResourceLoaderContext
$context, array $options = [] ) {
66 $this->context
= $context;
67 $this->resourceLoader
= $context->getResourceLoader();
68 $this->options
= $options +
[
76 * Set mw.config variables.
78 * @param array $vars Array of key/value pairs
80 public function setConfig( array $vars ) {
81 foreach ( $vars as $key => $value ) {
82 $this->config
[$key] = $value;
87 * Ensure one or more modules are loaded.
89 * @param array $modules Array of module names
91 public function setModules( array $modules ) {
92 $this->modules
= $modules;
96 * Ensure the styles of one or more modules are loaded.
98 * @deprecated since 1.28
99 * @param array $modules Array of module names
101 public function setModuleStyles( array $modules ) {
102 $this->moduleStyles
= $modules;
106 * Ensure the scripts of one or more modules are loaded.
108 * @deprecated since 1.28
109 * @param array $modules Array of module names
111 public function setModuleScripts( array $modules ) {
112 $this->moduleScripts
= $modules;
116 * Set state of special modules that are handled by the caller manually.
118 * See OutputPage::buildExemptModules() for use cases.
120 * @param array $states Module state keyed by module name
122 public function setExemptStates( array $states ) {
123 $this->exemptStates
= $states;
129 private function getData() {
131 // @codeCoverageIgnoreStart
133 // @codeCoverageIgnoreEnd
136 $rl = $this->resourceLoader
;
139 // moduleName => state
144 // Embedding for private modules
149 // Deprecations for style-only modules
150 'styleDeprecations' => [],
153 foreach ( $this->modules
as $name ) {
154 $module = $rl->getModule( $name );
159 $group = $module->getGroup();
160 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_COMBINED
);
161 if ( $module->isKnownEmpty( $context ) ) {
162 // Avoid needless request or embed for empty module
163 $data['states'][$name] = 'ready';
167 if ( $group === 'user' ||
$module->shouldEmbedModule( $this->context
) ) {
168 // Call makeLoad() to decide how to load these, instead of
169 // loading via mw.loader.load().
170 // - For group=user: We need to provide a pre-generated load.php
171 // url to the client that has the 'user' and 'version' parameters
172 // filled in. Without this, the client would wrongly use the static
173 // version hash, per T64602.
174 // - For shouldEmbed=true: Embed via mw.loader.implement, per T36907.
175 $data['embed']['general'][] = $name;
176 // Avoid duplicate request from mw.loader
177 $data['states'][$name] = 'loading';
179 // Load via mw.loader.load()
180 $data['general'][] = $name;
184 foreach ( $this->moduleStyles
as $name ) {
185 $module = $rl->getModule( $name );
190 if ( $module->getType() !== ResourceLoaderModule
::LOAD_STYLES
) {
191 $logger = $rl->getLogger();
192 $logger->error( 'Unexpected general module "{module}" in styles queue.', [
198 // Stylesheet doesn't trigger mw.loader callback.
199 // Set "ready" state to allow script modules to depend on this module (T87871).
200 // And to avoid duplicate requests at run-time from mw.loader.
201 $data['states'][$name] = 'ready';
203 $group = $module->getGroup();
204 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_STYLES
);
205 // Avoid needless request for empty module
206 if ( !$module->isKnownEmpty( $context ) ) {
207 if ( $module->shouldEmbedModule( $this->context
) ) {
208 // Embed via style element
209 $data['embed']['styles'][] = $name;
211 // Load from load.php?only=styles via <link rel=stylesheet>
212 $data['styles'][] = $name;
215 $deprecation = $module->getDeprecationInformation();
216 if ( $deprecation ) {
217 $data['styleDeprecations'][] = $deprecation;
221 foreach ( $this->moduleScripts
as $name ) {
222 $module = $rl->getModule( $name );
227 $group = $module->getGroup();
228 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_SCRIPTS
);
229 if ( $module->isKnownEmpty( $context ) ) {
230 // Avoid needless request for empty module
231 $data['states'][$name] = 'ready';
233 // Load from load.php?only=scripts via <script src></script>
234 $data['scripts'][] = $name;
236 // Avoid duplicate request from mw.loader
237 $data['states'][$name] = 'loading';
245 * @return array Attribute key-value pairs for the HTML document element
247 public function getDocumentAttributes() {
248 return [ 'class' => 'client-nojs' ];
252 * The order of elements in the head is as follows:
255 * - Async external script-src.
258 * - Script execution may be blocked on preceeding stylesheets.
259 * - Async scripts are not blocked on stylesheets.
260 * - Inline scripts can't be asynchronous.
261 * - For styles, earlier is better.
263 * @return string|WrappedStringList HTML
265 public function getHeadHtml() {
266 $nonce = $this->options
['nonce'];
267 $data = $this->getData();
270 // Change "client-nojs" class to client-js. This allows easy toggling of UI components.
271 // This happens synchronously on every page view to avoid flashes of wrong content.
272 // See also #getDocumentAttributes() and /resources/src/startup.js.
273 $chunks[] = Html
::inlineScript(
274 'document.documentElement.className = document.documentElement.className'
275 . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );',
279 // Inline RLQ: Set page variables
280 if ( $this->config
) {
281 $chunks[] = ResourceLoader
::makeInlineScript(
282 ResourceLoader
::makeConfigSetScript( $this->config
),
287 // Inline RLQ: Initial module states
288 $states = array_merge( $this->exemptStates
, $data['states'] );
290 $chunks[] = ResourceLoader
::makeInlineScript(
291 ResourceLoader
::makeLoaderStateScript( $states ),
296 // Inline RLQ: Embedded modules
297 if ( $data['embed']['general'] ) {
298 $chunks[] = $this->getLoad(
299 $data['embed']['general'],
300 ResourceLoaderModule
::TYPE_COMBINED
,
305 // Inline RLQ: Load general modules
306 if ( $data['general'] ) {
307 $chunks[] = ResourceLoader
::makeInlineScript(
308 Xml
::encodeJsCall( 'mw.loader.load', [ $data['general'] ] ),
313 // Inline RLQ: Load only=scripts
314 if ( $data['scripts'] ) {
315 $chunks[] = $this->getLoad(
317 ResourceLoaderModule
::TYPE_SCRIPTS
,
322 // External stylesheets (only=styles)
323 if ( $data['styles'] ) {
324 $chunks[] = $this->getLoad(
326 ResourceLoaderModule
::TYPE_STYLES
,
331 // Inline stylesheets (embedded only=styles)
332 if ( $data['embed']['styles'] ) {
333 $chunks[] = $this->getLoad(
334 $data['embed']['styles'],
335 ResourceLoaderModule
::TYPE_STYLES
,
340 // Async scripts. Once the startup is loaded, inline RLQ scripts will run.
341 // Pass-through a custom 'target' from OutputPage (T143066).
343 foreach ( [ 'target', 'safemode' ] as $param ) {
344 if ( $this->options
[$param] !== null ) {
345 $startupQuery[$param] = (string)$this->options
[$param];
348 $chunks[] = $this->getLoad(
350 ResourceLoaderModule
::TYPE_SCRIPTS
,
355 return WrappedString
::join( "\n", $chunks );
359 * @return string|WrappedStringList HTML
361 public function getBodyHtml() {
362 $data = $this->getData();
365 // Deprecations for only=styles modules
366 if ( $data['styleDeprecations'] ) {
367 $chunks[] = ResourceLoader
::makeInlineScript(
368 implode( '', $data['styleDeprecations'] ),
369 $this->options
['nonce']
373 return WrappedString
::join( "\n", $chunks );
376 private function getContext( $group, $type ) {
377 return self
::makeContext( $this->context
, $group, $type );
380 private function getLoad( $modules, $only, $nonce, array $extraQuery = [] ) {
381 return self
::makeLoad( $this->context
, (array)$modules, $only, $extraQuery, $nonce );
384 private static function makeContext( ResourceLoaderContext
$mainContext, $group, $type,
385 array $extraQuery = []
387 // Create new ResourceLoaderContext so that $extraQuery may trigger isRaw().
388 $req = new FauxRequest( array_merge( $mainContext->getRequest()->getValues(), $extraQuery ) );
389 // Set 'only' if not combined
390 $req->setVal( 'only', $type === ResourceLoaderModule
::TYPE_COMBINED ?
null : $type );
391 // Remove user parameter in most cases
392 if ( $group !== 'user' && $group !== 'private' ) {
393 $req->setVal( 'user', null );
395 $context = new ResourceLoaderContext( $mainContext->getResourceLoader(), $req );
396 // Allow caller to setVersion() and setModules()
397 $ret = new DerivativeResourceLoaderContext( $context );
398 $ret->setContentOverrideCallback( $mainContext->getContentOverrideCallback() );
403 * Explicily load or embed modules on a page.
405 * @param ResourceLoaderContext $mainContext
406 * @param array $modules One or more module names
407 * @param string $only ResourceLoaderModule TYPE_ class constant
408 * @param array $extraQuery [optional] Array with extra query parameters for the request
409 * @param string $nonce [optional] Content-Security-Policy nonce (from OutputPage::getCSPNonce)
410 * @return string|WrappedStringList HTML
412 public static function makeLoad( ResourceLoaderContext
$mainContext, array $modules, $only,
413 array $extraQuery = [], $nonce = null
415 $rl = $mainContext->getResourceLoader();
418 // Sort module names so requests are more uniform
421 if ( $mainContext->getDebug() && count( $modules ) > 1 ) {
423 // Recursively call us for every item
424 foreach ( $modules as $name ) {
425 $chunks[] = self
::makeLoad( $mainContext, [ $name ], $only, $extraQuery, $nonce );
427 return new WrappedStringList( "\n", $chunks );
430 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
432 foreach ( $modules as $name ) {
433 $module = $rl->getModule( $name );
435 $rl->getLogger()->warning( 'Unknown module "{module}"', [ 'module' => $name ] );
438 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
441 foreach ( $sortedModules as $source => $groups ) {
442 foreach ( $groups as $group => $grpModules ) {
443 $context = self
::makeContext( $mainContext, $group, $only, $extraQuery );
445 // Separate sets of linked and embedded modules while preserving order
448 foreach ( $grpModules as $name => $module ) {
449 $shouldEmbed = $module->shouldEmbedModule( $context );
450 if ( !$moduleSets ||
$moduleSets[$idx][0] !== $shouldEmbed ) {
451 $moduleSets[++
$idx] = [ $shouldEmbed, [] ];
453 $moduleSets[$idx][1][$name] = $module;
456 // Link/embed each set
457 foreach ( $moduleSets as list( $embed, $moduleSet ) ) {
458 $context->setModules( array_keys( $moduleSet ) );
460 // Decide whether to use style or script element
461 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
462 $chunks[] = Html
::inlineStyle(
463 $rl->makeModuleResponse( $context, $moduleSet )
466 $chunks[] = ResourceLoader
::makeInlineScript(
467 $rl->makeModuleResponse( $context, $moduleSet ),
472 // See if we have one or more raw modules
474 foreach ( $moduleSet as $key => $module ) {
475 $isRaw |
= $module->isRaw();
478 // Special handling for the user group; because users might change their stuff
479 // on-wiki like user pages, or user preferences; we need to find the highest
480 // timestamp of these user-changeable modules so we can ensure cache misses on change
481 // This should NOT be done for the site group (T29564) because anons get that too
482 // and we shouldn't be putting timestamps in CDN-cached HTML
483 if ( $group === 'user' ) {
484 // Must setModules() before makeVersionQuery()
485 $context->setVersion( $rl->makeVersionQuery( $context ) );
488 $url = $rl->createLoaderURL( $source, $context, $extraQuery );
490 // Decide whether to use 'style' or 'script' element
491 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
492 $chunk = Html
::linkedStyle( $url );
494 if ( $context->getRaw() ||
$isRaw ) {
495 $chunk = Html
::element( 'script', [
496 // In SpecialJavaScriptTest, QUnit must load synchronous
497 'async' => !isset( $extraQuery['sync'] ),
501 $chunk = ResourceLoader
::makeInlineScript(
502 Xml
::encodeJsCall( 'mw.loader.load', [ $url ] ),
508 if ( $group == 'noscript' ) {
509 $chunks[] = Html
::rawElement( 'noscript', [], $chunk );
518 return new WrappedStringList( "\n", $chunks );