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': Custom parameter passed to StartupModule.
62 public function __construct( ResourceLoaderContext
$context, array $options = [] ) {
63 $this->context
= $context;
64 $this->resourceLoader
= $context->getResourceLoader();
65 $this->options
= $options;
69 * Set mw.config variables.
71 * @param array $vars Array of key/value pairs
73 public function setConfig( array $vars ) {
74 foreach ( $vars as $key => $value ) {
75 $this->config
[$key] = $value;
80 * Ensure one or more modules are loaded.
82 * @param array $modules Array of module names
84 public function setModules( array $modules ) {
85 $this->modules
= $modules;
89 * Ensure the styles of one or more modules are loaded.
91 * @deprecated since 1.28
92 * @param array $modules Array of module names
94 public function setModuleStyles( array $modules ) {
95 $this->moduleStyles
= $modules;
99 * Ensure the scripts of one or more modules are loaded.
101 * @deprecated since 1.28
102 * @param array $modules Array of module names
104 public function setModuleScripts( array $modules ) {
105 $this->moduleScripts
= $modules;
109 * Set state of special modules that are handled by the caller manually.
111 * See OutputPage::buildExemptModules() for use cases.
113 * @param array $states Module state keyed by module name
115 public function setExemptStates( array $states ) {
116 $this->exemptStates
= $states;
122 private function getData() {
124 // @codeCoverageIgnoreStart
126 // @codeCoverageIgnoreEnd
129 $rl = $this->resourceLoader
;
132 // moduleName => state
137 // Embedding for private modules
145 foreach ( $this->modules
as $name ) {
146 $module = $rl->getModule( $name );
151 $group = $module->getGroup();
152 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_COMBINED
);
153 if ( $module->isKnownEmpty( $context ) ) {
154 // Avoid needless request or embed for empty module
155 $data['states'][$name] = 'ready';
159 if ( $group === 'user' ||
$module->shouldEmbedModule( $this->context
) ) {
160 // Call makeLoad() to decide how to load these, instead of
161 // loading via mw.loader.load().
162 // - For group=user: We need to provide a pre-generated load.php
163 // url to the client that has the 'user' and 'version' parameters
164 // filled in. Without this, the client would wrongly use the static
165 // version hash, per T64602.
166 // - For shouldEmbed=true: Embed via mw.loader.implement, per T36907.
167 $data['embed']['general'][] = $name;
168 // Avoid duplicate request from mw.loader
169 $data['states'][$name] = 'loading';
171 // Load via mw.loader.load()
172 $data['general'][] = $name;
176 foreach ( $this->moduleStyles
as $name ) {
177 $module = $rl->getModule( $name );
182 if ( $module->getType() !== ResourceLoaderModule
::LOAD_STYLES
) {
183 $logger = $rl->getLogger();
184 $logger->error( 'Unexpected general module "{module}" in styles queue.', [
190 // Stylesheet doesn't trigger mw.loader callback.
191 // Set "ready" state to allow script modules to depend on this module (T87871).
192 // And to avoid duplicate requests at run-time from mw.loader.
193 $data['states'][$name] = 'ready';
195 $group = $module->getGroup();
196 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_STYLES
);
197 // Avoid needless request for empty module
198 if ( !$module->isKnownEmpty( $context ) ) {
199 if ( $module->shouldEmbedModule( $this->context
) ) {
200 // Embed via style element
201 $data['embed']['styles'][] = $name;
203 // Load from load.php?only=styles via <link rel=stylesheet>
204 $data['styles'][] = $name;
209 foreach ( $this->moduleScripts
as $name ) {
210 $module = $rl->getModule( $name );
215 $group = $module->getGroup();
216 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_SCRIPTS
);
217 if ( $module->isKnownEmpty( $context ) ) {
218 // Avoid needless request for empty module
219 $data['states'][$name] = 'ready';
221 // Load from load.php?only=scripts via <script src></script>
222 $data['scripts'][] = $name;
224 // Avoid duplicate request from mw.loader
225 $data['states'][$name] = 'loading';
233 * @return array Attribute key-value pairs for the HTML document element
235 public function getDocumentAttributes() {
236 return [ 'class' => 'client-nojs' ];
240 * The order of elements in the head is as follows:
243 * - Async external script-src.
246 * - Script execution may be blocked on preceeding stylesheets.
247 * - Async scripts are not blocked on stylesheets.
248 * - Inline scripts can't be asynchronous.
249 * - For styles, earlier is better.
251 * @param string $nonce From OutputPage::getCSPNonce()
252 * @return string|WrappedStringList HTML
254 public function getHeadHtml( $nonce ) {
255 $data = $this->getData();
258 // Change "client-nojs" class to client-js. This allows easy toggling of UI components.
259 // This happens synchronously on every page view to avoid flashes of wrong content.
260 // See also #getDocumentAttributes() and /resources/src/startup.js.
261 $chunks[] = Html
::inlineScript(
262 'document.documentElement.className = document.documentElement.className'
263 . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );',
267 // Inline RLQ: Set page variables
268 if ( $this->config
) {
269 $chunks[] = ResourceLoader
::makeInlineScript(
270 ResourceLoader
::makeConfigSetScript( $this->config
),
275 // Inline RLQ: Initial module states
276 $states = array_merge( $this->exemptStates
, $data['states'] );
278 $chunks[] = ResourceLoader
::makeInlineScript(
279 ResourceLoader
::makeLoaderStateScript( $states ),
284 // Inline RLQ: Embedded modules
285 if ( $data['embed']['general'] ) {
286 $chunks[] = $this->getLoad(
287 $data['embed']['general'],
288 ResourceLoaderModule
::TYPE_COMBINED
,
293 // Inline RLQ: Load general modules
294 if ( $data['general'] ) {
295 $chunks[] = ResourceLoader
::makeInlineScript(
296 Xml
::encodeJsCall( 'mw.loader.load', [ $data['general'] ] ),
301 // Inline RLQ: Load only=scripts
302 if ( $data['scripts'] ) {
303 $chunks[] = $this->getLoad(
305 ResourceLoaderModule
::TYPE_SCRIPTS
,
310 // External stylesheets
311 if ( $data['styles'] ) {
312 $chunks[] = $this->getLoad(
314 ResourceLoaderModule
::TYPE_STYLES
,
319 // Inline stylesheets (embedded only=styles)
320 if ( $data['embed']['styles'] ) {
321 $chunks[] = $this->getLoad(
322 $data['embed']['styles'],
323 ResourceLoaderModule
::TYPE_STYLES
,
328 // Async scripts. Once the startup is loaded, inline RLQ scripts will run.
329 // Pass-through a custom 'target' from OutputPage (T143066).
330 $startupQuery = isset( $this->options
['target'] )
331 ?
[ 'target' => (string)$this->options
['target'] ]
333 $chunks[] = $this->getLoad(
335 ResourceLoaderModule
::TYPE_SCRIPTS
,
340 return WrappedStringList
::join( "\n", $chunks );
344 * @return string|WrappedStringList HTML
346 public function getBodyHtml() {
350 private function getContext( $group, $type ) {
351 return self
::makeContext( $this->context
, $group, $type );
354 private function getLoad( $modules, $only, $nonce, array $extraQuery = [] ) {
355 return self
::makeLoad( $this->context
, (array)$modules, $only, $extraQuery, $nonce );
358 private static function makeContext( ResourceLoaderContext
$mainContext, $group, $type,
359 array $extraQuery = []
361 // Create new ResourceLoaderContext so that $extraQuery may trigger isRaw().
362 $req = new FauxRequest( array_merge( $mainContext->getRequest()->getValues(), $extraQuery ) );
363 // Set 'only' if not combined
364 $req->setVal( 'only', $type === ResourceLoaderModule
::TYPE_COMBINED ?
null : $type );
365 // Remove user parameter in most cases
366 if ( $group !== 'user' && $group !== 'private' ) {
367 $req->setVal( 'user', null );
369 $context = new ResourceLoaderContext( $mainContext->getResourceLoader(), $req );
370 // Allow caller to setVersion() and setModules()
371 $ret = new DerivativeResourceLoaderContext( $context );
372 $ret->setContentOverrideCallback( $mainContext->getContentOverrideCallback() );
377 * Explicily load or embed modules on a page.
379 * @param ResourceLoaderContext $mainContext
380 * @param array $modules One or more module names
381 * @param string $only ResourceLoaderModule TYPE_ class constant
382 * @param array $extraQuery Array with extra query parameters for the request
383 * @param string $nonce See OutputPage::getCSPNonce() [Since 1.32]
384 * @return string|WrappedStringList HTML
386 public static function makeLoad( ResourceLoaderContext
$mainContext, array $modules, $only,
387 array $extraQuery, $nonce
389 $rl = $mainContext->getResourceLoader();
392 // Sort module names so requests are more uniform
395 if ( $mainContext->getDebug() && count( $modules ) > 1 ) {
397 // Recursively call us for every item
398 foreach ( $modules as $name ) {
399 $chunks[] = self
::makeLoad( $mainContext, [ $name ], $only, $extraQuery, $nonce );
401 return new WrappedStringList( "\n", $chunks );
404 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
406 foreach ( $modules as $name ) {
407 $module = $rl->getModule( $name );
409 $rl->getLogger()->warning( 'Unknown module "{module}"', [ 'module' => $name ] );
412 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
415 foreach ( $sortedModules as $source => $groups ) {
416 foreach ( $groups as $group => $grpModules ) {
417 $context = self
::makeContext( $mainContext, $group, $only, $extraQuery );
419 // Separate sets of linked and embedded modules while preserving order
422 foreach ( $grpModules as $name => $module ) {
423 $shouldEmbed = $module->shouldEmbedModule( $context );
424 if ( !$moduleSets ||
$moduleSets[$idx][0] !== $shouldEmbed ) {
425 $moduleSets[++
$idx] = [ $shouldEmbed, [] ];
427 $moduleSets[$idx][1][$name] = $module;
430 // Link/embed each set
431 foreach ( $moduleSets as list( $embed, $moduleSet ) ) {
432 $context->setModules( array_keys( $moduleSet ) );
434 // Decide whether to use style or script element
435 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
436 $chunks[] = Html
::inlineStyle(
437 $rl->makeModuleResponse( $context, $moduleSet )
440 $chunks[] = ResourceLoader
::makeInlineScript(
441 $rl->makeModuleResponse( $context, $moduleSet ),
446 // See if we have one or more raw modules
448 foreach ( $moduleSet as $key => $module ) {
449 $isRaw |
= $module->isRaw();
452 // Special handling for the user group; because users might change their stuff
453 // on-wiki like user pages, or user preferences; we need to find the highest
454 // timestamp of these user-changeable modules so we can ensure cache misses on change
455 // This should NOT be done for the site group (T29564) because anons get that too
456 // and we shouldn't be putting timestamps in CDN-cached HTML
457 if ( $group === 'user' ) {
458 // Must setModules() before makeVersionQuery()
459 $context->setVersion( $rl->makeVersionQuery( $context ) );
462 $url = $rl->createLoaderURL( $source, $context, $extraQuery );
464 // Decide whether to use 'style' or 'script' element
465 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
466 $chunk = Html
::linkedStyle( $url );
468 if ( $context->getRaw() ||
$isRaw ) {
469 $chunk = Html
::element( 'script', [
470 // In SpecialJavaScriptTest, QUnit must load synchronous
471 'async' => !isset( $extraQuery['sync'] ),
475 $chunk = ResourceLoader
::makeInlineScript(
476 Xml
::encodeJsCall( 'mw.loader.load', [ $url ] ),
482 if ( $group == 'noscript' ) {
483 $chunks[] = Html
::rawElement( 'noscript', [], $chunk );
492 return new WrappedStringList( "\n", $chunks );