resourceloader: Refactor CSP $nonce passing
[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 * - 'nonce': From OutputPage::getCSPNonce().
62 */
63 public function __construct( ResourceLoaderContext $context, array $options = [] ) {
64 $this->context = $context;
65 $this->resourceLoader = $context->getResourceLoader();
66 $this->options = $options + [
67 'target' => null,
68 'nonce' => null,
69 ];
70 }
71
72 /**
73 * Set mw.config variables.
74 *
75 * @param array $vars Array of key/value pairs
76 */
77 public function setConfig( array $vars ) {
78 foreach ( $vars as $key => $value ) {
79 $this->config[$key] = $value;
80 }
81 }
82
83 /**
84 * Ensure one or more modules are loaded.
85 *
86 * @param array $modules Array of module names
87 */
88 public function setModules( array $modules ) {
89 $this->modules = $modules;
90 }
91
92 /**
93 * Ensure the styles of one or more modules are loaded.
94 *
95 * @deprecated since 1.28
96 * @param array $modules Array of module names
97 */
98 public function setModuleStyles( array $modules ) {
99 $this->moduleStyles = $modules;
100 }
101
102 /**
103 * Ensure the scripts of one or more modules are loaded.
104 *
105 * @deprecated since 1.28
106 * @param array $modules Array of module names
107 */
108 public function setModuleScripts( array $modules ) {
109 $this->moduleScripts = $modules;
110 }
111
112 /**
113 * Set state of special modules that are handled by the caller manually.
114 *
115 * See OutputPage::buildExemptModules() for use cases.
116 *
117 * @param array $states Module state keyed by module name
118 */
119 public function setExemptStates( array $states ) {
120 $this->exemptStates = $states;
121 }
122
123 /**
124 * @return array
125 */
126 private function getData() {
127 if ( $this->data ) {
128 // @codeCoverageIgnoreStart
129 return $this->data;
130 // @codeCoverageIgnoreEnd
131 }
132
133 $rl = $this->resourceLoader;
134 $data = [
135 'states' => [
136 // moduleName => state
137 ],
138 'general' => [],
139 'styles' => [],
140 'scripts' => [],
141 // Embedding for private modules
142 'embed' => [
143 'styles' => [],
144 'general' => [],
145 ],
146
147 ];
148
149 foreach ( $this->modules as $name ) {
150 $module = $rl->getModule( $name );
151 if ( !$module ) {
152 continue;
153 }
154
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';
160 continue;
161 }
162
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';
174 } else {
175 // Load via mw.loader.load()
176 $data['general'][] = $name;
177 }
178 }
179
180 foreach ( $this->moduleStyles as $name ) {
181 $module = $rl->getModule( $name );
182 if ( !$module ) {
183 continue;
184 }
185
186 if ( $module->getType() !== ResourceLoaderModule::LOAD_STYLES ) {
187 $logger = $rl->getLogger();
188 $logger->error( 'Unexpected general module "{module}" in styles queue.', [
189 'module' => $name,
190 ] );
191 continue;
192 }
193
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';
198
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;
206 } else {
207 // Load from load.php?only=styles via <link rel=stylesheet>
208 $data['styles'][] = $name;
209 }
210 }
211 }
212
213 foreach ( $this->moduleScripts as $name ) {
214 $module = $rl->getModule( $name );
215 if ( !$module ) {
216 continue;
217 }
218
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';
224 } else {
225 // Load from load.php?only=scripts via <script src></script>
226 $data['scripts'][] = $name;
227
228 // Avoid duplicate request from mw.loader
229 $data['states'][$name] = 'loading';
230 }
231 }
232
233 return $data;
234 }
235
236 /**
237 * @return array Attribute key-value pairs for the HTML document element
238 */
239 public function getDocumentAttributes() {
240 return [ 'class' => 'client-nojs' ];
241 }
242
243 /**
244 * The order of elements in the head is as follows:
245 * - Inline scripts.
246 * - Stylesheets.
247 * - Async external script-src.
248 *
249 * Reasons:
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.
254 *
255 * @return string|WrappedStringList HTML
256 */
257 public function getHeadHtml() {
258 $nonce = $this->options['nonce'];
259 $data = $this->getData();
260 $chunks = [];
261
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" );',
268 $nonce
269 );
270
271 // Inline RLQ: Set page variables
272 if ( $this->config ) {
273 $chunks[] = ResourceLoader::makeInlineScript(
274 ResourceLoader::makeConfigSetScript( $this->config ),
275 $nonce
276 );
277 }
278
279 // Inline RLQ: Initial module states
280 $states = array_merge( $this->exemptStates, $data['states'] );
281 if ( $states ) {
282 $chunks[] = ResourceLoader::makeInlineScript(
283 ResourceLoader::makeLoaderStateScript( $states ),
284 $nonce
285 );
286 }
287
288 // Inline RLQ: Embedded modules
289 if ( $data['embed']['general'] ) {
290 $chunks[] = $this->getLoad(
291 $data['embed']['general'],
292 ResourceLoaderModule::TYPE_COMBINED,
293 $nonce
294 );
295 }
296
297 // Inline RLQ: Load general modules
298 if ( $data['general'] ) {
299 $chunks[] = ResourceLoader::makeInlineScript(
300 Xml::encodeJsCall( 'mw.loader.load', [ $data['general'] ] ),
301 $nonce
302 );
303 }
304
305 // Inline RLQ: Load only=scripts
306 if ( $data['scripts'] ) {
307 $chunks[] = $this->getLoad(
308 $data['scripts'],
309 ResourceLoaderModule::TYPE_SCRIPTS,
310 $nonce
311 );
312 }
313
314 // External stylesheets
315 if ( $data['styles'] ) {
316 $chunks[] = $this->getLoad(
317 $data['styles'],
318 ResourceLoaderModule::TYPE_STYLES,
319 $nonce
320 );
321 }
322
323 // Inline stylesheets (embedded only=styles)
324 if ( $data['embed']['styles'] ) {
325 $chunks[] = $this->getLoad(
326 $data['embed']['styles'],
327 ResourceLoaderModule::TYPE_STYLES,
328 $nonce
329 );
330 }
331
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'] ]
336 : [];
337 $chunks[] = $this->getLoad(
338 'startup',
339 ResourceLoaderModule::TYPE_SCRIPTS,
340 $nonce,
341 $startupQuery
342 );
343
344 return WrappedStringList::join( "\n", $chunks );
345 }
346
347 /**
348 * @return string|WrappedStringList HTML
349 */
350 public function getBodyHtml() {
351 return '';
352 }
353
354 private function getContext( $group, $type ) {
355 return self::makeContext( $this->context, $group, $type );
356 }
357
358 private function getLoad( $modules, $only, $nonce, array $extraQuery = [] ) {
359 return self::makeLoad( $this->context, (array)$modules, $only, $extraQuery, $nonce );
360 }
361
362 private static function makeContext( ResourceLoaderContext $mainContext, $group, $type,
363 array $extraQuery = []
364 ) {
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 );
372 }
373 $context = new ResourceLoaderContext( $mainContext->getResourceLoader(), $req );
374 // Allow caller to setVersion() and setModules()
375 $ret = new DerivativeResourceLoaderContext( $context );
376 $ret->setContentOverrideCallback( $mainContext->getContentOverrideCallback() );
377 return $ret;
378 }
379
380 /**
381 * Explicily load or embed modules on a page.
382 *
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
389 */
390 public static function makeLoad( ResourceLoaderContext $mainContext, array $modules, $only,
391 array $extraQuery = [], $nonce = null
392 ) {
393 $rl = $mainContext->getResourceLoader();
394 $chunks = [];
395
396 // Sort module names so requests are more uniform
397 sort( $modules );
398
399 if ( $mainContext->getDebug() && count( $modules ) > 1 ) {
400 $chunks = [];
401 // Recursively call us for every item
402 foreach ( $modules as $name ) {
403 $chunks[] = self::makeLoad( $mainContext, [ $name ], $only, $extraQuery, $nonce );
404 }
405 return new WrappedStringList( "\n", $chunks );
406 }
407
408 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
409 $sortedModules = [];
410 foreach ( $modules as $name ) {
411 $module = $rl->getModule( $name );
412 if ( !$module ) {
413 $rl->getLogger()->warning( 'Unknown module "{module}"', [ 'module' => $name ] );
414 continue;
415 }
416 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
417 }
418
419 foreach ( $sortedModules as $source => $groups ) {
420 foreach ( $groups as $group => $grpModules ) {
421 $context = self::makeContext( $mainContext, $group, $only, $extraQuery );
422
423 // Separate sets of linked and embedded modules while preserving order
424 $moduleSets = [];
425 $idx = -1;
426 foreach ( $grpModules as $name => $module ) {
427 $shouldEmbed = $module->shouldEmbedModule( $context );
428 if ( !$moduleSets || $moduleSets[$idx][0] !== $shouldEmbed ) {
429 $moduleSets[++$idx] = [ $shouldEmbed, [] ];
430 }
431 $moduleSets[$idx][1][$name] = $module;
432 }
433
434 // Link/embed each set
435 foreach ( $moduleSets as list( $embed, $moduleSet ) ) {
436 $context->setModules( array_keys( $moduleSet ) );
437 if ( $embed ) {
438 // Decide whether to use style or script element
439 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
440 $chunks[] = Html::inlineStyle(
441 $rl->makeModuleResponse( $context, $moduleSet )
442 );
443 } else {
444 $chunks[] = ResourceLoader::makeInlineScript(
445 $rl->makeModuleResponse( $context, $moduleSet ),
446 $nonce
447 );
448 }
449 } else {
450 // See if we have one or more raw modules
451 $isRaw = false;
452 foreach ( $moduleSet as $key => $module ) {
453 $isRaw |= $module->isRaw();
454 }
455
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 ) );
464 }
465
466 $url = $rl->createLoaderURL( $source, $context, $extraQuery );
467
468 // Decide whether to use 'style' or 'script' element
469 if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
470 $chunk = Html::linkedStyle( $url );
471 } else {
472 if ( $context->getRaw() || $isRaw ) {
473 $chunk = Html::element( 'script', [
474 // In SpecialJavaScriptTest, QUnit must load synchronous
475 'async' => !isset( $extraQuery['sync'] ),
476 'src' => $url
477 ] );
478 } else {
479 $chunk = ResourceLoader::makeInlineScript(
480 Xml::encodeJsCall( 'mw.loader.load', [ $url ] ),
481 $nonce
482 );
483 }
484 }
485
486 if ( $group == 'noscript' ) {
487 $chunks[] = Html::rawElement( 'noscript', [], $chunk );
488 } else {
489 $chunks[] = $chunk;
490 }
491 }
492 }
493 }
494 }
495
496 return new WrappedStringList( "\n", $chunks );
497 }
498 }