Debian Codegraph @

includes/ResourceLoader/StartUpModule.php

raw symbols SCIP
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 * @author Trevor Parscal
20 * @author Roan Kattouw
21 */
22 namespace MediaWiki\ResourceLoader;
23
24 use DomainException;
25 use Exception;
26 use MediaWiki\MainConfigNames;
27 use Wikimedia\RequestTimeout\TimeoutException;
28
29 /**
30 * Module for ResourceLoader initialization.
31 *
32 * See also <https://www.mediawiki.org/wiki/ResourceLoader/Features#Startup_Module>
33 *
34 * The startup module, as being called only from ClientHtml, has
35 * the ability to vary based extra query parameters, in addition to those
36 * from Context:
37 *
38 * - safemode: Only register modules that have ORIGIN_CORE as their origin.
39 * This disables ORIGIN_USER modules and mw.loader.store. (T185303, T145498)
40 * See also: OutputPage::disallowUserJs()
41 *
42 * @ingroup ResourceLoader
43 * @internal
44 */
45 class StartUpModule extends Module {
46
47 /**
48 * Cache version for client-side ResourceLoader module storage.
49 * Like ResourceLoaderStorageVersion but not configurable.
50 */
51 private const STORAGE_VERSION = '2';
52
53 /** @var int[] */
54 private $groupIds = [
55 // These reserved numbers MUST start at 0 and not skip any. These are preset
56 // for forward compatibility so that they can be safely referenced by mediawiki.js,
57 // even when the code is cached and the order of registrations (and implicit
58 // group ids) changes between versions of the software.
59 self::GROUP_USER => 0,
60 self::GROUP_PRIVATE => 1,
61 ];
62
63 /**
64 * Recursively get all explicit and implicit dependencies for to the given module.
65 *
66 * @param array $registryData
67 * @param string $moduleName
68 * @param string[] $handled Internal parameter for recursion. (Optional)
69 * @return array
70 * @throws CircularDependencyError
71 */
72 protected static function getImplicitDependencies(
73 array $registryData,
74 string $moduleName,
75 array $handled = []
76 ): array {
77 static $dependencyCache = [];
78
79 // No modules will be added or changed server-side after this point,
80 // so we can safely cache parts of the tree for re-use.
81 if ( !isset( $dependencyCache[$moduleName] ) ) {
82 if ( !isset( $registryData[$moduleName] ) ) {
83 // Unknown module names are allowed here, this is only an optimisation.
84 // Checks for illegal and unknown dependencies happen as PHPUnit structure tests,
85 // and also client-side at run-time.
86 $dependencyCache[$moduleName] = [];
87 return [];
88 }
89
90 $data = $registryData[$moduleName];
91 $flat = $data['dependencies'];
92
93 // Prevent recursion
94 $handled[] = $moduleName;
95 foreach ( $data['dependencies'] as $dependency ) {
96 if ( in_array( $dependency, $handled, true ) ) {
97 // If we encounter a circular dependency, then stop the optimiser and leave the
98 // original dependencies array unmodified. Circular dependencies are not
99 // supported in ResourceLoader. Awareness of them exists here so that we can
100 // optimise the registry when it isn't broken, and otherwise transport the
101 // registry unchanged. The client will handle this further.
102 throw new CircularDependencyError();
103 }
104 // Recursively add the dependencies of the dependencies
105 $flat = array_merge(
106 $flat,
107 self::getImplicitDependencies( $registryData, $dependency, $handled )
108 );
109 }
110
111 $dependencyCache[$moduleName] = $flat;
112 }
113
114 return $dependencyCache[$moduleName];
115 }
116
117 /**
118 * Optimize the dependency tree in $this->modules.
119 *
120 * The optimization basically works like this:
121 * Given we have module A with the dependencies B and C
122 * and module B with the dependency C.
123 * Now we don't have to tell the client to explicitly fetch module
124 * C as that's already included in module B.
125 *
126 * This way we can reasonably reduce the amount of module registration
127 * data send to the client.
128 *
129 * @param array[] &$registryData Modules keyed by name with properties:
130 * - string 'version'
131 * - array 'dependencies'
132 * - string|null 'group'
133 * - string 'source'
134 * @phan-param array<string,array{version:string,dependencies:array,group:?string,source:string}> &$registryData
135 */
136 public static function compileUnresolvedDependencies( array &$registryData ): void {
137 foreach ( $registryData as &$data ) {
138 $dependencies = $data['dependencies'];
139 try {
140 foreach ( $data['dependencies'] as $dependency ) {
141 $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
142 $dependencies = array_diff( $dependencies, $implicitDependencies );
143 }
144 } catch ( CircularDependencyError $err ) {
145 // Leave unchanged
146 $dependencies = $data['dependencies'];
147 }
148
149 // Rebuild keys
150 $data['dependencies'] = array_values( $dependencies );
151 }
152 }
153
154 /**
155 * Get registration code for all modules.
156 *
157 * @param Context $context
158 * @return string JavaScript code for registering all modules with the client loader
159 */
160 public function getModuleRegistrations( Context $context ): string {
161 $resourceLoader = $context->getResourceLoader();
162 // Future developers: Use WebRequest::getRawVal() instead getVal().
163 // The getVal() method performs slow Language+UTF logic. (f303bb9360)
164 $safemode = $context->getRequest()->getRawVal( 'safemode' ) === '1';
165 $skin = $context->getSkin();
166
167 $moduleNames = $resourceLoader->getModuleNames();
168
169 // Preload with a batch so that the below calls to getVersionHash() for each module
170 // don't require on-demand loading of more information.
171 try {
172 $resourceLoader->preloadModuleInfo( $moduleNames, $context );
173 } catch ( TimeoutException $e ) {
174 throw $e;
175 } catch ( Exception $e ) {
176 // Don't fail the request (T152266)
177 // Also print the error in the main output
178 $resourceLoader->outputErrorAndLog( $e,
179 'Preloading module info from startup failed: {exception}',
180 [ 'exception' => $e ]
181 );
182 }
183
184 // Get registry data
185 $states = [];
186 $registryData = [];
187 foreach ( $moduleNames as $name ) {
188 $module = $resourceLoader->getModule( $name );
189 $moduleSkins = $module->getSkins();
190 if (
191 ( $safemode && $module->getOrigin() > Module::ORIGIN_CORE_INDIVIDUAL )
192 || ( $moduleSkins !== null && !in_array( $skin, $moduleSkins ) )
193 ) {
194 continue;
195 }
196
197 if ( $module instanceof StartUpModule ) {
198 // Don't register 'startup' to the client because loading it lazily or depending
199 // on it doesn't make sense, because the startup module *is* the client.
200 // Registering would be a waste of bandwidth and memory and risks somehow causing
201 // it to load a second time.
202
203 // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
204 // Think carefully before making changes to this code!
205 // The below code is going to call Module::getVersionHash() for every module.
206 // For StartUpModule (this module) the hash is computed based on the manifest content,
207 // which is the very thing we are computing right here. As such, this must skip iterating
208 // over 'startup' itself.
209 continue;
210 }
211
212 // Optimization: Exclude modules in the `noscript` group. These are only ever used
213 // directly by HTML without use of JavaScript (T291735).
214 if ( $module->getGroup() === self::GROUP_NOSCRIPT ) {
215 continue;
216 }
217
218 try {
219 // The version should be formatted by ResourceLoader::makeHash and be of
220 // length ResourceLoader::HASH_LENGTH (or empty string).
221 // The getVersionHash method is final and is covered by tests, as is makeHash().
222 $versionHash = $module->getVersionHash( $context );
223 } catch ( TimeoutException $e ) {
224 throw $e;
225 } catch ( Exception $e ) {
226 // Don't fail the request (T152266)
227 // Also print the error in the main output
228 $resourceLoader->outputErrorAndLog( $e,
229 'Calculating version for "{module}" failed: {exception}',
230 [
231 'module' => $name,
232 'exception' => $e,
233 ]
234 );
235 $versionHash = '';
236 $states[$name] = 'error';
237 }
238
239 $skipFunction = $module->getSkipFunction();
240 if ( $skipFunction !== null && !$context->getDebug() ) {
241 $skipFunction = ResourceLoader::filter( 'minify-js', $skipFunction );
242 }
243
244 $registryData[$name] = [
245 'version' => $versionHash,
246 'dependencies' => $module->getDependencies( $context ),
247 'group' => $this->getGroupId( $module->getGroup() ),
248 'source' => $module->getSource(),
249 'skip' => $skipFunction,
250 ];
251 }
252
253 self::compileUnresolvedDependencies( $registryData );
254
255 // Register sources
256 $sources = $oldSources = $resourceLoader->getSources();
257 $this->getHookRunner()->onResourceLoaderModifyEmbeddedSourceUrls( $sources );
258 if ( array_keys( $sources ) !== array_keys( $oldSources ) ) {
259 throw new DomainException( 'ResourceLoaderModifyEmbeddedSourceUrls hook must not add or remove sources' );
260 }
261 $out = ResourceLoader::makeLoaderSourcesScript( $context, $sources );
262
263 // Figure out the different call signatures for mw.loader.register
264 $registrations = [];
265 foreach ( $registryData as $name => $data ) {
266 // Call mw.loader.register(name, version, dependencies, group, source, skip)
267 $registrations[] = [
268 $name,
269 $data['version'],
270 $data['dependencies'],
271 $data['group'],
272 // Swap default (local) for null
273 $data['source'] === 'local' ? null : $data['source'],
274 $data['skip']
275 ];
276 }
277
278 // Register modules
279 $out .= "\n" . ResourceLoader::makeLoaderRegisterScript( $context, $registrations );
280
281 if ( $states ) {
282 $out .= "\n" . ResourceLoader::makeLoaderStateScript( $context, $states );
283 }
284
285 return $out;
286 }
287
288 private function getGroupId( $groupName ): ?int {
289 if ( $groupName === null ) {
290 return null;
291 }
292
293 if ( !array_key_exists( $groupName, $this->groupIds ) ) {
294 $this->groupIds[$groupName] = count( $this->groupIds );
295 }
296
297 return $this->groupIds[$groupName];
298 }
299
300 /**
301 * Base modules implicitly available to all modules.
302 *
303 * @return array
304 */
305 private function getBaseModules(): array {
306 return [ 'jquery', 'mediawiki.base' ];
307 }
308
309 /**
310 * Get the localStorage key for the entire module store. The key references
311 * $wgDBname to prevent clashes between wikis under the same web domain.
312 *
313 * @return string localStorage item key for JavaScript
314 */
315 private function getStoreKey(): string {
316 return 'MediaWikiModuleStore:' . $this->getConfig()->get( MainConfigNames::DBname );
317 }
318
319 /**
320 * @see $wgResourceLoaderMaxQueryLength
321 * @return int
322 */
323 private function getMaxQueryLength(): int {
324 $len = $this->getConfig()->get( MainConfigNames::ResourceLoaderMaxQueryLength );
325 // - Ignore -1, which in MW 1.34 and earlier was used to mean "unlimited".
326 // - Ignore invalid values, e.g. non-int or other negative values.
327 if ( $len === false || $len < 0 ) {
328 // Default
329 $len = 2000;
330 }
331 return $len;
332 }
333
334 /**
335 * Get the key on which the JavaScript module cache (mw.loader.store) will vary.
336 *
337 * @param Context $context
338 * @return string String of concatenated vary conditions
339 */
340 private function getStoreVary( Context $context ): string {
341 return implode( ':', [
342 $context->getSkin(),
343 self::STORAGE_VERSION,
344 $this->getConfig()->get( MainConfigNames::ResourceLoaderStorageVersion ),
345 $context->getLanguage(),
346 ] );
347 }
348
349 /**
350 * @param Context $context
351 * @return string|array JavaScript code
352 */
353 public function getScript( Context $context ) {
354 global $IP;
355 $conf = $this->getConfig();
356
357 if ( $context->getOnly() !== 'scripts' ) {
358 return '/* Requires only=scripts */';
359 }
360
361 $enableJsProfiler = $conf->get( MainConfigNames::ResourceLoaderEnableJSProfiler );
362
363 $startupCode = file_get_contents( "$IP/resources/src/startup/startup.js" );
364
365 $mwLoaderCode = file_get_contents( "$IP/resources/src/startup/mediawiki.js" ) .
366 file_get_contents( "$IP/resources/src/startup/mediawiki.loader.js" ) .
367 file_get_contents( "$IP/resources/src/startup/mediawiki.requestIdleCallback.js" );
368 if ( $conf->get( MainConfigNames::ResourceLoaderEnableJSProfiler ) ) {
369 $mwLoaderCode .= file_get_contents( "$IP/resources/src/startup/profiler.js" );
370 }
371
372 // Perform replacements for mediawiki.js
373 $mwLoaderPairs = [
374 // This should always be an object, even if the base vars are empty
375 // (such as when using the default lang/skin).
376 '$VARS.reqBase' => $context->encodeJson( (object)$context->getReqBase() ),
377 '$VARS.baseModules' => $context->encodeJson( $this->getBaseModules() ),
378 '$VARS.maxQueryLength' => $context->encodeJson(
379 // In debug mode (except legacy debug mode), let the client fetch each module in
380 // its own dedicated request (T85805).
381 // This is effectively the equivalent of ClientHtml::makeLoad,
382 // which does this for stylesheets.
383 ( !$context->getDebug() || $context->getDebug() === $context::DEBUG_LEGACY ) ?
384 $this->getMaxQueryLength() :
385 0
386 ),
387 '$VARS.storeEnabled' => $context->encodeJson(
388 $conf->get( MainConfigNames::ResourceLoaderStorageEnabled )
389 && !$context->getDebug()
390 && $context->getRequest()->getRawVal( 'safemode' ) !== '1'
391 ),
392 '$VARS.storeKey' => $context->encodeJson( $this->getStoreKey() ),
393 '$VARS.storeVary' => $context->encodeJson( $this->getStoreVary( $context ) ),
394 '$VARS.groupUser' => $context->encodeJson( $this->getGroupId( self::GROUP_USER ) ),
395 '$VARS.groupPrivate' => $context->encodeJson( $this->getGroupId( self::GROUP_PRIVATE ) ),
396 '$VARS.sourceMapLinks' => $context->encodeJson(
397 $conf->get( MainConfigNames::ResourceLoaderEnableSourceMapLinks )
398 ),
399
400 // When profiling is enabled, insert the calls.
401 // When disabled (the default), insert nothing.
402 '$CODE.profileExecuteStart();' => $enableJsProfiler
403 ? 'mw.loader.profiler.onExecuteStart( module );'
404 : '',
405 '$CODE.profileExecuteEnd();' => $enableJsProfiler
406 ? 'mw.loader.profiler.onExecuteEnd( module );'
407 : '',
408 '$CODE.profileScriptStart();' => $enableJsProfiler
409 ? 'mw.loader.profiler.onScriptStart( module );'
410 : '',
411 '$CODE.profileScriptEnd();' => $enableJsProfiler
412 ? 'mw.loader.profiler.onScriptEnd( module );'
413 : '',
414
415 // Debug stubs
416 '$CODE.consoleLog();' => $context->getDebug()
417 ? 'console.log.apply( console, arguments );'
418 : '',
419
420 // As a paranoia measure, create a window.QUnit placeholder that shadows any
421 // DOM global (e.g. for <h2 id="QUnit">), to avoid test code in prod (T356768).
422 '$CODE.undefineQUnit();' => !$conf->get( MainConfigNames::EnableJavaScriptTest )
423 ? 'window.QUnit = undefined;'
424 : '',
425 ];
426 $mwLoaderCode = strtr( $mwLoaderCode, $mwLoaderPairs );
427
428 // Perform string replacements for startup.js
429 $pairs = [
430 // Raw JavaScript code (not JSON)
431 '$CODE.registrations();' => trim( $this->getModuleRegistrations( $context ) ),
432 '$CODE.defineLoader();' => $mwLoaderCode,
433 ];
434 $startupCode = strtr( $startupCode, $pairs );
435
436 return [
437 'plainScripts' => [
438 [
439 'virtualFilePath' => new FilePath(
440 'resources/src/startup/startup.js',
441 MW_INSTALL_PATH,
442 $conf->get( MainConfigNames::ResourceBasePath )
443 ),
444 'content' => $startupCode,
445 ],
446 ],
447 ];
448 }
449
450 /**
451 * @return bool
452 */
453 public function supportsURLLoading(): bool {
454 return false;
455 }
456
457 /**
458 * @return bool
459 */
460 public function enableModuleContentVersion(): bool {
461 // Enabling this means that ResourceLoader::getVersionHash will simply call getScript()
462 // and hash it to determine the version (as used by E-Tag HTTP response header).
463 return true;
464 }
465 }