Fix ApiBase::getErrorFromStatus() and ApiMessages
[mediawiki.git] / includes / resourceloader / ResourceLoaderStartUpModule.php
blob34866f3635726794aabcefb16ec25598dec6146d
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 // Build list of variables
70 $vars = [
71 'wgLoadScript' => wfScript( 'load' ),
72 'debug' => $context->getDebug(),
73 'skin' => $context->getSkin(),
74 'stylepath' => $conf->get( 'StylePath' ),
75 'wgUrlProtocols' => wfUrlProtocols(),
76 'wgArticlePath' => $conf->get( 'ArticlePath' ),
77 'wgScriptPath' => $conf->get( 'ScriptPath' ),
78 'wgScriptExtension' => '.php',
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 (bug 34604)
84 'wgActionPaths' => (object)$conf->get( 'ActionPaths' ),
85 'wgServer' => $conf->get( 'Server' ),
86 'wgServerName' => $conf->get( 'ServerName' ),
87 'wgUserLanguage' => $context->getLanguage(),
88 'wgContentLanguage' => $wgContLang->getCode(),
89 'wgTranslateNumerals' => $conf->get( 'TranslateNumerals' ),
90 'wgVersion' => $conf->get( 'Version' ),
91 'wgEnableAPI' => $conf->get( 'EnableAPI' ),
92 'wgEnableWriteAPI' => $conf->get( 'EnableWriteAPI' ),
93 'wgMainPageTitle' => $mainPage->getPrefixedText(),
94 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
95 'wgNamespaceIds' => $namespaceIds,
96 'wgContentNamespaces' => MWNamespace::getContentNamespaces(),
97 'wgSiteName' => $conf->get( 'Sitename' ),
98 'wgDBname' => $conf->get( 'DBname' ),
99 'wgExtraSignatureNamespaces' => $conf->get( 'ExtraSignatureNamespaces' ),
100 'wgAvailableSkins' => Skin::getSkinNames(),
101 'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
102 // MediaWiki sets cookies to have this prefix by default
103 'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
104 'wgCookieDomain' => $conf->get( 'CookieDomain' ),
105 'wgCookiePath' => $conf->get( 'CookiePath' ),
106 'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
107 'wgResourceLoaderMaxQueryLength' => $conf->get( 'ResourceLoaderMaxQueryLength' ),
108 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
109 'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass( Title::legalChars() ),
110 'wgResourceLoaderStorageVersion' => $conf->get( 'ResourceLoaderStorageVersion' ),
111 'wgResourceLoaderStorageEnabled' => $conf->get( 'ResourceLoaderStorageEnabled' ),
112 'wgResourceLoaderLegacyModules' => self::getLegacyModules(),
113 'wgForeignUploadTargets' => $conf->get( 'ForeignUploadTargets' ),
114 'wgEnableUploads' => $conf->get( 'EnableUploads' ),
117 Hooks::run( 'ResourceLoaderGetConfigVars', [ &$vars ] );
119 $this->configVars[$hash] = $vars;
120 return $this->configVars[$hash];
124 * Recursively get all explicit and implicit dependencies for to the given module.
126 * @param array $registryData
127 * @param string $moduleName
128 * @return array
130 protected static function getImplicitDependencies( array $registryData, $moduleName ) {
131 static $dependencyCache = [];
133 // The list of implicit dependencies won't be altered, so we can
134 // cache them without having to worry.
135 if ( !isset( $dependencyCache[$moduleName] ) ) {
137 if ( !isset( $registryData[$moduleName] ) ) {
138 // Dependencies may not exist
139 $dependencyCache[$moduleName] = [];
140 } else {
141 $data = $registryData[$moduleName];
142 $dependencyCache[$moduleName] = $data['dependencies'];
144 foreach ( $data['dependencies'] as $dependency ) {
145 // Recursively get the dependencies of the dependencies
146 $dependencyCache[$moduleName] = array_merge(
147 $dependencyCache[$moduleName],
148 self::getImplicitDependencies( $registryData, $dependency )
154 return $dependencyCache[$moduleName];
158 * Optimize the dependency tree in $this->modules.
160 * The optimization basically works like this:
161 * Given we have module A with the dependencies B and C
162 * and module B with the dependency C.
163 * Now we don't have to tell the client to explicitly fetch module
164 * C as that's already included in module B.
166 * This way we can reasonably reduce the amount of module registration
167 * data send to the client.
169 * @param array &$registryData Modules keyed by name with properties:
170 * - string 'version'
171 * - array 'dependencies'
172 * - string|null 'group'
173 * - string 'source'
175 public static function compileUnresolvedDependencies( array &$registryData ) {
176 foreach ( $registryData as $name => &$data ) {
177 $dependencies = $data['dependencies'];
178 foreach ( $data['dependencies'] as $dependency ) {
179 $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
180 $dependencies = array_diff( $dependencies, $implicitDependencies );
182 // Rebuild keys
183 $data['dependencies'] = array_values( $dependencies );
188 * Get registration code for all modules.
190 * @param ResourceLoaderContext $context
191 * @return string JavaScript code for registering all modules with the client loader
193 public function getModuleRegistrations( ResourceLoaderContext $context ) {
195 $resourceLoader = $context->getResourceLoader();
196 $target = $context->getRequest()->getVal( 'target', 'desktop' );
197 // Bypass target filter if this request is Special:JavaScriptTest.
198 // To prevent misuse in production, this is only allowed if testing is enabled server-side.
199 $byPassTargetFilter = $this->getConfig()->get( 'EnableJavaScriptTest' ) && $target === 'test';
201 $out = '';
202 $registryData = [];
204 // Get registry data
205 foreach ( $resourceLoader->getModuleNames() as $name ) {
206 $module = $resourceLoader->getModule( $name );
207 $moduleTargets = $module->getTargets();
208 if ( !$byPassTargetFilter && !in_array( $target, $moduleTargets ) ) {
209 continue;
212 if ( $module->isRaw() ) {
213 // Don't register "raw" modules (like 'jquery' and 'mediawiki') client-side because
214 // depending on them is illegal anyway and would only lead to them being reloaded
215 // causing any state to be lost (like jQuery plugins, mw.config etc.)
216 continue;
219 $versionHash = $module->getVersionHash( $context );
220 if ( strlen( $versionHash ) !== 8 ) {
221 $context->getLogger()->warning(
222 "Module '{module}' produced an invalid version hash: '{version}'.",
224 'module' => $name,
225 'version' => $versionHash,
228 // Module implementation either broken or deviated from ResourceLoader::makeHash
229 // Asserted by tests/phpunit/structure/ResourcesTest.
230 $versionHash = ResourceLoader::makeHash( $versionHash );
233 $skipFunction = $module->getSkipFunction();
234 if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
235 $skipFunction = ResourceLoader::filter( 'minify-js', $skipFunction );
238 $registryData[$name] = [
239 'version' => $versionHash,
240 'dependencies' => $module->getDependencies( $context ),
241 'group' => $module->getGroup(),
242 'source' => $module->getSource(),
243 'skip' => $skipFunction,
247 self::compileUnresolvedDependencies( $registryData );
249 // Register sources
250 $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
252 // Figure out the different call signatures for mw.loader.register
253 $registrations = [];
254 foreach ( $registryData as $name => $data ) {
255 // Call mw.loader.register(name, version, dependencies, group, source, skip)
256 $registrations[] = [
257 $name,
258 $data['version'],
259 $data['dependencies'],
260 $data['group'],
261 // Swap default (local) for null
262 $data['source'] === 'local' ? null : $data['source'],
263 $data['skip']
267 // Register modules
268 $out .= "\n" . ResourceLoader::makeLoaderRegisterScript( $registrations );
270 return $out;
274 * @return bool
276 public function isRaw() {
277 return true;
281 * Base modules required for the base environment of ResourceLoader
283 * @return array
285 public static function getStartupModules() {
286 return [ 'jquery', 'mediawiki' ];
289 public static function getLegacyModules() {
290 global $wgIncludeLegacyJavaScript;
292 $legacyModules = [];
293 if ( $wgIncludeLegacyJavaScript ) {
294 $legacyModules[] = 'mediawiki.legacy.wikibits';
297 return $legacyModules;
301 * Get the load URL of the startup modules.
303 * This is a helper for getScript(), but can also be called standalone, such
304 * as when generating an AppCache manifest.
306 * @param ResourceLoaderContext $context
307 * @return string
309 public static function getStartupModulesUrl( ResourceLoaderContext $context ) {
310 $rl = $context->getResourceLoader();
311 $moduleNames = self::getStartupModules();
313 $query = [
314 'modules' => ResourceLoader::makePackedModulesString( $moduleNames ),
315 'only' => 'scripts',
316 'lang' => $context->getLanguage(),
317 'skin' => $context->getSkin(),
318 'debug' => $context->getDebug() ? 'true' : 'false',
319 'version' => $rl->getCombinedVersion( $context, $moduleNames ),
321 // Ensure uniform query order
322 ksort( $query );
323 return wfAppendQuery( wfScript( 'load' ), $query );
327 * @param ResourceLoaderContext $context
328 * @return string
330 public function getScript( ResourceLoaderContext $context ) {
331 global $IP;
332 if ( $context->getOnly() !== 'scripts' ) {
333 return '/* Requires only=script */';
336 $out = file_get_contents( "$IP/resources/src/startup.js" );
338 $pairs = array_map( function ( $value ) {
339 $value = FormatJson::encode( $value, ResourceLoader::inDebugMode(), FormatJson::ALL_OK );
340 // Fix indentation
341 $value = str_replace( "\n", "\n\t", $value );
342 return $value;
343 }, [
344 '$VARS.wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
345 '$VARS.configuration' => $this->getConfigSettings( $context ),
346 '$VARS.baseModulesUri' => self::getStartupModulesUrl( $context ),
347 ] );
348 $pairs['$CODE.registrations()'] = str_replace(
349 "\n",
350 "\n\t",
351 trim( $this->getModuleRegistrations( $context ) )
354 return strtr( $out, $pairs );
358 * @return bool
360 public function supportsURLLoading() {
361 return false;
365 * Get the definition summary for this module.
367 * @param ResourceLoaderContext $context
368 * @return array
370 public function getDefinitionSummary( ResourceLoaderContext $context ) {
371 global $IP;
372 $summary = parent::getDefinitionSummary( $context );
373 $summary[] = [
374 // Detect changes to variables exposed in mw.config (T30899).
375 'vars' => $this->getConfigSettings( $context ),
376 // Changes how getScript() creates mw.Map for mw.config
377 'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
378 // Detect changes to the module registrations
379 'moduleHashes' => $this->getAllModuleHashes( $context ),
381 'fileMtimes' => [
382 filemtime( "$IP/resources/src/startup.js" ),
385 return $summary;
389 * Helper method for getDefinitionSummary().
391 * @param ResourceLoaderContext $context
392 * @return string SHA-1
394 protected function getAllModuleHashes( ResourceLoaderContext $context ) {
395 $rl = $context->getResourceLoader();
396 // Preload for getCombinedVersion()
397 $rl->preloadModuleInfo( $rl->getModuleNames(), $context );
399 // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
400 // Think carefully before making changes to this code!
401 // Pre-populate versionHash with something because the loop over all modules below includes
402 // the startup module (this module).
403 // See ResourceLoaderModule::getVersionHash() for usage of this cache.
404 $this->versionHash[$context->getHash()] = null;
406 return $rl->getCombinedVersion( $context, $rl->getModuleNames() );
410 * @return string
412 public function getGroup() {
413 return 'startup';