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' );
79 // Build list of variables
80 $skin = $context->getSkin();
82 'wgLoadScript' => wfScript( 'load' ),
83 'debug' => $context->getDebug(),
85 'stylepath' => $conf->get( 'StylePath' ),
86 'wgUrlProtocols' => wfUrlProtocols(),
87 'wgArticlePath' => $conf->get( 'ArticlePath' ),
88 'wgScriptPath' => $conf->get( 'ScriptPath' ),
89 'wgScript' => wfScript(),
90 'wgSearchType' => $conf->get( 'SearchType' ),
91 'wgVariantArticlePath' => $conf->get( 'VariantArticlePath' ),
92 // Force object to avoid "empty" associative array from
93 // becoming [] instead of {} in JS (T36604)
94 'wgActionPaths' => (object)$conf->get( 'ActionPaths' ),
95 'wgServer' => $conf->get( 'Server' ),
96 'wgServerName' => $conf->get( 'ServerName' ),
97 'wgUserLanguage' => $context->getLanguage(),
98 'wgContentLanguage' => $contLang->getCode(),
99 'wgTranslateNumerals' => $conf->get( 'TranslateNumerals' ),
100 'wgVersion' => $conf->get( 'Version' ),
101 'wgEnableAPI' => true, // Deprecated since MW 1.32
102 'wgEnableWriteAPI' => true, // Deprecated since MW 1.32
103 'wgMainPageTitle' => $mainPage->getPrefixedText(),
104 'wgFormattedNamespaces' => $contLang->getFormattedNamespaces(),
105 'wgNamespaceIds' => $namespaceIds,
106 'wgContentNamespaces' => MWNamespace
::getContentNamespaces(),
107 'wgSiteName' => $conf->get( 'Sitename' ),
108 'wgDBname' => $conf->get( 'DBname' ),
109 'wgExtraSignatureNamespaces' => $conf->get( 'ExtraSignatureNamespaces' ),
110 'wgAvailableSkins' => Skin
::getSkinNames(),
111 'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
112 // MediaWiki sets cookies to have this prefix by default
113 'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
114 'wgCookieDomain' => $conf->get( 'CookieDomain' ),
115 'wgCookiePath' => $conf->get( 'CookiePath' ),
116 'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
117 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
118 'wgLegalTitleChars' => Title
::convertByteClassToUnicodeClass( Title
::legalChars() ),
119 'wgIllegalFileChars' => Title
::convertByteClassToUnicodeClass( $illegalFileChars ),
120 'wgResourceLoaderStorageVersion' => $conf->get( 'ResourceLoaderStorageVersion' ),
121 'wgResourceLoaderStorageEnabled' => $conf->get( 'ResourceLoaderStorageEnabled' ),
122 'wgForeignUploadTargets' => $conf->get( 'ForeignUploadTargets' ),
123 'wgEnableUploads' => $conf->get( 'EnableUploads' ),
124 'wgCommentByteLimit' => null,
125 'wgCommentCodePointLimit' => CommentStore
::COMMENT_CHARACTER_LIMIT
,
128 Hooks
::run( 'ResourceLoaderGetConfigVars', [ &$vars, $skin ] );
134 * Recursively get all explicit and implicit dependencies for to the given module.
136 * @param array $registryData
137 * @param string $moduleName
140 protected static function getImplicitDependencies( array $registryData, $moduleName ) {
141 static $dependencyCache = [];
143 // The list of implicit dependencies won't be altered, so we can
144 // cache them without having to worry.
145 if ( !isset( $dependencyCache[$moduleName] ) ) {
146 if ( !isset( $registryData[$moduleName] ) ) {
147 // Dependencies may not exist
148 $dependencyCache[$moduleName] = [];
150 $data = $registryData[$moduleName];
151 $dependencyCache[$moduleName] = $data['dependencies'];
153 foreach ( $data['dependencies'] as $dependency ) {
154 // Recursively get the dependencies of the dependencies
155 $dependencyCache[$moduleName] = array_merge(
156 $dependencyCache[$moduleName],
157 self
::getImplicitDependencies( $registryData, $dependency )
163 return $dependencyCache[$moduleName];
167 * Optimize the dependency tree in $this->modules.
169 * The optimization basically works like this:
170 * Given we have module A with the dependencies B and C
171 * and module B with the dependency C.
172 * Now we don't have to tell the client to explicitly fetch module
173 * C as that's already included in module B.
175 * This way we can reasonably reduce the amount of module registration
176 * data send to the client.
178 * @param array &$registryData Modules keyed by name with properties:
180 * - array 'dependencies'
181 * - string|null 'group'
184 public static function compileUnresolvedDependencies( array &$registryData ) {
185 foreach ( $registryData as $name => &$data ) {
186 $dependencies = $data['dependencies'];
187 foreach ( $data['dependencies'] as $dependency ) {
188 $implicitDependencies = self
::getImplicitDependencies( $registryData, $dependency );
189 $dependencies = array_diff( $dependencies, $implicitDependencies );
192 $data['dependencies'] = array_values( $dependencies );
197 * Get registration code for all modules.
199 * @param ResourceLoaderContext $context
200 * @return string JavaScript code for registering all modules with the client loader
202 public function getModuleRegistrations( ResourceLoaderContext
$context ) {
203 $resourceLoader = $context->getResourceLoader();
204 // Future developers: Use WebRequest::getRawVal() instead getVal().
205 // The getVal() method performs slow Language+UTF logic. (f303bb9360)
206 $target = $context->getRequest()->getRawVal( 'target', 'desktop' );
207 $safemode = $context->getRequest()->getRawVal( 'safemode' ) === '1';
208 // Bypass target filter if this request is Special:JavaScriptTest.
209 // To prevent misuse in production, this is only allowed if testing is enabled server-side.
210 $byPassTargetFilter = $this->getConfig()->get( 'EnableJavaScriptTest' ) && $target === 'test';
215 $moduleNames = $resourceLoader->getModuleNames();
217 // Preload with a batch so that the below calls to getVersionHash() for each module
218 // don't require on-demand loading of more information.
220 $resourceLoader->preloadModuleInfo( $moduleNames, $context );
221 } catch ( Exception
$e ) {
222 // Don't fail the request (T152266)
223 // Also print the error in the main output
224 $resourceLoader->outputErrorAndLog( $e,
225 'Preloading module info from startup failed: {exception}',
226 [ 'exception' => $e ]
231 foreach ( $moduleNames as $name ) {
232 $module = $resourceLoader->getModule( $name );
233 $moduleTargets = $module->getTargets();
235 ( !$byPassTargetFilter && !in_array( $target, $moduleTargets ) )
236 ||
( $safemode && $module->getOrigin() > ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
)
241 if ( $module->isRaw() ) {
242 // Don't register "raw" modules (like 'startup') client-side because depending on them
243 // is illegal anyway and would only lead to them being loaded a second time,
244 // causing any state to be lost.
246 // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
247 // Think carefully before making changes to this code!
248 // The below code is going to call ResourceLoaderModule::getVersionHash() for every module.
249 // For StartUpModule (this module) the hash is computed based on the manifest content,
250 // which is the very thing we are computing right here. As such, this must skip iterating
251 // over 'startup' itself.
256 $versionHash = $module->getVersionHash( $context );
257 } catch ( Exception
$e ) {
258 // Don't fail the request (T152266)
259 // Also print the error in the main output
260 $resourceLoader->outputErrorAndLog( $e,
261 'Calculating version for "{module}" failed: {exception}',
268 $states[$name] = 'error';
271 if ( $versionHash !== '' && strlen( $versionHash ) !== 7 ) {
272 $context->getLogger()->warning(
273 "Module '{module}' produced an invalid version hash: '{version}'.",
276 'version' => $versionHash,
279 // Module implementation either broken or deviated from ResourceLoader::makeHash
280 // Asserted by tests/phpunit/structure/ResourcesTest.
281 $versionHash = ResourceLoader
::makeHash( $versionHash );
284 $skipFunction = $module->getSkipFunction();
285 if ( $skipFunction !== null && !ResourceLoader
::inDebugMode() ) {
286 $skipFunction = ResourceLoader
::filter( 'minify-js', $skipFunction );
289 $registryData[$name] = [
290 'version' => $versionHash,
291 'dependencies' => $module->getDependencies( $context ),
292 'group' => $module->getGroup(),
293 'source' => $module->getSource(),
294 'skip' => $skipFunction,
298 self
::compileUnresolvedDependencies( $registryData );
301 $out .= ResourceLoader
::makeLoaderSourcesScript( $resourceLoader->getSources() );
303 // Figure out the different call signatures for mw.loader.register
305 foreach ( $registryData as $name => $data ) {
306 // Call mw.loader.register(name, version, dependencies, group, source, skip)
310 $data['dependencies'],
312 // Swap default (local) for null
313 $data['source'] === 'local' ?
null : $data['source'],
319 $out .= "\n" . ResourceLoader
::makeLoaderRegisterScript( $registrations );
322 $out .= "\n" . ResourceLoader
::makeLoaderStateScript( $states );
331 public function isRaw() {
336 * Internal modules used by ResourceLoader that cannot be depended on.
338 * These module(s) should have isRaw() return true, and are not
339 * legal dependencies (enforced by structure/ResourcesTest).
341 * @deprecated since 1.32 No longer used.
344 public static function getStartupModules() {
345 wfDeprecated( __METHOD__
, '1.32' );
350 * @deprecated since 1.32 No longer used.
353 public static function getLegacyModules() {
354 wfDeprecated( __METHOD__
, '1.32' );
359 * @private For internal use by SpecialJavaScriptTest
363 public function getBaseModulesInternal() {
364 return $this->getBaseModules();
368 * Base modules implicitly available to all modules.
372 private function getBaseModules() {
373 global $wgIncludeLegacyJavaScript;
375 $baseModules = [ 'jquery', 'mediawiki.base' ];
376 if ( $wgIncludeLegacyJavaScript ) {
377 $baseModules[] = 'mediawiki.legacy.wikibits';
384 * @param ResourceLoaderContext $context
385 * @return string JavaScript code
387 public function getScript( ResourceLoaderContext
$context ) {
389 $conf = $this->getConfig();
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 ( $conf->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() ),
411 '$VARS.maxQueryLength' => ResourceLoader
::encodeJsonForScript(
412 $conf->get( 'ResourceLoaderMaxQueryLength' )
416 '$CODE.profileExecuteStart();' => 'mw.loader.profiler.onExecuteStart( module );',
417 '$CODE.profileExecuteEnd();' => 'mw.loader.profiler.onExecuteEnd( module );',
418 '$CODE.profileScriptStart();' => 'mw.loader.profiler.onScriptStart( module );',
419 '$CODE.profileScriptEnd();' => 'mw.loader.profiler.onScriptEnd( module );',
421 if ( $conf->get( 'ResourceLoaderEnableJSProfiler' ) ) {
422 // When profiling is enabled, insert the calls.
423 $mwLoaderPairs +
= $profilerStubs;
425 // When disabled (by default), insert nothing.
426 $mwLoaderPairs +
= array_fill_keys( array_keys( $profilerStubs ), '' );
428 $mwLoaderCode = strtr( $mwLoaderCode, $mwLoaderPairs );
430 // Perform string replacements for startup.js
432 '$VARS.wgLegacyJavaScriptGlobals' => ResourceLoader
::encodeJsonForScript(
433 $conf->get( 'LegacyJavaScriptGlobals' )
435 '$VARS.configuration' => ResourceLoader
::encodeJsonForScript(
436 $this->getConfigSettings( $context )
438 // Raw JavaScript code (not JSON)
439 '$CODE.registrations();' => trim( $this->getModuleRegistrations( $context ) ),
440 '$CODE.defineLoader();' => $mwLoaderCode,
442 $startupCode = strtr( $startupCode, $pairs );
450 public function supportsURLLoading() {
457 public function enableModuleContentVersion() {
458 // Enabling this means that ResourceLoader::getVersionHash will simply call getScript()
459 // and hash it to determine the version (as used by E-Tag HTTP response header).
466 public function getGroup() {