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 'wgScriptExtension' => '.php',
92 'wgScript' => wfScript(),
93 'wgSearchType' => $conf->get( 'SearchType' ),
94 'wgVariantArticlePath' => $conf->get( 'VariantArticlePath' ),
95 // Force object to avoid "empty" associative array from
96 // becoming [] instead of {} in JS (T36604)
97 'wgActionPaths' => (object)$conf->get( 'ActionPaths' ),
98 'wgServer' => $conf->get( 'Server' ),
99 'wgServerName' => $conf->get( 'ServerName' ),
100 'wgUserLanguage' => $context->getLanguage(),
101 'wgContentLanguage' => $wgContLang->getCode(),
102 'wgTranslateNumerals' => $conf->get( 'TranslateNumerals' ),
103 'wgVersion' => $conf->get( 'Version' ),
104 'wgEnableAPI' => $conf->get( 'EnableAPI' ),
105 'wgEnableWriteAPI' => $conf->get( 'EnableWriteAPI' ),
106 'wgMainPageTitle' => $mainPage->getPrefixedText(),
107 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
108 'wgNamespaceIds' => $namespaceIds,
109 'wgContentNamespaces' => MWNamespace
::getContentNamespaces(),
110 'wgSiteName' => $conf->get( 'Sitename' ),
111 'wgDBname' => $conf->get( 'DBname' ),
112 'wgExtraSignatureNamespaces' => $conf->get( 'ExtraSignatureNamespaces' ),
113 'wgAvailableSkins' => Skin
::getSkinNames(),
114 'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
115 // MediaWiki sets cookies to have this prefix by default
116 'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
117 'wgCookieDomain' => $conf->get( 'CookieDomain' ),
118 'wgCookiePath' => $conf->get( 'CookiePath' ),
119 'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
120 'wgResourceLoaderMaxQueryLength' => $conf->get( 'ResourceLoaderMaxQueryLength' ),
121 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
122 'wgLegalTitleChars' => Title
::convertByteClassToUnicodeClass( Title
::legalChars() ),
123 'wgIllegalFileChars' => Title
::convertByteClassToUnicodeClass( $illegalFileChars ),
124 'wgResourceLoaderStorageVersion' => $conf->get( 'ResourceLoaderStorageVersion' ),
125 'wgResourceLoaderStorageEnabled' => $conf->get( 'ResourceLoaderStorageEnabled' ),
126 'wgForeignUploadTargets' => $conf->get( 'ForeignUploadTargets' ),
127 'wgEnableUploads' => $conf->get( 'EnableUploads' ),
128 'wgCommentByteLimit' => $oldCommentSchema ?
255 : null,
129 'wgCommentCodePointLimit' => $oldCommentSchema ?
null : CommentStore
::COMMENT_CHARACTER_LIMIT
,
132 Hooks
::run( 'ResourceLoaderGetConfigVars', [ &$vars ] );
134 $this->configVars
[$hash] = $vars;
135 return $this->configVars
[$hash];
139 * Recursively get all explicit and implicit dependencies for to the given module.
141 * @param array $registryData
142 * @param string $moduleName
145 protected static function getImplicitDependencies( array $registryData, $moduleName ) {
146 static $dependencyCache = [];
148 // The list of implicit dependencies won't be altered, so we can
149 // cache them without having to worry.
150 if ( !isset( $dependencyCache[$moduleName] ) ) {
151 if ( !isset( $registryData[$moduleName] ) ) {
152 // Dependencies may not exist
153 $dependencyCache[$moduleName] = [];
155 $data = $registryData[$moduleName];
156 $dependencyCache[$moduleName] = $data['dependencies'];
158 foreach ( $data['dependencies'] as $dependency ) {
159 // Recursively get the dependencies of the dependencies
160 $dependencyCache[$moduleName] = array_merge(
161 $dependencyCache[$moduleName],
162 self
::getImplicitDependencies( $registryData, $dependency )
168 return $dependencyCache[$moduleName];
172 * Optimize the dependency tree in $this->modules.
174 * The optimization basically works like this:
175 * Given we have module A with the dependencies B and C
176 * and module B with the dependency C.
177 * Now we don't have to tell the client to explicitly fetch module
178 * C as that's already included in module B.
180 * This way we can reasonably reduce the amount of module registration
181 * data send to the client.
183 * @param array &$registryData Modules keyed by name with properties:
185 * - array 'dependencies'
186 * - string|null 'group'
189 public static function compileUnresolvedDependencies( array &$registryData ) {
190 foreach ( $registryData as $name => &$data ) {
191 $dependencies = $data['dependencies'];
192 foreach ( $data['dependencies'] as $dependency ) {
193 $implicitDependencies = self
::getImplicitDependencies( $registryData, $dependency );
194 $dependencies = array_diff( $dependencies, $implicitDependencies );
197 $data['dependencies'] = array_values( $dependencies );
202 * Get registration code for all modules.
204 * @param ResourceLoaderContext $context
205 * @return string JavaScript code for registering all modules with the client loader
207 public function getModuleRegistrations( ResourceLoaderContext
$context ) {
208 $resourceLoader = $context->getResourceLoader();
209 $target = $context->getRequest()->getVal( 'target', 'desktop' );
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';
219 foreach ( $resourceLoader->getModuleNames() as $name ) {
220 $module = $resourceLoader->getModule( $name );
221 $moduleTargets = $module->getTargets();
222 if ( !$byPassTargetFilter && !in_array( $target, $moduleTargets ) ) {
226 if ( $module->isRaw() ) {
227 // Don't register "raw" modules (like 'jquery' and 'mediawiki') client-side because
228 // depending on them is illegal anyway and would only lead to them being reloaded
229 // causing any state to be lost (like jQuery plugins, mw.config etc.)
234 $versionHash = $module->getVersionHash( $context );
235 } catch ( Exception
$e ) {
236 // See also T152266 and ResourceLoader::getCombinedVersion()
237 MWExceptionHandler
::logException( $e );
238 $context->getLogger()->warning(
239 'Calculating version for "{module}" failed: {exception}',
246 $states[$name] = 'error';
249 if ( $versionHash !== '' && strlen( $versionHash ) !== 7 ) {
250 $context->getLogger()->warning(
251 "Module '{module}' produced an invalid version hash: '{version}'.",
254 'version' => $versionHash,
257 // Module implementation either broken or deviated from ResourceLoader::makeHash
258 // Asserted by tests/phpunit/structure/ResourcesTest.
259 $versionHash = ResourceLoader
::makeHash( $versionHash );
262 $skipFunction = $module->getSkipFunction();
263 if ( $skipFunction !== null && !ResourceLoader
::inDebugMode() ) {
264 $skipFunction = ResourceLoader
::filter( 'minify-js', $skipFunction );
267 $registryData[$name] = [
268 'version' => $versionHash,
269 'dependencies' => $module->getDependencies( $context ),
270 'group' => $module->getGroup(),
271 'source' => $module->getSource(),
272 'skip' => $skipFunction,
276 self
::compileUnresolvedDependencies( $registryData );
279 $out .= ResourceLoader
::makeLoaderSourcesScript( $resourceLoader->getSources() );
281 // Figure out the different call signatures for mw.loader.register
283 foreach ( $registryData as $name => $data ) {
284 // Call mw.loader.register(name, version, dependencies, group, source, skip)
288 $data['dependencies'],
290 // Swap default (local) for null
291 $data['source'] === 'local' ?
null : $data['source'],
297 $out .= "\n" . ResourceLoader
::makeLoaderRegisterScript( $registrations );
300 $out .= "\n" . ResourceLoader
::makeLoaderStateScript( $states );
309 public function isRaw() {
314 * @param ResourceLoaderContext $context
317 public function getPreloadLinks( ResourceLoaderContext
$context ) {
318 $url = self
::getStartupModulesUrl( $context );
320 $url => [ 'as' => 'script' ]
325 * Base modules required for the base environment of ResourceLoader
329 public static function getStartupModules() {
330 return [ 'jquery', 'mediawiki' ];
333 public static function getLegacyModules() {
334 global $wgIncludeLegacyJavaScript;
337 if ( $wgIncludeLegacyJavaScript ) {
338 $legacyModules[] = 'mediawiki.legacy.wikibits';
341 return $legacyModules;
345 * Get the load URL of the startup modules.
347 * This is a helper for getScript(), but can also be called standalone, such
348 * as when generating an AppCache manifest.
350 * @param ResourceLoaderContext $context
353 public static function getStartupModulesUrl( ResourceLoaderContext
$context ) {
354 $rl = $context->getResourceLoader();
355 $derivative = new DerivativeResourceLoaderContext( $context );
356 $derivative->setModules( array_merge(
357 self
::getStartupModules(),
358 self
::getLegacyModules()
360 $derivative->setOnly( 'scripts' );
361 // Must setModules() before makeVersionQuery()
362 $derivative->setVersion( $rl->makeVersionQuery( $derivative ) );
364 return $rl->createLoaderURL( 'local', $derivative );
368 * @param ResourceLoaderContext $context
369 * @return string JavaScript code
371 public function getScript( ResourceLoaderContext
$context ) {
373 if ( $context->getOnly() !== 'scripts' ) {
374 return '/* Requires only=script */';
377 $out = file_get_contents( "$IP/resources/src/startup.js" );
379 $pairs = array_map( function ( $value ) {
380 $value = FormatJson
::encode( $value, ResourceLoader
::inDebugMode(), FormatJson
::ALL_OK
);
382 $value = str_replace( "\n", "\n\t", $value );
385 '$VARS.wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
386 '$VARS.configuration' => $this->getConfigSettings( $context ),
387 // This url may be preloaded. See getPreloadLinks().
388 '$VARS.baseModulesUri' => self
::getStartupModulesUrl( $context ),
390 $pairs['$CODE.registrations()'] = str_replace(
393 trim( $this->getModuleRegistrations( $context ) )
396 return strtr( $out, $pairs );
402 public function supportsURLLoading() {
407 * Get the definition summary for this module.
409 * @param ResourceLoaderContext $context
412 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
414 $summary = parent
::getDefinitionSummary( $context );
416 // Detect changes to variables exposed in mw.config (T30899).
417 'vars' => $this->getConfigSettings( $context ),
418 // Changes how getScript() creates mw.Map for mw.config
419 'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
420 // Detect changes to the module registrations
421 'moduleHashes' => $this->getAllModuleHashes( $context ),
424 filemtime( "$IP/resources/src/startup.js" ),
431 * Helper method for getDefinitionSummary().
433 * @param ResourceLoaderContext $context
434 * @return string SHA-1
436 protected function getAllModuleHashes( ResourceLoaderContext
$context ) {
437 $rl = $context->getResourceLoader();
438 // Preload for getCombinedVersion()
439 $rl->preloadModuleInfo( $rl->getModuleNames(), $context );
441 // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
442 // Think carefully before making changes to this code!
443 // Pre-populate versionHash with something because the loop over all modules below includes
444 // the startup module (this module).
445 // See ResourceLoaderModule::getVersionHash() for usage of this cache.
446 $this->versionHash
[$context->getHash()] = null;
448 return $rl->getCombinedVersion( $context, $rl->getModuleNames() );
454 public function getGroup() {