Merge "Add 3D filetype for STL files"
[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 $modules 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->warning( 'Unexpected general module "{module}" in styles queue.', [
174 'module' => $name,
175 ] );
176 } else {
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
182 $group = $module->getGroup();
183 $context = $this->getContext( $group, ResourceLoaderModule::TYPE_STYLES );
184 if ( $module->isKnownEmpty( $context ) ) {
185 // Avoid needless request for empty module
186 $data['states'][$name] = 'ready';
187 } else {
188 if ( $group === 'private' ) {
189 // Embed via style element
190 $data['embed']['styles'][] = $name;
191 // Avoid duplicate request from mw.loader
192 $data['states'][$name] = 'ready';
193 } else {
194 // Load from load.php?only=styles via <link rel=stylesheet>
195 $data['styles'][] = $name;
196 }
197 }
198 }
199
200 foreach ( $this->moduleScripts as $name ) {
201 $module = $rl->getModule( $name );
202 if ( !$module ) {
203 continue;
204 }
205
206 $group = $module->getGroup();
207 $context = $this->getContext( $group, ResourceLoaderModule::TYPE_SCRIPTS );
208 if ( $module->isKnownEmpty( $context ) ) {
209 // Avoid needless request for empty module
210 $data['states'][$name] = 'ready';
211 } else {
212 // Load from load.php?only=scripts via <script src></script>
213 $data['scripts'][] = $name;
214
215 // Avoid duplicate request from mw.loader
216 $data['states'][$name] = 'loading';
217 }
218 }
219
220 return $data;
221 }
222
223 /**
224 * @return array Attribute key-value pairs for the HTML document element
225 */
226 public function getDocumentAttributes() {
227 return [ 'class' => 'client-nojs' ];
228 }
229
230 /**
231 * The order of elements in the head is as follows:
232 * - Inline scripts.
233 * - Stylesheets.
234 * - Async external script-src.
235 *
236 * Reasons:
237 * - Script execution may be blocked on preceeding stylesheets.
238 * - Async scripts are not blocked on stylesheets.
239 * - Inline scripts can't be asynchronous.
240 * - For styles, earlier is better.
241 *
242 * @return string|WrappedStringList HTML
243 */
244 public function getHeadHtml() {
245 $data = $this->getData();
246 $chunks = [];
247
248 // Change "client-nojs" class to client-js. This allows easy toggling of UI components.
249 // This happens synchronously on every page view to avoid flashes of wrong content.
250 // See also #getDocumentAttributes() and /resources/src/startup.js.
251 $chunks[] = Html::inlineScript(
252 'document.documentElement.className = document.documentElement.className'
253 . '.replace( /(^|\s)client-nojs(\s|$)/, "$1client-js$2" );'
254 );
255
256 // Inline RLQ: Set page variables
257 if ( $this->config ) {
258 $chunks[] = ResourceLoader::makeInlineScript(
259 ResourceLoader::makeConfigSetScript( $this->config )
260 );
261 }
262
263 // Inline RLQ: Initial module states
264 $states = array_merge( $this->exemptStates, $data['states'] );
265 if ( $states ) {
266 $chunks[] = ResourceLoader::makeInlineScript(
267 ResourceLoader::makeLoaderStateScript( $states )
268 );
269 }
270
271 // Inline RLQ: Embedded modules
272 if ( $data['embed']['general'] ) {
273 $chunks[] = $this->getLoad(
274 $data['embed']['general'],
275 ResourceLoaderModule::TYPE_COMBINED
276 );
277 }
278
279 // Inline RLQ: Load general modules
280 if ( $data['general'] ) {
281 $chunks[] = ResourceLoader::makeInlineScript(
282 Xml::encodeJsCall( 'mw.loader.load', [ $data['general'] ] )
283 );
284 }
285
286 // Inline RLQ: Load only=scripts
287 if ( $data['scripts'] ) {
288 $chunks[] = $this->getLoad(
289 $data['scripts'],
290 ResourceLoaderModule::TYPE_SCRIPTS
291 );
292 }
293
294 // External stylesheets
295 if ( $data['styles'] ) {
296 $chunks[] = $this->getLoad(
297 $data['styles'],
298 ResourceLoaderModule::TYPE_STYLES
299 );
300 }
301
302 // Inline stylesheets (embedded only=styles)
303 if ( $data['embed']['styles'] ) {
304 $chunks[] = $this->getLoad(
305 $data['embed']['styles'],
306 ResourceLoaderModule::TYPE_STYLES
307 );
308 }
309
310 // Async scripts. Once the startup is loaded, inline RLQ scripts will run.
311 // Pass-through a custom target from OutputPage (T143066).
312 $startupQuery = $this->target ? [ 'target' => $this->target ] : [];
313 $chunks[] = $this->getLoad(
314 'startup',
315 ResourceLoaderModule::TYPE_SCRIPTS,
316 $startupQuery
317 );
318
319 return WrappedStringList::join( "\n", $chunks );
320 }
321
322 /**
323 * @return string|WrappedStringList HTML
324 */
325 public function getBodyHtml() {
326 return '';
327 }
328
329 private function getContext( $group, $type ) {
330 return self::makeContext( $this->context, $group, $type );
331 }
332
333 private function getLoad( $modules, $only, array $extraQuery = [] ) {
334 return self::makeLoad( $this->context, (array)$modules, $only, $extraQuery );
335 }
336
337 private static function makeContext( ResourceLoaderContext $mainContext, $group, $type,
338 array $extraQuery = []
339 ) {
340 // Create new ResourceLoaderContext so that $extraQuery may trigger isRaw().
341 $req = new FauxRequest( array_merge( $mainContext->getRequest()->getValues(), $extraQuery ) );
342 // Set 'only' if not combined
343 $req->setVal( 'only', $type === ResourceLoaderModule::TYPE_COMBINED ? null : $type );
344 // Remove user parameter in most cases
345 if ( $group !== 'user' && $group !== 'private' ) {
346 $req->setVal( 'user', null );
347 }
348 $context = new ResourceLoaderContext( $mainContext->getResourceLoader(), $req );
349 // Allow caller to setVersion() and setModules()
350 return new DerivativeResourceLoaderContext( $context );
351 }
352
353 /**
354 * Explicily load or embed modules on a page.
355 *
356 * @param ResourceLoaderContext $mainContext
357 * @param array $modules One or more module names
358 * @param string $only ResourceLoaderModule TYPE_ class constant
359 * @param array $extraQuery [optional] Array with extra query parameters for the request
360 * @return string|WrappedStringList HTML
361 */
362 public static function makeLoad( ResourceLoaderContext $mainContext, array $modules, $only,
363 array $extraQuery = []
364 ) {
365 $rl = $mainContext->getResourceLoader();
366 $chunks = [];
367
368 // Sort module names so requests are more uniform
369 sort( $modules );
370
371 if ( $mainContext->getDebug() && count( $modules ) > 1 ) {
372
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 }