Added release notes for 'ContentHandler::runLegacyHooks' removal
[mediawiki.git] / includes / resourceloader / ResourceLoaderStartUpModule.php
bloba99305ca6142953233824047859317a27ea44cb8
1 <?php
2 /**
3 * Module for ResourceLoader initialization.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @author Trevor Parscal
22 * @author Roan Kattouw
25 class ResourceLoaderStartUpModule extends ResourceLoaderModule {
27 // Cache for getConfigSettings() as it's called by multiple methods
28 protected $configVars = [];
29 protected $targets = [ 'desktop', 'mobile' ];
31 /**
32 * @param ResourceLoaderContext $context
33 * @return array
35 protected function getConfigSettings( $context ) {
37 $hash = $context->getHash();
38 if ( isset( $this->configVars[$hash] ) ) {
39 return $this->configVars[$hash];
42 global $wgContLang;
43 $conf = $this->getConfig();
45 // We can't use Title::newMainPage() if 'mainpage' is in
46 // $wgForceUIMsgAsContentMsg because that will try to use the session
47 // user's language and we have no session user. This does the
48 // equivalent but falling back to our ResourceLoaderContext language
49 // instead.
50 $mainPage = Title::newFromText( $context->msg( 'mainpage' )->inContentLanguage()->text() );
51 if ( !$mainPage ) {
52 $mainPage = Title::newFromText( 'Main Page' );
55 /**
56 * Namespace related preparation
57 * - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces.
58 * - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive.
60 $namespaceIds = $wgContLang->getNamespaceIds();
61 $caseSensitiveNamespaces = [];
62 foreach ( MWNamespace::getCanonicalNamespaces() as $index => $name ) {
63 $namespaceIds[$wgContLang->lc( $name )] = $index;
64 if ( !MWNamespace::isCapitalized( $index ) ) {
65 $caseSensitiveNamespaces[] = $index;
69 $illegalFileChars = $conf->get( 'IllegalFileChars' );
71 // Build list of variables
72 $vars = [
73 'wgLoadScript' => wfScript( 'load' ),
74 'debug' => $context->getDebug(),
75 'skin' => $context->getSkin(),
76 'stylepath' => $conf->get( 'StylePath' ),
77 'wgUrlProtocols' => wfUrlProtocols(),
78 'wgArticlePath' => $conf->get( 'ArticlePath' ),
79 'wgScriptPath' => $conf->get( 'ScriptPath' ),
80 'wgScriptExtension' => '.php',
81 'wgScript' => wfScript(),
82 'wgSearchType' => $conf->get( 'SearchType' ),
83 'wgVariantArticlePath' => $conf->get( 'VariantArticlePath' ),
84 // Force object to avoid "empty" associative array from
85 // becoming [] instead of {} in JS (bug 34604)
86 'wgActionPaths' => (object)$conf->get( 'ActionPaths' ),
87 'wgServer' => $conf->get( 'Server' ),
88 'wgServerName' => $conf->get( 'ServerName' ),
89 'wgUserLanguage' => $context->getLanguage(),
90 'wgContentLanguage' => $wgContLang->getCode(),
91 'wgTranslateNumerals' => $conf->get( 'TranslateNumerals' ),
92 'wgVersion' => $conf->get( 'Version' ),
93 'wgEnableAPI' => $conf->get( 'EnableAPI' ),
94 'wgEnableWriteAPI' => $conf->get( 'EnableWriteAPI' ),
95 'wgMainPageTitle' => $mainPage->getPrefixedText(),
96 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
97 'wgNamespaceIds' => $namespaceIds,
98 'wgContentNamespaces' => MWNamespace::getContentNamespaces(),
99 'wgSiteName' => $conf->get( 'Sitename' ),
100 'wgDBname' => $conf->get( 'DBname' ),
101 'wgExtraSignatureNamespaces' => $conf->get( 'ExtraSignatureNamespaces' ),
102 'wgAvailableSkins' => Skin::getSkinNames(),
103 'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
104 // MediaWiki sets cookies to have this prefix by default
105 'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
106 'wgCookieDomain' => $conf->get( 'CookieDomain' ),
107 'wgCookiePath' => $conf->get( 'CookiePath' ),
108 'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
109 'wgResourceLoaderMaxQueryLength' => $conf->get( 'ResourceLoaderMaxQueryLength' ),
110 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
111 'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass( Title::legalChars() ),
112 'wgIllegalFileChars' => Title::convertByteClassToUnicodeClass( $illegalFileChars ),
113 'wgResourceLoaderStorageVersion' => $conf->get( 'ResourceLoaderStorageVersion' ),
114 'wgResourceLoaderStorageEnabled' => $conf->get( 'ResourceLoaderStorageEnabled' ),
115 'wgResourceLoaderLegacyModules' => self::getLegacyModules(),
116 'wgForeignUploadTargets' => $conf->get( 'ForeignUploadTargets' ),
117 'wgEnableUploads' => $conf->get( 'EnableUploads' ),
120 Hooks::run( 'ResourceLoaderGetConfigVars', [ &$vars ] );
122 $this->configVars[$hash] = $vars;
123 return $this->configVars[$hash];
127 * Recursively get all explicit and implicit dependencies for to the given module.
129 * @param array $registryData
130 * @param string $moduleName
131 * @return array
133 protected static function getImplicitDependencies( array $registryData, $moduleName ) {
134 static $dependencyCache = [];
136 // The list of implicit dependencies won't be altered, so we can
137 // cache them without having to worry.
138 if ( !isset( $dependencyCache[$moduleName] ) ) {
140 if ( !isset( $registryData[$moduleName] ) ) {
141 // Dependencies may not exist
142 $dependencyCache[$moduleName] = [];
143 } else {
144 $data = $registryData[$moduleName];
145 $dependencyCache[$moduleName] = $data['dependencies'];
147 foreach ( $data['dependencies'] as $dependency ) {
148 // Recursively get the dependencies of the dependencies
149 $dependencyCache[$moduleName] = array_merge(
150 $dependencyCache[$moduleName],
151 self::getImplicitDependencies( $registryData, $dependency )
157 return $dependencyCache[$moduleName];
161 * Optimize the dependency tree in $this->modules.
163 * The optimization basically works like this:
164 * Given we have module A with the dependencies B and C
165 * and module B with the dependency C.
166 * Now we don't have to tell the client to explicitly fetch module
167 * C as that's already included in module B.
169 * This way we can reasonably reduce the amount of module registration
170 * data send to the client.
172 * @param array &$registryData Modules keyed by name with properties:
173 * - string 'version'
174 * - array 'dependencies'
175 * - string|null 'group'
176 * - string 'source'
178 public static function compileUnresolvedDependencies( array &$registryData ) {
179 foreach ( $registryData as $name => &$data ) {
180 $dependencies = $data['dependencies'];
181 foreach ( $data['dependencies'] as $dependency ) {
182 $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
183 $dependencies = array_diff( $dependencies, $implicitDependencies );
185 // Rebuild keys
186 $data['dependencies'] = array_values( $dependencies );
191 * Get registration code for all modules.
193 * @param ResourceLoaderContext $context
194 * @return string JavaScript code for registering all modules with the client loader
196 public function getModuleRegistrations( ResourceLoaderContext $context ) {
197 $resourceLoader = $context->getResourceLoader();
198 $target = $context->getRequest()->getVal( 'target', 'desktop' );
199 // Bypass target filter if this request is Special:JavaScriptTest.
200 // To prevent misuse in production, this is only allowed if testing is enabled server-side.
201 $byPassTargetFilter = $this->getConfig()->get( 'EnableJavaScriptTest' ) && $target === 'test';
203 $out = '';
204 $states = [];
205 $registryData = [];
207 // Get registry data
208 foreach ( $resourceLoader->getModuleNames() as $name ) {
209 $module = $resourceLoader->getModule( $name );
210 $moduleTargets = $module->getTargets();
211 if ( !$byPassTargetFilter && !in_array( $target, $moduleTargets ) ) {
212 continue;
215 if ( $module->isRaw() ) {
216 // Don't register "raw" modules (like 'jquery' and 'mediawiki') client-side because
217 // depending on them is illegal anyway and would only lead to them being reloaded
218 // causing any state to be lost (like jQuery plugins, mw.config etc.)
219 continue;
222 try {
223 $versionHash = $module->getVersionHash( $context );
224 } catch ( Exception $e ) {
225 // See also T152266 and ResourceLoader::getCombinedVersion()
226 MWExceptionHandler::logException( $e );
227 $context->getLogger()->warning(
228 'Calculating version for "{module}" failed: {exception}',
230 'module' => $name,
231 'exception' => $e,
234 $versionHash = '';
235 $states[$name] = 'error';
238 if ( $versionHash !== '' && strlen( $versionHash ) !== 7 ) {
239 $context->getLogger()->warning(
240 "Module '{module}' produced an invalid version hash: '{version}'.",
242 'module' => $name,
243 'version' => $versionHash,
246 // Module implementation either broken or deviated from ResourceLoader::makeHash
247 // Asserted by tests/phpunit/structure/ResourcesTest.
248 $versionHash = ResourceLoader::makeHash( $versionHash );
251 $skipFunction = $module->getSkipFunction();
252 if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
253 $skipFunction = ResourceLoader::filter( 'minify-js', $skipFunction );
256 $registryData[$name] = [
257 'version' => $versionHash,
258 'dependencies' => $module->getDependencies( $context ),
259 'group' => $module->getGroup(),
260 'source' => $module->getSource(),
261 'skip' => $skipFunction,
265 self::compileUnresolvedDependencies( $registryData );
267 // Register sources
268 $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
270 // Figure out the different call signatures for mw.loader.register
271 $registrations = [];
272 foreach ( $registryData as $name => $data ) {
273 // Call mw.loader.register(name, version, dependencies, group, source, skip)
274 $registrations[] = [
275 $name,
276 $data['version'],
277 $data['dependencies'],
278 $data['group'],
279 // Swap default (local) for null
280 $data['source'] === 'local' ? null : $data['source'],
281 $data['skip']
285 // Register modules
286 $out .= "\n" . ResourceLoader::makeLoaderRegisterScript( $registrations );
288 if ( $states ) {
289 $out .= "\n" . ResourceLoader::makeLoaderStateScript( $states );
292 return $out;
296 * @return bool
298 public function isRaw() {
299 return true;
303 * Base modules required for the base environment of ResourceLoader
305 * @return array
307 public static function getStartupModules() {
308 return [ 'jquery', 'mediawiki' ];
311 public static function getLegacyModules() {
312 global $wgIncludeLegacyJavaScript;
314 $legacyModules = [];
315 if ( $wgIncludeLegacyJavaScript ) {
316 $legacyModules[] = 'mediawiki.legacy.wikibits';
319 return $legacyModules;
323 * Get the load URL of the startup modules.
325 * This is a helper for getScript(), but can also be called standalone, such
326 * as when generating an AppCache manifest.
328 * @param ResourceLoaderContext $context
329 * @return string
331 public static function getStartupModulesUrl( ResourceLoaderContext $context ) {
332 $rl = $context->getResourceLoader();
334 $derivative = new DerivativeResourceLoaderContext( $context );
335 $derivative->setModules( self::getStartupModules() );
336 $derivative->setOnly( 'scripts' );
337 // Must setModules() before makeVersionQuery()
338 $derivative->setVersion( $rl->makeVersionQuery( $derivative ) );
340 return $rl->createLoaderURL( 'local', $derivative );
344 * @param ResourceLoaderContext $context
345 * @return string
347 public function getScript( ResourceLoaderContext $context ) {
348 global $IP;
349 if ( $context->getOnly() !== 'scripts' ) {
350 return '/* Requires only=script */';
353 $out = file_get_contents( "$IP/resources/src/startup.js" );
355 $pairs = array_map( function ( $value ) {
356 $value = FormatJson::encode( $value, ResourceLoader::inDebugMode(), FormatJson::ALL_OK );
357 // Fix indentation
358 $value = str_replace( "\n", "\n\t", $value );
359 return $value;
360 }, [
361 '$VARS.wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
362 '$VARS.configuration' => $this->getConfigSettings( $context ),
363 '$VARS.baseModulesUri' => self::getStartupModulesUrl( $context ),
364 ] );
365 $pairs['$CODE.registrations()'] = str_replace(
366 "\n",
367 "\n\t",
368 trim( $this->getModuleRegistrations( $context ) )
371 return strtr( $out, $pairs );
375 * @return bool
377 public function supportsURLLoading() {
378 return false;
382 * Get the definition summary for this module.
384 * @param ResourceLoaderContext $context
385 * @return array
387 public function getDefinitionSummary( ResourceLoaderContext $context ) {
388 global $IP;
389 $summary = parent::getDefinitionSummary( $context );
390 $summary[] = [
391 // Detect changes to variables exposed in mw.config (T30899).
392 'vars' => $this->getConfigSettings( $context ),
393 // Changes how getScript() creates mw.Map for mw.config
394 'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
395 // Detect changes to the module registrations
396 'moduleHashes' => $this->getAllModuleHashes( $context ),
398 'fileMtimes' => [
399 filemtime( "$IP/resources/src/startup.js" ),
402 return $summary;
406 * Helper method for getDefinitionSummary().
408 * @param ResourceLoaderContext $context
409 * @return string SHA-1
411 protected function getAllModuleHashes( ResourceLoaderContext $context ) {
412 $rl = $context->getResourceLoader();
413 // Preload for getCombinedVersion()
414 $rl->preloadModuleInfo( $rl->getModuleNames(), $context );
416 // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
417 // Think carefully before making changes to this code!
418 // Pre-populate versionHash with something because the loop over all modules below includes
419 // the startup module (this module).
420 // See ResourceLoaderModule::getVersionHash() for usage of this cache.
421 $this->versionHash[$context->getHash()] = null;
423 return $rl->getCombinedVersion( $context, $rl->getModuleNames() );
427 * @return string
429 public function getGroup() {
430 return 'startup';