Merge "Rewrite pref cleanup script"
[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 string|null */
37 private $target;
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 string|null $target [optional] Custom 'target' parameter for the startup module
60 */
61 public function __construct( ResourceLoaderContext $context, $target = null ) {
62 $this->context = $context;
63 $this->resourceLoader = $context->getResourceLoader();
64 $this->target = $target;
65 }
66
67 /**
68 * Set mw.config variables.
69 *
70 * @param array $vars Array of key/value pairs
71 */
72 public function setConfig( array $vars ) {
73 foreach ( $vars as $key => $value ) {
74 $this->config[$key] = $value;
75 }
76 }
77
78 /**
79 * Ensure one or more modules are loaded.
80 *
81 * @param array $modules Array of module names
82 */
83 public function setModules( array $modules ) {
84 $this->modules = $modules;
85 }
86
87 /**
88 * Ensure the styles of one or more modules are loaded.
89 *
90 * @deprecated since 1.28
91 * @param array $modules Array of module names
92 */
93 public function setModuleStyles( array $modules ) {
94 $this->moduleStyles = $modules;
95 }
96
97 /**
98 * Ensure the scripts of one or more modules are loaded.
99 *
100 * @deprecated since 1.28
101 * @param array $modules Array of module names
102 */
103 public function setModuleScripts( array $modules ) {
104 $this->moduleScripts = $modules;
105 }
106
107 /**
108 * Set state of special modules that are handled by the caller manually.
109 *
110 * See OutputPage::buildExemptModules() for use cases.
111 *
112 * @param array $states Module state keyed by module name
113 */
114 public function setExemptStates( array $states ) {
115 $this->exemptStates = $states;
116 }
117
118 /**
119 * @return array
120 */
121 private function getData() {
122 if ( $this->data ) {
123 // @codeCoverageIgnoreStart
124 return $this->data;
125 // @codeCoverageIgnoreEnd
126 }
127
128 $rl = $this->resourceLoader;
129 $data = [
130 'states' => [
131 // moduleName => state
132 ],
133 'general' => [],
134 'styles' => [
135 // moduleName
136 ],
137 'scripts' => [],
138 // Embedding for private modules
139 'embed' => [
140 'styles' => [],
141 'general' => [],
142 ],
143
144 ];
145
146 foreach ( $this->modules as $name ) {
147 $module = $rl->getModule( $name );
148 if ( !$module ) {
149 continue;
150 }
151
152 $context = $this->getContext( $module->getGroup(), 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 ( $module->shouldEmbedModule( $this->context ) ) {
160 // Embed via mw.loader.implement per T36907.
161 $data['embed']['general'][] = $name;
162 // Avoid duplicate request from mw.loader
163 $data['states'][$name] = 'loading';
164 } else {
165 // Load via mw.loader.load()
166 $data['general'][] = $name;
167 }
168 }
169
170 foreach ( $this->moduleStyles as $name ) {
171 $module = $rl->getModule( $name );
172 if ( !$module ) {
173 continue;
174 }
175
176 if ( $module->getType() !== ResourceLoaderModule::LOAD_STYLES ) {
177 $logger = $rl->getLogger();
178 $logger->error( 'Unexpected general module "{module}" in styles queue.', [
179 'module' => $name,
180 ] );
181 continue;
182 }
183
184 // Stylesheet doesn't trigger mw.loader callback.
185 // Set "ready" state to allow dependencies and avoid duplicate requests. (T87871)
186 $data['states'][$name] = 'ready';
187
188 $group = $module->getGroup();
189 $context = $this->getContext( $group, ResourceLoaderModule::TYPE_STYLES );
190 if ( $module->isKnownEmpty( $context ) ) {
191 // Avoid needless request for empty module
192 $data['states'][$name] = 'ready';
193 } else {
194 if ( $module->shouldEmbedModule( $this->context ) ) {
195 // Embed via style element
196 $data['embed']['styles'][] = $name;
197 // Avoid duplicate request from mw.loader
198 $data['states'][$name] = 'ready';
199 } else {
200 // Load from load.php?only=styles via <link rel=stylesheet>
201 $data['styles'][] = $name;
202 }
203 }
204 }
205
206 foreach ( $this->moduleScripts as $name ) {
207 $module = $rl->getModule( $name );
208 if ( !$module ) {
209 continue;
210 }
211
212 $group = $module->getGroup();
213 $context = $this->getContext( $group, ResourceLoaderModule::TYPE_SCRIPTS );
214 if ( $module->isKnownEmpty( $context ) ) {
215 // Avoid needless request for empty module
216 $data['states'][$name] = 'ready';
217 } else {
218 // Load from load.php?only=scripts via <script src></script>
219 $data['scripts'][] = $name;
220
221 // Avoid duplicate request from mw.loader
222 $data['states'][$name] = 'loading';
223 }
224 }
225
226 return $data;
227 }
228
229 /**
230 * @return array Attribute key-value pairs for the HTML document element
231 */
232 public function getDocumentAttributes() {
233 return [ 'class' => 'client-nojs' ];
234 }
235
236 /**
237 * The order of elements in the head is as follows:
238 * - Inline scripts.
239 * - Stylesheets.
240 * - Async external script-src.
241 *
242 * Reasons:
243 * - Script execution may be blocked on preceeding stylesheets.
244 * - Async scripts are not blocked on stylesheets.
245 * - Inline scripts can't be asynchronous.
246 * - For styles, earlier is better.
247 *
248 * @return string|WrappedStringList HTML
249 */
250 public function getHeadHtml() {
251 $data = $this->getData();
252 $chunks = [];
253
254 // Change "client-nojs" class to client-js. This allows easy toggling of UI components.
255 // This happens synchronously on every page view to avoid flashes of wrong content.
256 // See also #getDocumentAttributes() and /resources/src/startup.js.
257 $chunks[] = Html::inlineScript(
258 'document.documentElement.className = document.documentElement.className'
259 . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );'
260 );
261
262 // Inline RLQ: Set page variables
263 if ( $this->config ) {
264 $chunks[] = ResourceLoader::makeInlineScript(
265 ResourceLoader::makeConfigSetScript( $this->config )
266 );
267 }
268
269 // Inline RLQ: Initial module states
270 $states = array_merge( $this->exemptStates, $data['states'] );
271 if ( $states ) {
272 $chunks[] = ResourceLoader::makeInlineScript(
273 ResourceLoader::makeLoaderStateScript( $states )
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 );
283 }
284
285 // Inline RLQ: Load general modules
286 if ( $data['general'] ) {
287 $chunks[] = ResourceLoader::makeInlineScript(
288 Xml::encodeJsCall( 'mw.loader.load', [ $data['general'] ] )
289 );
290 }
291
292 // Inline RLQ: Load only=scripts
293 if ( $data['scripts'] ) {
294 $chunks[] = $this->getLoad(
295 $data['scripts'],
296 ResourceLoaderModule::TYPE_SCRIPTS
297 );
298 }
299
300 // External stylesheets
301 if ( $data['styles'] ) {
302 $chunks[] = $this->getLoad(
303 $data['styles'],
304 ResourceLoaderModule::TYPE_STYLES
305 );
306 }
307
308 // Inline stylesheets (embedded only=styles)
309 if ( $data['embed']['styles'] ) {
310 $chunks[] = $this->getLoad(
311 $data['embed']['styles'],
312 ResourceLoaderModule::TYPE_STYLES
313 );
314 }
315
316 // Async scripts. Once the startup is loaded, inline RLQ scripts will run.
317 // Pass-through a custom target from OutputPage (T143066).
318 $startupQuery = $this->target ? [ 'target' => $this->target ] : [];
319 $chunks[] = $this->getLoad(
320 'startup',
321 ResourceLoaderModule::TYPE_SCRIPTS,
322 $startupQuery
323 );
324
325 return WrappedStringList::join( "\n", $chunks );
326 }
327
328 /**
329 * @return string|WrappedStringList HTML
330 */
331 public function getBodyHtml() {
332 return '';
333 }
334
335 private function getContext( $group, $type ) {
336 return self::makeContext( $this->context, $group, $type );
337 }
338
339 private function getLoad( $modules, $only, array $extraQuery = [] ) {
340 return self::makeLoad( $this->context, (array)$modules, $only, $extraQuery );
341 }
342
343 private static function makeContext( ResourceLoaderContext $mainContext, $group, $type,
344 array $extraQuery = []
345 ) {
346 // Create new ResourceLoaderContext so that $extraQuery may trigger isRaw().
347 $req = new FauxRequest( array_merge( $mainContext->getRequest()->getValues(), $extraQuery ) );
348 // Set 'only' if not combined
349 $req->setVal( 'only', $type === ResourceLoaderModule::TYPE_COMBINED ? null : $type );
350 // Remove user parameter in most cases
351 if ( $group !== 'user' && $group !== 'private' ) {
352 $req->setVal( 'user', null );
353 }
354 $context = new ResourceLoaderContext( $mainContext->getResourceLoader(), $req );
355 // Allow caller to setVersion() and setModules()
356 return new DerivativeResourceLoaderContext( $context );
357 }
358
359 /**
360 * Explicily load or embed modules on a page.
361 *
362 * @param ResourceLoaderContext $mainContext
363 * @param array $modules One or more module names
364 * @param string $only ResourceLoaderModule TYPE_ class constant
365 * @param array $extraQuery [optional] Array with extra query parameters for the request
366 * @return string|WrappedStringList HTML
367 */
368 public static function makeLoad( ResourceLoaderContext $mainContext, array $modules, $only,
369 array $extraQuery = []
370 ) {
371 $rl = $mainContext->getResourceLoader();
372 $chunks = [];
373
374 // Sort module names so requests are more uniform
375 sort( $modules );
376
377 if ( $mainContext->getDebug() && count( $modules ) > 1 ) {
378 $chunks = [];
379 // Recursively call us for every item
380 foreach ( $modules as $name ) {
381 $chunks[] = self::makeLoad( $mainContext, [ $name ], $only, $extraQuery );
382 }
383 return new WrappedStringList( "\n", $chunks );
384 }
385
386 // Create keyed-by-source and then keyed-by-group list of module objects from modules list
387 $sortedModules = [];
388 foreach ( $modules as $name ) {
389 $module = $rl->getModule( $name );
390 if ( !$module ) {
391 $rl->getLogger()->warning( 'Unknown module "{module}"', [ 'module' => $name ] );
392 continue;
393 }
394 $sortedModules[$module->getSource()][$module->getGroup()][$name] = $module;
395 }
396
397 foreach ( $sortedModules as $source => $groups ) {
398 foreach ( $groups as $group => $grpModules ) {
399 $context = self::makeContext( $mainContext, $group, $only, $extraQuery );
400
401 // Separate sets of linked and embedded modules while preserving order
402 $moduleSets = [];
403 $idx = -1;
404 foreach ( $grpModules as $name => $module ) {
405 $shouldEmbed = $module->shouldEmbedModule( $context );
406 if ( !$moduleSets || $moduleSets[$idx][0] !== $shouldEmbed ) {
407 $moduleSets[++$idx] = [ $shouldEmbed, [] ];
408 }
409 $moduleSets[$idx][1][$name] = $module;
410 }
411
412 // Link/embed each set
413 foreach ( $moduleSets as list( $embed, $moduleSet ) ) {
414 $context->setModules( array_keys( $moduleSet ) );
415 if ( $embed ) {
416 // Decide whether to use style or script element
417 if ( $only == ResourceLoaderModule::TYPE_STYLES ) {
418 $chunks[] = Html::inlineStyle(
419 $rl->makeModuleResponse( $context, $moduleSet )
420 );
421 } else {
422 $chunks[] = ResourceLoader::makeInlineScript(
423 $rl->makeModuleResponse( $context, $moduleSet )
424 );
425 }
426 } else {
427 // See if we have one or more raw modules
428 $isRaw = false;
429 foreach ( $moduleSet as $key => $module ) {
430 $isRaw |= $module->isRaw();
431 }
432
433 // Special handling for the user group; because users might change their stuff
434 // on-wiki like user pages, or user preferences; we need to find the highest
435 // timestamp of these user-changeable modules so we can ensure cache misses on change
436 // This should NOT be done for the site group (T29564) because anons get that too
437 // and we shouldn't be putting timestamps in CDN-cached HTML
438 if ( $group === 'user' ) {
439 // Must setModules() before makeVersionQuery()
440 $context->setVersion( $rl->makeVersionQuery( $context ) );
441 }
442
443 $url = $rl->createLoaderURL( $source, $context, $extraQuery );
444
445 // Decide whether to use 'style' or 'script' element
446 if ( $only === ResourceLoaderModule::TYPE_STYLES ) {
447 $chunk = Html::linkedStyle( $url );
448 } else {
449 if ( $context->getRaw() || $isRaw ) {
450 $chunk = Html::element( 'script', [
451 // In SpecialJavaScriptTest, QUnit must load synchronous
452 'async' => !isset( $extraQuery['sync'] ),
453 'src' => $url
454 ] );
455 } else {
456 $chunk = ResourceLoader::makeInlineScript(
457 Xml::encodeJsCall( 'mw.loader.load', [ $url ] )
458 );
459 }
460 }
461
462 if ( $group == 'noscript' ) {
463 $chunks[] = Html::rawElement( 'noscript', [], $chunk );
464 } else {
465 $chunks[] = $chunk;
466 }
467 }
468 }
469 }
470 }
471
472 return new WrappedStringList( "\n", $chunks );
473 }
474 }