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