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 wfRunHooks( '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 and return it.
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 amout 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 // getModifiedTime() is supposed to return a UNIX timestamp, but it doesn't always
215 // seem to do that, and custom implementations might forget. Coerce it to TS_UNIX
216 $moduleMtime = wfTimestamp( TS_UNIX
, $module->getModifiedTime( $context ) );
217 $mtime = max( $moduleMtime, wfTimestamp( TS_UNIX
, $this->getConfig()->get( 'CacheEpoch' ) ) );
219 // FIXME: Convert to numbers, wfTimestamp always gives us stings, even for TS_UNIX
221 $skipFunction = $module->getSkipFunction();
222 if ( $skipFunction !== null && !ResourceLoader
::inDebugMode() ) {
223 $skipFunction = $resourceLoader->filter( 'minify-js',
225 // There will potentially be lots of these little string in the registrations
226 // manifest, we don't want to blow up the startup module with
227 // "/* cache key: ... */" all over it in non-debug mode.
228 /* cacheReport = */ false
232 $registryData[$name] = array(
234 'dependencies' => $module->getDependencies(),
235 'group' => $module->getGroup(),
236 'source' => $module->getSource(),
237 'loader' => $module->getLoaderScript(),
238 'skip' => $skipFunction,
242 self
::compileUnresolvedDependencies( $registryData );
245 $out .= ResourceLoader
::makeLoaderSourcesScript( $resourceLoader->getSources() );
247 // Concatenate module loader scripts and figure out the different call
248 // signatures for mw.loader.register
249 $registrations = array();
250 foreach ( $registryData as $name => $data ) {
251 if ( $data['loader'] !== false ) {
252 $out .= ResourceLoader
::makeCustomLoaderScript(
254 wfTimestamp( TS_ISO_8601_BASIC
, $data['version'] ),
255 $data['dependencies'],
264 !count( $data['dependencies'] ) &&
265 $data['group'] === null &&
266 $data['source'] === 'local' &&
267 $data['skip'] === null
269 // Modules with no dependencies, group, foreign source or skip function;
270 // call mw.loader.register(name, timestamp)
271 $registrations[] = array( $name, $data['version'] );
273 $data['group'] === null &&
274 $data['source'] === 'local' &&
275 $data['skip'] === null
277 // Modules with dependencies but no group, foreign source or skip function;
278 // call mw.loader.register(name, timestamp, dependencies)
279 $registrations[] = array( $name, $data['version'], $data['dependencies'] );
281 $data['source'] === 'local' &&
282 $data['skip'] === null
284 // Modules with a group but no foreign source or skip function;
285 // call mw.loader.register(name, timestamp, dependencies, group)
286 $registrations[] = array(
289 $data['dependencies'],
292 } elseif ( $data['skip'] === null ) {
293 // Modules with a foreign source but no skip function;
294 // call mw.loader.register(name, timestamp, dependencies, group, source)
295 $registrations[] = array(
298 $data['dependencies'],
303 // Modules with a skip function;
304 // call mw.loader.register(name, timestamp, dependencies, group, source, skip)
305 $registrations[] = array(
308 $data['dependencies'],
317 $out .= ResourceLoader
::makeLoaderRegisterScript( $registrations );
319 wfProfileOut( __METHOD__
);
328 public function isRaw() {
333 * Base modules required for the the base environment of ResourceLoader
337 public static function getStartupModules() {
338 return array( 'jquery', 'mediawiki' );
342 * Get the load URL of the startup modules.
344 * This is a helper for getScript(), but can also be called standalone, such
345 * as when generating an AppCache manifest.
347 * @param ResourceLoaderContext $context
350 public static function getStartupModulesUrl( ResourceLoaderContext
$context ) {
351 $moduleNames = self
::getStartupModules();
353 // Get the latest version
354 $loader = $context->getResourceLoader();
356 foreach ( $moduleNames as $moduleName ) {
357 $version = max( $version,
358 $loader->getModule( $moduleName )->getModifiedTime( $context )
363 'modules' => ResourceLoader
::makePackedModulesString( $moduleNames ),
365 'lang' => $context->getLanguage(),
366 'skin' => $context->getSkin(),
367 'debug' => $context->getDebug() ?
'true' : 'false',
368 'version' => wfTimestamp( TS_ISO_8601_BASIC
, $version )
370 // Ensure uniform query order
372 return wfAppendQuery( wfScript( 'load' ), $query );
376 * @param ResourceLoaderContext $context
379 public function getScript( ResourceLoaderContext
$context ) {
382 $out = file_get_contents( "$IP/resources/src/startup.js" );
383 if ( $context->getOnly() === 'scripts' ) {
386 $configuration = $this->getConfigSettings( $context );
387 $registrations = $this->getModuleRegistrations( $context );
389 $registrations = str_replace( "\n", "\n\t", trim( $registrations ) );
390 $mwMapJsCall = Xml
::encodeJsCall(
392 array( $this->getConfig()->get( 'LegacyJavaScriptGlobals' ) )
394 $mwConfigSetJsCall = Xml
::encodeJsCall(
396 array( $configuration )
399 $out .= "var startUp = function () {\n" .
400 "\tmw.config = new " .
401 $mwMapJsCall . "\n" .
402 "\t$registrations\n" .
403 "\t" . $mwConfigSetJsCall .
406 // Conditional script injection
407 $scriptTag = Html
::linkedScript( self
::getStartupModulesUrl( $context ) );
408 $out .= "if ( isCompatible() ) {\n" .
409 "\t" . Xml
::encodeJsCall( 'document.write', array( $scriptTag ) ) .
419 public function supportsURLLoading() {
424 * @param ResourceLoaderContext $context
425 * @return array|mixed
427 public function getModifiedTime( ResourceLoaderContext
$context ) {
430 $hash = $context->getHash();
431 if ( isset( $this->modifiedTime
[$hash] ) ) {
432 return $this->modifiedTime
[$hash];
435 // Call preloadModuleInfo() on ALL modules as we're about
436 // to call getModifiedTime() on all of them
437 $loader = $context->getResourceLoader();
438 $loader->preloadModuleInfo( $loader->getModuleNames(), $context );
441 wfTimestamp( TS_UNIX
, $this->getConfig()->get( 'CacheEpoch' ) ),
442 filemtime( "$IP/resources/src/startup.js" ),
443 $this->getHashMtime( $context )
446 // ATTENTION!: Because of the line below, this is not going to cause
447 // infinite recursion - think carefully before making changes to this
449 // Pre-populate modifiedTime with something because the the loop over
450 // all modules below includes the the startup module (this module).
451 $this->modifiedTime
[$hash] = 1;
453 foreach ( $loader->getModuleNames() as $name ) {
454 $module = $loader->getModule( $name );
455 $time = max( $time, $module->getModifiedTime( $context ) );
458 $this->modifiedTime
[$hash] = $time;
459 return $this->modifiedTime
[$hash];
463 * Hash of all dynamic data embedded in getScript().
465 * Detect changes to mw.config settings embedded in #getScript (bug 28899).
467 * @param ResourceLoaderContext $context
468 * @return string Hash
470 public function getModifiedHash( ResourceLoaderContext
$context ) {
472 'vars' => $this->getConfigSettings( $context ),
473 'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
476 return md5( serialize( $data ) );
482 public function getGroup() {