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