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 getConfig( $context ) {
41 $hash = $context->getHash();
42 if ( isset( $this->configVars
[$hash] ) ) {
43 return $this->configVars
[$hash];
46 global $wgLoadScript, $wgScript, $wgStylePath, $wgScriptExtension,
47 $wgArticlePath, $wgScriptPath, $wgServer, $wgServerName,
48 $wgContLang, $wgVariantArticlePath, $wgActionPaths, $wgVersion,
49 $wgEnableAPI, $wgEnableWriteAPI, $wgDBname,
50 $wgSitename, $wgFileExtensions, $wgExtensionAssetsPath,
51 $wgCookiePrefix, $wgResourceLoaderMaxQueryLength,
52 $wgResourceLoaderStorageEnabled, $wgResourceLoaderStorageVersion,
55 $mainPage = Title
::newMainPage();
58 * Namespace related preparation
59 * - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces.
60 * - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive.
62 $namespaceIds = $wgContLang->getNamespaceIds();
63 $caseSensitiveNamespaces = array();
64 foreach ( MWNamespace
::getCanonicalNamespaces() as $index => $name ) {
65 $namespaceIds[$wgContLang->lc( $name )] = $index;
66 if ( !MWNamespace
::isCapitalized( $index ) ) {
67 $caseSensitiveNamespaces[] = $index;
71 // Build list of variables
73 'wgLoadScript' => $wgLoadScript,
74 'debug' => $context->getDebug(),
75 'skin' => $context->getSkin(),
76 'stylepath' => $wgStylePath,
77 'wgUrlProtocols' => wfUrlProtocols(),
78 'wgArticlePath' => $wgArticlePath,
79 'wgScriptPath' => $wgScriptPath,
80 'wgScriptExtension' => $wgScriptExtension,
81 'wgScript' => $wgScript,
82 'wgSearchType' => $wgSearchType,
83 'wgVariantArticlePath' => $wgVariantArticlePath,
84 // Force object to avoid "empty" associative array from
85 // becoming [] instead of {} in JS (bug 34604)
86 'wgActionPaths' => (object)$wgActionPaths,
87 'wgServer' => $wgServer,
88 'wgServerName' => $wgServerName,
89 'wgUserLanguage' => $context->getLanguage(),
90 'wgContentLanguage' => $wgContLang->getCode(),
91 'wgVersion' => $wgVersion,
92 'wgEnableAPI' => $wgEnableAPI,
93 'wgEnableWriteAPI' => $wgEnableWriteAPI,
94 'wgMainPageTitle' => $mainPage->getPrefixedText(),
95 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
96 'wgNamespaceIds' => $namespaceIds,
97 'wgContentNamespaces' => MWNamespace
::getContentNamespaces(),
98 'wgSiteName' => $wgSitename,
99 'wgFileExtensions' => array_values( array_unique( $wgFileExtensions ) ),
100 'wgDBname' => $wgDBname,
101 // This sucks, it is only needed on Special:Upload, but I could
102 // not find a way to add vars only for a certain module
103 'wgFileCanRotate' => BitmapHandler
::canRotate(),
104 'wgAvailableSkins' => Skin
::getSkinNames(),
105 'wgExtensionAssetsPath' => $wgExtensionAssetsPath,
106 // MediaWiki sets cookies to have this prefix by default
107 'wgCookiePrefix' => $wgCookiePrefix,
108 'wgResourceLoaderMaxQueryLength' => $wgResourceLoaderMaxQueryLength,
109 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
110 'wgLegalTitleChars' => Title
::convertByteClassToUnicodeClass( Title
::legalChars() ),
111 'wgResourceLoaderStorageVersion' => $wgResourceLoaderStorageVersion,
112 'wgResourceLoaderStorageEnabled' => $wgResourceLoaderStorageEnabled,
115 wfRunHooks( 'ResourceLoaderGetConfigVars', array( &$vars ) );
117 $this->configVars
[$hash] = $vars;
118 return $this->configVars
[$hash];
122 * Recursively get all explicit and implicit dependencies for to the given module.
124 * @param array $registryData
125 * @param string $moduleName
128 protected static function getImplicitDependencies( Array $registryData, $moduleName ) {
129 static $dependencyCache = array();
131 // The list of implicit dependencies won't be altered, so we can
132 // cache them without having to worry.
133 if ( !isset( $dependencyCache[$moduleName] ) ) {
135 if ( !isset( $registryData[$moduleName] ) ) {
136 // Dependencies may not exist
137 $dependencyCache[$moduleName] = array();
139 $data = $registryData[$moduleName];
140 $dependencyCache[$moduleName] = $data['dependencies'];
142 foreach ( $data['dependencies'] as $dependency ) {
143 // Recursively get the dependencies of the dependencies
144 $dependencyCache[$moduleName] = array_merge(
145 $dependencyCache[$moduleName],
146 self
::getImplicitDependencies( $registryData, $dependency )
152 return $dependencyCache[$moduleName];
156 * Optimize the dependency tree in $this->modules and return it.
158 * The optimization basically works like this:
159 * Given we have module A with the dependencies B and C
160 * and module B with the dependency C.
161 * Now we don't have to tell the client to explicitly fetch module
162 * C as that's already included in module B.
164 * This way we can reasonably reduce the amout of module registration
165 * data send to the client.
167 * @param Array &$registryData Modules keyed by name with properties:
169 * - array 'dependencies'
170 * - string|null 'group'
172 * - string|false 'loader'
174 public static function compileUnresolvedDependencies( Array &$registryData ) {
175 foreach ( $registryData as $name => &$data ) {
176 if ( $data['loader'] !== false ) {
179 $dependencies = $data['dependencies'];
180 foreach ( $data['dependencies'] as $dependency ) {
181 $implicitDependencies = self
::getImplicitDependencies( $registryData, $dependency );
182 $dependencies = array_diff( $dependencies, $implicitDependencies );
185 $data['dependencies'] = array_values( $dependencies );
191 * Get registration code for all modules.
193 * @param ResourceLoaderContext $context
194 * @return string JavaScript code for registering all modules with the client loader
196 public static function getModuleRegistrations( ResourceLoaderContext
$context ) {
197 global $wgCacheEpoch;
198 wfProfileIn( __METHOD__
);
200 $resourceLoader = $context->getResourceLoader();
201 $target = $context->getRequest()->getVal( 'target', 'desktop' );
204 $registryData = array();
207 foreach ( $resourceLoader->getModuleNames() as $name ) {
208 $module = $resourceLoader->getModule( $name );
209 $moduleTargets = $module->getTargets();
210 if ( !in_array( $target, $moduleTargets ) ) {
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
, $wgCacheEpoch ) );
219 // FIXME: Convert to numbers, wfTimestamp always gives us stings, even for TS_UNIX
221 $registryData[ $name ] = array(
223 'dependencies' => $module->getDependencies(),
224 'group' => $module->getGroup(),
225 'source' => $module->getSource(),
226 'loader' => $module->getLoaderScript(),
230 self
::compileUnresolvedDependencies( $registryData );
233 $out .= ResourceLoader
::makeLoaderSourcesScript( $resourceLoader->getSources() );
235 // Concatenate module loader scripts and figure out the different call
236 // signatures for mw.loader.register
237 $registrations = array();
238 foreach ( $registryData as $name => $data ) {
239 if ( $data['loader'] !== false ) {
240 $out .= ResourceLoader
::makeCustomLoaderScript(
242 wfTimestamp( TS_ISO_8601_BASIC
, $data['version'] ),
243 $data['dependencies'],
252 !count( $data['dependencies'] ) &&
253 $data['group'] === null &&
254 $data['source'] === 'local'
256 // Modules without dependencies, a group or a foreign source;
257 // call mw.loader.register(name, timestamp)
258 $registrations[] = array( $name, $data['version'] );
259 } elseif ( $data['group'] === null && $data['source'] === 'local' ) {
260 // Modules with dependencies but no group or foreign source;
261 // call mw.loader.register(name, timestamp, dependencies)
262 $registrations[] = array( $name, $data['version'], $data['dependencies'] );
263 } elseif ( $data['source'] === 'local' ) {
264 // Modules with a group but no foreign source;
265 // call mw.loader.register(name, timestamp, dependencies, group)
266 $registrations[] = array(
269 $data['dependencies'],
273 // Modules with a foreign source;
274 // call mw.loader.register(name, timestamp, dependencies, group, source)
275 $registrations[] = array(
278 $data['dependencies'],
286 $out .= ResourceLoader
::makeLoaderRegisterScript( $registrations );
288 wfProfileOut( __METHOD__
);
297 public function isRaw() {
302 * Get the load URL of the startup modules.
304 * This is a helper for getScript(), but can also be called standalone, such
305 * as when generating an AppCache manifest.
307 * @param ResourceLoaderContext $context
310 public static function getStartupModulesUrl( ResourceLoaderContext
$context ) {
312 $moduleNames = array( 'jquery', 'mediawiki' );
313 wfRunHooks( 'ResourceLoaderGetStartupModules', array( &$moduleNames ), '1.23' );
315 // Get the latest version
316 $loader = $context->getResourceLoader();
318 foreach ( $moduleNames as $moduleName ) {
319 $version = max( $version,
320 $loader->getModule( $moduleName )->getModifiedTime( $context )
325 'modules' => ResourceLoader
::makePackedModulesString( $moduleNames ),
327 'lang' => $context->getLanguage(),
328 'skin' => $context->getSkin(),
329 'debug' => $context->getDebug() ?
'true' : 'false',
330 'version' => wfTimestamp( TS_ISO_8601_BASIC
, $version )
332 // Ensure uniform query order
334 return wfAppendQuery( wfScript( 'load' ), $query );
338 * @param ResourceLoaderContext $context
341 public function getScript( ResourceLoaderContext
$context ) {
342 global $IP, $wgLegacyJavaScriptGlobals;
344 $out = file_get_contents( "$IP/resources/src/startup.js" );
345 if ( $context->getOnly() === 'scripts' ) {
348 $configuration = $this->getConfig( $context );
349 $registrations = self
::getModuleRegistrations( $context );
351 $registrations = str_replace( "\n", "\n\t", trim( $registrations ) );
352 $out .= "var startUp = function () {\n" .
353 "\tmw.config = new " .
354 Xml
::encodeJsCall( 'mw.Map', array( $wgLegacyJavaScriptGlobals ) ) . "\n" .
355 "\t$registrations\n" .
356 "\t" . Xml
::encodeJsCall( 'mw.config.set', array( $configuration ) ) .
359 // Conditional script injection
360 $scriptTag = Html
::linkedScript( self
::getStartupModulesUrl( $context ) );
361 $out .= "if ( isCompatible() ) {\n" .
362 "\t" . Xml
::encodeJsCall( 'document.write', array( $scriptTag ) ) .
372 public function supportsURLLoading() {
377 * @param ResourceLoaderContext $context
378 * @return array|mixed
380 public function getModifiedTime( ResourceLoaderContext
$context ) {
381 global $IP, $wgCacheEpoch;
383 $hash = $context->getHash();
384 if ( isset( $this->modifiedTime
[$hash] ) ) {
385 return $this->modifiedTime
[$hash];
388 // Call preloadModuleInfo() on ALL modules as we're about
389 // to call getModifiedTime() on all of them
390 $loader = $context->getResourceLoader();
391 $loader->preloadModuleInfo( $loader->getModuleNames(), $context );
394 wfTimestamp( TS_UNIX
, $wgCacheEpoch ),
395 filemtime( "$IP/resources/src/startup.js" ),
396 $this->getHashMtime( $context )
399 // ATTENTION!: Because of the line below, this is not going to cause
400 // infinite recursion - think carefully before making changes to this
402 // Pre-populate modifiedTime with something because the the loop over
403 // all modules below includes the the startup module (this module).
404 $this->modifiedTime
[$hash] = 1;
406 foreach ( $loader->getModuleNames() as $name ) {
407 $module = $loader->getModule( $name );
408 $time = max( $time, $module->getModifiedTime( $context ) );
411 $this->modifiedTime
[$hash] = $time;
412 return $this->modifiedTime
[$hash];
416 * Hash of all dynamic data embedded in getScript().
418 * Detect changes to mw.config settings embedded in #getScript (bug 28899).
420 * @param ResourceLoaderContext $context
421 * @return string Hash
423 public function getModifiedHash( ResourceLoaderContext
$context ) {
424 global $wgLegacyJavaScriptGlobals;
427 'vars' => $this->getConfig( $context ),
428 'wgLegacyJavaScriptGlobals' => $wgLegacyJavaScriptGlobals,
431 return md5( serialize( $data ) );
437 public function getGroup() {