wfMsgForContentNoTrans() was removed
[mediawiki.git] / includes / resourceloader / ResourceLoaderStartUpModule.php
blob4a68f8ed92d11e533285c1c50552e52e7355abb1
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 = array();
29 protected $targets = array( '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;
44 $mainPage = Title::newMainPage();
46 /**
47 * Namespace related preparation
48 * - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces.
49 * - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive.
51 $namespaceIds = $wgContLang->getNamespaceIds();
52 $caseSensitiveNamespaces = array();
53 foreach ( MWNamespace::getCanonicalNamespaces() as $index => $name ) {
54 $namespaceIds[$wgContLang->lc( $name )] = $index;
55 if ( !MWNamespace::isCapitalized( $index ) ) {
56 $caseSensitiveNamespaces[] = $index;
60 $conf = $this->getConfig();
61 // Build list of variables
62 $vars = array(
63 'wgLoadScript' => wfScript( 'load' ),
64 'debug' => $context->getDebug(),
65 'skin' => $context->getSkin(),
66 'stylepath' => $conf->get( 'StylePath' ),
67 'wgUrlProtocols' => wfUrlProtocols(),
68 'wgArticlePath' => $conf->get( 'ArticlePath' ),
69 'wgScriptPath' => $conf->get( 'ScriptPath' ),
70 'wgScriptExtension' => '.php',
71 'wgScript' => wfScript(),
72 'wgSearchType' => $conf->get( 'SearchType' ),
73 'wgVariantArticlePath' => $conf->get( 'VariantArticlePath' ),
74 // Force object to avoid "empty" associative array from
75 // becoming [] instead of {} in JS (bug 34604)
76 'wgActionPaths' => (object)$conf->get( 'ActionPaths' ),
77 'wgServer' => $conf->get( 'Server' ),
78 'wgServerName' => $conf->get( 'ServerName' ),
79 'wgUserLanguage' => $context->getLanguage(),
80 'wgContentLanguage' => $wgContLang->getCode(),
81 'wgTranslateNumerals' => $conf->get( 'TranslateNumerals' ),
82 'wgVersion' => $conf->get( 'Version' ),
83 'wgEnableAPI' => $conf->get( 'EnableAPI' ),
84 'wgEnableWriteAPI' => $conf->get( 'EnableWriteAPI' ),
85 'wgMainPageTitle' => $mainPage->getPrefixedText(),
86 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
87 'wgNamespaceIds' => $namespaceIds,
88 'wgContentNamespaces' => MWNamespace::getContentNamespaces(),
89 'wgSiteName' => $conf->get( 'Sitename' ),
90 'wgDBname' => $conf->get( 'DBname' ),
91 'wgExtraSignatureNamespaces' => $conf->get( 'ExtraSignatureNamespaces' ),
92 'wgAvailableSkins' => Skin::getSkinNames(),
93 'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
94 // MediaWiki sets cookies to have this prefix by default
95 'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
96 'wgCookieDomain' => $conf->get( 'CookieDomain' ),
97 'wgCookiePath' => $conf->get( 'CookiePath' ),
98 'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
99 'wgResourceLoaderMaxQueryLength' => $conf->get( 'ResourceLoaderMaxQueryLength' ),
100 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
101 'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass( Title::legalChars() ),
102 'wgResourceLoaderStorageVersion' => $conf->get( 'ResourceLoaderStorageVersion' ),
103 'wgResourceLoaderStorageEnabled' => $conf->get( 'ResourceLoaderStorageEnabled' ),
104 'wgResourceLoaderLegacyModules' => self::getLegacyModules(),
105 'wgForeignUploadTargets' => $conf->get( 'ForeignUploadTargets' ),
106 'wgEnableUploads' => $conf->get( 'EnableUploads' ),
107 'wgForeignUploadTestEnabled' => $conf->get( 'ForeignUploadTestEnabled' ),
108 'wgForeignUploadTestDefault' => $conf->get( 'ForeignUploadTestDefault' ),
111 Hooks::run( 'ResourceLoaderGetConfigVars', array( &$vars ) );
113 $this->configVars[$hash] = $vars;
114 return $this->configVars[$hash];
118 * Recursively get all explicit and implicit dependencies for to the given module.
120 * @param array $registryData
121 * @param string $moduleName
122 * @return array
124 protected static function getImplicitDependencies( array $registryData, $moduleName ) {
125 static $dependencyCache = array();
127 // The list of implicit dependencies won't be altered, so we can
128 // cache them without having to worry.
129 if ( !isset( $dependencyCache[$moduleName] ) ) {
131 if ( !isset( $registryData[$moduleName] ) ) {
132 // Dependencies may not exist
133 $dependencyCache[$moduleName] = array();
134 } else {
135 $data = $registryData[$moduleName];
136 $dependencyCache[$moduleName] = $data['dependencies'];
138 foreach ( $data['dependencies'] as $dependency ) {
139 // Recursively get the dependencies of the dependencies
140 $dependencyCache[$moduleName] = array_merge(
141 $dependencyCache[$moduleName],
142 self::getImplicitDependencies( $registryData, $dependency )
148 return $dependencyCache[$moduleName];
152 * Optimize the dependency tree in $this->modules.
154 * The optimization basically works like this:
155 * Given we have module A with the dependencies B and C
156 * and module B with the dependency C.
157 * Now we don't have to tell the client to explicitly fetch module
158 * C as that's already included in module B.
160 * This way we can reasonably reduce the amount of module registration
161 * data send to the client.
163 * @param array &$registryData Modules keyed by name with properties:
164 * - string 'version'
165 * - array 'dependencies'
166 * - string|null 'group'
167 * - string 'source'
169 public static function compileUnresolvedDependencies( array &$registryData ) {
170 foreach ( $registryData as $name => &$data ) {
171 $dependencies = $data['dependencies'];
172 foreach ( $data['dependencies'] as $dependency ) {
173 $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
174 $dependencies = array_diff( $dependencies, $implicitDependencies );
176 // Rebuild keys
177 $data['dependencies'] = array_values( $dependencies );
182 * Get registration code for all modules.
184 * @param ResourceLoaderContext $context
185 * @return string JavaScript code for registering all modules with the client loader
187 public function getModuleRegistrations( ResourceLoaderContext $context ) {
189 $resourceLoader = $context->getResourceLoader();
190 $target = $context->getRequest()->getVal( 'target', 'desktop' );
191 // Bypass target filter if this request is Special:JavaScriptTest.
192 // To prevent misuse in production, this is only allowed if testing is enabled server-side.
193 $byPassTargetFilter = $this->getConfig()->get( 'EnableJavaScriptTest' ) && $target === 'test';
195 $out = '';
196 $registryData = array();
198 // Get registry data
199 foreach ( $resourceLoader->getModuleNames() as $name ) {
200 $module = $resourceLoader->getModule( $name );
201 $moduleTargets = $module->getTargets();
202 if ( !$byPassTargetFilter && !in_array( $target, $moduleTargets ) ) {
203 continue;
206 if ( $module->isRaw() ) {
207 // Don't register "raw" modules (like 'jquery' and 'mediawiki') client-side because
208 // depending on them is illegal anyway and would only lead to them being reloaded
209 // causing any state to be lost (like jQuery plugins, mw.config etc.)
210 continue;
213 $versionHash = $module->getVersionHash( $context );
214 if ( strlen( $versionHash ) !== 8 ) {
215 $context->getLogger()->warning(
216 "Module '{module}' produced an invalid version hash: '{version}'.",
217 array(
218 'module' => $name,
219 'version' => $versionHash,
222 // Module implementation either broken or deviated from ResourceLoader::makeHash
223 // Asserted by tests/phpunit/structure/ResourcesTest.
224 $versionHash = ResourceLoader::makeHash( $versionHash );
227 $skipFunction = $module->getSkipFunction();
228 if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
229 $skipFunction = ResourceLoader::filter( 'minify-js', $skipFunction );
232 $registryData[$name] = array(
233 'version' => $versionHash,
234 'dependencies' => $module->getDependencies( $context ),
235 'group' => $module->getGroup(),
236 'source' => $module->getSource(),
237 'skip' => $skipFunction,
241 self::compileUnresolvedDependencies( $registryData );
243 // Register sources
244 $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
246 // Figure out the different call signatures for mw.loader.register
247 $registrations = array();
248 foreach ( $registryData as $name => $data ) {
249 // Call mw.loader.register(name, version, dependencies, group, source, skip)
250 $registrations[] = array(
251 $name,
252 $data['version'],
253 $data['dependencies'],
254 $data['group'],
255 // Swap default (local) for null
256 $data['source'] === 'local' ? null : $data['source'],
257 $data['skip']
261 // Register modules
262 $out .= "\n" . ResourceLoader::makeLoaderRegisterScript( $registrations );
264 return $out;
268 * @return bool
270 public function isRaw() {
271 return true;
275 * Base modules required for the base environment of ResourceLoader
277 * @return array
279 public static function getStartupModules() {
280 return array( 'jquery', 'mediawiki' );
283 public static function getLegacyModules() {
284 global $wgIncludeLegacyJavaScript, $wgPreloadJavaScriptMwUtil;
286 $legacyModules = array();
287 if ( $wgIncludeLegacyJavaScript ) {
288 $legacyModules[] = 'mediawiki.legacy.wikibits';
290 if ( $wgPreloadJavaScriptMwUtil ) {
291 $legacyModules[] = 'mediawiki.util';
294 return $legacyModules;
298 * Get the load URL of the startup modules.
300 * This is a helper for getScript(), but can also be called standalone, such
301 * as when generating an AppCache manifest.
303 * @param ResourceLoaderContext $context
304 * @return string
306 public static function getStartupModulesUrl( ResourceLoaderContext $context ) {
307 $rl = $context->getResourceLoader();
308 $moduleNames = self::getStartupModules();
310 $query = array(
311 'modules' => ResourceLoader::makePackedModulesString( $moduleNames ),
312 'only' => 'scripts',
313 'lang' => $context->getLanguage(),
314 'skin' => $context->getSkin(),
315 'debug' => $context->getDebug() ? 'true' : 'false',
316 'version' => $rl->getCombinedVersion( $context, $moduleNames ),
318 // Ensure uniform query order
319 ksort( $query );
320 return wfAppendQuery( wfScript( 'load' ), $query );
324 * @param ResourceLoaderContext $context
325 * @return string
327 public function getScript( ResourceLoaderContext $context ) {
328 global $IP;
329 if ( $context->getOnly() !== 'scripts' ) {
330 return '/* Requires only=script */';
333 $out = file_get_contents( "$IP/resources/src/startup.js" );
335 $pairs = array_map( function ( $value ) {
336 $value = FormatJson::encode( $value, ResourceLoader::inDebugMode(), FormatJson::ALL_OK );
337 // Fix indentation
338 $value = str_replace( "\n", "\n\t", $value );
339 return $value;
340 }, array(
341 '$VARS.wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
342 '$VARS.configuration' => $this->getConfigSettings( $context ),
343 '$VARS.baseModulesUri' => self::getStartupModulesUrl( $context ),
344 ) );
345 $pairs['$CODE.registrations()'] = str_replace(
346 "\n",
347 "\n\t",
348 trim( $this->getModuleRegistrations( $context ) )
351 return strtr( $out, $pairs );
355 * @return bool
357 public function supportsURLLoading() {
358 return false;
362 * Get the definition summary for this module.
364 * @param ResourceLoaderContext $context
365 * @return array
367 public function getDefinitionSummary( ResourceLoaderContext $context ) {
368 global $IP;
369 $summary = parent::getDefinitionSummary( $context );
370 $summary[] = array(
371 // Detect changes to variables exposed in mw.config (T30899).
372 'vars' => $this->getConfigSettings( $context ),
373 // Changes how getScript() creates mw.Map for mw.config
374 'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
375 // Detect changes to the module registrations
376 'moduleHashes' => $this->getAllModuleHashes( $context ),
378 'fileMtimes' => array(
379 filemtime( "$IP/resources/src/startup.js" ),
382 return $summary;
386 * Helper method for getDefinitionSummary().
388 * @param ResourceLoaderContext $context
389 * @return string SHA-1
391 protected function getAllModuleHashes( ResourceLoaderContext $context ) {
392 $rl = $context->getResourceLoader();
393 // Preload for getCombinedVersion()
394 $rl->preloadModuleInfo( $rl->getModuleNames(), $context );
396 // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
397 // Think carefully before making changes to this code!
398 // Pre-populate versionHash with something because the loop over all modules below includes
399 // the startup module (this module).
400 // See ResourceLoaderModule::getVersionHash() for usage of this cache.
401 $this->versionHash[$context->getHash()] = null;
403 return $rl->getCombinedVersion( $context, $rl->getModuleNames() );
407 * @return string
409 public function getGroup() {
410 return 'startup';