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, $wgContLang,
48 $wgVariantArticlePath, $wgActionPaths, $wgVersion,
49 $wgEnableAPI, $wgEnableWriteAPI, $wgDBname,
50 $wgSitename, $wgFileExtensions, $wgExtensionAssetsPath,
51 $wgCookiePrefix, $wgCookieDomain, $wgCookiePath,
52 $wgCookieExpiration, $wgResourceLoaderMaxQueryLength,
53 $wgResourceLoaderStorageEnabled, $wgResourceLoaderStorageVersion,
56 $mainPage = Title
::newMainPage();
59 * Namespace related preparation
60 * - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces.
61 * - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive.
63 $namespaceIds = $wgContLang->getNamespaceIds();
64 $caseSensitiveNamespaces = array();
65 foreach ( MWNamespace
::getCanonicalNamespaces() as $index => $name ) {
66 $namespaceIds[$wgContLang->lc( $name )] = $index;
67 if ( !MWNamespace
::isCapitalized( $index ) ) {
68 $caseSensitiveNamespaces[] = $index;
72 // Build list of variables
74 'wgLoadScript' => $wgLoadScript,
75 'debug' => $context->getDebug(),
76 'skin' => $context->getSkin(),
77 'stylepath' => $wgStylePath,
78 'wgUrlProtocols' => wfUrlProtocols(),
79 'wgArticlePath' => $wgArticlePath,
80 'wgScriptPath' => $wgScriptPath,
81 'wgScriptExtension' => $wgScriptExtension,
82 'wgScript' => $wgScript,
83 'wgSearchType' => $wgSearchType,
84 'wgVariantArticlePath' => $wgVariantArticlePath,
85 // Force object to avoid "empty" associative array from
86 // becoming [] instead of {} in JS (bug 34604)
87 'wgActionPaths' => (object)$wgActionPaths,
88 'wgServer' => $wgServer,
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 'wgCookieDomain' => $wgCookieDomain,
109 'wgCookiePath' => $wgCookiePath,
110 'wgCookieExpiration' => $wgCookieExpiration,
111 'wgResourceLoaderMaxQueryLength' => $wgResourceLoaderMaxQueryLength,
112 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
113 'wgLegalTitleChars' => Title
::convertByteClassToUnicodeClass( Title
::legalChars() ),
114 'wgResourceLoaderStorageVersion' => $wgResourceLoaderStorageVersion,
115 'wgResourceLoaderStorageEnabled' => $wgResourceLoaderStorageEnabled,
118 wfRunHooks( 'ResourceLoaderGetConfigVars', array( &$vars ) );
120 $this->configVars
[$hash] = $vars;
121 return $this->configVars
[$hash];
125 * Recursively get all explicit and implicit dependencies for to the given module.
127 * @param array $registryData
128 * @param string $moduleName
131 protected static function getImplicitDependencies( Array $registryData, $moduleName ) {
132 static $dependencyCache = array();
134 // The list of implicit dependencies won't be altered, so we can
135 // cache them without having to worry.
136 if ( !isset( $dependencyCache[$moduleName] ) ) {
138 if ( !isset( $registryData[$moduleName] ) ) {
139 // Dependencies may not exist
140 $dependencyCache[$moduleName] = array();
142 $data = $registryData[$moduleName];
143 $dependencyCache[$moduleName] = $data['dependencies'];
145 foreach ( $data['dependencies'] as $dependency ) {
146 // Recursively get the dependencies of the dependencies
147 $dependencyCache[$moduleName] = array_merge(
148 $dependencyCache[$moduleName],
149 self
::getImplicitDependencies( $registryData, $dependency )
155 return $dependencyCache[$moduleName];
159 * Optimize the dependency tree in $this->modules and return it.
161 * The optimization basically works like this:
162 * Given we have module A with the dependencies B and C
163 * and module B with the dependency C.
164 * Now we don't have to tell the client to explicitly fetch module
165 * C as that's already included in module B.
167 * This way we can reasonably reduce the amout of module registration
168 * data send to the client.
170 * @param Array &$registryData Modules keyed by name with properties:
172 * - array 'dependencies'
173 * - string|null 'group'
175 * - string|false 'loader'
177 public static function compileUnresolvedDependencies( Array &$registryData ) {
178 foreach ( $registryData as $name => &$data ) {
179 if ( $data['loader'] !== false ) {
182 $dependencies = $data['dependencies'];
183 foreach ( $data['dependencies'] as $dependency ) {
184 $implicitDependencies = self
::getImplicitDependencies( $registryData, $dependency );
185 $dependencies = array_diff( $dependencies, $implicitDependencies );
188 $data['dependencies'] = array_values( $dependencies );
194 * Get registration code for all modules.
196 * @param ResourceLoaderContext $context
197 * @return string JavaScript code for registering all modules with the client loader
199 public static function getModuleRegistrations( ResourceLoaderContext
$context ) {
200 global $wgCacheEpoch;
201 wfProfileIn( __METHOD__
);
203 $resourceLoader = $context->getResourceLoader();
204 $target = $context->getRequest()->getVal( 'target', 'desktop' );
207 $registryData = array();
210 foreach ( $resourceLoader->getModuleNames() as $name ) {
211 $module = $resourceLoader->getModule( $name );
212 $moduleTargets = $module->getTargets();
213 if ( !in_array( $target, $moduleTargets ) ) {
217 // getModifiedTime() is supposed to return a UNIX timestamp, but it doesn't always
218 // seem to do that, and custom implementations might forget. Coerce it to TS_UNIX
219 $moduleMtime = wfTimestamp( TS_UNIX
, $module->getModifiedTime( $context ) );
220 $mtime = max( $moduleMtime, wfTimestamp( TS_UNIX
, $wgCacheEpoch ) );
222 // FIXME: Convert to numbers, wfTimestamp always gives us stings, even for TS_UNIX
224 $registryData[ $name ] = array(
226 'dependencies' => $module->getDependencies(),
227 'group' => $module->getGroup(),
228 'source' => $module->getSource(),
229 'loader' => $module->getLoaderScript(),
233 self
::compileUnresolvedDependencies( $registryData );
236 $out .= ResourceLoader
::makeLoaderSourcesScript( $resourceLoader->getSources() );
238 // Concatenate module loader scripts and figure out the different call
239 // signatures for mw.loader.register
240 $registrations = array();
241 foreach ( $registryData as $name => $data ) {
242 if ( $data['loader'] !== false ) {
243 $out .= ResourceLoader
::makeCustomLoaderScript(
245 wfTimestamp( TS_ISO_8601_BASIC
, $data['version'] ),
246 $data['dependencies'],
255 !count( $data['dependencies'] ) &&
256 $data['group'] === null &&
257 $data['source'] === 'local'
259 // Modules without dependencies, a group or a foreign source;
260 // call mw.loader.register(name, timestamp)
261 $registrations[] = array( $name, $data['version'] );
262 } elseif ( $data['group'] === null && $data['source'] === 'local' ) {
263 // Modules with dependencies but no group or foreign source;
264 // call mw.loader.register(name, timestamp, dependencies)
265 $registrations[] = array( $name, $data['version'], $data['dependencies'] );
266 } elseif ( $data['source'] === 'local' ) {
267 // Modules with a group but no foreign source;
268 // call mw.loader.register(name, timestamp, dependencies, group)
269 $registrations[] = array(
272 $data['dependencies'],
276 // Modules with a foreign source;
277 // call mw.loader.register(name, timestamp, dependencies, group, source)
278 $registrations[] = array(
281 $data['dependencies'],
289 $out .= ResourceLoader
::makeLoaderRegisterScript( $registrations );
291 wfProfileOut( __METHOD__
);
300 public function isRaw() {
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 ) {
315 $moduleNames = array( 'jquery', 'mediawiki' );
316 wfRunHooks( 'ResourceLoaderGetStartupModules', array( &$moduleNames ), '1.23' );
318 // Get the latest version
319 $loader = $context->getResourceLoader();
321 foreach ( $moduleNames as $moduleName ) {
322 $version = max( $version,
323 $loader->getModule( $moduleName )->getModifiedTime( $context )
328 'modules' => ResourceLoader
::makePackedModulesString( $moduleNames ),
330 'lang' => $context->getLanguage(),
331 'skin' => $context->getSkin(),
332 'debug' => $context->getDebug() ?
'true' : 'false',
333 'version' => wfTimestamp( TS_ISO_8601_BASIC
, $version )
335 // Ensure uniform query order
337 return wfAppendQuery( wfScript( 'load' ), $query );
341 * @param ResourceLoaderContext $context
344 public function getScript( ResourceLoaderContext
$context ) {
345 global $IP, $wgLegacyJavaScriptGlobals;
347 $out = file_get_contents( "$IP/resources/src/startup.js" );
348 if ( $context->getOnly() === 'scripts' ) {
351 $configuration = $this->getConfig( $context );
352 $registrations = self
::getModuleRegistrations( $context );
354 $registrations = str_replace( "\n", "\n\t", trim( $registrations ) );
355 $out .= "var startUp = function () {\n" .
356 "\tmw.config = new " .
357 Xml
::encodeJsCall( 'mw.Map', array( $wgLegacyJavaScriptGlobals ) ) . "\n" .
358 "\t$registrations\n" .
359 "\t" . Xml
::encodeJsCall( 'mw.config.set', array( $configuration ) ) .
362 // Conditional script injection
363 $scriptTag = Html
::linkedScript( self
::getStartupModulesUrl( $context ) );
364 $out .= "if ( isCompatible() ) {\n" .
365 "\t" . Xml
::encodeJsCall( 'document.write', array( $scriptTag ) ) .
375 public function supportsURLLoading() {
380 * @param ResourceLoaderContext $context
381 * @return array|mixed
383 public function getModifiedTime( ResourceLoaderContext
$context ) {
384 global $IP, $wgCacheEpoch;
386 $hash = $context->getHash();
387 if ( isset( $this->modifiedTime
[$hash] ) ) {
388 return $this->modifiedTime
[$hash];
391 // Call preloadModuleInfo() on ALL modules as we're about
392 // to call getModifiedTime() on all of them
393 $loader = $context->getResourceLoader();
394 $loader->preloadModuleInfo( $loader->getModuleNames(), $context );
397 wfTimestamp( TS_UNIX
, $wgCacheEpoch ),
398 filemtime( "$IP/resources/src/startup.js" ),
399 $this->getHashMtime( $context )
402 // ATTENTION!: Because of the line below, this is not going to cause
403 // infinite recursion - think carefully before making changes to this
405 // Pre-populate modifiedTime with something because the the loop over
406 // all modules below includes the the startup module (this module).
407 $this->modifiedTime
[$hash] = 1;
409 foreach ( $loader->getModuleNames() as $name ) {
410 $module = $loader->getModule( $name );
411 $time = max( $time, $module->getModifiedTime( $context ) );
414 $this->modifiedTime
[$hash] = $time;
415 return $this->modifiedTime
[$hash];
419 * Hash of all dynamic data embedded in getScript().
421 * Detect changes to mw.config settings embedded in #getScript (bug 28899).
423 * @param ResourceLoaderContext $context
424 * @return string Hash
426 public function getModifiedHash( ResourceLoaderContext
$context ) {
427 global $wgLegacyJavaScriptGlobals;
430 'vars' => $this->getConfig( $context ),
431 'wgLegacyJavaScriptGlobals' => $wgLegacyJavaScriptGlobals,
434 return md5( serialize( $data ) );
440 public function getGroup() {