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