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();
53 * Namespace related preparation
54 * - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces.
55 * - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive.
57 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
58 $namespaceIds = $contLang->getNamespaceIds();
59 $caseSensitiveNamespaces = [];
60 foreach ( MWNamespace
::getCanonicalNamespaces() as $index => $name ) {
61 $namespaceIds[$contLang->lc( $name )] = $index;
62 if ( !MWNamespace
::isCapitalized( $index ) ) {
63 $caseSensitiveNamespaces[] = $index;
67 $illegalFileChars = $conf->get( 'IllegalFileChars' );
69 // Build list of variables
70 $skin = $context->getSkin();
72 'wgLoadScript' => wfScript( 'load' ),
73 'debug' => $context->getDebug(),
75 'stylepath' => $conf->get( 'StylePath' ),
76 'wgUrlProtocols' => wfUrlProtocols(),
77 'wgArticlePath' => $conf->get( 'ArticlePath' ),
78 'wgScriptPath' => $conf->get( 'ScriptPath' ),
79 'wgScript' => wfScript(),
80 'wgSearchType' => $conf->get( 'SearchType' ),
81 'wgVariantArticlePath' => $conf->get( 'VariantArticlePath' ),
82 // Force object to avoid "empty" associative array from
83 // becoming [] instead of {} in JS (T36604)
84 'wgActionPaths' => (object)$conf->get( 'ActionPaths' ),
85 'wgServer' => $conf->get( 'Server' ),
86 'wgServerName' => $conf->get( 'ServerName' ),
87 'wgUserLanguage' => $context->getLanguage(),
88 'wgContentLanguage' => $contLang->getCode(),
89 'wgTranslateNumerals' => $conf->get( 'TranslateNumerals' ),
90 'wgVersion' => $conf->get( 'Version' ),
91 'wgEnableAPI' => true, // Deprecated since MW 1.32
92 'wgEnableWriteAPI' => true, // Deprecated since MW 1.32
93 'wgFormattedNamespaces' => $contLang->getFormattedNamespaces(),
94 'wgNamespaceIds' => $namespaceIds,
95 'wgContentNamespaces' => MWNamespace
::getContentNamespaces(),
96 'wgSiteName' => $conf->get( 'Sitename' ),
97 'wgDBname' => $conf->get( 'DBname' ),
98 'wgExtraSignatureNamespaces' => $conf->get( 'ExtraSignatureNamespaces' ),
99 'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
100 // MediaWiki sets cookies to have this prefix by default
101 'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
102 'wgCookieDomain' => $conf->get( 'CookieDomain' ),
103 'wgCookiePath' => $conf->get( 'CookiePath' ),
104 'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
105 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
106 'wgLegalTitleChars' => Title
::convertByteClassToUnicodeClass( Title
::legalChars() ),
107 'wgIllegalFileChars' => Title
::convertByteClassToUnicodeClass( $illegalFileChars ),
108 'wgResourceLoaderStorageVersion' => $conf->get( 'ResourceLoaderStorageVersion' ),
109 'wgResourceLoaderStorageEnabled' => $conf->get( 'ResourceLoaderStorageEnabled' ),
110 'wgForeignUploadTargets' => $conf->get( 'ForeignUploadTargets' ),
111 'wgEnableUploads' => $conf->get( 'EnableUploads' ),
112 'wgCommentByteLimit' => null,
113 'wgCommentCodePointLimit' => CommentStore
::COMMENT_CHARACTER_LIMIT
,
116 Hooks
::run( 'ResourceLoaderGetConfigVars', [ &$vars, $skin ] );
122 * Recursively get all explicit and implicit dependencies for to the given module.
124 * @param array $registryData
125 * @param string $moduleName
128 protected static function getImplicitDependencies( array $registryData, $moduleName ) {
129 static $dependencyCache = [];
131 // The list of implicit dependencies won't be altered, so we can
132 // cache them without having to worry.
133 if ( !isset( $dependencyCache[$moduleName] ) ) {
134 if ( !isset( $registryData[$moduleName] ) ) {
135 // Dependencies may not exist
136 $dependencyCache[$moduleName] = [];
138 $data = $registryData[$moduleName];
139 $dependencyCache[$moduleName] = $data['dependencies'];
141 foreach ( $data['dependencies'] as $dependency ) {
142 // Recursively get the dependencies of the dependencies
143 $dependencyCache[$moduleName] = array_merge(
144 $dependencyCache[$moduleName],
145 self
::getImplicitDependencies( $registryData, $dependency )
151 return $dependencyCache[$moduleName];
155 * Optimize the dependency tree in $this->modules.
157 * The optimization basically works like this:
158 * Given we have module A with the dependencies B and C
159 * and module B with the dependency C.
160 * Now we don't have to tell the client to explicitly fetch module
161 * C as that's already included in module B.
163 * This way we can reasonably reduce the amount of module registration
164 * data send to the client.
166 * @param array &$registryData Modules keyed by name with properties:
168 * - array 'dependencies'
169 * - string|null 'group'
172 public static function compileUnresolvedDependencies( array &$registryData ) {
173 foreach ( $registryData as $name => &$data ) {
174 $dependencies = $data['dependencies'];
175 foreach ( $data['dependencies'] as $dependency ) {
176 $implicitDependencies = self
::getImplicitDependencies( $registryData, $dependency );
177 $dependencies = array_diff( $dependencies, $implicitDependencies );
180 $data['dependencies'] = array_values( $dependencies );
185 * Get registration code for all modules.
187 * @param ResourceLoaderContext $context
188 * @return string JavaScript code for registering all modules with the client loader
190 public function getModuleRegistrations( ResourceLoaderContext
$context ) {
191 $resourceLoader = $context->getResourceLoader();
192 // Future developers: Use WebRequest::getRawVal() instead getVal().
193 // The getVal() method performs slow Language+UTF logic. (f303bb9360)
194 $target = $context->getRequest()->getRawVal( 'target', 'desktop' );
195 $safemode = $context->getRequest()->getRawVal( 'safemode' ) === '1';
196 // Bypass target filter if this request is Special:JavaScriptTest.
197 // To prevent misuse in production, this is only allowed if testing is enabled server-side.
198 $byPassTargetFilter = $this->getConfig()->get( 'EnableJavaScriptTest' ) && $target === 'test';
203 $moduleNames = $resourceLoader->getModuleNames();
205 // Preload with a batch so that the below calls to getVersionHash() for each module
206 // don't require on-demand loading of more information.
208 $resourceLoader->preloadModuleInfo( $moduleNames, $context );
209 } catch ( Exception
$e ) {
210 // Don't fail the request (T152266)
211 // Also print the error in the main output
212 $resourceLoader->outputErrorAndLog( $e,
213 'Preloading module info from startup failed: {exception}',
214 [ 'exception' => $e ]
219 foreach ( $moduleNames as $name ) {
220 $module = $resourceLoader->getModule( $name );
221 $moduleTargets = $module->getTargets();
223 ( !$byPassTargetFilter && !in_array( $target, $moduleTargets ) )
224 ||
( $safemode && $module->getOrigin() > ResourceLoaderModule
::ORIGIN_CORE_INDIVIDUAL
)
229 if ( $module->isRaw() ) {
230 // Don't register "raw" modules (like 'startup') client-side because depending on them
231 // is illegal anyway and would only lead to them being loaded a second time,
232 // causing any state to be lost.
234 // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
235 // Think carefully before making changes to this code!
236 // The below code is going to call ResourceLoaderModule::getVersionHash() for every module.
237 // For StartUpModule (this module) the hash is computed based on the manifest content,
238 // which is the very thing we are computing right here. As such, this must skip iterating
239 // over 'startup' itself.
244 $versionHash = $module->getVersionHash( $context );
245 } catch ( Exception
$e ) {
246 // Don't fail the request (T152266)
247 // Also print the error in the main output
248 $resourceLoader->outputErrorAndLog( $e,
249 'Calculating version for "{module}" failed: {exception}',
256 $states[$name] = 'error';
259 if ( $versionHash !== '' && strlen( $versionHash ) !== 7 ) {
260 $context->getLogger()->warning(
261 "Module '{module}' produced an invalid version hash: '{version}'.",
264 'version' => $versionHash,
267 // Module implementation either broken or deviated from ResourceLoader::makeHash
268 // Asserted by tests/phpunit/structure/ResourcesTest.
269 $versionHash = ResourceLoader
::makeHash( $versionHash );
272 $skipFunction = $module->getSkipFunction();
273 if ( $skipFunction !== null && !ResourceLoader
::inDebugMode() ) {
274 $skipFunction = ResourceLoader
::filter( 'minify-js', $skipFunction );
277 $registryData[$name] = [
278 'version' => $versionHash,
279 'dependencies' => $module->getDependencies( $context ),
280 'group' => $module->getGroup(),
281 'source' => $module->getSource(),
282 'skip' => $skipFunction,
286 self
::compileUnresolvedDependencies( $registryData );
289 $out .= ResourceLoader
::makeLoaderSourcesScript( $resourceLoader->getSources() );
291 // Figure out the different call signatures for mw.loader.register
293 foreach ( $registryData as $name => $data ) {
294 // Call mw.loader.register(name, version, dependencies, group, source, skip)
298 $data['dependencies'],
300 // Swap default (local) for null
301 $data['source'] === 'local' ?
null : $data['source'],
307 $out .= "\n" . ResourceLoader
::makeLoaderRegisterScript( $registrations );
310 $out .= "\n" . ResourceLoader
::makeLoaderStateScript( $states );
319 public function isRaw() {
324 * Internal modules used by ResourceLoader that cannot be depended on.
326 * These module(s) should have isRaw() return true, and are not
327 * legal dependencies (enforced by structure/ResourcesTest).
329 * @deprecated since 1.32 No longer used.
332 public static function getStartupModules() {
333 wfDeprecated( __METHOD__
, '1.32' );
338 * @deprecated since 1.32 No longer used.
341 public static function getLegacyModules() {
342 wfDeprecated( __METHOD__
, '1.32' );
347 * @private For internal use by SpecialJavaScriptTest
351 public function getBaseModulesInternal() {
352 return $this->getBaseModules();
356 * Base modules implicitly available to all modules.
360 private function getBaseModules() {
361 global $wgIncludeLegacyJavaScript;
363 $baseModules = [ 'jquery', 'mediawiki.base' ];
364 if ( $wgIncludeLegacyJavaScript ) {
365 $baseModules[] = 'mediawiki.legacy.wikibits';
372 * @param ResourceLoaderContext $context
373 * @return string JavaScript code
375 public function getScript( ResourceLoaderContext
$context ) {
377 $conf = $this->getConfig();
379 if ( $context->getOnly() !== 'scripts' ) {
380 return '/* Requires only=script */';
383 $startupCode = file_get_contents( "$IP/resources/src/startup/startup.js" );
385 // The files read here MUST be kept in sync with maintenance/jsduck/eg-iframe.html,
386 // and MUST be considered by 'fileHashes' in StartUpModule::getDefinitionSummary().
387 $mwLoaderCode = file_get_contents( "$IP/resources/src/startup/mediawiki.js" ) .
388 file_get_contents( "$IP/resources/src/startup/mediawiki.requestIdleCallback.js" );
389 if ( $context->getDebug() ) {
390 $mwLoaderCode .= file_get_contents( "$IP/resources/src/startup/mediawiki.log.js" );
392 if ( $conf->get( 'ResourceLoaderEnableJSProfiler' ) ) {
393 $mwLoaderCode .= file_get_contents( "$IP/resources/src/startup/profiler.js" );
396 // Perform replacements for mediawiki.js
398 '$VARS.baseModules' => ResourceLoader
::encodeJsonForScript( $this->getBaseModules() ),
399 '$VARS.maxQueryLength' => ResourceLoader
::encodeJsonForScript(
400 $conf->get( 'ResourceLoaderMaxQueryLength' )
404 '$CODE.profileExecuteStart();' => 'mw.loader.profiler.onExecuteStart( module );',
405 '$CODE.profileExecuteEnd();' => 'mw.loader.profiler.onExecuteEnd( module );',
406 '$CODE.profileScriptStart();' => 'mw.loader.profiler.onScriptStart( module );',
407 '$CODE.profileScriptEnd();' => 'mw.loader.profiler.onScriptEnd( module );',
409 if ( $conf->get( 'ResourceLoaderEnableJSProfiler' ) ) {
410 // When profiling is enabled, insert the calls.
411 $mwLoaderPairs +
= $profilerStubs;
413 // When disabled (by default), insert nothing.
414 $mwLoaderPairs +
= array_fill_keys( array_keys( $profilerStubs ), '' );
416 $mwLoaderCode = strtr( $mwLoaderCode, $mwLoaderPairs );
418 // Perform string replacements for startup.js
420 '$VARS.wgLegacyJavaScriptGlobals' => ResourceLoader
::encodeJsonForScript(
421 $conf->get( 'LegacyJavaScriptGlobals' )
423 '$VARS.configuration' => ResourceLoader
::encodeJsonForScript(
424 $this->getConfigSettings( $context )
426 // Raw JavaScript code (not JSON)
427 '$CODE.registrations();' => trim( $this->getModuleRegistrations( $context ) ),
428 '$CODE.defineLoader();' => $mwLoaderCode,
430 $startupCode = strtr( $startupCode, $pairs );
438 public function supportsURLLoading() {
445 public function enableModuleContentVersion() {
446 // Enabling this means that ResourceLoader::getVersionHash will simply call getScript()
447 // and hash it to determine the version (as used by E-Tag HTTP response header).
454 public function getGroup() {