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 /* Protected Members */
29 protected $modifiedTime = array();
30 protected $configVars = array();
31 protected $targets = array( 'desktop', 'mobile' );
33 /* Protected Methods */
36 * @param ResourceLoaderContext $context
39 protected function getConfigSettings( $context ) {
41 $hash = $context->getHash();
42 if ( isset( $this->configVars
[$hash] ) ) {
43 return $this->configVars
[$hash];
48 $mainPage = Title
::newMainPage();
51 * Namespace related preparation
52 * - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces.
53 * - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive.
55 $namespaceIds = $wgContLang->getNamespaceIds();
56 $caseSensitiveNamespaces = array();
57 foreach ( MWNamespace
::getCanonicalNamespaces() as $index => $name ) {
58 $namespaceIds[$wgContLang->lc( $name )] = $index;
59 if ( !MWNamespace
::isCapitalized( $index ) ) {
60 $caseSensitiveNamespaces[] = $index;
64 $conf = $this->getConfig();
65 // Build list of variables
67 'wgLoadScript' => wfScript( 'load' ),
68 'debug' => $context->getDebug(),
69 'skin' => $context->getSkin(),
70 'stylepath' => $conf->get( 'StylePath' ),
71 'wgUrlProtocols' => wfUrlProtocols(),
72 'wgArticlePath' => $conf->get( 'ArticlePath' ),
73 'wgScriptPath' => $conf->get( 'ScriptPath' ),
74 'wgScriptExtension' => $conf->get( 'ScriptExtension' ),
75 'wgScript' => wfScript(),
76 'wgSearchType' => $conf->get( 'SearchType' ),
77 'wgVariantArticlePath' => $conf->get( 'VariantArticlePath' ),
78 // Force object to avoid "empty" associative array from
79 // becoming [] instead of {} in JS (bug 34604)
80 'wgActionPaths' => (object)$conf->get( 'ActionPaths' ),
81 'wgServer' => $conf->get( 'Server' ),
82 'wgServerName' => $conf->get( 'ServerName' ),
83 'wgUserLanguage' => $context->getLanguage(),
84 'wgContentLanguage' => $wgContLang->getCode(),
85 'wgVersion' => $conf->get( 'Version' ),
86 'wgEnableAPI' => $conf->get( 'EnableAPI' ),
87 'wgEnableWriteAPI' => $conf->get( 'EnableWriteAPI' ),
88 'wgMainPageTitle' => $mainPage->getPrefixedText(),
89 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
90 'wgNamespaceIds' => $namespaceIds,
91 'wgContentNamespaces' => MWNamespace
::getContentNamespaces(),
92 'wgSiteName' => $conf->get( 'Sitename' ),
93 'wgFileExtensions' => array_values( array_unique( $conf->get( 'FileExtensions' ) ) ),
94 'wgDBname' => $conf->get( 'DBname' ),
95 'wgAvailableSkins' => Skin
::getSkinNames(),
96 'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
97 // MediaWiki sets cookies to have this prefix by default
98 'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
99 'wgCookieDomain' => $conf->get( 'CookieDomain' ),
100 'wgCookiePath' => $conf->get( 'CookiePath' ),
101 'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
102 'wgResourceLoaderMaxQueryLength' => $conf->get( 'ResourceLoaderMaxQueryLength' ),
103 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
104 'wgLegalTitleChars' => Title
::convertByteClassToUnicodeClass( Title
::legalChars() ),
105 'wgResourceLoaderStorageVersion' => $conf->get( 'ResourceLoaderStorageVersion' ),
106 'wgResourceLoaderStorageEnabled' => $conf->get( 'ResourceLoaderStorageEnabled' ),
109 Hooks
::run( 'ResourceLoaderGetConfigVars', array( &$vars ) );
111 $this->configVars
[$hash] = $vars;
112 return $this->configVars
[$hash];
116 * Recursively get all explicit and implicit dependencies for to the given module.
118 * @param array $registryData
119 * @param string $moduleName
122 protected static function getImplicitDependencies( array $registryData, $moduleName ) {
123 static $dependencyCache = array();
125 // The list of implicit dependencies won't be altered, so we can
126 // cache them without having to worry.
127 if ( !isset( $dependencyCache[$moduleName] ) ) {
129 if ( !isset( $registryData[$moduleName] ) ) {
130 // Dependencies may not exist
131 $dependencyCache[$moduleName] = array();
133 $data = $registryData[$moduleName];
134 $dependencyCache[$moduleName] = $data['dependencies'];
136 foreach ( $data['dependencies'] as $dependency ) {
137 // Recursively get the dependencies of the dependencies
138 $dependencyCache[$moduleName] = array_merge(
139 $dependencyCache[$moduleName],
140 self
::getImplicitDependencies( $registryData, $dependency )
146 return $dependencyCache[$moduleName];
150 * Optimize the dependency tree in $this->modules.
152 * The optimization basically works like this:
153 * Given we have module A with the dependencies B and C
154 * and module B with the dependency C.
155 * Now we don't have to tell the client to explicitly fetch module
156 * C as that's already included in module B.
158 * This way we can reasonably reduce the amount of module registration
159 * data send to the client.
161 * @param array &$registryData Modules keyed by name with properties:
163 * - array 'dependencies'
164 * - string|null 'group'
166 * - string|false 'loader'
168 public static function compileUnresolvedDependencies( array &$registryData ) {
169 foreach ( $registryData as $name => &$data ) {
170 if ( $data['loader'] !== false ) {
173 $dependencies = $data['dependencies'];
174 foreach ( $data['dependencies'] as $dependency ) {
175 $implicitDependencies = self
::getImplicitDependencies( $registryData, $dependency );
176 $dependencies = array_diff( $dependencies, $implicitDependencies );
179 $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 wfProfileIn( __METHOD__
);
193 $resourceLoader = $context->getResourceLoader();
194 $target = $context->getRequest()->getVal( 'target', 'desktop' );
197 $registryData = array();
200 foreach ( $resourceLoader->getModuleNames() as $name ) {
201 $module = $resourceLoader->getModule( $name );
202 $moduleTargets = $module->getTargets();
203 if ( !in_array( $target, $moduleTargets ) ) {
207 if ( $module->isRaw() ) {
208 // Don't register "raw" modules (like 'jquery' and 'mediawiki') client-side because
209 // depending on them is illegal anyway and would only lead to them being reloaded
210 // causing any state to be lost (like jQuery plugins, mw.config etc.)
214 // Coerce module timestamp to UNIX timestamp.
215 // getModifiedTime() is supposed to return a UNIX timestamp, but custom implementations
216 // might forget. TODO: Maybe emit warning?
217 $moduleMtime = wfTimestamp( TS_UNIX
, $module->getModifiedTime( $context ) );
219 $skipFunction = $module->getSkipFunction();
220 if ( $skipFunction !== null && !ResourceLoader
::inDebugMode() ) {
221 $skipFunction = $resourceLoader->filter( 'minify-js',
223 // There will potentially be lots of these little string in the registrations
224 // manifest, we don't want to blow up the startup module with
225 // "/* cache key: ... */" all over it in non-debug mode.
226 /* cacheReport = */ false
232 wfTimestamp( TS_UNIX
, $this->getConfig()->get( 'CacheEpoch' ) )
235 $registryData[$name] = array(
236 // Convert to numbers as wfTimestamp always returns a string, even for TS_UNIX
237 'version' => (int) $mtime,
238 'dependencies' => $module->getDependencies(),
239 'group' => $module->getGroup(),
240 'source' => $module->getSource(),
241 'loader' => $module->getLoaderScript(),
242 'skip' => $skipFunction,
246 self
::compileUnresolvedDependencies( $registryData );
249 $out .= ResourceLoader
::makeLoaderSourcesScript( $resourceLoader->getSources() );
251 // Concatenate module loader scripts and figure out the different call
252 // signatures for mw.loader.register
253 $registrations = array();
254 foreach ( $registryData as $name => $data ) {
255 if ( $data['loader'] !== false ) {
256 $out .= ResourceLoader
::makeCustomLoaderScript(
259 $data['dependencies'],
267 // Call mw.loader.register(name, timestamp, dependencies, group, source, skip)
268 $registrations[] = array(
271 $data['dependencies'],
273 // Swap default (local) for null
274 $data['source'] === 'local' ?
null : $data['source'],
280 $out .= ResourceLoader
::makeLoaderRegisterScript( $registrations );
282 wfProfileOut( __METHOD__
);
291 public function isRaw() {
296 * Base modules required for the the base environment of ResourceLoader
300 public static function getStartupModules() {
301 return array( 'jquery', 'mediawiki' );
305 * Get the load URL of the startup modules.
307 * This is a helper for getScript(), but can also be called standalone, such
308 * as when generating an AppCache manifest.
310 * @param ResourceLoaderContext $context
313 public static function getStartupModulesUrl( ResourceLoaderContext
$context ) {
314 $moduleNames = self
::getStartupModules();
316 // Get the latest version
317 $loader = $context->getResourceLoader();
319 foreach ( $moduleNames as $moduleName ) {
320 $version = max( $version,
321 $loader->getModule( $moduleName )->getModifiedTime( $context )
326 'modules' => ResourceLoader
::makePackedModulesString( $moduleNames ),
328 'lang' => $context->getLanguage(),
329 'skin' => $context->getSkin(),
330 'debug' => $context->getDebug() ?
'true' : 'false',
331 'version' => wfTimestamp( TS_ISO_8601_BASIC
, $version )
333 // Ensure uniform query order
335 return wfAppendQuery( wfScript( 'load' ), $query );
339 * @param ResourceLoaderContext $context
342 public function getScript( ResourceLoaderContext
$context ) {
345 $out = file_get_contents( "$IP/resources/src/startup.js" );
346 if ( $context->getOnly() === 'scripts' ) {
349 $configuration = $this->getConfigSettings( $context );
350 $registrations = $this->getModuleRegistrations( $context );
352 $registrations = str_replace( "\n", "\n\t", trim( $registrations ) );
353 $mwMapJsCall = Xml
::encodeJsCall(
355 array( $this->getConfig()->get( 'LegacyJavaScriptGlobals' ) )
357 $mwConfigSetJsCall = Xml
::encodeJsCall(
359 array( $configuration )
362 $out .= "var startUp = function () {\n" .
363 "\tmw.config = new " .
364 $mwMapJsCall . "\n" .
365 "\t$registrations\n" .
366 "\t" . $mwConfigSetJsCall .
369 // Conditional script injection
370 $scriptTag = Html
::linkedScript( self
::getStartupModulesUrl( $context ) );
371 $out .= "if ( isCompatible() ) {\n" .
372 "\t" . Xml
::encodeJsCall( 'document.write', array( $scriptTag ) ) .
382 public function supportsURLLoading() {
387 * @param ResourceLoaderContext $context
388 * @return array|mixed
390 public function getModifiedTime( ResourceLoaderContext
$context ) {
393 $hash = $context->getHash();
394 if ( isset( $this->modifiedTime
[$hash] ) ) {
395 return $this->modifiedTime
[$hash];
398 // Call preloadModuleInfo() on ALL modules as we're about
399 // to call getModifiedTime() on all of them
400 $loader = $context->getResourceLoader();
401 $loader->preloadModuleInfo( $loader->getModuleNames(), $context );
404 wfTimestamp( TS_UNIX
, $this->getConfig()->get( 'CacheEpoch' ) ),
405 filemtime( "$IP/resources/src/startup.js" ),
406 $this->getHashMtime( $context )
409 // ATTENTION!: Because of the line below, this is not going to cause
410 // infinite recursion - think carefully before making changes to this
412 // Pre-populate modifiedTime with something because the the loop over
413 // all modules below includes the the startup module (this module).
414 $this->modifiedTime
[$hash] = 1;
416 foreach ( $loader->getModuleNames() as $name ) {
417 $module = $loader->getModule( $name );
418 $time = max( $time, $module->getModifiedTime( $context ) );
421 $this->modifiedTime
[$hash] = $time;
422 return $this->modifiedTime
[$hash];
426 * Hash of all dynamic data embedded in getScript().
428 * Detect changes to mw.config settings embedded in #getScript (bug 28899).
430 * @param ResourceLoaderContext $context
431 * @return string Hash
433 public function getModifiedHash( ResourceLoaderContext
$context ) {
435 'vars' => $this->getConfigSettings( $context ),
436 'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
439 return md5( serialize( $data ) );
445 public function getGroup() {