Merge "Selenium: replace UserLoginPage with BlankPage where possible"
[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\WrappedString;
22 use Wikimedia\WrappedStringList;
23
24 /**
25 * Load and configure a ResourceLoader client on an HTML page.
26 *
27 * @since 1.28
28 */
29 class ResourceLoaderClientHtml {
30
31 /** @var ResourceLoaderContext */
32 private $context;
33
34 /** @var ResourceLoader */
35 private $resourceLoader;
36
37 /** @var array */
38 private $options;
39
40 /** @var array */
41 private $config = [];
42
43 /** @var array */
44 private $modules = [];
45
46 /** @var array */
47 private $moduleStyles = [];
48
49 /** @var array */
50 private $exemptStates = [];
51
52 /** @var array */
53 private $data;
54
55 /**
56 * @param ResourceLoaderContext $context
57 * @param array $options [optional] Array of options
58 * - 'target': Parameter for modules=startup request, see ResourceLoaderStartUpModule.
59 * - 'safemode': Parameter for modules=startup request, see ResourceLoaderStartUpModule.
60 * - 'nonce': From OutputPage::getCSPNonce().
61 */
62 public function __construct( ResourceLoaderContext $context, array $options = [] ) {
63 $this->context = $context;
64 $this->resourceLoader = $context->getResourceLoader();
65 $this->options = $options + [
66 'target' => null,
67 'safemode' => 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 * @param array $modules Array of module names
96 */
97 public function setModuleStyles( array $modules ) {
98 $this->moduleStyles = $modules;
99 }
100
101 /**
102 * Set state of special modules that are handled by the caller manually.
103 *
104 * See OutputPage::buildExemptModules() for use cases.
105 *
106 * @param array $states Module state keyed by module name
107 */
108 public function setExemptStates( array $states ) {
109 $this->exemptStates = $states;
110 }
111
112 /**
113 * @return array
114 */
115 private function getData() {
116 if ( $this->data ) {
117 // @codeCoverageIgnoreStart
118 return $this->data;
119 // @codeCoverageIgnoreEnd
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 // Deprecations 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, ResourceLoaderModule::TYPE_COMBINED );
146 if ( $module->isKnownEmpty( $context ) ) {
147 // Avoid needless request or embed for empty module
148 $data['states'][$name] = 'ready';
149 continue;
150 }
151
152 if ( $group === 'user' || $module->shouldEmbedModule( $this->context ) ) {
153 // Call makeLoad() to decide how to load these, instead of
154 // loading via mw.loader.load().
155 // - For group=user: We need to provide a pre-generated load.php
156 // url to the client that has the 'user' and 'version' parameters
157 // filled in. Without this, the client would wrongly use the static
158 // version hash, per T64602.
159 // - For shouldEmbed=true: Embed via mw.loader.implement, per T36907.
160 $data['embed']['general'][] = $name;
161 // Avoid duplicate request from mw.loader
162 $data['states'][$name] = 'loading';
163 } else {
164 // Load via mw.loader.load()
165 $data['general'][] = $name;
166 }
167 }
168
169 foreach ( $this->moduleStyles as $name ) {
170 $module = $rl->getModule( $name );
171 if ( !$module ) {
172 continue;
173 }
174
175 if ( $module->getType() !== ResourceLoaderModule::LOAD_STYLES ) {
176 $logger = $rl->getLogger();
177 $logger->error( 'Unexpected general module "{module}" in styles queue.', [
178 'module' => $name,
179 ] );
180 continue;
181 }
182
183 // Stylesheet doesn't trigger mw.loader callback.
184 // Set "ready" state to allow script modules to depend on this module (T87871).
185 // And to avoid duplicate requests at run-time from mw.loader.
186 $data['states'][$name] = 'ready';
187
188 $group = $module->getGroup();
189 $context = $this->getContext( $group, ResourceLoaderModule::TYPE_STYLES );
190 // Avoid needless request for empty module
191 if ( !$module->isKnownEmpty( $context ) ) {
192 if ( $module->shouldEmbedModule( $this->context ) ) {
193 // Embed via style element
194 $data['embed']['styles'][] = $name;
195 } else {
196 // Load from load.php?only=styles via <link rel=stylesheet>
197 $data['styles'][] = $name;
198 }
199 }
200 $deprecation = $module->getDeprecationInformation();
201 if ( $deprecation ) {
202 $data['styleDeprecations'][] = $deprecation;
203 }
204 }
205
206 return $data;
207 }
208
209 /**
210 * @return array Attribute key-value pairs for the HTML document element
211 */
212 public function getDocumentAttributes() {
213 return [ 'class' => 'client-nojs' ];
214 }
215
216 /**
217 * The order of elements in the head is as follows:
218 * - Inline scripts.
219 * - Stylesheets.
220 * - Async external script-src.
221 *
222 * Reasons:
223 * - Script execution may be blocked on preceeding stylesheets.
224 * - Async scripts are not blocked on stylesheets.
225 * - Inline scripts can't be asynchronous.
226 * - For styles, earlier is better.
227 *
228 * @return string|WrappedStringList HTML
229 */
230 public function getHeadHtml() {
231 $nonce = $this->options['nonce'];
232 $data = $this->getData();
233 $chunks = [];
234
235 // Change "client-nojs" class to client-js. This allows easy toggling of UI components.
236 // This must happen synchronously on every page view to avoid flashes of wrong content.
237 // See also #getDocumentAttributes() and /resources/src/startup.js.
238 $script = <<<JAVASCRIPT
239 document.documentElement.className = document.documentElement.className
240 .replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );
241 JAVASCRIPT;
242
243 // Inline script: Declare mw.config variables for this page.
244 if ( $this->config ) {
245 $confJson = ResourceLoader::encodeJsonForScript( $this->config );
246 $script .= <<<JAVASCRIPT
247 RLCONF = {$confJson};
248 JAVASCRIPT;
249 }
250
251 // Inline script: Declare initial module states for this page.
252 $states = array_merge( $this->exemptStates, $data['states'] );
253 if ( $states ) {
254 $stateJson = ResourceLoader::encodeJsonForScript( $states );
255 $script .= <<<JAVASCRIPT
256 RLSTATE = {$stateJson};
257 JAVASCRIPT;
258 }
259
260 // Inline script: Declare general modules to load on this page.
261 if ( $data['general'] ) {
262 $pageModulesJson = ResourceLoader::encodeJsonForScript( $data['general'] );
263 $script .= <<<JAVASCRIPT
264 RLPAGEMODULES = {$pageModulesJson};
265 JAVASCRIPT;
266 }
267
268 if ( $this->context->getDebug() ) {
269 $chunks[] = Html::inlineScript( $script, $nonce );
270 } else {
271 $chunks[] = Html::inlineScript(
272 ResourceLoader::filter( 'minify-js', $script, [ 'cache' => false ] ),
273 $nonce
274 );
275 }
276
277 // Inline RLQ: Embedded modules
278 if ( $data['embed']['general'] ) {
279 $chunks[] = $this->getLoad(
280 $data['embed']['general'],
281 ResourceLoaderModule::TYPE_COMBINED,
282 $nonce
283 );
284 }
285
286 // External stylesheets (only=styles)
287 if ( $data['styles'] ) {
288 $chunks[] = $this->getLoad(
289 $data['styles'],
290 ResourceLoaderModule::TYPE_STYLES,
291 $nonce
292 );
293 }
294
295 // Inline stylesheets (embedded only=styles)
296 if ( $data['embed']['styles'] ) {
297 $chunks[] = $this->getLoad(
298 $data['embed']['styles'],
299 ResourceLoaderModule::TYPE_STYLES,
300 $nonce
301 );
302 }
303
304 // Async scripts. Once the startup is loaded, inline RLQ scripts will run.
305 // Pass-through a custom 'target' from OutputPage (T143066).
306 $startupQuery = [ 'raw' => '1' ];
307 foreach ( [ 'target', 'safemode' ] as $param ) {
308 if ( $this->options[$param] !== null ) {
309 $startupQuery[$param] = (string)$this->options[$param];
310 }
311 }
312 $chunks[] = $this->getLoad(
313 'startup',
314 ResourceLoaderModule::TYPE_SCRIPTS,
315 $nonce,
316 $startupQuery
317 );
318
319 return WrappedString::join( "\n", $chunks );
320 }
321
322 /**
323 * @return string|WrappedStringList HTML
324 */
325 public function getBodyHtml() {
326 $data = $this->getData();
327 $chunks = [];
328
329 // Deprecations for only=styles modules
330 if ( $data['styleDeprecations'] ) {
331 $chunks[] = ResourceLoader::makeInlineScript(
332 implode( '', $data['styleDeprecations'] ),
333 $this->options['nonce']
334 );
335 }
336
337 return WrappedString::join( "\n", $chunks );
338 }
339
340 private function getContext( $group, $type ) {
341 return self::makeContext( $this->context, $group, $type );
342 }
343
344 private function getLoad( $modules, $only, $nonce, array $extraQuery = [] ) {
345 return self::makeLoad( $this->context, (array)$modules, $only, $extraQuery, $nonce );
346 }
347
348 private static function makeContext( ResourceLoaderContext $mainContext, $group, $type,
349 array $extraQuery = []
350 ) {
351 // Create new ResourceLoaderContext so that $extraQuery is supported (eg. for 'sync=1').
352 $req = new FauxRequest( array_merge( $mainContext->getRequest()->getValues(), $extraQuery ) );
353 // Set 'only' if not combined
354 $req->setVal( 'only', $type === ResourceLoaderModule::TYPE_COMBINED ? null : $type );
355 // Remove user parameter in most cases
356 if ( $group !== 'user' && $group !== 'private' ) {
357 $req->setVal( 'user', null );
358 }
359 $context = new ResourceLoaderContext( $mainContext->getResourceLoader(), $req );
360 // Allow caller to setVersion() and setModules()
361 $ret = new DerivativeResourceLoaderContext( $context );
362 $ret->setContentOverrideCallback( $mainContext->getContentOverrideCallback() );
363 return $ret;
364 }
365
366 /**
367 * Explicily load or embed modules on a page.
368 *
369 * @param ResourceLoaderContext $mainContext
370 * @param array $modules One or more module names
371 * @param string $only ResourceLoaderModule TYPE_ class constant
372 * @param array $extraQuery [optional] Array with extra query parameters for the request
373 * @param string|null $nonce [optional] Content-Security-Policy nonce
374 * (from OutputPage::getCSPNonce)
375 * @return string|WrappedStringList HTML
376 */
377 public static function makeLoad( ResourceLoaderContext $mainContext, array $modules, $only,
378 array $extraQuery = [], $nonce = null
379 ) {
380 $rl = $mainContext->getResourceLoader();
381 $chunks = [];
382
383 // Sort module names so requests are more uniform
384 sort( $modules );
385
386 if ( $mainContext->getDebug() && count( $modules ) > 1 ) {
387 $chunks = [];
388 // Recursively call us for every item
389 foreach ( $modules as $name ) {
390 $chunks[] = self::makeLoad( $mainContext, [ $name ], $only, $extraQuery, $nonce );
391 }
392 return new WrappedStringList( "\n", $chunks );
393 }
394
395 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
396 $sortedModules = [];
397 foreach ( $modules as $name ) {
398 $module = $rl->getModule( $name );
399 if ( !$module ) {
400 $rl->getLogger()->warning( 'Unknown module "{module}"', [ 'module' => $name ] );
401 continue;
402 }
403 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
404 }
405
406 foreach ( $sortedModules as $source => $groups ) {
407 foreach ( $groups as $group => $grpModules ) {
408 $context = self::makeContext( $mainContext, $group, $only, $extraQuery );
409
410 // Separate sets of linked and embedded modules while preserving order
411 $moduleSets = [];
412 $idx = -1;
413 foreach ( $grpModules as $name => $module ) {
414 $shouldEmbed = $module->shouldEmbedModule( $context );
415 if ( !$moduleSets || $moduleSets[$idx][0] !== $shouldEmbed ) {
416 $moduleSets[++$idx] = [ $shouldEmbed, [] ];
417 }
418 $moduleSets[$idx][1][$name] = $module;
419 }
420
421 // Link/embed each set
422 foreach ( $moduleSets as list( $embed, $moduleSet ) ) {
423 $context->setModules( array_keys( $moduleSet ) );
424 if ( $embed ) {
425 // Decide whether to use style or script element
426 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
427 $chunks[] = Html::inlineStyle(
428 $rl->makeModuleResponse( $context, $moduleSet )
429 );
430 } else {
431 $chunks[] = ResourceLoader::makeInlineScript(
432 $rl->makeModuleResponse( $context, $moduleSet ),
433 $nonce
434 );
435 }
436 } else {
437 // Special handling for the user group; because users might change their stuff
438 // on-wiki like user pages, or user preferences; we need to find the highest
439 // timestamp of these user-changeable modules so we can ensure cache misses on change
440 // This should NOT be done for the site group (T29564) because anons get that too
441 // and we shouldn't be putting timestamps in CDN-cached HTML
442 if ( $group === 'user' ) {
443 // Must setModules() before makeVersionQuery()
444 $context->setVersion( $rl->makeVersionQuery( $context ) );
445 }
446
447 $url = $rl->createLoaderURL( $source, $context, $extraQuery );
448
449 // Decide whether to use 'style' or 'script' element
450 if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
451 $chunk = Html::linkedStyle( $url );
452 } elseif ( $context->getRaw() ) {
453 // This request is asking for the module to be delivered standalone,
454 // (aka "raw") without communicating to any mw.loader client.
455 // Use cases:
456 // - startup (naturally because this is what will define mw.loader)
457 // - html5shiv (loads synchronously in old IE before the async startup module arrives)
458 // - QUnit (needed in SpecialJavaScriptTest before async startup)
459 $chunk = Html::element( 'script', [
460 // The 'sync' option is only supported in combination with 'raw'.
461 'async' => !isset( $extraQuery['sync'] ),
462 'src' => $url
463 ] );
464 } else {
465 $chunk = ResourceLoader::makeInlineScript(
466 Xml::encodeJsCall( 'mw.loader.load', [ $url ] ),
467 $nonce
468 );
469 }
470
471 if ( $group == 'noscript' ) {
472 $chunks[] = Html::rawElement( 'noscript', [], $chunk );
473 } else {
474 $chunks[] = $chunk;
475 }
476 }
477 }
478 }
479 }
480
481 return new WrappedStringList( "\n", $chunks );
482 }
483 }