3 * Module for resource loader 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
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' );
32 * @param ResourceLoaderContext $context
35 protected function getConfigSettings( $context ) {
37 $hash = $context->getHash();
38 if ( isset( $this->configVars
[$hash] ) ) {
39 return $this->configVars
[$hash];
44 $mainPage = Title
::newMainPage();
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
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' => $conf->get( 'ScriptExtension' ),
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 'wgVersion' => $conf->get( 'Version' ),
82 'wgEnableAPI' => $conf->get( 'EnableAPI' ),
83 'wgEnableWriteAPI' => $conf->get( 'EnableWriteAPI' ),
84 'wgMainPageTitle' => $mainPage->getPrefixedText(),
85 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
86 'wgNamespaceIds' => $namespaceIds,
87 'wgContentNamespaces' => MWNamespace
::getContentNamespaces(),
88 'wgSiteName' => $conf->get( 'Sitename' ),
89 'wgDBname' => $conf->get( 'DBname' ),
90 'wgAvailableSkins' => Skin
::getSkinNames(),
91 'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
92 // MediaWiki sets cookies to have this prefix by default
93 'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
94 'wgCookieDomain' => $conf->get( 'CookieDomain' ),
95 'wgCookiePath' => $conf->get( 'CookiePath' ),
96 'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
97 'wgResourceLoaderMaxQueryLength' => $conf->get( 'ResourceLoaderMaxQueryLength' ),
98 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
99 'wgLegalTitleChars' => Title
::convertByteClassToUnicodeClass( Title
::legalChars() ),
100 'wgResourceLoaderStorageVersion' => $conf->get( 'ResourceLoaderStorageVersion' ),
101 'wgResourceLoaderStorageEnabled' => $conf->get( 'ResourceLoaderStorageEnabled' ),
104 Hooks
::run( 'ResourceLoaderGetConfigVars', array( &$vars ) );
106 $this->configVars
[$hash] = $vars;
107 return $this->configVars
[$hash];
111 * Recursively get all explicit and implicit dependencies for to the given module.
113 * @param array $registryData
114 * @param string $moduleName
117 protected static function getImplicitDependencies( array $registryData, $moduleName ) {
118 static $dependencyCache = array();
120 // The list of implicit dependencies won't be altered, so we can
121 // cache them without having to worry.
122 if ( !isset( $dependencyCache[$moduleName] ) ) {
124 if ( !isset( $registryData[$moduleName] ) ) {
125 // Dependencies may not exist
126 $dependencyCache[$moduleName] = array();
128 $data = $registryData[$moduleName];
129 $dependencyCache[$moduleName] = $data['dependencies'];
131 foreach ( $data['dependencies'] as $dependency ) {
132 // Recursively get the dependencies of the dependencies
133 $dependencyCache[$moduleName] = array_merge(
134 $dependencyCache[$moduleName],
135 self
::getImplicitDependencies( $registryData, $dependency )
141 return $dependencyCache[$moduleName];
145 * Optimize the dependency tree in $this->modules.
147 * The optimization basically works like this:
148 * Given we have module A with the dependencies B and C
149 * and module B with the dependency C.
150 * Now we don't have to tell the client to explicitly fetch module
151 * C as that's already included in module B.
153 * This way we can reasonably reduce the amount of module registration
154 * data send to the client.
156 * @param array &$registryData Modules keyed by name with properties:
158 * - array 'dependencies'
159 * - string|null 'group'
161 * - string|false 'loader'
163 public static function compileUnresolvedDependencies( array &$registryData ) {
164 foreach ( $registryData as $name => &$data ) {
165 if ( $data['loader'] !== false ) {
168 $dependencies = $data['dependencies'];
169 foreach ( $data['dependencies'] as $dependency ) {
170 $implicitDependencies = self
::getImplicitDependencies( $registryData, $dependency );
171 $dependencies = array_diff( $dependencies, $implicitDependencies );
174 $data['dependencies'] = array_values( $dependencies );
180 * Get registration code for all modules.
182 * @param ResourceLoaderContext $context
183 * @return string JavaScript code for registering all modules with the client loader
185 public function getModuleRegistrations( ResourceLoaderContext
$context ) {
187 $resourceLoader = $context->getResourceLoader();
188 $target = $context->getRequest()->getVal( 'target', 'desktop' );
191 $registryData = array();
194 foreach ( $resourceLoader->getModuleNames() as $name ) {
195 $module = $resourceLoader->getModule( $name );
196 $moduleTargets = $module->getTargets();
197 if ( !in_array( $target, $moduleTargets ) ) {
201 if ( $module->isRaw() ) {
202 // Don't register "raw" modules (like 'jquery' and 'mediawiki') client-side because
203 // depending on them is illegal anyway and would only lead to them being reloaded
204 // causing any state to be lost (like jQuery plugins, mw.config etc.)
208 $versionHash = $module->getVersionHash( $context );
209 if ( strlen( $versionHash ) !== 8 ) {
210 // Module implementation either broken or deviated from ResourceLoader::makeHash
211 // Asserted by tests/phpunit/structure/ResourcesTest.
212 $versionHash = ResourceLoader
::makeHash( $versionHash );
215 $skipFunction = $module->getSkipFunction();
216 if ( $skipFunction !== null && !ResourceLoader
::inDebugMode() ) {
217 $skipFunction = $resourceLoader->filter( 'minify-js',
219 // There will potentially be lots of these little string in the registrations
220 // manifest, we don't want to blow up the startup module with
221 // "/* cache key: ... */" all over it in non-debug mode.
222 /* cacheReport = */ false
226 $registryData[$name] = array(
227 'version' => $versionHash,
228 'dependencies' => $module->getDependencies(),
229 'group' => $module->getGroup(),
230 'source' => $module->getSource(),
231 'loader' => $module->getLoaderScript(),
232 'skip' => $skipFunction,
236 self
::compileUnresolvedDependencies( $registryData );
239 $out .= ResourceLoader
::makeLoaderSourcesScript( $resourceLoader->getSources() );
241 // Concatenate module loader scripts and figure out the different call
242 // signatures for mw.loader.register
243 $registrations = array();
244 foreach ( $registryData as $name => $data ) {
245 if ( $data['loader'] !== false ) {
246 $out .= ResourceLoader
::makeCustomLoaderScript(
249 $data['dependencies'],
257 // Call mw.loader.register(name, version, dependencies, group, source, skip)
258 $registrations[] = array(
261 $data['dependencies'],
263 // Swap default (local) for null
264 $data['source'] === 'local' ?
null : $data['source'],
270 $out .= ResourceLoader
::makeLoaderRegisterScript( $registrations );
278 public function isRaw() {
283 * Base modules required for the base environment of ResourceLoader
287 public static function getStartupModules() {
288 return array( 'jquery', 'mediawiki' );
292 * Get the load URL of the startup modules.
294 * This is a helper for getScript(), but can also be called standalone, such
295 * as when generating an AppCache manifest.
297 * @param ResourceLoaderContext $context
300 public static function getStartupModulesUrl( ResourceLoaderContext
$context ) {
301 $rl = $context->getResourceLoader();
302 $moduleNames = self
::getStartupModules();
305 'modules' => ResourceLoader
::makePackedModulesString( $moduleNames ),
307 'lang' => $context->getLanguage(),
308 'skin' => $context->getSkin(),
309 'debug' => $context->getDebug() ?
'true' : 'false',
310 'version' => $rl->getCombinedVersion( $context, $moduleNames ),
312 // Ensure uniform query order
314 return wfAppendQuery( wfScript( 'load' ), $query );
318 * @param ResourceLoaderContext $context
321 public function getScript( ResourceLoaderContext
$context ) {
324 $out = file_get_contents( "$IP/resources/src/startup.js" );
325 if ( $context->getOnly() === 'scripts' ) {
328 $configuration = $this->getConfigSettings( $context );
329 $registrations = $this->getModuleRegistrations( $context );
331 $registrations = str_replace( "\n", "\n\t", trim( $registrations ) );
332 $mwMapJsCall = Xml
::encodeJsCall(
334 array( $this->getConfig()->get( 'LegacyJavaScriptGlobals' ) )
336 $mwConfigSetJsCall = Xml
::encodeJsCall(
338 array( $configuration ),
339 ResourceLoader
::inDebugMode()
342 $out .= "var startUp = function () {\n" .
343 "\tmw.config = new " .
344 $mwMapJsCall . "\n" .
345 "\t$registrations\n" .
346 "\t" . $mwConfigSetJsCall .
349 // Conditional script injection
350 $scriptTag = Html
::linkedScript( self
::getStartupModulesUrl( $context ) );
351 $out .= "if ( isCompatible() ) {\n" .
352 "\t" . Xml
::encodeJsCall( 'document.write', array( $scriptTag ) ) .
362 public function supportsURLLoading() {
367 * Get the definition summary for this module.
369 * @param ResourceLoaderContext $context
372 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
374 $summary = parent
::getDefinitionSummary( $context );
376 // Detect changes to variables exposed in mw.config (T30899).
377 'vars' => $this->getConfigSettings( $context ),
378 // Changes how getScript() creates mw.Map for mw.config
379 'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
380 // Detect changes to the module registrations
381 'moduleHashes' => $this->getAllModuleHashes( $context ),
383 'fileMtimes' => array(
384 filemtime( "$IP/resources/src/startup.js" ),
391 * Helper method for getDefinitionSummary().
393 * @param ResourceLoaderContext $context
394 * @return string SHA-1
396 protected function getAllModuleHashes( ResourceLoaderContext
$context ) {
397 $rl = $context->getResourceLoader();
398 // Preload for getCombinedVersion()
399 $rl->preloadModuleInfo( $rl->getModuleNames(), $context );
401 // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
402 // Think carefully before making changes to this code!
403 // Pre-populate versionHash with something because the loop over all modules below includes
404 // the startup module (this module).
405 // See ResourceLoaderModule::getVersionHash() for usage of this cache.
406 $this->versionHash
[ $context->getHash() ] = null;
408 return $rl->getCombinedVersion( $context, $rl->getModuleNames() );
414 public function getGroup() {