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