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 intended for this target.
34 * See also: OutputPage::setTarget(), ResourceLoaderModule::getTargets().
36 * - safemode: Only register modules that have ORIGIN_CORE as their origin.
37 * This effectively disables ORIGIN_USER modules. (T185303)
38 * See also: OutputPage::disallowUserJs()
40 class ResourceLoaderStartUpModule
extends ResourceLoaderModule
{
42 // Cache for getConfigSettings() as it's called by multiple methods
43 protected $configVars = [];
44 protected $targets = [ 'desktop', 'mobile' ];
47 * @param ResourceLoaderContext $context
50 protected function getConfigSettings( $context ) {
51 $hash = $context->getHash();
52 if ( isset( $this->configVars
[$hash] ) ) {
53 return $this->configVars
[$hash];
57 $conf = $this->getConfig();
59 // We can't use Title::newMainPage() if 'mainpage' is in
60 // $wgForceUIMsgAsContentMsg because that will try to use the session
61 // user's language and we have no session user. This does the
62 // equivalent but falling back to our ResourceLoaderContext language
64 $mainPage = Title
::newFromText( $context->msg( 'mainpage' )->inContentLanguage()->text() );
66 $mainPage = Title
::newFromText( 'Main Page' );
70 * Namespace related preparation
71 * - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces.
72 * - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive.
74 $namespaceIds = $wgContLang->getNamespaceIds();
75 $caseSensitiveNamespaces = [];
76 foreach ( MWNamespace
::getCanonicalNamespaces() as $index => $name ) {
77 $namespaceIds[$wgContLang->lc( $name )] = $index;
78 if ( !MWNamespace
::isCapitalized( $index ) ) {
79 $caseSensitiveNamespaces[] = $index;
83 $illegalFileChars = $conf->get( 'IllegalFileChars' );
84 $oldCommentSchema = $conf->get( 'CommentTableSchemaMigrationStage' ) === MIGRATION_OLD
;
86 // Build list of variables
88 'wgLoadScript' => wfScript( 'load' ),
89 'debug' => $context->getDebug(),
90 'skin' => $context->getSkin(),
91 'stylepath' => $conf->get( 'StylePath' ),
92 'wgUrlProtocols' => wfUrlProtocols(),
93 'wgArticlePath' => $conf->get( 'ArticlePath' ),
94 'wgScriptPath' => $conf->get( 'ScriptPath' ),
95 'wgScript' => wfScript(),
96 'wgSearchType' => $conf->get( 'SearchType' ),
97 'wgVariantArticlePath' => $conf->get( 'VariantArticlePath' ),
98 // Force object to avoid "empty" associative array from
99 // becoming [] instead of {} in JS (T36604)
100 'wgActionPaths' => (object)$conf->get( 'ActionPaths' ),
101 'wgServer' => $conf->get( 'Server' ),
102 'wgServerName' => $conf->get( 'ServerName' ),
103 'wgUserLanguage' => $context->getLanguage(),
104 'wgContentLanguage' => $wgContLang->getCode(),
105 'wgTranslateNumerals' => $conf->get( 'TranslateNumerals' ),
106 'wgVersion' => $conf->get( 'Version' ),
107 'wgEnableAPI' => true, // Deprecated since MW 1.32
108 'wgEnableWriteAPI' => true, // Deprecated since MW 1.32
109 'wgMainPageTitle' => $mainPage->getPrefixedText(),
110 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
111 'wgNamespaceIds' => $namespaceIds,
112 'wgContentNamespaces' => MWNamespace
::getContentNamespaces(),
113 'wgSiteName' => $conf->get( 'Sitename' ),
114 'wgDBname' => $conf->get( 'DBname' ),
115 'wgExtraSignatureNamespaces' => $conf->get( 'ExtraSignatureNamespaces' ),
116 'wgAvailableSkins' => Skin
::getSkinNames(),
117 'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
118 // MediaWiki sets cookies to have this prefix by default
119 'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
120 'wgCookieDomain' => $conf->get( 'CookieDomain' ),
121 'wgCookiePath' => $conf->get( 'CookiePath' ),
122 'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
123 'wgResourceLoaderMaxQueryLength' => $conf->get( 'ResourceLoaderMaxQueryLength' ),
124 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
125 'wgLegalTitleChars' => Title
::convertByteClassToUnicodeClass( Title
::legalChars() ),
126 'wgIllegalFileChars' => Title
::convertByteClassToUnicodeClass( $illegalFileChars ),
127 'wgResourceLoaderStorageVersion' => $conf->get( 'ResourceLoaderStorageVersion' ),
128 'wgResourceLoaderStorageEnabled' => $conf->get( 'ResourceLoaderStorageEnabled' ),
129 'wgForeignUploadTargets' => $conf->get( 'ForeignUploadTargets' ),
130 'wgEnableUploads' => $conf->get( 'EnableUploads' ),
131 'wgCommentByteLimit' => $oldCommentSchema ?
255 : null,
132 'wgCommentCodePointLimit' => $oldCommentSchema ?
null : CommentStore
::COMMENT_CHARACTER_LIMIT
,
135 Hooks
::run( 'ResourceLoaderGetConfigVars', [ &$vars ] );
137 $this->configVars
[$hash] = $vars;
138 return $this->configVars
[$hash];
142 * Recursively get all explicit and implicit dependencies for to the given module.
144 * @param array $registryData
145 * @param string $moduleName
148 protected static function getImplicitDependencies( array $registryData, $moduleName ) {
149 static $dependencyCache = [];
151 // The list of implicit dependencies won't be altered, so we can
152 // cache them without having to worry.
153 if ( !isset( $dependencyCache[$moduleName] ) ) {
154 if ( !isset( $registryData[$moduleName] ) ) {
155 // Dependencies may not exist
156 $dependencyCache[$moduleName] = [];
158 $data = $registryData[$moduleName];
159 $dependencyCache[$moduleName] = $data['dependencies'];
161 foreach ( $data['dependencies'] as $dependency ) {
162 // Recursively get the dependencies of the dependencies
163 $dependencyCache[$moduleName] = array_merge(
164 $dependencyCache[$moduleName],
165 self
::getImplicitDependencies( $registryData, $dependency )
171 return $dependencyCache[$moduleName];
175 * Optimize the dependency tree in $this->modules.
177 * The optimization basically works like this:
178 * Given we have module A with the dependencies B and C
179 * and module B with the dependency C.
180 * Now we don't have to tell the client to explicitly fetch module
181 * C as that's already included in module B.
183 * This way we can reasonably reduce the amount of module registration
184 * data send to the client.
186 * @param array &$registryData Modules keyed by name with properties:
188 * - array 'dependencies'
189 * - string|null 'group'
192 public static function compileUnresolvedDependencies( array &$registryData ) {
193 foreach ( $registryData as $name => &$data ) {
194 $dependencies = $data['dependencies'];
195 foreach ( $data['dependencies'] as $dependency ) {
196 $implicitDependencies = self
::getImplicitDependencies( $registryData, $dependency );
197 $dependencies = array_diff( $dependencies, $implicitDependencies );
200 $data['dependencies'] = array_values( $dependencies );
205 * Get registration code for all modules.
207 * @param ResourceLoaderContext $context
208 * @return string JavaScript code for registering all modules with the client loader
210 public function getModuleRegistrations( ResourceLoaderContext
$context ) {
211 $resourceLoader = $context->getResourceLoader();
212 // Future developers: Use WebRequest::getRawVal() instead getVal().
213 // The getVal() method performs slow Language+UTF logic. (f303bb9360)
214 $target = $context->getRequest()->getRawVal( 'target', 'desktop' );
215 $safemode = $context->getRequest()->getRawVal( 'safemode' ) === '1';
216 // Bypass target filter if this request is Special:JavaScriptTest.
217 // To prevent misuse in production, this is only allowed if testing is enabled server-side.
218 $byPassTargetFilter = $this->getConfig()->get( 'EnableJavaScriptTest' ) && $target === 'test';
225 foreach ( $resourceLoader->getModuleNames() as $name ) {
226 $module = $resourceLoader->getModule( $name );
227 $moduleTargets = $module->getTargets();
229 ( !$byPassTargetFilter && !in_array( $target, $moduleTargets ) )
230 ||
( $safemode && $module->getOrigin() > ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
)
235 if ( $module->isRaw() ) {
236 // Don't register "raw" modules (like 'jquery' and 'mediawiki') client-side because
237 // depending on them is illegal anyway and would only lead to them being reloaded
238 // causing any state to be lost (like jQuery plugins, mw.config etc.)
243 $versionHash = $module->getVersionHash( $context );
244 } catch ( Exception
$e ) {
245 // See also T152266 and ResourceLoader::getCombinedVersion()
246 MWExceptionHandler
::logException( $e );
247 $context->getLogger()->warning(
248 'Calculating version for "{module}" failed: {exception}',
255 $states[$name] = 'error';
258 if ( $versionHash !== '' && strlen( $versionHash ) !== 7 ) {
259 $context->getLogger()->warning(
260 "Module '{module}' produced an invalid version hash: '{version}'.",
263 'version' => $versionHash,
266 // Module implementation either broken or deviated from ResourceLoader::makeHash
267 // Asserted by tests/phpunit/structure/ResourcesTest.
268 $versionHash = ResourceLoader
::makeHash( $versionHash );
271 $skipFunction = $module->getSkipFunction();
272 if ( $skipFunction !== null && !ResourceLoader
::inDebugMode() ) {
273 $skipFunction = ResourceLoader
::filter( 'minify-js', $skipFunction );
276 $registryData[$name] = [
277 'version' => $versionHash,
278 'dependencies' => $module->getDependencies( $context ),
279 'group' => $module->getGroup(),
280 'source' => $module->getSource(),
281 'skip' => $skipFunction,
285 self
::compileUnresolvedDependencies( $registryData );
288 $out .= ResourceLoader
::makeLoaderSourcesScript( $resourceLoader->getSources() );
290 // Figure out the different call signatures for mw.loader.register
292 foreach ( $registryData as $name => $data ) {
293 // Call mw.loader.register(name, version, dependencies, group, source, skip)
297 $data['dependencies'],
299 // Swap default (local) for null
300 $data['source'] === 'local' ?
null : $data['source'],
306 $out .= "\n" . ResourceLoader
::makeLoaderRegisterScript( $registrations );
309 $out .= "\n" . ResourceLoader
::makeLoaderStateScript( $states );
318 public function isRaw() {
323 * @param ResourceLoaderContext $context
326 public function getPreloadLinks( ResourceLoaderContext
$context ) {
327 $url = self
::getStartupModulesUrl( $context );
329 $url => [ 'as' => 'script' ]
334 * Base modules required for the base environment of ResourceLoader
338 public static function getStartupModules() {
339 return [ 'jquery', 'mediawiki', 'mediawiki.base' ];
342 public static function getLegacyModules() {
343 global $wgIncludeLegacyJavaScript;
346 if ( $wgIncludeLegacyJavaScript ) {
347 $legacyModules[] = 'mediawiki.legacy.wikibits';
350 return $legacyModules;
354 * Get the load URL of the startup modules.
356 * This is a helper for getScript(), but can also be called standalone, such
357 * as when generating an AppCache manifest.
359 * @param ResourceLoaderContext $context
362 public static function getStartupModulesUrl( ResourceLoaderContext
$context ) {
363 $rl = $context->getResourceLoader();
364 $derivative = new DerivativeResourceLoaderContext( $context );
365 $derivative->setModules( array_merge(
366 self
::getStartupModules(),
367 self
::getLegacyModules()
369 $derivative->setOnly( 'scripts' );
370 // Must setModules() before makeVersionQuery()
371 $derivative->setVersion( $rl->makeVersionQuery( $derivative ) );
373 return $rl->createLoaderURL( 'local', $derivative );
377 * @param ResourceLoaderContext $context
378 * @return string JavaScript code
380 public function getScript( ResourceLoaderContext
$context ) {
382 if ( $context->getOnly() !== 'scripts' ) {
383 return '/* Requires only=script */';
386 $out = file_get_contents( "$IP/resources/src/startup.js" );
388 $pairs = array_map( function ( $value ) {
389 $value = FormatJson
::encode( $value, ResourceLoader
::inDebugMode(), FormatJson
::ALL_OK
);
391 $value = str_replace( "\n", "\n\t", $value );
394 '$VARS.wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
395 '$VARS.configuration' => $this->getConfigSettings( $context ),
396 // This url may be preloaded. See getPreloadLinks().
397 '$VARS.baseModulesUri' => self
::getStartupModulesUrl( $context ),
399 $pairs['$CODE.registrations();'] = str_replace(
402 trim( $this->getModuleRegistrations( $context ) )
405 return strtr( $out, $pairs );
411 public function supportsURLLoading() {
416 * Get the definition summary for this module.
418 * @param ResourceLoaderContext $context
421 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
423 $summary = parent
::getDefinitionSummary( $context );
425 // Detect changes to variables exposed in mw.config (T30899).
426 'vars' => $this->getConfigSettings( $context ),
427 // Changes how getScript() creates mw.Map for mw.config
428 'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
429 // Detect changes to the module registrations
430 'moduleHashes' => $this->getAllModuleHashes( $context ),
433 $this->safeFileHash( "$IP/resources/src/startup.js" ),
440 * Helper method for getDefinitionSummary().
442 * @param ResourceLoaderContext $context
443 * @return string SHA-1
445 protected function getAllModuleHashes( ResourceLoaderContext
$context ) {
446 $rl = $context->getResourceLoader();
447 // Preload for getCombinedVersion()
448 $rl->preloadModuleInfo( $rl->getModuleNames(), $context );
450 // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
451 // Think carefully before making changes to this code!
452 // Pre-populate versionHash with something because the loop over all modules below includes
453 // the startup module (this module).
454 // See ResourceLoaderModule::getVersionHash() for usage of this cache.
455 $this->versionHash
[$context->getHash()] = null;
457 return $rl->getCombinedVersion( $context, $rl->getModuleNames() );
463 public function getGroup() {