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