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.
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.
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
19 * @author Trevor Parscal
20 * @author Roan Kattouw
23 use MediaWiki\MediaWikiServices
;
26 * Module for ResourceLoader initialization.
28 * See also <https://www.mediawiki.org/wiki/ResourceLoader/Features#Startup_Module>
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:
34 * - target: Only register modules in the client intended for this target.
36 * See also: OutputPage::setTarget(), ResourceLoaderModule::getTargets().
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()
42 class ResourceLoaderStartUpModule
extends ResourceLoaderModule
{
43 protected $targets = [ 'desktop', 'mobile' ];
46 * @param ResourceLoaderContext $context
49 private function getConfigSettings( $context ) {
50 $conf = $this->getConfig();
52 // We can't use Title::newMainPage() if 'mainpage' is in
53 // $wgForceUIMsgAsContentMsg because that will try to use the session
54 // user's language and we have no session user. This does the
55 // equivalent but falling back to our ResourceLoaderContext language
57 $mainPage = Title
::newFromText( $context->msg( 'mainpage' )->inContentLanguage()->text() );
59 $mainPage = Title
::newFromText( 'Main Page' );
63 * Namespace related preparation
64 * - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces.
65 * - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive.
67 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
68 $namespaceIds = $contLang->getNamespaceIds();
69 $caseSensitiveNamespaces = [];
70 foreach ( MWNamespace
::getCanonicalNamespaces() as $index => $name ) {
71 $namespaceIds[$contLang->lc( $name )] = $index;
72 if ( !MWNamespace
::isCapitalized( $index ) ) {
73 $caseSensitiveNamespaces[] = $index;
77 $illegalFileChars = $conf->get( 'IllegalFileChars' );
78 $oldCommentSchema = $conf->get( 'CommentTableSchemaMigrationStage' ) === MIGRATION_OLD
;
80 // Build list of variables
81 $skin = $context->getSkin();
83 'wgLoadScript' => wfScript( 'load' ),
84 'debug' => $context->getDebug(),
86 'stylepath' => $conf->get( 'StylePath' ),
87 'wgUrlProtocols' => wfUrlProtocols(),
88 'wgArticlePath' => $conf->get( 'ArticlePath' ),
89 'wgScriptPath' => $conf->get( 'ScriptPath' ),
90 'wgScript' => wfScript(),
91 'wgSearchType' => $conf->get( 'SearchType' ),
92 'wgVariantArticlePath' => $conf->get( 'VariantArticlePath' ),
93 // Force object to avoid "empty" associative array from
94 // becoming [] instead of {} in JS (T36604)
95 'wgActionPaths' => (object)$conf->get( 'ActionPaths' ),
96 'wgServer' => $conf->get( 'Server' ),
97 'wgServerName' => $conf->get( 'ServerName' ),
98 'wgUserLanguage' => $context->getLanguage(),
99 'wgContentLanguage' => $contLang->getCode(),
100 'wgTranslateNumerals' => $conf->get( 'TranslateNumerals' ),
101 'wgVersion' => $conf->get( 'Version' ),
102 'wgEnableAPI' => true, // Deprecated since MW 1.32
103 'wgEnableWriteAPI' => true, // Deprecated since MW 1.32
104 'wgMainPageTitle' => $mainPage->getPrefixedText(),
105 'wgFormattedNamespaces' => $contLang->getFormattedNamespaces(),
106 'wgNamespaceIds' => $namespaceIds,
107 'wgContentNamespaces' => MWNamespace
::getContentNamespaces(),
108 'wgSiteName' => $conf->get( 'Sitename' ),
109 'wgDBname' => $conf->get( 'DBname' ),
110 'wgExtraSignatureNamespaces' => $conf->get( 'ExtraSignatureNamespaces' ),
111 'wgAvailableSkins' => Skin
::getSkinNames(),
112 'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
113 // MediaWiki sets cookies to have this prefix by default
114 'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
115 'wgCookieDomain' => $conf->get( 'CookieDomain' ),
116 'wgCookiePath' => $conf->get( 'CookiePath' ),
117 'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
118 'wgResourceLoaderMaxQueryLength' => $conf->get( 'ResourceLoaderMaxQueryLength' ),
119 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
120 'wgLegalTitleChars' => Title
::convertByteClassToUnicodeClass( Title
::legalChars() ),
121 'wgIllegalFileChars' => Title
::convertByteClassToUnicodeClass( $illegalFileChars ),
122 'wgResourceLoaderStorageVersion' => $conf->get( 'ResourceLoaderStorageVersion' ),
123 'wgResourceLoaderStorageEnabled' => $conf->get( 'ResourceLoaderStorageEnabled' ),
124 'wgForeignUploadTargets' => $conf->get( 'ForeignUploadTargets' ),
125 'wgEnableUploads' => $conf->get( 'EnableUploads' ),
126 'wgCommentByteLimit' => $oldCommentSchema ?
255 : null,
127 'wgCommentCodePointLimit' => $oldCommentSchema ?
null : CommentStore
::COMMENT_CHARACTER_LIMIT
,
130 Hooks
::run( 'ResourceLoaderGetConfigVars', [ &$vars, $skin ] );
136 * Recursively get all explicit and implicit dependencies for to the given module.
138 * @param array $registryData
139 * @param string $moduleName
142 protected static function getImplicitDependencies( array $registryData, $moduleName ) {
143 static $dependencyCache = [];
145 // The list of implicit dependencies won't be altered, so we can
146 // cache them without having to worry.
147 if ( !isset( $dependencyCache[$moduleName] ) ) {
148 if ( !isset( $registryData[$moduleName] ) ) {
149 // Dependencies may not exist
150 $dependencyCache[$moduleName] = [];
152 $data = $registryData[$moduleName];
153 $dependencyCache[$moduleName] = $data['dependencies'];
155 foreach ( $data['dependencies'] as $dependency ) {
156 // Recursively get the dependencies of the dependencies
157 $dependencyCache[$moduleName] = array_merge(
158 $dependencyCache[$moduleName],
159 self
::getImplicitDependencies( $registryData, $dependency )
165 return $dependencyCache[$moduleName];
169 * Optimize the dependency tree in $this->modules.
171 * The optimization basically works like this:
172 * Given we have module A with the dependencies B and C
173 * and module B with the dependency C.
174 * Now we don't have to tell the client to explicitly fetch module
175 * C as that's already included in module B.
177 * This way we can reasonably reduce the amount of module registration
178 * data send to the client.
180 * @param array &$registryData Modules keyed by name with properties:
182 * - array 'dependencies'
183 * - string|null 'group'
186 public static function compileUnresolvedDependencies( array &$registryData ) {
187 foreach ( $registryData as $name => &$data ) {
188 $dependencies = $data['dependencies'];
189 foreach ( $data['dependencies'] as $dependency ) {
190 $implicitDependencies = self
::getImplicitDependencies( $registryData, $dependency );
191 $dependencies = array_diff( $dependencies, $implicitDependencies );
194 $data['dependencies'] = array_values( $dependencies );
199 * Get registration code for all modules.
201 * @param ResourceLoaderContext $context
202 * @return string JavaScript code for registering all modules with the client loader
204 public function getModuleRegistrations( ResourceLoaderContext
$context ) {
205 $resourceLoader = $context->getResourceLoader();
206 // Future developers: Use WebRequest::getRawVal() instead getVal().
207 // The getVal() method performs slow Language+UTF logic. (f303bb9360)
208 $target = $context->getRequest()->getRawVal( 'target', 'desktop' );
209 $safemode = $context->getRequest()->getRawVal( 'safemode' ) === '1';
210 // Bypass target filter if this request is Special:JavaScriptTest.
211 // To prevent misuse in production, this is only allowed if testing is enabled server-side.
212 $byPassTargetFilter = $this->getConfig()->get( 'EnableJavaScriptTest' ) && $target === 'test';
217 $moduleNames = $resourceLoader->getModuleNames();
219 // Preload with a batch so that the below calls to getVersionHash() for each module
220 // don't require on-demand loading of more information.
222 $resourceLoader->preloadModuleInfo( $moduleNames, $context );
223 } catch ( Exception
$e ) {
224 // Don't fail the request (T152266)
225 // Also print the error in the main output
226 $resourceLoader->outputErrorAndLog( $e,
227 'Preloading module info from startup failed: {exception}',
228 [ 'exception' => $e ]
233 foreach ( $moduleNames as $name ) {
234 $module = $resourceLoader->getModule( $name );
235 $moduleTargets = $module->getTargets();
237 ( !$byPassTargetFilter && !in_array( $target, $moduleTargets ) )
238 ||
( $safemode && $module->getOrigin() > ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
)
243 if ( $module->isRaw() ) {
244 // Don't register "raw" modules (like 'startup') client-side because depending on them
245 // is illegal anyway and would only lead to them being loaded a second time,
246 // causing any state to be lost.
248 // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
249 // Think carefully before making changes to this code!
250 // The below code is going to call ResourceLoaderModule::getVersionHash() for every module.
251 // For StartUpModule (this module) the hash is computed based on the manifest content,
252 // which is the very thing we are computing right here. As such, this must skip iterating
253 // over 'startup' itself.
258 $versionHash = $module->getVersionHash( $context );
259 } catch ( Exception
$e ) {
260 // Don't fail the request (T152266)
261 // Also print the error in the main output
262 $resourceLoader->outputErrorAndLog( $e,
263 'Calculating version for "{module}" failed: {exception}',
270 $states[$name] = 'error';
273 if ( $versionHash !== '' && strlen( $versionHash ) !== 7 ) {
274 $context->getLogger()->warning(
275 "Module '{module}' produced an invalid version hash: '{version}'.",
278 'version' => $versionHash,
281 // Module implementation either broken or deviated from ResourceLoader::makeHash
282 // Asserted by tests/phpunit/structure/ResourcesTest.
283 $versionHash = ResourceLoader
::makeHash( $versionHash );
286 $skipFunction = $module->getSkipFunction();
287 if ( $skipFunction !== null && !ResourceLoader
::inDebugMode() ) {
288 $skipFunction = ResourceLoader
::filter( 'minify-js', $skipFunction );
291 $registryData[$name] = [
292 'version' => $versionHash,
293 'dependencies' => $module->getDependencies( $context ),
294 'group' => $module->getGroup(),
295 'source' => $module->getSource(),
296 'skip' => $skipFunction,
300 self
::compileUnresolvedDependencies( $registryData );
303 $out .= ResourceLoader
::makeLoaderSourcesScript( $resourceLoader->getSources() );
305 // Figure out the different call signatures for mw.loader.register
307 foreach ( $registryData as $name => $data ) {
308 // Call mw.loader.register(name, version, dependencies, group, source, skip)
312 $data['dependencies'],
314 // Swap default (local) for null
315 $data['source'] === 'local' ?
null : $data['source'],
321 $out .= "\n" . ResourceLoader
::makeLoaderRegisterScript( $registrations );
324 $out .= "\n" . ResourceLoader
::makeLoaderStateScript( $states );
333 public function isRaw() {
338 * Internal modules used by ResourceLoader that cannot be depended on.
340 * These module(s) should have isRaw() return true, and are not
341 * legal dependencies (enforced by structure/ResourcesTest).
343 * @deprecated since 1.32 No longer used.
346 public static function getStartupModules() {
347 wfDeprecated( __METHOD__
, '1.32' );
352 * @deprecated since 1.32 No longer used.
355 public static function getLegacyModules() {
356 wfDeprecated( __METHOD__
, '1.32' );
361 * @private For internal use by SpecialJavaScriptTest
365 public function getBaseModulesInternal() {
366 return $this->getBaseModules();
370 * Base modules implicitly available to all modules.
374 private function getBaseModules() {
375 global $wgIncludeLegacyJavaScript;
377 $baseModules = [ 'jquery', 'mediawiki.base' ];
378 if ( $wgIncludeLegacyJavaScript ) {
379 $baseModules[] = 'mediawiki.legacy.wikibits';
386 * @param ResourceLoaderContext $context
387 * @return string JavaScript code
389 public function getScript( ResourceLoaderContext
$context ) {
391 if ( $context->getOnly() !== 'scripts' ) {
392 return '/* Requires only=script */';
395 $startupCode = file_get_contents( "$IP/resources/src/startup/startup.js" );
397 // The files read here MUST be kept in sync with maintenance/jsduck/eg-iframe.html,
398 // and MUST be considered by 'fileHashes' in StartUpModule::getDefinitionSummary().
399 $mwLoaderCode = file_get_contents( "$IP/resources/src/startup/mediawiki.js" ) .
400 file_get_contents( "$IP/resources/src/startup/mediawiki.requestIdleCallback.js" );
401 if ( $context->getDebug() ) {
402 $mwLoaderCode .= file_get_contents( "$IP/resources/src/startup/mediawiki.log.js" );
404 if ( $this->getConfig()->get( 'ResourceLoaderEnableJSProfiler' ) ) {
405 $mwLoaderCode .= file_get_contents( "$IP/resources/src/startup/profiler.js" );
408 // Perform replacements for mediawiki.js
410 '$VARS.baseModules' => ResourceLoader
::encodeJsonForScript( $this->getBaseModules() ),
413 '$CODE.profileExecuteStart();' => 'mw.loader.profiler.onExecuteStart( module );',
414 '$CODE.profileExecuteEnd();' => 'mw.loader.profiler.onExecuteEnd( module );',
415 '$CODE.profileScriptStart();' => 'mw.loader.profiler.onScriptStart( module );',
416 '$CODE.profileScriptEnd();' => 'mw.loader.profiler.onScriptEnd( module );',
418 if ( $this->getConfig()->get( 'ResourceLoaderEnableJSProfiler' ) ) {
419 // When profiling is enabled, insert the calls.
420 $mwLoaderPairs +
= $profilerStubs;
422 // When disabled (by default), insert nothing.
423 $mwLoaderPairs +
= array_fill_keys( array_keys( $profilerStubs ), '' );
425 $mwLoaderCode = strtr( $mwLoaderCode, $mwLoaderPairs );
427 // Perform string replacements for startup.js
429 '$VARS.wgLegacyJavaScriptGlobals' => ResourceLoader
::encodeJsonForScript(
430 $this->getConfig()->get( 'LegacyJavaScriptGlobals' )
432 '$VARS.configuration' => ResourceLoader
::encodeJsonForScript(
433 $this->getConfigSettings( $context )
435 // Raw JavaScript code (not JSON)
436 '$CODE.registrations();' => trim( $this->getModuleRegistrations( $context ) ),
437 '$CODE.defineLoader();' => $mwLoaderCode,
439 $startupCode = strtr( $startupCode, $pairs );
447 public function supportsURLLoading() {
454 public function enableModuleContentVersion() {
455 // Enabling this means that ResourceLoader::getVersionHash will simply call getScript()
456 // and hash it to determine the version (as used by E-Tag HTTP response header).
463 public function getGroup() {