Debian Codegraph @

includes/ResourceLoader/ClientHtml.php

raw symbols SCIP
1 <?php
2 /**
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.
7 *
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.
12 *
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
17 *
18 * @file
19 */
20
21 namespace MediaWiki\ResourceLoader;
22
23 use MediaWiki\Html\Html;
24 use Wikimedia\WrappedString;
25 use Wikimedia\WrappedStringList;
26
27 /**
28 * Load and configure a ResourceLoader client on an HTML page.
29 *
30 * @ingroup ResourceLoader
31 * @since 1.28
32 */
33 class ClientHtml {
34 /** @var Context */
35 private $context;
36
37 /** @var ResourceLoader */
38 private $resourceLoader;
39
40 /** @var array<string,string|null|false> */
41 private $options;
42
43 /** @var array<string,mixed> */
44 private $config = [];
45
46 /** @var string[] */
47 private $modules = [];
48
49 /** @var string[] */
50 private $moduleStyles = [];
51
52 /** @var array<string,string> */
53 private $exemptStates = [];
54
55 /** @var array */
56 private $data;
57
58 /**
59 * @param Context $context
60 * @param array $options [optional] Array of options
61 * - 'target': Parameter for modules=startup request, see StartUpModule.
62 * - 'safemode': Parameter for modules=startup request, see StartUpModule.
63 * - 'clientPrefEnabled': See Skin options.
64 * - 'clientPrefCookiePrefix': See $wgCookiePrefix.
65 */
66 public function __construct( Context $context, array $options = [] ) {
67 $this->context = $context;
68 $this->resourceLoader = $context->getResourceLoader();
69 $this->options = $options + [
70 'target' => null,
71 'safemode' => null,
72 'clientPrefEnabled' => false,
73 'clientPrefCookiePrefix' => '',
74 ];
75 }
76
77 /**
78 * Set mw.config variables.
79 *
80 * @param array $vars Array of key/value pairs
81 */
82 public function setConfig( array $vars ): void {
83 foreach ( $vars as $key => $value ) {
84 $this->config[$key] = $value;
85 }
86 }
87
88 /**
89 * Ensure one or more modules are loaded.
90 *
91 * @param string[] $modules Array of module names
92 */
93 public function setModules( array $modules ): void {
94 $this->modules = $modules;
95 }
96
97 /**
98 * Ensure the styles of one or more modules are loaded.
99 *
100 * @param string[] $modules Array of module names
101 */
102 public function setModuleStyles( array $modules ): void {
103 $this->moduleStyles = $modules;
104 }
105
106 /**
107 * Set state of special modules that are handled by the caller manually.
108 *
109 * See OutputPage::buildExemptModules() for use cases.
110 *
111 * @param array<string,string> $states Module state keyed by module name
112 */
113 public function setExemptStates( array $states ): void {
114 $this->exemptStates = $states;
115 }
116
117 private function getData(): array {
118 if ( $this->data ) {
119 return $this->data;
120 }
121
122 $rl = $this->resourceLoader;
123 $data = [
124 'states' => [
125 // moduleName => state
126 ],
127 'general' => [],
128 'styles' => [],
129 // Embedding for private modules
130 'embed' => [
131 'styles' => [],
132 'general' => [],
133 ],
134 // Deprecation warnings for style-only modules
135 'styleDeprecations' => [],
136 ];
137
138 foreach ( $this->modules as $name ) {
139 $module = $rl->getModule( $name );
140 if ( !$module ) {
141 continue;
142 }
143
144 $group = $module->getGroup();
145 $context = $this->getContext( $group, Module::TYPE_COMBINED );
146 $shouldEmbed = $module->shouldEmbedModule( $this->context );
147
148 if ( ( $group === Module::GROUP_USER || $shouldEmbed ) &&
149 $module->isKnownEmpty( $context ) ) {
150 // This is a user-specific or embedded module, which means its output
151 // can be specific to the current page or user. As such, we can optimise
152 // the way we load it based on the current version of the module.
153 // Avoid needless embed for empty module, preset ready state.
154 $data['states'][$name] = 'ready';
155 } elseif ( $group === Module::GROUP_USER || $shouldEmbed ) {
156 // - For group=user: We need to provide a pre-generated load.php
157 // url to the client that has the 'user' and 'version' parameters
158 // filled in. Without this, the client would wrongly use the static
159 // version hash, per T64602.
160 // - For shouldEmbed=true: Embed via mw.loader.impl, per T36907.
161 $data['embed']['general'][] = $name;
162 // Avoid duplicate request from mw.loader
163 $data['states'][$name] = 'loading';
164 } else {
165 // Load via mw.loader.load()
166 $data['general'][] = $name;
167 }
168 }
169
170 foreach ( $this->moduleStyles as $name ) {
171 $module = $rl->getModule( $name );
172 if ( !$module ) {
173 continue;
174 }
175
176 if ( $module->getType() !== Module::LOAD_STYLES ) {
177 $logger = $rl->getLogger();
178 $logger->error( 'Unexpected general module "{module}" in styles queue.', [
179 'module' => $name,
180 ] );
181 continue;
182 }
183
184 // Stylesheet doesn't trigger mw.loader callback.
185 // Set "ready" state to allow script modules to depend on this module (T87871).
186 // And to avoid duplicate requests at run-time from mw.loader.
187 //
188 // Optimization: Exclude state for "noscript" modules. Since these are also excluded
189 // from the startup registry, no need to send their states (T291735).
190 $group = $module->getGroup();
191 if ( $group !== Module::GROUP_NOSCRIPT ) {
192 $data['states'][$name] = 'ready';
193 }
194
195 $context = $this->getContext( $group, Module::TYPE_STYLES );
196 if ( $module->shouldEmbedModule( $this->context ) ) {
197 // Avoid needless embed for private embeds we know are empty.
198 // (Set "ready" state directly instead, which we do a few lines above.)
199 if ( !$module->isKnownEmpty( $context ) ) {
200 // Embed via <style> element
201 $data['embed']['styles'][] = $name;
202 }
203 // For other style modules, always request them, regardless of whether they are
204 // currently known to be empty. Because:
205 // 1. Those modules are requested in batch, so there is no extra request overhead
206 // or extra HTML element to be avoided.
207 // 2. Checking isKnownEmpty for those can be expensive and slow down page view
208 // generation (T230260).
209 // 3. We don't want cached HTML to vary on the current state of a module.
210 // If the module becomes non-empty a few minutes later, it should start working
211 // on cached HTML without requiring a purge.
212 //
213 // But, user-specific modules:
214 // * ... are used on page views not publicly cached.
215 // * ... are in their own group and thus a require a request we can avoid
216 // * ... have known-empty status preloaded by ResourceLoader.
217 } elseif ( $group !== Module::GROUP_USER || !$module->isKnownEmpty( $context ) ) {
218 // Load from load.php?only=styles via <link rel=stylesheet>
219 $data['styles'][] = $name;
220 }
221 $deprecation = $module->getDeprecationWarning();
222 if ( $deprecation ) {
223 $data['styleDeprecations'][] = $deprecation;
224 }
225 }
226
227 $this->data = $data;
228
229 return $this->data;
230 }
231
232 /**
233 * @return array<string,string> Attributes pairs for the HTML document element
234 */
235 public function getDocumentAttributes() {
236 return [ 'class' => 'client-nojs' ];
237 }
238
239 /**
240 * Set relevant classes on document.documentElement
241 *
242 * @param string|null $nojsClass Class name that Skin will set on HTML document
243 * @return string
244 */
245 private function getDocumentClassNameScript( $nojsClass ) {
246 // Change "client-nojs" to "client-js".
247 // This enables server rendering of UI components, even for those that should be hidden
248 // in Grade C where JavaScript is unsupported, whilst avoiding a flash of wrong content.
249 //
250 // See also Skin:getHtmlElementAttributes() and startup/startup.js.
251 //
252 // Optimisation: Produce shorter and faster JS by only writing to DOM.
253 // This is possible because Skin informs RL about the final value of <html class>, and
254 // because RL already controls the first element in HTML <head> for performance reasons.
255 // - Avoid reading HTMLElement.className
256 // - Avoid executing JS regexes in the common case, by doing the string replace in PHP.
257 $nojsClass ??= $this->getDocumentAttributes()['class'];
258 $jsClass = preg_replace( '/(^|\s)client-nojs(\s|$)/', '$1client-js$2', $nojsClass );
259 $jsClassJson = $this->context->encodeJson( $jsClass );
260
261 // Apply client preferences stored by mw.user.clientPrefs as "class1,class2", where each
262 // item is an <html> class following the pattern "<key>-clientpref-<value>" (T339268)
263 if ( $this->options['clientPrefEnabled'] ) {
264 $cookiePrefix = $this->options['clientPrefCookiePrefix'];
265 $script = strtr(
266 file_get_contents( MW_INSTALL_PATH . '/resources/src/startup/clientprefs.js' ),
267 [
268 '$VARS.jsClass' => $jsClassJson,
269 '__COOKIE_PREFIX__' => $cookiePrefix,
270 ]
271 );
272 } else {
273 $script = "document.documentElement.className = {$jsClassJson};";
274 }
275
276 return $script;
277 }
278
279 /**
280 * The order of elements in the head is as follows:
281 * - Inline scripts.
282 * - Stylesheets.
283 * - Async external script-src.
284 *
285 * Reasons:
286 * - Script execution may be blocked on preceding stylesheets.
287 * - Async scripts are not blocked on stylesheets.
288 * - Inline scripts can't be asynchronous.
289 * - For styles, earlier is better.
290 *
291 * @param string|null $nojsClass Class name that caller uses on HTML document element
292 * @return string|WrappedStringList HTML
293 */
294 public function getHeadHtml( $nojsClass = null ) {
295 $script = $this->getDocumentClassNameScript( $nojsClass );
296
297 // Inline script: Declare mw.config variables for this page.
298 if ( $this->config ) {
299 $confJson = $this->context->encodeJson( $this->config );
300 $script .= "
301 RLCONF = {$confJson};
302 ";
303 }
304
305 $data = $this->getData();
306
307 // Inline script: Declare initial module states for this page.
308 $states = array_merge( $this->exemptStates, $data['states'] );
309 if ( $states ) {
310 $stateJson = $this->context->encodeJson( $states );
311 $script .= "
312 RLSTATE = {$stateJson};
313 ";
314 }
315
316 // Inline script: Declare general modules to load on this page.
317 if ( $data['general'] ) {
318 $pageModulesJson = $this->context->encodeJson( $data['general'] );
319 $script .= "
320 RLPAGEMODULES = {$pageModulesJson};
321 ";
322 }
323
324 if ( !$this->context->getDebug() ) {
325 $script = ResourceLoader::filter( 'minify-js', $script, [ 'cache' => false ] );
326 }
327
328 $chunks = [];
329 $chunks[] = Html::inlineScript( $script );
330
331 // Inline RLQ: Embedded modules
332 if ( $data['embed']['general'] ) {
333 $chunks[] = $this->getLoad(
334 $data['embed']['general'],
335 Module::TYPE_COMBINED
336 );
337 }
338
339 // External stylesheets (only=styles)
340 if ( $data['styles'] ) {
341 $chunks[] = $this->getLoad(
342 $data['styles'],
343 Module::TYPE_STYLES
344 );
345 }
346
347 // Inline stylesheets (embedded only=styles)
348 if ( $data['embed']['styles'] ) {
349 $chunks[] = $this->getLoad(
350 $data['embed']['styles'],
351 Module::TYPE_STYLES
352 );
353 }
354
355 // Async scripts. Once the startup is loaded, inline RLQ scripts will run.
356 // Pass-through a custom 'target' from OutputPage (T143066).
357 $startupQuery = [ 'raw' => '1' ];
358 foreach ( [ 'target', 'safemode' ] as $param ) {
359 if ( $this->options[$param] !== null ) {
360 $startupQuery[$param] = (string)$this->options[$param];
361 }
362 }
363 $chunks[] = $this->getLoad(
364 'startup',
365 Module::TYPE_SCRIPTS,
366 $startupQuery
367 );
368
369 return WrappedString::join( "\n", $chunks );
370 }
371
372 /**
373 * @return string|WrappedStringList HTML
374 */
375 public function getBodyHtml() {
376 $data = $this->getData();
377 $chunks = [];
378
379 // Deprecations for only=styles modules
380 if ( $data['styleDeprecations'] ) {
381 $calls = '';
382 foreach ( $data['styleDeprecations'] as $warning ) {
383 $calls .= Html::encodeJsCall( 'mw.log.warn', [ $warning ] );
384 }
385 $chunks[] = ResourceLoader::makeInlineScript( $calls );
386 }
387
388 return WrappedString::join( "\n", $chunks );
389 }
390
391 private function getContext( $group, $type ): Context {
392 return self::makeContext( $this->context, $group, $type );
393 }
394
395 private function getLoad( $modules, $only, array $extraQuery = [] ) {
396 return self::makeLoad( $this->context, (array)$modules, $only, $extraQuery );
397 }
398
399 private static function makeContext( Context $mainContext, $group, $type,
400 array $extraQuery = []
401 ): DerivativeContext {
402 // Allow caller to setVersion() and setModules()
403 $ret = new DerivativeContext( $mainContext );
404 // Set 'only' if not combined
405 $ret->setOnly( $type === Module::TYPE_COMBINED ? null : $type );
406 // Remove user parameter in most cases
407 if ( $group !== Module::GROUP_USER && $group !== Module::GROUP_PRIVATE ) {
408 $ret->setUser( null );
409 }
410 if ( isset( $extraQuery['raw'] ) ) {
411 $ret->setRaw( true );
412 }
413 return $ret;
414 }
415
416 /**
417 * Explicitly load or embed modules on a page.
418 *
419 * @param Context $mainContext
420 * @param string[] $modules One or more module names
421 * @param string $only Module TYPE_ class constant
422 * @param array $extraQuery [optional] Array with extra query parameters for the request
423 * @return string|WrappedStringList HTML
424 */
425 public static function makeLoad( Context $mainContext, array $modules, $only,
426 array $extraQuery = []
427 ) {
428 $rl = $mainContext->getResourceLoader();
429 $chunks = [];
430
431 // Sort module names so requests are more uniform
432 sort( $modules );
433
434 if ( $mainContext->getDebug() && count( $modules ) > 1 ) {
435 // Recursively call us for every item
436 foreach ( $modules as $name ) {
437 $chunks[] = self::makeLoad( $mainContext, [ $name ], $only, $extraQuery );
438 }
439 return new WrappedStringList( "\n", $chunks );
440 }
441
442 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
443 $sortedModules = [];
444 foreach ( $modules as $name ) {
445 $module = $rl->getModule( $name );
446 if ( !$module ) {
447 $rl->getLogger()->warning( 'Unknown module "{module}"', [ 'module' => $name ] );
448 continue;
449 }
450 $sortedModules[$module->getSource()][$module->getGroup() ?? ''][$name] = $module;
451 }
452
453 foreach ( $sortedModules as $source => $groups ) {
454 foreach ( $groups as $group => $grpModules ) {
455 $context = self::makeContext( $mainContext, $group, $only, $extraQuery );
456
457 // Separate sets of linked and embedded modules while preserving order
458 $moduleSets = [];
459 $idx = -1;
460 foreach ( $grpModules as $name => $module ) {
461 $shouldEmbed = $module->shouldEmbedModule( $context );
462 if ( !$moduleSets || $moduleSets[$idx][0] !== $shouldEmbed ) {
463 $moduleSets[++$idx] = [ $shouldEmbed, [] ];
464 }
465 $moduleSets[$idx][1][$name] = $module;
466 }
467
468 // Link/embed each set
469 foreach ( $moduleSets as [ $embed, $moduleSet ] ) {
470 $moduleSetNames = array_keys( $moduleSet );
471 $context->setModules( $moduleSetNames );
472 if ( $embed ) {
473 $response = $rl->makeModuleResponse( $context, $moduleSet );
474 // Decide whether to use style or script element
475 if ( $only == Module::TYPE_STYLES ) {
476 $chunks[] = Html::inlineStyle( $response );
477 } else {
478 $chunks[] = ResourceLoader::makeInlineScript( $response );
479 }
480 } else {
481 // Not embedded
482
483 // Special handling for the user group; because users might change their stuff
484 // on-wiki like user pages, or user preferences; we need to find the highest
485 // timestamp of these user-changeable modules so we can ensure cache misses on change
486 // This should NOT be done for the site group (T29564) because anons get that too
487 // and we shouldn't be putting timestamps in CDN-cached HTML
488 if ( $group === Module::GROUP_USER ) {
489 $context->setVersion( $rl->makeVersionQuery( $context, $moduleSetNames ) );
490 }
491
492 // Must setModules() before createLoaderURL()
493 $url = $rl->createLoaderURL( $source, $context, $extraQuery );
494
495 // Decide whether to use 'style' or 'script' element
496 if ( $only === Module::TYPE_STYLES ) {
497 $chunk = Html::linkedStyle( $url );
498 } elseif ( $context->getRaw() ) {
499 // This request is asking for the module to be delivered standalone,
500 // (aka "raw") without communicating to any mw.loader client.
501 // For:
502 // - startup (naturally because this is what will define mw.loader)
503 $chunk = Html::element( 'script', [
504 'async' => true,
505 'src' => $url,
506 ] );
507 } else {
508 $chunk = ResourceLoader::makeInlineScript(
509 'mw.loader.load(' . $mainContext->encodeJson( $url ) . ');'
510 );
511 }
512
513 if ( $group == Module::GROUP_NOSCRIPT ) {
514 $chunks[] = Html::rawElement( 'noscript', [], $chunk );
515 } else {
516 $chunks[] = $chunk;
517 }
518 }
519 }
520 }
521 }
522
523 return new WrappedStringList( "\n", $chunks );
524 }
525 }