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
24 * Module for ResourceLoader initialization.
26 * See also <https://www.mediawiki.org/wiki/ResourceLoader/Features#Startup_Module>
28 * The startup module, as being called only from ResourceLoaderClientHtml, has
29 * the ability to vary based extra query parameters, in addition to those
30 * from ResourceLoaderContext:
32 * - target: Only register modules in the client allowed within this target.
34 * See also: OutputPage::setTarget(), ResourceLoaderModule::getTargets().
36 class ResourceLoaderStartUpModule
extends ResourceLoaderModule
{
38 // Cache for getConfigSettings() as it's called by multiple methods
39 protected $configVars = [];
40 protected $targets = [ 'desktop', 'mobile' ];
43 * @param ResourceLoaderContext $context
46 protected function getConfigSettings( $context ) {
47 $hash = $context->getHash();
48 if ( isset( $this->configVars
[$hash] ) ) {
49 return $this->configVars
[$hash];
53 $conf = $this->getConfig();
55 // We can't use Title::newMainPage() if 'mainpage' is in
56 // $wgForceUIMsgAsContentMsg because that will try to use the session
57 // user's language and we have no session user. This does the
58 // equivalent but falling back to our ResourceLoaderContext language
60 $mainPage = Title
::newFromText( $context->msg( 'mainpage' )->inContentLanguage()->text() );
62 $mainPage = Title
::newFromText( 'Main Page' );
66 * Namespace related preparation
67 * - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces.
68 * - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive.
70 $namespaceIds = $wgContLang->getNamespaceIds();
71 $caseSensitiveNamespaces = [];
72 foreach ( MWNamespace
::getCanonicalNamespaces() as $index => $name ) {
73 $namespaceIds[$wgContLang->lc( $name )] = $index;
74 if ( !MWNamespace
::isCapitalized( $index ) ) {
75 $caseSensitiveNamespaces[] = $index;
79 $illegalFileChars = $conf->get( 'IllegalFileChars' );
80 $oldCommentSchema = $conf->get( 'CommentTableSchemaMigrationStage' ) === MIGRATION_OLD
;
82 // Build list of variables
84 'wgLoadScript' => wfScript( 'load' ),
85 'debug' => $context->getDebug(),
86 'skin' => $context->getSkin(),
87 'stylepath' => $conf->get( 'StylePath' ),
88 'wgUrlProtocols' => wfUrlProtocols(),
89 'wgArticlePath' => $conf->get( 'ArticlePath' ),
90 'wgScriptPath' => $conf->get( 'ScriptPath' ),
91 'wgScript' => wfScript(),
92 'wgSearchType' => $conf->get( 'SearchType' ),
93 'wgVariantArticlePath' => $conf->get( 'VariantArticlePath' ),
94 // Force object to avoid "empty" associative array from
95 // becoming [] instead of {} in JS (T36604)
96 'wgActionPaths' => (object)$conf->get( 'ActionPaths' ),
97 'wgServer' => $conf->get( 'Server' ),
98 'wgServerName' => $conf->get( 'ServerName' ),
99 'wgUserLanguage' => $context->getLanguage(),
100 'wgContentLanguage' => $wgContLang->getCode(),
101 'wgTranslateNumerals' => $conf->get( 'TranslateNumerals' ),
102 'wgVersion' => $conf->get( 'Version' ),
103 'wgEnableAPI' => true, // Deprecated since MW 1.32
104 'wgEnableWriteAPI' => true, // Deprecated since MW 1.32
105 'wgMainPageTitle' => $mainPage->getPrefixedText(),
106 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
107 'wgNamespaceIds' => $namespaceIds,
108 'wgContentNamespaces' => MWNamespace
::getContentNamespaces(),
109 'wgSiteName' => $conf->get( 'Sitename' ),
110 'wgDBname' => $conf->get( 'DBname' ),
111 'wgExtraSignatureNamespaces' => $conf->get( 'ExtraSignatureNamespaces' ),
112 'wgAvailableSkins' => Skin
::getSkinNames(),
113 'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
114 // MediaWiki sets cookies to have this prefix by default
115 'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
116 'wgCookieDomain' => $conf->get( 'CookieDomain' ),
117 'wgCookiePath' => $conf->get( 'CookiePath' ),
118 'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
119 'wgResourceLoaderMaxQueryLength' => $conf->get( 'ResourceLoaderMaxQueryLength' ),
120 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
121 'wgLegalTitleChars' => Title
::convertByteClassToUnicodeClass( Title
::legalChars() ),
122 'wgIllegalFileChars' => Title
::convertByteClassToUnicodeClass( $illegalFileChars ),
123 'wgResourceLoaderStorageVersion' => $conf->get( 'ResourceLoaderStorageVersion' ),
124 'wgResourceLoaderStorageEnabled' => $conf->get( 'ResourceLoaderStorageEnabled' ),
125 'wgForeignUploadTargets' => $conf->get( 'ForeignUploadTargets' ),
126 'wgEnableUploads' => $conf->get( 'EnableUploads' ),
127 'wgCommentByteLimit' => $oldCommentSchema ?
255 : null,
128 'wgCommentCodePointLimit' => $oldCommentSchema ?
null : CommentStore
::COMMENT_CHARACTER_LIMIT
,
131 Hooks
::run( 'ResourceLoaderGetConfigVars', [ &$vars ] );
133 $this->configVars
[$hash] = $vars;
134 return $this->configVars
[$hash];
138 * Recursively get all explicit and implicit dependencies for to the given module.
140 * @param array $registryData
141 * @param string $moduleName
144 protected static function getImplicitDependencies( array $registryData, $moduleName ) {
145 static $dependencyCache = [];
147 // The list of implicit dependencies won't be altered, so we can
148 // cache them without having to worry.
149 if ( !isset( $dependencyCache[$moduleName] ) ) {
150 if ( !isset( $registryData[$moduleName] ) ) {
151 // Dependencies may not exist
152 $dependencyCache[$moduleName] = [];
154 $data = $registryData[$moduleName];
155 $dependencyCache[$moduleName] = $data['dependencies'];
157 foreach ( $data['dependencies'] as $dependency ) {
158 // Recursively get the dependencies of the dependencies
159 $dependencyCache[$moduleName] = array_merge(
160 $dependencyCache[$moduleName],
161 self
::getImplicitDependencies( $registryData, $dependency )
167 return $dependencyCache[$moduleName];
171 * Optimize the dependency tree in $this->modules.
173 * The optimization basically works like this:
174 * Given we have module A with the dependencies B and C
175 * and module B with the dependency C.
176 * Now we don't have to tell the client to explicitly fetch module
177 * C as that's already included in module B.
179 * This way we can reasonably reduce the amount of module registration
180 * data send to the client.
182 * @param array &$registryData Modules keyed by name with properties:
184 * - array 'dependencies'
185 * - string|null 'group'
188 public static function compileUnresolvedDependencies( array &$registryData ) {
189 foreach ( $registryData as $name => &$data ) {
190 $dependencies = $data['dependencies'];
191 foreach ( $data['dependencies'] as $dependency ) {
192 $implicitDependencies = self
::getImplicitDependencies( $registryData, $dependency );
193 $dependencies = array_diff( $dependencies, $implicitDependencies );
196 $data['dependencies'] = array_values( $dependencies );
201 * Get registration code for all modules.
203 * @param ResourceLoaderContext $context
204 * @return string JavaScript code for registering all modules with the client loader
206 public function getModuleRegistrations( ResourceLoaderContext
$context ) {
207 $resourceLoader = $context->getResourceLoader();
208 // Future developers: Use WebRequest::getRawVal() instead getVal().
209 // The getVal() method performs slow Language+UTF logic. (f303bb9360)
210 $target = $context->getRequest()->getRawVal( 'target', 'desktop' );
211 // Bypass target filter if this request is Special:JavaScriptTest.
212 // To prevent misuse in production, this is only allowed if testing is enabled server-side.
213 $byPassTargetFilter = $this->getConfig()->get( 'EnableJavaScriptTest' ) && $target === 'test';
220 foreach ( $resourceLoader->getModuleNames() as $name ) {
221 $module = $resourceLoader->getModule( $name );
222 $moduleTargets = $module->getTargets();
223 if ( !$byPassTargetFilter && !in_array( $target, $moduleTargets ) ) {
227 if ( $module->isRaw() ) {
228 // Don't register "raw" modules (like 'jquery' and 'mediawiki') client-side because
229 // depending on them is illegal anyway and would only lead to them being reloaded
230 // causing any state to be lost (like jQuery plugins, mw.config etc.)
235 $versionHash = $module->getVersionHash( $context );
236 } catch ( Exception
$e ) {
237 // See also T152266 and ResourceLoader::getCombinedVersion()
238 MWExceptionHandler
::logException( $e );
239 $context->getLogger()->warning(
240 'Calculating version for "{module}" failed: {exception}',
247 $states[$name] = 'error';
250 if ( $versionHash !== '' && strlen( $versionHash ) !== 7 ) {
251 $context->getLogger()->warning(
252 "Module '{module}' produced an invalid version hash: '{version}'.",
255 'version' => $versionHash,
258 // Module implementation either broken or deviated from ResourceLoader::makeHash
259 // Asserted by tests/phpunit/structure/ResourcesTest.
260 $versionHash = ResourceLoader
::makeHash( $versionHash );
263 $skipFunction = $module->getSkipFunction();
264 if ( $skipFunction !== null && !ResourceLoader
::inDebugMode() ) {
265 $skipFunction = ResourceLoader
::filter( 'minify-js', $skipFunction );
268 $registryData[$name] = [
269 'version' => $versionHash,
270 'dependencies' => $module->getDependencies( $context ),
271 'group' => $module->getGroup(),
272 'source' => $module->getSource(),
273 'skip' => $skipFunction,
277 self
::compileUnresolvedDependencies( $registryData );
280 $out .= ResourceLoader
::makeLoaderSourcesScript( $resourceLoader->getSources() );
282 // Figure out the different call signatures for mw.loader.register
284 foreach ( $registryData as $name => $data ) {
285 // Call mw.loader.register(name, version, dependencies, group, source, skip)
289 $data['dependencies'],
291 // Swap default (local) for null
292 $data['source'] === 'local' ?
null : $data['source'],
298 $out .= "\n" . ResourceLoader
::makeLoaderRegisterScript( $registrations );
301 $out .= "\n" . ResourceLoader
::makeLoaderStateScript( $states );
310 public function isRaw() {
315 * @param ResourceLoaderContext $context
318 public function getPreloadLinks( ResourceLoaderContext
$context ) {
319 $url = self
::getStartupModulesUrl( $context );
321 $url => [ 'as' => 'script' ]
326 * Base modules required for the base environment of ResourceLoader
330 public static function getStartupModules() {
331 return [ 'jquery', 'mediawiki' ];
334 public static function getLegacyModules() {
335 global $wgIncludeLegacyJavaScript;
338 if ( $wgIncludeLegacyJavaScript ) {
339 $legacyModules[] = 'mediawiki.legacy.wikibits';
342 return $legacyModules;
346 * Get the load URL of the startup modules.
348 * This is a helper for getScript(), but can also be called standalone, such
349 * as when generating an AppCache manifest.
351 * @param ResourceLoaderContext $context
354 public static function getStartupModulesUrl( ResourceLoaderContext
$context ) {
355 $rl = $context->getResourceLoader();
356 $derivative = new DerivativeResourceLoaderContext( $context );
357 $derivative->setModules( array_merge(
358 self
::getStartupModules(),
359 self
::getLegacyModules()
361 $derivative->setOnly( 'scripts' );
362 // Must setModules() before makeVersionQuery()
363 $derivative->setVersion( $rl->makeVersionQuery( $derivative ) );
365 return $rl->createLoaderURL( 'local', $derivative );
369 * @param ResourceLoaderContext $context
370 * @return string JavaScript code
372 public function getScript( ResourceLoaderContext
$context ) {
374 if ( $context->getOnly() !== 'scripts' ) {
375 return '/* Requires only=script */';
378 $out = file_get_contents( "$IP/resources/src/startup.js" );
380 $pairs = array_map( function ( $value ) {
381 $value = FormatJson
::encode( $value, ResourceLoader
::inDebugMode(), FormatJson
::ALL_OK
);
383 $value = str_replace( "\n", "\n\t", $value );
386 '$VARS.wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
387 '$VARS.configuration' => $this->getConfigSettings( $context ),
388 // This url may be preloaded. See getPreloadLinks().
389 '$VARS.baseModulesUri' => self
::getStartupModulesUrl( $context ),
391 $pairs['$CODE.registrations()'] = str_replace(
394 trim( $this->getModuleRegistrations( $context ) )
397 return strtr( $out, $pairs );
403 public function supportsURLLoading() {
408 * Get the definition summary for this module.
410 * @param ResourceLoaderContext $context
413 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
415 $summary = parent
::getDefinitionSummary( $context );
417 // Detect changes to variables exposed in mw.config (T30899).
418 'vars' => $this->getConfigSettings( $context ),
419 // Changes how getScript() creates mw.Map for mw.config
420 'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
421 // Detect changes to the module registrations
422 'moduleHashes' => $this->getAllModuleHashes( $context ),
425 filemtime( "$IP/resources/src/startup.js" ),
432 * Helper method for getDefinitionSummary().
434 * @param ResourceLoaderContext $context
435 * @return string SHA-1
437 protected function getAllModuleHashes( ResourceLoaderContext
$context ) {
438 $rl = $context->getResourceLoader();
439 // Preload for getCombinedVersion()
440 $rl->preloadModuleInfo( $rl->getModuleNames(), $context );
442 // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
443 // Think carefully before making changes to this code!
444 // Pre-populate versionHash with something because the loop over all modules below includes
445 // the startup module (this module).
446 // See ResourceLoaderModule::getVersionHash() for usage of this cache.
447 $this->versionHash
[$context->getHash()] = null;
449 return $rl->getCombinedVersion( $context, $rl->getModuleNames() );
455 public function getGroup() {