Special:Preferences: Construct fake tabs to avoid FOUC
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoaderClientHtml.php
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 use Wikimedia\WrappedStringList;
22
23 /**
24 * Bootstrap a ResourceLoader client on an HTML page.
25 *
26 * @since 1.28
27 */
28 class ResourceLoaderClientHtml {
29
30 /** @var ResourceLoaderContext */
31 private $context;
32
33 /** @var ResourceLoader */
34 private $resourceLoader;
35
36 /** @var array */
37 private $options;
38
39 /** @var array */
40 private $config = [];
41
42 /** @var array */
43 private $modules = [];
44
45 /** @var array */
46 private $moduleStyles = [];
47
48 /** @var array */
49 private $moduleScripts = [];
50
51 /** @var array */
52 private $exemptStates = [];
53
54 /** @var array */
55 private $data;
56
57 /**
58 * @param ResourceLoaderContext $context
59 * @param array $options [optional] Array of options
60 * - 'target': Custom parameter passed to StartupModule.
61 */
62 public function __construct( ResourceLoaderContext $context, array $options = [] ) {
63 $this->context = $context;
64 $this->resourceLoader = $context->getResourceLoader();
65 $this->options = $options;
66 }
67
68 /**
69 * Set mw.config variables.
70 *
71 * @param array $vars Array of key/value pairs
72 */
73 public function setConfig( array $vars ) {
74 foreach ( $vars as $key => $value ) {
75 $this->config[$key] = $value;
76 }
77 }
78
79 /**
80 * Ensure one or more modules are loaded.
81 *
82 * @param array $modules Array of module names
83 */
84 public function setModules( array $modules ) {
85 $this->modules = $modules;
86 }
87
88 /**
89 * Ensure the styles of one or more modules are loaded.
90 *
91 * @deprecated since 1.28
92 * @param array $modules Array of module names
93 */
94 public function setModuleStyles( array $modules ) {
95 $this->moduleStyles = $modules;
96 }
97
98 /**
99 * Ensure the scripts of one or more modules are loaded.
100 *
101 * @deprecated since 1.28
102 * @param array $modules Array of module names
103 */
104 public function setModuleScripts( array $modules ) {
105 $this->moduleScripts = $modules;
106 }
107
108 /**
109 * Set state of special modules that are handled by the caller manually.
110 *
111 * See OutputPage::buildExemptModules() for use cases.
112 *
113 * @param array $states Module state keyed by module name
114 */
115 public function setExemptStates( array $states ) {
116 $this->exemptStates = $states;
117 }
118
119 /**
120 * @return array
121 */
122 private function getData() {
123 if ( $this->data ) {
124 // @codeCoverageIgnoreStart
125 return $this->data;
126 // @codeCoverageIgnoreEnd
127 }
128
129 $rl = $this->resourceLoader;
130 $data = [
131 'states' => [
132 // moduleName => state
133 ],
134 'general' => [],
135 'styles' => [],
136 'scripts' => [],
137 // Embedding for private modules
138 'embed' => [
139 'styles' => [],
140 'general' => [],
141 ],
142
143 ];
144
145 foreach ( $this->modules as $name ) {
146 $module = $rl->getModule( $name );
147 if ( !$module ) {
148 continue;
149 }
150
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';
156 continue;
157 }
158
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';
170 } else {
171 // Load via mw.loader.load()
172 $data['general'][] = $name;
173 }
174 }
175
176 foreach ( $this->moduleStyles as $name ) {
177 $module = $rl->getModule( $name );
178 if ( !$module ) {
179 continue;
180 }
181
182 if ( $module->getType() !== ResourceLoaderModule::LOAD_STYLES ) {
183 $logger = $rl->getLogger();
184 $logger->error( 'Unexpected general module "{module}" in styles queue.', [
185 'module' => $name,
186 ] );
187 continue;
188 }
189
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';
194
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;
202 } else {
203 // Load from load.php?only=styles via <link rel=stylesheet>
204 $data['styles'][] = $name;
205 }
206 }
207 }
208
209 foreach ( $this->moduleScripts as $name ) {
210 $module = $rl->getModule( $name );
211 if ( !$module ) {
212 continue;
213 }
214
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';
220 } else {
221 // Load from load.php?only=scripts via <script src></script>
222 $data['scripts'][] = $name;
223
224 // Avoid duplicate request from mw.loader
225 $data['states'][$name] = 'loading';
226 }
227 }
228
229 return $data;
230 }
231
232 /**
233 * @return array Attribute key-value pairs for the HTML document element
234 */
235 public function getDocumentAttributes() {
236 return [ 'class' => 'client-nojs' ];
237 }
238
239 /**
240 * The order of elements in the head is as follows:
241 * - Inline scripts.
242 * - Stylesheets.
243 * - Async external script-src.
244 *
245 * Reasons:
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.
250 *
251 * @param string $nonce From OutputPage::getCSPNonce()
252 * @return string|WrappedStringList HTML
253 */
254 public function getHeadHtml( $nonce ) {
255 $data = $this->getData();
256 $chunks = [];
257
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" );',
264 $nonce
265 );
266
267 // Inline RLQ: Set page variables
268 if ( $this->config ) {
269 $chunks[] = ResourceLoader::makeInlineScript(
270 ResourceLoader::makeConfigSetScript( $this->config ),
271 $nonce
272 );
273 }
274
275 // Inline RLQ: Initial module states
276 $states = array_merge( $this->exemptStates, $data['states'] );
277 if ( $states ) {
278 $chunks[] = ResourceLoader::makeInlineScript(
279 ResourceLoader::makeLoaderStateScript( $states ),
280 $nonce
281 );
282 }
283
284 // Inline RLQ: Embedded modules
285 if ( $data['embed']['general'] ) {
286 $chunks[] = $this->getLoad(
287 $data['embed']['general'],
288 ResourceLoaderModule::TYPE_COMBINED,
289 $nonce
290 );
291 }
292
293 // Inline RLQ: Load general modules
294 if ( $data['general'] ) {
295 $chunks[] = ResourceLoader::makeInlineScript(
296 Xml::encodeJsCall( 'mw.loader.load', [ $data['general'] ] ),
297 $nonce
298 );
299 }
300
301 // Inline RLQ: Load only=scripts
302 if ( $data['scripts'] ) {
303 $chunks[] = $this->getLoad(
304 $data['scripts'],
305 ResourceLoaderModule::TYPE_SCRIPTS,
306 $nonce
307 );
308 }
309
310 // External stylesheets
311 if ( $data['styles'] ) {
312 $chunks[] = $this->getLoad(
313 $data['styles'],
314 ResourceLoaderModule::TYPE_STYLES,
315 $nonce
316 );
317 }
318
319 // Inline stylesheets (embedded only=styles)
320 if ( $data['embed']['styles'] ) {
321 $chunks[] = $this->getLoad(
322 $data['embed']['styles'],
323 ResourceLoaderModule::TYPE_STYLES,
324 $nonce
325 );
326 }
327
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'] ]
332 : [];
333 $chunks[] = $this->getLoad(
334 'startup',
335 ResourceLoaderModule::TYPE_SCRIPTS,
336 $nonce,
337 $startupQuery
338 );
339
340 return WrappedStringList::join( "\n", $chunks );
341 }
342
343 /**
344 * @return string|WrappedStringList HTML
345 */
346 public function getBodyHtml() {
347 return '';
348 }
349
350 private function getContext( $group, $type ) {
351 return self::makeContext( $this->context, $group, $type );
352 }
353
354 private function getLoad( $modules, $only, $nonce, array $extraQuery = [] ) {
355 return self::makeLoad( $this->context, (array)$modules, $only, $extraQuery, $nonce );
356 }
357
358 private static function makeContext( ResourceLoaderContext $mainContext, $group, $type,
359 array $extraQuery = []
360 ) {
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 );
368 }
369 $context = new ResourceLoaderContext( $mainContext->getResourceLoader(), $req );
370 // Allow caller to setVersion() and setModules()
371 $ret = new DerivativeResourceLoaderContext( $context );
372 $ret->setContentOverrideCallback( $mainContext->getContentOverrideCallback() );
373 return $ret;
374 }
375
376 /**
377 * Explicily load or embed modules on a page.
378 *
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
385 */
386 public static function makeLoad( ResourceLoaderContext $mainContext, array $modules, $only,
387 array $extraQuery, $nonce
388 ) {
389 $rl = $mainContext->getResourceLoader();
390 $chunks = [];
391
392 // Sort module names so requests are more uniform
393 sort( $modules );
394
395 if ( $mainContext->getDebug() && count( $modules ) > 1 ) {
396 $chunks = [];
397 // Recursively call us for every item
398 foreach ( $modules as $name ) {
399 $chunks[] = self::makeLoad( $mainContext, [ $name ], $only, $extraQuery, $nonce );
400 }
401 return new WrappedStringList( "\n", $chunks );
402 }
403
404 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
405 $sortedModules = [];
406 foreach ( $modules as $name ) {
407 $module = $rl->getModule( $name );
408 if ( !$module ) {
409 $rl->getLogger()->warning( 'Unknown module "{module}"', [ 'module' => $name ] );
410 continue;
411 }
412 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
413 }
414
415 foreach ( $sortedModules as $source => $groups ) {
416 foreach ( $groups as $group => $grpModules ) {
417 $context = self::makeContext( $mainContext, $group, $only, $extraQuery );
418
419 // Separate sets of linked and embedded modules while preserving order
420 $moduleSets = [];
421 $idx = -1;
422 foreach ( $grpModules as $name => $module ) {
423 $shouldEmbed = $module->shouldEmbedModule( $context );
424 if ( !$moduleSets || $moduleSets[$idx][0] !== $shouldEmbed ) {
425 $moduleSets[++$idx] = [ $shouldEmbed, [] ];
426 }
427 $moduleSets[$idx][1][$name] = $module;
428 }
429
430 // Link/embed each set
431 foreach ( $moduleSets as list( $embed, $moduleSet ) ) {
432 $context->setModules( array_keys( $moduleSet ) );
433 if ( $embed ) {
434 // Decide whether to use style or script element
435 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
436 $chunks[] = Html::inlineStyle(
437 $rl->makeModuleResponse( $context, $moduleSet )
438 );
439 } else {
440 $chunks[] = ResourceLoader::makeInlineScript(
441 $rl->makeModuleResponse( $context, $moduleSet ),
442 $nonce
443 );
444 }
445 } else {
446 // See if we have one or more raw modules
447 $isRaw = false;
448 foreach ( $moduleSet as $key => $module ) {
449 $isRaw |= $module->isRaw();
450 }
451
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 ) );
460 }
461
462 $url = $rl->createLoaderURL( $source, $context, $extraQuery );
463
464 // Decide whether to use 'style' or 'script' element
465 if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
466 $chunk = Html::linkedStyle( $url );
467 } else {
468 if ( $context->getRaw() || $isRaw ) {
469 $chunk = Html::element( 'script', [
470 // In SpecialJavaScriptTest, QUnit must load synchronous
471 'async' => !isset( $extraQuery['sync'] ),
472 'src' => $url
473 ] );
474 } else {
475 $chunk = ResourceLoader::makeInlineScript(
476 Xml::encodeJsCall( 'mw.loader.load', [ $url ] ),
477 $nonce
478 );
479 }
480 }
481
482 if ( $group == 'noscript' ) {
483 $chunks[] = Html::rawElement( 'noscript', [], $chunk );
484 } else {
485 $chunks[] = $chunk;
486 }
487 }
488 }
489 }
490 }
491
492 return new WrappedStringList( "\n", $chunks );
493 }
494 }