resourceloader: Reduce width of module hash from 7 chars to 5
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoaderStartUpModule.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 * @author Trevor Parscal
20 * @author Roan Kattouw
21 */
22
23 use MediaWiki\MediaWikiServices;
24
25 /**
26 * Module for ResourceLoader initialization.
27 *
28 * See also <https://www.mediawiki.org/wiki/ResourceLoader/Features#Startup_Module>
29 *
30 * The startup module, as being called only from ResourceLoaderClientHtml, has
31 * the ability to vary based extra query parameters, in addition to those
32 * from ResourceLoaderContext:
33 *
34 * - target: Only register modules in the client intended for this target.
35 * Default: "desktop".
36 * See also: OutputPage::setTarget(), ResourceLoaderModule::getTargets().
37 *
38 * - safemode: Only register modules that have ORIGIN_CORE as their origin.
39 * This effectively disables ORIGIN_USER modules. (T185303)
40 * See also: OutputPage::disallowUserJs()
41 */
42 class ResourceLoaderStartUpModule extends ResourceLoaderModule {
43 protected $targets = [ 'desktop', 'mobile' ];
44
45 private $groupIds = [
46 // These reserved numbers MUST start at 0 and not skip any. These are preset
47 // for forward compatiblity so that they can be safely referenced by mediawiki.js,
48 // even when the code is cached and the order of registrations (and implicit
49 // group ids) changes between versions of the software.
50 'user' => 0,
51 'private' => 1,
52 ];
53
54 /**
55 * @param ResourceLoaderContext $context
56 * @return array
57 */
58 private function getConfigSettings( $context ) {
59 $conf = $this->getConfig();
60
61 /**
62 * Namespace related preparation
63 * - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces.
64 * - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive.
65 */
66 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
67 $namespaceIds = $contLang->getNamespaceIds();
68 $caseSensitiveNamespaces = [];
69 $nsInfo = MediaWikiServices::getInstance()->getNamespaceInfo();
70 foreach ( $nsInfo->getCanonicalNamespaces() as $index => $name ) {
71 $namespaceIds[$contLang->lc( $name )] = $index;
72 if ( !$nsInfo->isCapitalized( $index ) ) {
73 $caseSensitiveNamespaces[] = $index;
74 }
75 }
76
77 $illegalFileChars = $conf->get( 'IllegalFileChars' );
78
79 // Build list of variables
80 $skin = $context->getSkin();
81 $vars = [
82 'debug' => $context->getDebug(),
83 'skin' => $skin,
84 'stylepath' => $conf->get( 'StylePath' ),
85 'wgUrlProtocols' => wfUrlProtocols(),
86 'wgArticlePath' => $conf->get( 'ArticlePath' ),
87 'wgScriptPath' => $conf->get( 'ScriptPath' ),
88 'wgScript' => $conf->get( 'Script' ),
89 'wgSearchType' => $conf->get( 'SearchType' ),
90 'wgVariantArticlePath' => $conf->get( 'VariantArticlePath' ),
91 // Force object to avoid "empty" associative array from
92 // becoming [] instead of {} in JS (T36604)
93 'wgActionPaths' => (object)$conf->get( 'ActionPaths' ),
94 'wgServer' => $conf->get( 'Server' ),
95 'wgServerName' => $conf->get( 'ServerName' ),
96 'wgUserLanguage' => $context->getLanguage(),
97 'wgContentLanguage' => $contLang->getCode(),
98 'wgTranslateNumerals' => $conf->get( 'TranslateNumerals' ),
99 'wgVersion' => $conf->get( 'Version' ),
100 'wgEnableAPI' => true, // Deprecated since MW 1.32
101 'wgEnableWriteAPI' => true, // Deprecated since MW 1.32
102 'wgFormattedNamespaces' => $contLang->getFormattedNamespaces(),
103 'wgNamespaceIds' => $namespaceIds,
104 'wgContentNamespaces' => $nsInfo->getContentNamespaces(),
105 'wgSiteName' => $conf->get( 'Sitename' ),
106 'wgDBname' => $conf->get( 'DBname' ),
107 'wgExtraSignatureNamespaces' => $conf->get( 'ExtraSignatureNamespaces' ),
108 'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
109 // MediaWiki sets cookies to have this prefix by default
110 'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
111 'wgCookieDomain' => $conf->get( 'CookieDomain' ),
112 'wgCookiePath' => $conf->get( 'CookiePath' ),
113 'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
114 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
115 'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass( Title::legalChars() ),
116 'wgIllegalFileChars' => Title::convertByteClassToUnicodeClass( $illegalFileChars ),
117 'wgForeignUploadTargets' => $conf->get( 'ForeignUploadTargets' ),
118 'wgEnableUploads' => $conf->get( 'EnableUploads' ),
119 'wgCommentByteLimit' => null,
120 'wgCommentCodePointLimit' => CommentStore::COMMENT_CHARACTER_LIMIT,
121 ];
122
123 Hooks::run( 'ResourceLoaderGetConfigVars', [ &$vars, $skin ] );
124
125 return $vars;
126 }
127
128 /**
129 * Recursively get all explicit and implicit dependencies for to the given module.
130 *
131 * @param array $registryData
132 * @param string $moduleName
133 * @param string[] $handled Internal parameter for recursion. (Optional)
134 * @return array
135 * @throws ResourceLoaderCircularDependencyError
136 */
137 protected static function getImplicitDependencies(
138 array $registryData,
139 $moduleName,
140 array $handled = []
141 ) {
142 static $dependencyCache = [];
143
144 // No modules will be added or changed server-side after this point,
145 // so we can safely cache parts of the tree for re-use.
146 if ( !isset( $dependencyCache[$moduleName] ) ) {
147 if ( !isset( $registryData[$moduleName] ) ) {
148 // Unknown module names are allowed here, this is only an optimisation.
149 // Checks for illegal and unknown dependencies happen as PHPUnit structure tests,
150 // and also client-side at run-time.
151 $flat = [];
152 } else {
153 $data = $registryData[$moduleName];
154 $flat = $data['dependencies'];
155
156 // Prevent recursion
157 $handled[] = $moduleName;
158 foreach ( $data['dependencies'] as $dependency ) {
159 if ( in_array( $dependency, $handled, true ) ) {
160 // If we encounter a circular dependency, then stop the optimiser and leave the
161 // original dependencies array unmodified. Circular dependencies are not
162 // supported in ResourceLoader. Awareness of them exists here so that we can
163 // optimise the registry when it isn't broken, and otherwise transport the
164 // registry unchanged. The client will handle this further.
165 throw new ResourceLoaderCircularDependencyError();
166 } else {
167 // Recursively add the dependencies of the dependencies
168 $flat = array_merge(
169 $flat,
170 self::getImplicitDependencies( $registryData, $dependency, $handled )
171 );
172 }
173 }
174 }
175
176 $dependencyCache[$moduleName] = $flat;
177 }
178
179 return $dependencyCache[$moduleName];
180 }
181
182 /**
183 * Optimize the dependency tree in $this->modules.
184 *
185 * The optimization basically works like this:
186 * Given we have module A with the dependencies B and C
187 * and module B with the dependency C.
188 * Now we don't have to tell the client to explicitly fetch module
189 * C as that's already included in module B.
190 *
191 * This way we can reasonably reduce the amount of module registration
192 * data send to the client.
193 *
194 * @param array &$registryData Modules keyed by name with properties:
195 * - string 'version'
196 * - array 'dependencies'
197 * - string|null 'group'
198 * - string 'source'
199 */
200 public static function compileUnresolvedDependencies( array &$registryData ) {
201 foreach ( $registryData as $name => &$data ) {
202 $dependencies = $data['dependencies'];
203 try {
204 foreach ( $data['dependencies'] as $dependency ) {
205 $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
206 $dependencies = array_diff( $dependencies, $implicitDependencies );
207 }
208 } catch ( ResourceLoaderCircularDependencyError $err ) {
209 // Leave unchanged
210 $dependencies = $data['dependencies'];
211 }
212
213 // Rebuild keys
214 $data['dependencies'] = array_values( $dependencies );
215 }
216 }
217
218 /**
219 * Get registration code for all modules.
220 *
221 * @param ResourceLoaderContext $context
222 * @return string JavaScript code for registering all modules with the client loader
223 */
224 public function getModuleRegistrations( ResourceLoaderContext $context ) {
225 $resourceLoader = $context->getResourceLoader();
226 // Future developers: Use WebRequest::getRawVal() instead getVal().
227 // The getVal() method performs slow Language+UTF logic. (f303bb9360)
228 $target = $context->getRequest()->getRawVal( 'target', 'desktop' );
229 $safemode = $context->getRequest()->getRawVal( 'safemode' ) === '1';
230 // Bypass target filter if this request is Special:JavaScriptTest.
231 // To prevent misuse in production, this is only allowed if testing is enabled server-side.
232 $byPassTargetFilter = $this->getConfig()->get( 'EnableJavaScriptTest' ) && $target === 'test';
233
234 $out = '';
235 $states = [];
236 $registryData = [];
237 $moduleNames = $resourceLoader->getModuleNames();
238
239 // Preload with a batch so that the below calls to getVersionHash() for each module
240 // don't require on-demand loading of more information.
241 try {
242 $resourceLoader->preloadModuleInfo( $moduleNames, $context );
243 } catch ( Exception $e ) {
244 // Don't fail the request (T152266)
245 // Also print the error in the main output
246 $resourceLoader->outputErrorAndLog( $e,
247 'Preloading module info from startup failed: {exception}',
248 [ 'exception' => $e ]
249 );
250 }
251
252 // Get registry data
253 foreach ( $moduleNames as $name ) {
254 $module = $resourceLoader->getModule( $name );
255 $moduleTargets = $module->getTargets();
256 if (
257 ( !$byPassTargetFilter && !in_array( $target, $moduleTargets ) )
258 || ( $safemode && $module->getOrigin() > ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL )
259 ) {
260 continue;
261 }
262
263 if ( $module instanceof ResourceLoaderStartUpModule ) {
264 // Don't register 'startup' to the client because loading it lazily or depending
265 // on it doesn't make sense, because the startup module *is* the client.
266 // Registering would be a waste of bandwidth and memory and risks somehow causing
267 // it to load a second time.
268
269 // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
270 // Think carefully before making changes to this code!
271 // The below code is going to call ResourceLoaderModule::getVersionHash() for every module.
272 // For StartUpModule (this module) the hash is computed based on the manifest content,
273 // which is the very thing we are computing right here. As such, this must skip iterating
274 // over 'startup' itself.
275 continue;
276 }
277
278 try {
279 $versionHash = $module->getVersionHash( $context );
280 } catch ( Exception $e ) {
281 // Don't fail the request (T152266)
282 // Also print the error in the main output
283 $resourceLoader->outputErrorAndLog( $e,
284 'Calculating version for "{module}" failed: {exception}',
285 [
286 'module' => $name,
287 'exception' => $e,
288 ]
289 );
290 $versionHash = '';
291 $states[$name] = 'error';
292 }
293
294 if ( $versionHash !== '' && strlen( $versionHash ) !== ResourceLoader::HASH_LENGTH ) {
295 $e = new RuntimeException( "Badly formatted module version hash" );
296 $resourceLoader->outputErrorAndLog( $e,
297 "Module '{module}' produced an invalid version hash: '{version}'.",
298 [
299 'module' => $name,
300 'version' => $versionHash,
301 ]
302 );
303 // Module implementation either broken or deviated from ResourceLoader::makeHash
304 // Asserted by tests/phpunit/structure/ResourcesTest.
305 $versionHash = ResourceLoader::makeHash( $versionHash );
306 }
307
308 $skipFunction = $module->getSkipFunction();
309 if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
310 $skipFunction = ResourceLoader::filter( 'minify-js', $skipFunction );
311 }
312
313 $registryData[$name] = [
314 'version' => $versionHash,
315 'dependencies' => $module->getDependencies( $context ),
316 'group' => $this->getGroupId( $module->getGroup() ),
317 'source' => $module->getSource(),
318 'skip' => $skipFunction,
319 ];
320 }
321
322 self::compileUnresolvedDependencies( $registryData );
323
324 // Register sources
325 $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
326
327 // Figure out the different call signatures for mw.loader.register
328 $registrations = [];
329 foreach ( $registryData as $name => $data ) {
330 // Call mw.loader.register(name, version, dependencies, group, source, skip)
331 $registrations[] = [
332 $name,
333 $data['version'],
334 $data['dependencies'],
335 $data['group'],
336 // Swap default (local) for null
337 $data['source'] === 'local' ? null : $data['source'],
338 $data['skip']
339 ];
340 }
341
342 // Register modules
343 $out .= "\n" . ResourceLoader::makeLoaderRegisterScript( $registrations );
344
345 if ( $states ) {
346 $out .= "\n" . ResourceLoader::makeLoaderStateScript( $states );
347 }
348
349 return $out;
350 }
351
352 private function getGroupId( $groupName ) {
353 if ( $groupName === null ) {
354 return null;
355 }
356
357 if ( !array_key_exists( $groupName, $this->groupIds ) ) {
358 $this->groupIds[$groupName] = count( $this->groupIds );
359 }
360
361 return $this->groupIds[$groupName];
362 }
363
364 /**
365 * Base modules implicitly available to all modules.
366 *
367 * @return array
368 */
369 private function getBaseModules() {
370 $baseModules = [ 'jquery', 'mediawiki.base' ];
371 return $baseModules;
372 }
373
374 /**
375 * Get the localStorage key for the entire module store. The key references
376 * $wgDBname to prevent clashes between wikis under the same web domain.
377 *
378 * @return string localStorage item key for JavaScript
379 */
380 private function getStoreKey() {
381 return 'MediaWikiModuleStore:' . $this->getConfig()->get( 'DBname' );
382 }
383
384 /**
385 * Get the key on which the JavaScript module cache (mw.loader.store) will vary.
386 *
387 * @param ResourceLoaderContext $context
388 * @return string String of concatenated vary conditions
389 */
390 private function getStoreVary( ResourceLoaderContext $context ) {
391 return implode( ':', [
392 $context->getSkin(),
393 $this->getConfig()->get( 'ResourceLoaderStorageVersion' ),
394 $context->getLanguage(),
395 ] );
396 }
397
398 /**
399 * @param ResourceLoaderContext $context
400 * @return string JavaScript code
401 */
402 public function getScript( ResourceLoaderContext $context ) {
403 global $IP;
404 $conf = $this->getConfig();
405
406 if ( $context->getOnly() !== 'scripts' ) {
407 return '/* Requires only=script */';
408 }
409
410 $startupCode = file_get_contents( "$IP/resources/src/startup/startup.js" );
411
412 // The files read here MUST be kept in sync with maintenance/jsduck/eg-iframe.html,
413 // and MUST be considered by 'fileHashes' in StartUpModule::getDefinitionSummary().
414 $mwLoaderCode = file_get_contents( "$IP/resources/src/startup/mediawiki.js" ) .
415 file_get_contents( "$IP/resources/src/startup/mediawiki.requestIdleCallback.js" );
416 if ( $context->getDebug() ) {
417 $mwLoaderCode .= file_get_contents( "$IP/resources/src/startup/mediawiki.log.js" );
418 }
419 if ( $conf->get( 'ResourceLoaderEnableJSProfiler' ) ) {
420 $mwLoaderCode .= file_get_contents( "$IP/resources/src/startup/profiler.js" );
421 }
422
423 // Perform replacements for mediawiki.js
424 $mwLoaderPairs = [
425 '$VARS.reqBase' => ResourceLoader::encodeJsonForScript( $context->getReqBase() ),
426 '$VARS.baseModules' => ResourceLoader::encodeJsonForScript( $this->getBaseModules() ),
427 '$VARS.maxQueryLength' => ResourceLoader::encodeJsonForScript(
428 $conf->get( 'ResourceLoaderMaxQueryLength' )
429 ),
430 // The client-side module cache can be disabled by site configuration.
431 // It is also always disabled in debug mode.
432 '$VARS.storeEnabled' => ResourceLoader::encodeJsonForScript(
433 $conf->get( 'ResourceLoaderStorageEnabled' ) && !$context->getDebug()
434 ),
435 '$VARS.wgLegacyJavaScriptGlobals' => ResourceLoader::encodeJsonForScript(
436 $conf->get( 'LegacyJavaScriptGlobals' )
437 ),
438 '$VARS.storeKey' => ResourceLoader::encodeJsonForScript( $this->getStoreKey() ),
439 '$VARS.storeVary' => ResourceLoader::encodeJsonForScript( $this->getStoreVary( $context ) ),
440 '$VARS.groupUser' => ResourceLoader::encodeJsonForScript( $this->getGroupId( 'user' ) ),
441 '$VARS.groupPrivate' => ResourceLoader::encodeJsonForScript( $this->getGroupId( 'private' ) ),
442 ];
443 $profilerStubs = [
444 '$CODE.profileExecuteStart();' => 'mw.loader.profiler.onExecuteStart( module );',
445 '$CODE.profileExecuteEnd();' => 'mw.loader.profiler.onExecuteEnd( module );',
446 '$CODE.profileScriptStart();' => 'mw.loader.profiler.onScriptStart( module );',
447 '$CODE.profileScriptEnd();' => 'mw.loader.profiler.onScriptEnd( module );',
448 ];
449 if ( $conf->get( 'ResourceLoaderEnableJSProfiler' ) ) {
450 // When profiling is enabled, insert the calls.
451 $mwLoaderPairs += $profilerStubs;
452 } else {
453 // When disabled (by default), insert nothing.
454 $mwLoaderPairs += array_fill_keys( array_keys( $profilerStubs ), '' );
455 }
456 $mwLoaderCode = strtr( $mwLoaderCode, $mwLoaderPairs );
457
458 // Perform string replacements for startup.js
459 $pairs = [
460 '$VARS.configuration' => ResourceLoader::encodeJsonForScript(
461 $this->getConfigSettings( $context )
462 ),
463 // Raw JavaScript code (not JSON)
464 '$CODE.registrations();' => trim( $this->getModuleRegistrations( $context ) ),
465 '$CODE.defineLoader();' => $mwLoaderCode,
466 ];
467 $startupCode = strtr( $startupCode, $pairs );
468
469 return $startupCode;
470 }
471
472 /**
473 * @return bool
474 */
475 public function supportsURLLoading() {
476 return false;
477 }
478
479 /**
480 * @return bool
481 */
482 public function enableModuleContentVersion() {
483 // Enabling this means that ResourceLoader::getVersionHash will simply call getScript()
484 // and hash it to determine the version (as used by E-Tag HTTP response header).
485 return true;
486 }
487 }