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\WrappedStringList
;
24 * Bootstrap a ResourceLoader client on an HTML page.
28 class ResourceLoaderClientHtml
{
30 /** @var ResourceLoaderContext */
33 /** @var ResourceLoader */
34 private $resourceLoader;
43 private $modules = [];
46 private $moduleStyles = [];
49 private $moduleScripts = [];
52 private $exemptStates = [];
58 * @param ResourceLoaderContext $context
59 * @param array $options [optional] Array of options
60 * - 'target': Parameter for modules=startup request, see ResourceLoaderStartUpModule.
61 * - 'safemode': Parameter for modules=startup request, see ResourceLoaderStartUpModule.
62 * - 'nonce': From OutputPage::getCSPNonce().
64 public function __construct( ResourceLoaderContext
$context, array $options = [] ) {
65 $this->context
= $context;
66 $this->resourceLoader
= $context->getResourceLoader();
67 $this->options
= $options +
[
75 * Set mw.config variables.
77 * @param array $vars Array of key/value pairs
79 public function setConfig( array $vars ) {
80 foreach ( $vars as $key => $value ) {
81 $this->config
[$key] = $value;
86 * Ensure one or more modules are loaded.
88 * @param array $modules Array of module names
90 public function setModules( array $modules ) {
91 $this->modules
= $modules;
95 * Ensure the styles of one or more modules are loaded.
97 * @deprecated since 1.28
98 * @param array $modules Array of module names
100 public function setModuleStyles( array $modules ) {
101 $this->moduleStyles
= $modules;
105 * Ensure the scripts of one or more modules are loaded.
107 * @deprecated since 1.28
108 * @param array $modules Array of module names
110 public function setModuleScripts( array $modules ) {
111 $this->moduleScripts
= $modules;
115 * Set state of special modules that are handled by the caller manually.
117 * See OutputPage::buildExemptModules() for use cases.
119 * @param array $states Module state keyed by module name
121 public function setExemptStates( array $states ) {
122 $this->exemptStates
= $states;
128 private function getData() {
130 // @codeCoverageIgnoreStart
132 // @codeCoverageIgnoreEnd
135 $rl = $this->resourceLoader
;
138 // moduleName => state
143 // Embedding for private modules
148 // Deprecations for style-only modules
149 'styledeprecations' => [],
152 foreach ( $this->modules
as $name ) {
153 $module = $rl->getModule( $name );
158 $group = $module->getGroup();
159 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_COMBINED
);
160 if ( $module->isKnownEmpty( $context ) ) {
161 // Avoid needless request or embed for empty module
162 $data['states'][$name] = 'ready';
166 if ( $group === 'user' ||
$module->shouldEmbedModule( $this->context
) ) {
167 // Call makeLoad() to decide how to load these, instead of
168 // loading via mw.loader.load().
169 // - For group=user: We need to provide a pre-generated load.php
170 // url to the client that has the 'user' and 'version' parameters
171 // filled in. Without this, the client would wrongly use the static
172 // version hash, per T64602.
173 // - For shouldEmbed=true: Embed via mw.loader.implement, per T36907.
174 $data['embed']['general'][] = $name;
175 // Avoid duplicate request from mw.loader
176 $data['states'][$name] = 'loading';
178 // Load via mw.loader.load()
179 $data['general'][] = $name;
183 foreach ( $this->moduleStyles
as $name ) {
184 $module = $rl->getModule( $name );
189 if ( $module->getType() !== ResourceLoaderModule
::LOAD_STYLES
) {
190 $logger = $rl->getLogger();
191 $logger->error( 'Unexpected general module "{module}" in styles queue.', [
197 // Stylesheet doesn't trigger mw.loader callback.
198 // Set "ready" state to allow script modules to depend on this module (T87871).
199 // And to avoid duplicate requests at run-time from mw.loader.
200 $data['states'][$name] = 'ready';
202 $group = $module->getGroup();
203 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_STYLES
);
204 // Avoid needless request for empty module
205 if ( !$module->isKnownEmpty( $context ) ) {
206 if ( $module->shouldEmbedModule( $this->context
) ) {
207 // Embed via style element
208 $data['embed']['styles'][] = $name;
210 // Load from load.php?only=styles via <link rel=stylesheet>
211 $data['styles'][] = $name;
214 $deprecation = $module->getDeprecationInformation();
215 if ( $deprecation ) {
216 $data['styledeprecations'][] = $deprecation;
220 foreach ( $this->moduleScripts
as $name ) {
221 $module = $rl->getModule( $name );
226 $group = $module->getGroup();
227 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_SCRIPTS
);
228 if ( $module->isKnownEmpty( $context ) ) {
229 // Avoid needless request for empty module
230 $data['states'][$name] = 'ready';
232 // Load from load.php?only=scripts via <script src></script>
233 $data['scripts'][] = $name;
235 // Avoid duplicate request from mw.loader
236 $data['states'][$name] = 'loading';
244 * @return array Attribute key-value pairs for the HTML document element
246 public function getDocumentAttributes() {
247 return [ 'class' => 'client-nojs' ];
251 * The order of elements in the head is as follows:
254 * - Async external script-src.
257 * - Script execution may be blocked on preceeding stylesheets.
258 * - Async scripts are not blocked on stylesheets.
259 * - Inline scripts can't be asynchronous.
260 * - For styles, earlier is better.
262 * @return string|WrappedStringList HTML
264 public function getHeadHtml() {
265 $nonce = $this->options
['nonce'];
266 $data = $this->getData();
269 // Change "client-nojs" class to client-js. This allows easy toggling of UI components.
270 // This happens synchronously on every page view to avoid flashes of wrong content.
271 // See also #getDocumentAttributes() and /resources/src/startup.js.
272 $chunks[] = Html
::inlineScript(
273 'document.documentElement.className = document.documentElement.className'
274 . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );',
278 // Inline RLQ: Set page variables
279 if ( $this->config
) {
280 $chunks[] = ResourceLoader
::makeInlineScript(
281 ResourceLoader
::makeConfigSetScript( $this->config
),
286 // Inline RLQ: Initial module states
287 $states = array_merge( $this->exemptStates
, $data['states'] );
289 $chunks[] = ResourceLoader
::makeInlineScript(
290 ResourceLoader
::makeLoaderStateScript( $states ),
295 // Inline RLQ: Embedded modules
296 if ( $data['embed']['general'] ) {
297 $chunks[] = $this->getLoad(
298 $data['embed']['general'],
299 ResourceLoaderModule
::TYPE_COMBINED
,
304 // Inline RLQ: Load general modules
305 if ( $data['general'] ) {
306 $chunks[] = ResourceLoader
::makeInlineScript(
307 Xml
::encodeJsCall( 'mw.loader.load', [ $data['general'] ] ),
312 // Inline RLQ: Load only=scripts
313 if ( $data['scripts'] ) {
314 $chunks[] = $this->getLoad(
316 ResourceLoaderModule
::TYPE_SCRIPTS
,
321 // Deprecations for only=styles modules
322 if ( $data['styledeprecations'] ) {
323 $chunks[] = ResourceLoader
::makeInlineScript(
324 implode( '', $data['styledeprecations'] ),
329 // External stylesheets (only=styles)
330 if ( $data['styles'] ) {
331 $chunks[] = $this->getLoad(
333 ResourceLoaderModule
::TYPE_STYLES
,
338 // Inline stylesheets (embedded only=styles)
339 if ( $data['embed']['styles'] ) {
340 $chunks[] = $this->getLoad(
341 $data['embed']['styles'],
342 ResourceLoaderModule
::TYPE_STYLES
,
347 // Async scripts. Once the startup is loaded, inline RLQ scripts will run.
348 // Pass-through a custom 'target' from OutputPage (T143066).
350 foreach ( [ 'target', 'safemode' ] as $param ) {
351 if ( $this->options
[$param] !== null ) {
352 $startupQuery[$param] = (string)$this->options
[$param];
355 $chunks[] = $this->getLoad(
357 ResourceLoaderModule
::TYPE_SCRIPTS
,
362 return WrappedStringList
::join( "\n", $chunks );
366 * @return string|WrappedStringList HTML
368 public function getBodyHtml() {
372 private function getContext( $group, $type ) {
373 return self
::makeContext( $this->context
, $group, $type );
376 private function getLoad( $modules, $only, $nonce, array $extraQuery = [] ) {
377 return self
::makeLoad( $this->context
, (array)$modules, $only, $extraQuery, $nonce );
380 private static function makeContext( ResourceLoaderContext
$mainContext, $group, $type,
381 array $extraQuery = []
383 // Create new ResourceLoaderContext so that $extraQuery may trigger isRaw().
384 $req = new FauxRequest( array_merge( $mainContext->getRequest()->getValues(), $extraQuery ) );
385 // Set 'only' if not combined
386 $req->setVal( 'only', $type === ResourceLoaderModule
::TYPE_COMBINED ?
null : $type );
387 // Remove user parameter in most cases
388 if ( $group !== 'user' && $group !== 'private' ) {
389 $req->setVal( 'user', null );
391 $context = new ResourceLoaderContext( $mainContext->getResourceLoader(), $req );
392 // Allow caller to setVersion() and setModules()
393 $ret = new DerivativeResourceLoaderContext( $context );
394 $ret->setContentOverrideCallback( $mainContext->getContentOverrideCallback() );
399 * Explicily load or embed modules on a page.
401 * @param ResourceLoaderContext $mainContext
402 * @param array $modules One or more module names
403 * @param string $only ResourceLoaderModule TYPE_ class constant
404 * @param array $extraQuery [optional] Array with extra query parameters for the request
405 * @param string $nonce [optional] Content-Security-Policy nonce (from OutputPage::getCSPNonce)
406 * @return string|WrappedStringList HTML
408 public static function makeLoad( ResourceLoaderContext
$mainContext, array $modules, $only,
409 array $extraQuery = [], $nonce = null
411 $rl = $mainContext->getResourceLoader();
414 // Sort module names so requests are more uniform
417 if ( $mainContext->getDebug() && count( $modules ) > 1 ) {
419 // Recursively call us for every item
420 foreach ( $modules as $name ) {
421 $chunks[] = self
::makeLoad( $mainContext, [ $name ], $only, $extraQuery, $nonce );
423 return new WrappedStringList( "\n", $chunks );
426 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
428 foreach ( $modules as $name ) {
429 $module = $rl->getModule( $name );
431 $rl->getLogger()->warning( 'Unknown module "{module}"', [ 'module' => $name ] );
434 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
437 foreach ( $sortedModules as $source => $groups ) {
438 foreach ( $groups as $group => $grpModules ) {
439 $context = self
::makeContext( $mainContext, $group, $only, $extraQuery );
441 // Separate sets of linked and embedded modules while preserving order
444 foreach ( $grpModules as $name => $module ) {
445 $shouldEmbed = $module->shouldEmbedModule( $context );
446 if ( !$moduleSets ||
$moduleSets[$idx][0] !== $shouldEmbed ) {
447 $moduleSets[++
$idx] = [ $shouldEmbed, [] ];
449 $moduleSets[$idx][1][$name] = $module;
452 // Link/embed each set
453 foreach ( $moduleSets as list( $embed, $moduleSet ) ) {
454 $context->setModules( array_keys( $moduleSet ) );
456 // Decide whether to use style or script element
457 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
458 $chunks[] = Html
::inlineStyle(
459 $rl->makeModuleResponse( $context, $moduleSet )
462 $chunks[] = ResourceLoader
::makeInlineScript(
463 $rl->makeModuleResponse( $context, $moduleSet ),
468 // See if we have one or more raw modules
470 foreach ( $moduleSet as $key => $module ) {
471 $isRaw |
= $module->isRaw();
474 // Special handling for the user group; because users might change their stuff
475 // on-wiki like user pages, or user preferences; we need to find the highest
476 // timestamp of these user-changeable modules so we can ensure cache misses on change
477 // This should NOT be done for the site group (T29564) because anons get that too
478 // and we shouldn't be putting timestamps in CDN-cached HTML
479 if ( $group === 'user' ) {
480 // Must setModules() before makeVersionQuery()
481 $context->setVersion( $rl->makeVersionQuery( $context ) );
484 $url = $rl->createLoaderURL( $source, $context, $extraQuery );
486 // Decide whether to use 'style' or 'script' element
487 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
488 $chunk = Html
::linkedStyle( $url );
490 if ( $context->getRaw() ||
$isRaw ) {
491 $chunk = Html
::element( 'script', [
492 // In SpecialJavaScriptTest, QUnit must load synchronous
493 'async' => !isset( $extraQuery['sync'] ),
497 $chunk = ResourceLoader
::makeInlineScript(
498 Xml
::encodeJsCall( 'mw.loader.load', [ $url ] ),
504 if ( $group == 'noscript' ) {
505 $chunks[] = Html
::rawElement( 'noscript', [], $chunk );
514 return new WrappedStringList( "\n", $chunks );