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.
61 * - 'nonce': From OutputPage::getCSPNonce().
63 public function __construct( ResourceLoaderContext
$context, array $options = [] ) {
64 $this->context
= $context;
65 $this->resourceLoader
= $context->getResourceLoader();
66 $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 * @deprecated since 1.28
96 * @param array $modules Array of module names
98 public function setModuleStyles( array $modules ) {
99 $this->moduleStyles
= $modules;
103 * Ensure the scripts of one or more modules are loaded.
105 * @deprecated since 1.28
106 * @param array $modules Array of module names
108 public function setModuleScripts( array $modules ) {
109 $this->moduleScripts
= $modules;
113 * Set state of special modules that are handled by the caller manually.
115 * See OutputPage::buildExemptModules() for use cases.
117 * @param array $states Module state keyed by module name
119 public function setExemptStates( array $states ) {
120 $this->exemptStates
= $states;
126 private function getData() {
128 // @codeCoverageIgnoreStart
130 // @codeCoverageIgnoreEnd
133 $rl = $this->resourceLoader
;
136 // moduleName => state
141 // Embedding for private modules
149 foreach ( $this->modules
as $name ) {
150 $module = $rl->getModule( $name );
155 $group = $module->getGroup();
156 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_COMBINED
);
157 if ( $module->isKnownEmpty( $context ) ) {
158 // Avoid needless request or embed for empty module
159 $data['states'][$name] = 'ready';
163 if ( $group === 'user' ||
$module->shouldEmbedModule( $this->context
) ) {
164 // Call makeLoad() to decide how to load these, instead of
165 // loading via mw.loader.load().
166 // - For group=user: We need to provide a pre-generated load.php
167 // url to the client that has the 'user' and 'version' parameters
168 // filled in. Without this, the client would wrongly use the static
169 // version hash, per T64602.
170 // - For shouldEmbed=true: Embed via mw.loader.implement, per T36907.
171 $data['embed']['general'][] = $name;
172 // Avoid duplicate request from mw.loader
173 $data['states'][$name] = 'loading';
175 // Load via mw.loader.load()
176 $data['general'][] = $name;
180 foreach ( $this->moduleStyles
as $name ) {
181 $module = $rl->getModule( $name );
186 if ( $module->getType() !== ResourceLoaderModule
::LOAD_STYLES
) {
187 $logger = $rl->getLogger();
188 $logger->error( 'Unexpected general module "{module}" in styles queue.', [
194 // Stylesheet doesn't trigger mw.loader callback.
195 // Set "ready" state to allow script modules to depend on this module (T87871).
196 // And to avoid duplicate requests at run-time from mw.loader.
197 $data['states'][$name] = 'ready';
199 $group = $module->getGroup();
200 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_STYLES
);
201 // Avoid needless request for empty module
202 if ( !$module->isKnownEmpty( $context ) ) {
203 if ( $module->shouldEmbedModule( $this->context
) ) {
204 // Embed via style element
205 $data['embed']['styles'][] = $name;
207 // Load from load.php?only=styles via <link rel=stylesheet>
208 $data['styles'][] = $name;
213 foreach ( $this->moduleScripts
as $name ) {
214 $module = $rl->getModule( $name );
219 $group = $module->getGroup();
220 $context = $this->getContext( $group, ResourceLoaderModule
::TYPE_SCRIPTS
);
221 if ( $module->isKnownEmpty( $context ) ) {
222 // Avoid needless request for empty module
223 $data['states'][$name] = 'ready';
225 // Load from load.php?only=scripts via <script src></script>
226 $data['scripts'][] = $name;
228 // Avoid duplicate request from mw.loader
229 $data['states'][$name] = 'loading';
237 * @return array Attribute key-value pairs for the HTML document element
239 public function getDocumentAttributes() {
240 return [ 'class' => 'client-nojs' ];
244 * The order of elements in the head is as follows:
247 * - Async external script-src.
250 * - Script execution may be blocked on preceeding stylesheets.
251 * - Async scripts are not blocked on stylesheets.
252 * - Inline scripts can't be asynchronous.
253 * - For styles, earlier is better.
255 * @return string|WrappedStringList HTML
257 public function getHeadHtml() {
258 $nonce = $this->options
['nonce'];
259 $data = $this->getData();
262 // Change "client-nojs" class to client-js. This allows easy toggling of UI components.
263 // This happens synchronously on every page view to avoid flashes of wrong content.
264 // See also #getDocumentAttributes() and /resources/src/startup.js.
265 $chunks[] = Html
::inlineScript(
266 'document.documentElement.className = document.documentElement.className'
267 . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );',
271 // Inline RLQ: Set page variables
272 if ( $this->config
) {
273 $chunks[] = ResourceLoader
::makeInlineScript(
274 ResourceLoader
::makeConfigSetScript( $this->config
),
279 // Inline RLQ: Initial module states
280 $states = array_merge( $this->exemptStates
, $data['states'] );
282 $chunks[] = ResourceLoader
::makeInlineScript(
283 ResourceLoader
::makeLoaderStateScript( $states ),
288 // Inline RLQ: Embedded modules
289 if ( $data['embed']['general'] ) {
290 $chunks[] = $this->getLoad(
291 $data['embed']['general'],
292 ResourceLoaderModule
::TYPE_COMBINED
,
297 // Inline RLQ: Load general modules
298 if ( $data['general'] ) {
299 $chunks[] = ResourceLoader
::makeInlineScript(
300 Xml
::encodeJsCall( 'mw.loader.load', [ $data['general'] ] ),
305 // Inline RLQ: Load only=scripts
306 if ( $data['scripts'] ) {
307 $chunks[] = $this->getLoad(
309 ResourceLoaderModule
::TYPE_SCRIPTS
,
314 // External stylesheets
315 if ( $data['styles'] ) {
316 $chunks[] = $this->getLoad(
318 ResourceLoaderModule
::TYPE_STYLES
,
323 // Inline stylesheets (embedded only=styles)
324 if ( $data['embed']['styles'] ) {
325 $chunks[] = $this->getLoad(
326 $data['embed']['styles'],
327 ResourceLoaderModule
::TYPE_STYLES
,
332 // Async scripts. Once the startup is loaded, inline RLQ scripts will run.
333 // Pass-through a custom 'target' from OutputPage (T143066).
334 $startupQuery = $this->options
['target'] !== null
335 ?
[ 'target' => (string)$this->options
['target'] ]
337 $chunks[] = $this->getLoad(
339 ResourceLoaderModule
::TYPE_SCRIPTS
,
344 return WrappedStringList
::join( "\n", $chunks );
348 * @return string|WrappedStringList HTML
350 public function getBodyHtml() {
354 private function getContext( $group, $type ) {
355 return self
::makeContext( $this->context
, $group, $type );
358 private function getLoad( $modules, $only, $nonce, array $extraQuery = [] ) {
359 return self
::makeLoad( $this->context
, (array)$modules, $only, $extraQuery, $nonce );
362 private static function makeContext( ResourceLoaderContext
$mainContext, $group, $type,
363 array $extraQuery = []
365 // Create new ResourceLoaderContext so that $extraQuery may trigger isRaw().
366 $req = new FauxRequest( array_merge( $mainContext->getRequest()->getValues(), $extraQuery ) );
367 // Set 'only' if not combined
368 $req->setVal( 'only', $type === ResourceLoaderModule
::TYPE_COMBINED ?
null : $type );
369 // Remove user parameter in most cases
370 if ( $group !== 'user' && $group !== 'private' ) {
371 $req->setVal( 'user', null );
373 $context = new ResourceLoaderContext( $mainContext->getResourceLoader(), $req );
374 // Allow caller to setVersion() and setModules()
375 $ret = new DerivativeResourceLoaderContext( $context );
376 $ret->setContentOverrideCallback( $mainContext->getContentOverrideCallback() );
381 * Explicily load or embed modules on a page.
383 * @param ResourceLoaderContext $mainContext
384 * @param array $modules One or more module names
385 * @param string $only ResourceLoaderModule TYPE_ class constant
386 * @param array $extraQuery [optional] Array with extra query parameters for the request
387 * @param string $nonce [optional] Content-Security-Policy nonce (from OutputPage::getCSPNonce)
388 * @return string|WrappedStringList HTML
390 public static function makeLoad( ResourceLoaderContext
$mainContext, array $modules, $only,
391 array $extraQuery = [], $nonce = null
393 $rl = $mainContext->getResourceLoader();
396 // Sort module names so requests are more uniform
399 if ( $mainContext->getDebug() && count( $modules ) > 1 ) {
401 // Recursively call us for every item
402 foreach ( $modules as $name ) {
403 $chunks[] = self
::makeLoad( $mainContext, [ $name ], $only, $extraQuery, $nonce );
405 return new WrappedStringList( "\n", $chunks );
408 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
410 foreach ( $modules as $name ) {
411 $module = $rl->getModule( $name );
413 $rl->getLogger()->warning( 'Unknown module "{module}"', [ 'module' => $name ] );
416 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
419 foreach ( $sortedModules as $source => $groups ) {
420 foreach ( $groups as $group => $grpModules ) {
421 $context = self
::makeContext( $mainContext, $group, $only, $extraQuery );
423 // Separate sets of linked and embedded modules while preserving order
426 foreach ( $grpModules as $name => $module ) {
427 $shouldEmbed = $module->shouldEmbedModule( $context );
428 if ( !$moduleSets ||
$moduleSets[$idx][0] !== $shouldEmbed ) {
429 $moduleSets[++
$idx] = [ $shouldEmbed, [] ];
431 $moduleSets[$idx][1][$name] = $module;
434 // Link/embed each set
435 foreach ( $moduleSets as list( $embed, $moduleSet ) ) {
436 $context->setModules( array_keys( $moduleSet ) );
438 // Decide whether to use style or script element
439 if ( $only == ResourceLoaderModule
::TYPE_STYLES
) {
440 $chunks[] = Html
::inlineStyle(
441 $rl->makeModuleResponse( $context, $moduleSet )
444 $chunks[] = ResourceLoader
::makeInlineScript(
445 $rl->makeModuleResponse( $context, $moduleSet ),
450 // See if we have one or more raw modules
452 foreach ( $moduleSet as $key => $module ) {
453 $isRaw |
= $module->isRaw();
456 // Special handling for the user group; because users might change their stuff
457 // on-wiki like user pages, or user preferences; we need to find the highest
458 // timestamp of these user-changeable modules so we can ensure cache misses on change
459 // This should NOT be done for the site group (T29564) because anons get that too
460 // and we shouldn't be putting timestamps in CDN-cached HTML
461 if ( $group === 'user' ) {
462 // Must setModules() before makeVersionQuery()
463 $context->setVersion( $rl->makeVersionQuery( $context ) );
466 $url = $rl->createLoaderURL( $source, $context, $extraQuery );
468 // Decide whether to use 'style' or 'script' element
469 if ( $only === ResourceLoaderModule
::TYPE_STYLES
) {
470 $chunk = Html
::linkedStyle( $url );
472 if ( $context->getRaw() ||
$isRaw ) {
473 $chunk = Html
::element( 'script', [
474 // In SpecialJavaScriptTest, QUnit must load synchronous
475 'async' => !isset( $extraQuery['sync'] ),
479 $chunk = ResourceLoader
::makeInlineScript(
480 Xml
::encodeJsCall( 'mw.loader.load', [ $url ] ),
486 if ( $group == 'noscript' ) {
487 $chunks[] = Html
::rawElement( 'noscript', [], $chunk );
496 return new WrappedStringList( "\n", $chunks );