Merge "Use {{int:}} on MediaWiki:Blockedtext and MediaWiki:Autoblockedtext"
[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 * @return string|WrappedStringList HTML
252 */
253 public function getHeadHtml() {
254 $data = $this->getData();
255 $chunks = [];
256
257 // Change "client-nojs" class to client-js. This allows easy toggling of UI components.
258 // This happens synchronously on every page view to avoid flashes of wrong content.
259 // See also #getDocumentAttributes() and /resources/src/startup.js.
260 $chunks[] = Html::inlineScript(
261 'document.documentElement.className = document.documentElement.className'
262 . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );'
263 );
264
265 // Inline RLQ: Set page variables
266 if ( $this->config ) {
267 $chunks[] = ResourceLoader::makeInlineScript(
268 ResourceLoader::makeConfigSetScript( $this->config )
269 );
270 }
271
272 // Inline RLQ: Initial module states
273 $states = array_merge( $this->exemptStates, $data['states'] );
274 if ( $states ) {
275 $chunks[] = ResourceLoader::makeInlineScript(
276 ResourceLoader::makeLoaderStateScript( $states )
277 );
278 }
279
280 // Inline RLQ: Embedded modules
281 if ( $data['embed']['general'] ) {
282 $chunks[] = $this->getLoad(
283 $data['embed']['general'],
284 ResourceLoaderModule::TYPE_COMBINED
285 );
286 }
287
288 // Inline RLQ: Load general modules
289 if ( $data['general'] ) {
290 $chunks[] = ResourceLoader::makeInlineScript(
291 Xml::encodeJsCall( 'mw.loader.load', [ $data['general'] ] )
292 );
293 }
294
295 // Inline RLQ: Load only=scripts
296 if ( $data['scripts'] ) {
297 $chunks[] = $this->getLoad(
298 $data['scripts'],
299 ResourceLoaderModule::TYPE_SCRIPTS
300 );
301 }
302
303 // External stylesheets
304 if ( $data['styles'] ) {
305 $chunks[] = $this->getLoad(
306 $data['styles'],
307 ResourceLoaderModule::TYPE_STYLES
308 );
309 }
310
311 // Inline stylesheets (embedded only=styles)
312 if ( $data['embed']['styles'] ) {
313 $chunks[] = $this->getLoad(
314 $data['embed']['styles'],
315 ResourceLoaderModule::TYPE_STYLES
316 );
317 }
318
319 // Async scripts. Once the startup is loaded, inline RLQ scripts will run.
320 // Pass-through a custom 'target' from OutputPage (T143066).
321 $startupQuery = isset( $this->options['target'] )
322 ? [ 'target' => (string)$this->options['target'] ]
323 : [];
324 $chunks[] = $this->getLoad(
325 'startup',
326 ResourceLoaderModule::TYPE_SCRIPTS,
327 $startupQuery
328 );
329
330 return WrappedStringList::join( "\n", $chunks );
331 }
332
333 /**
334 * @return string|WrappedStringList HTML
335 */
336 public function getBodyHtml() {
337 return '';
338 }
339
340 private function getContext( $group, $type ) {
341 return self::makeContext( $this->context, $group, $type );
342 }
343
344 private function getLoad( $modules, $only, array $extraQuery = [] ) {
345 return self::makeLoad( $this->context, (array)$modules, $only, $extraQuery );
346 }
347
348 private static function makeContext( ResourceLoaderContext $mainContext, $group, $type,
349 array $extraQuery = []
350 ) {
351 // Create new ResourceLoaderContext so that $extraQuery may trigger isRaw().
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 * @return string|WrappedStringList HTML
374 */
375 public static function makeLoad( ResourceLoaderContext $mainContext, array $modules, $only,
376 array $extraQuery = []
377 ) {
378 $rl = $mainContext->getResourceLoader();
379 $chunks = [];
380
381 // Sort module names so requests are more uniform
382 sort( $modules );
383
384 if ( $mainContext->getDebug() && count( $modules ) > 1 ) {
385 $chunks = [];
386 // Recursively call us for every item
387 foreach ( $modules as $name ) {
388 $chunks[] = self::makeLoad( $mainContext, [ $name ], $only, $extraQuery );
389 }
390 return new WrappedStringList( "\n", $chunks );
391 }
392
393 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
394 $sortedModules = [];
395 foreach ( $modules as $name ) {
396 $module = $rl->getModule( $name );
397 if ( !$module ) {
398 $rl->getLogger()->warning( 'Unknown module "{module}"', [ 'module' => $name ] );
399 continue;
400 }
401 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
402 }
403
404 foreach ( $sortedModules as $source => $groups ) {
405 foreach ( $groups as $group => $grpModules ) {
406 $context = self::makeContext( $mainContext, $group, $only, $extraQuery );
407
408 // Separate sets of linked and embedded modules while preserving order
409 $moduleSets = [];
410 $idx = -1;
411 foreach ( $grpModules as $name => $module ) {
412 $shouldEmbed = $module->shouldEmbedModule( $context );
413 if ( !$moduleSets || $moduleSets[$idx][0] !== $shouldEmbed ) {
414 $moduleSets[++$idx] = [ $shouldEmbed, [] ];
415 }
416 $moduleSets[$idx][1][$name] = $module;
417 }
418
419 // Link/embed each set
420 foreach ( $moduleSets as list( $embed, $moduleSet ) ) {
421 $context->setModules( array_keys( $moduleSet ) );
422 if ( $embed ) {
423 // Decide whether to use style or script element
424 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
425 $chunks[] = Html::inlineStyle(
426 $rl->makeModuleResponse( $context, $moduleSet )
427 );
428 } else {
429 $chunks[] = ResourceLoader::makeInlineScript(
430 $rl->makeModuleResponse( $context, $moduleSet )
431 );
432 }
433 } else {
434 // See if we have one or more raw modules
435 $isRaw = false;
436 foreach ( $moduleSet as $key => $module ) {
437 $isRaw |= $module->isRaw();
438 }
439
440 // Special handling for the user group; because users might change their stuff
441 // on-wiki like user pages, or user preferences; we need to find the highest
442 // timestamp of these user-changeable modules so we can ensure cache misses on change
443 // This should NOT be done for the site group (T29564) because anons get that too
444 // and we shouldn't be putting timestamps in CDN-cached HTML
445 if ( $group === 'user' ) {
446 // Must setModules() before makeVersionQuery()
447 $context->setVersion( $rl->makeVersionQuery( $context ) );
448 }
449
450 $url = $rl->createLoaderURL( $source, $context, $extraQuery );
451
452 // Decide whether to use 'style' or 'script' element
453 if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
454 $chunk = Html::linkedStyle( $url );
455 } else {
456 if ( $context->getRaw() || $isRaw ) {
457 $chunk = Html::element( 'script', [
458 // In SpecialJavaScriptTest, QUnit must load synchronous
459 'async' => !isset( $extraQuery['sync'] ),
460 'src' => $url
461 ] );
462 } else {
463 $chunk = ResourceLoader::makeInlineScript(
464 Xml::encodeJsCall( 'mw.loader.load', [ $url ] )
465 );
466 }
467 }
468
469 if ( $group == 'noscript' ) {
470 $chunks[] = Html::rawElement( 'noscript', [], $chunk );
471 } else {
472 $chunks[] = $chunk;
473 }
474 }
475 }
476 }
477 }
478
479 return new WrappedStringList( "\n", $chunks );
480 }
481 }