Merge "DatabaseMssql: Don't duplicate body of makeList()"
[mediawiki.git] / includes / resourceloader / ResourceLoaderStartUpModule.php
blob48b357653d9d13ec775f6fbb46885b4ce5230911
1 <?php
2 /**
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
20 * @file
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 */
35 /**
36 * @param ResourceLoaderContext $context
37 * @return array
39 protected function getConfigSettings( $context ) {
41 $hash = $context->getHash();
42 if ( isset( $this->configVars[$hash] ) ) {
43 return $this->configVars[$hash];
46 global $wgContLang;
48 $mainPage = Title::newMainPage();
50 /**
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
66 $vars = array(
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 'wgDBname' => $conf->get( 'DBname' ),
94 'wgAvailableSkins' => Skin::getSkinNames(),
95 'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
96 // MediaWiki sets cookies to have this prefix by default
97 'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
98 'wgCookieDomain' => $conf->get( 'CookieDomain' ),
99 'wgCookiePath' => $conf->get( 'CookiePath' ),
100 'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
101 'wgResourceLoaderMaxQueryLength' => $conf->get( 'ResourceLoaderMaxQueryLength' ),
102 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
103 'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass( Title::legalChars() ),
104 'wgResourceLoaderStorageVersion' => $conf->get( 'ResourceLoaderStorageVersion' ),
105 'wgResourceLoaderStorageEnabled' => $conf->get( 'ResourceLoaderStorageEnabled' ),
108 Hooks::run( 'ResourceLoaderGetConfigVars', array( &$vars ) );
110 $this->configVars[$hash] = $vars;
111 return $this->configVars[$hash];
115 * Recursively get all explicit and implicit dependencies for to the given module.
117 * @param array $registryData
118 * @param string $moduleName
119 * @return array
121 protected static function getImplicitDependencies( array $registryData, $moduleName ) {
122 static $dependencyCache = array();
124 // The list of implicit dependencies won't be altered, so we can
125 // cache them without having to worry.
126 if ( !isset( $dependencyCache[$moduleName] ) ) {
128 if ( !isset( $registryData[$moduleName] ) ) {
129 // Dependencies may not exist
130 $dependencyCache[$moduleName] = array();
131 } else {
132 $data = $registryData[$moduleName];
133 $dependencyCache[$moduleName] = $data['dependencies'];
135 foreach ( $data['dependencies'] as $dependency ) {
136 // Recursively get the dependencies of the dependencies
137 $dependencyCache[$moduleName] = array_merge(
138 $dependencyCache[$moduleName],
139 self::getImplicitDependencies( $registryData, $dependency )
145 return $dependencyCache[$moduleName];
149 * Optimize the dependency tree in $this->modules.
151 * The optimization basically works like this:
152 * Given we have module A with the dependencies B and C
153 * and module B with the dependency C.
154 * Now we don't have to tell the client to explicitly fetch module
155 * C as that's already included in module B.
157 * This way we can reasonably reduce the amount of module registration
158 * data send to the client.
160 * @param array &$registryData Modules keyed by name with properties:
161 * - number 'version'
162 * - array 'dependencies'
163 * - string|null 'group'
164 * - string 'source'
165 * - string|false 'loader'
167 public static function compileUnresolvedDependencies( array &$registryData ) {
168 foreach ( $registryData as $name => &$data ) {
169 if ( $data['loader'] !== false ) {
170 continue;
172 $dependencies = $data['dependencies'];
173 foreach ( $data['dependencies'] as $dependency ) {
174 $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
175 $dependencies = array_diff( $dependencies, $implicitDependencies );
177 // Rebuild keys
178 $data['dependencies'] = array_values( $dependencies );
184 * Get registration code for all modules.
186 * @param ResourceLoaderContext $context
187 * @return string JavaScript code for registering all modules with the client loader
189 public function getModuleRegistrations( ResourceLoaderContext $context ) {
191 $resourceLoader = $context->getResourceLoader();
192 $target = $context->getRequest()->getVal( 'target', 'desktop' );
194 $out = '';
195 $registryData = array();
197 // Get registry data
198 foreach ( $resourceLoader->getModuleNames() as $name ) {
199 $module = $resourceLoader->getModule( $name );
200 $moduleTargets = $module->getTargets();
201 if ( !in_array( $target, $moduleTargets ) ) {
202 continue;
205 if ( $module->isRaw() ) {
206 // Don't register "raw" modules (like 'jquery' and 'mediawiki') client-side because
207 // depending on them is illegal anyway and would only lead to them being reloaded
208 // causing any state to be lost (like jQuery plugins, mw.config etc.)
209 continue;
212 // Coerce module timestamp to UNIX timestamp.
213 // getModifiedTime() is supposed to return a UNIX timestamp, but custom implementations
214 // might forget. TODO: Maybe emit warning?
215 $moduleMtime = wfTimestamp( TS_UNIX, $module->getModifiedTime( $context ) );
217 $skipFunction = $module->getSkipFunction();
218 if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
219 $skipFunction = $resourceLoader->filter( 'minify-js',
220 $skipFunction,
221 // There will potentially be lots of these little string in the registrations
222 // manifest, we don't want to blow up the startup module with
223 // "/* cache key: ... */" all over it in non-debug mode.
224 /* cacheReport = */ false
228 $mtime = max(
229 $moduleMtime,
230 wfTimestamp( TS_UNIX, $this->getConfig()->get( 'CacheEpoch' ) )
233 $registryData[$name] = array(
234 // Convert to numbers as wfTimestamp always returns a string, even for TS_UNIX
235 'version' => (int) $mtime,
236 'dependencies' => $module->getDependencies(),
237 'group' => $module->getGroup(),
238 'source' => $module->getSource(),
239 'loader' => $module->getLoaderScript(),
240 'skip' => $skipFunction,
244 self::compileUnresolvedDependencies( $registryData );
246 // Register sources
247 $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
249 // Concatenate module loader scripts and figure out the different call
250 // signatures for mw.loader.register
251 $registrations = array();
252 foreach ( $registryData as $name => $data ) {
253 if ( $data['loader'] !== false ) {
254 $out .= ResourceLoader::makeCustomLoaderScript(
255 $name,
256 $data['version'],
257 $data['dependencies'],
258 $data['group'],
259 $data['source'],
260 $data['loader']
262 continue;
265 // Call mw.loader.register(name, timestamp, dependencies, group, source, skip)
266 $registrations[] = array(
267 $name,
268 $data['version'],
269 $data['dependencies'],
270 $data['group'],
271 // Swap default (local) for null
272 $data['source'] === 'local' ? null : $data['source'],
273 $data['skip']
277 // Register modules
278 $out .= ResourceLoader::makeLoaderRegisterScript( $registrations );
280 return $out;
283 /* Methods */
286 * @return bool
288 public function isRaw() {
289 return true;
293 * Base modules required for the base environment of ResourceLoader
295 * @return array
297 public static function getStartupModules() {
298 return array( 'jquery', 'mediawiki' );
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
308 * @return string
310 public static function getStartupModulesUrl( ResourceLoaderContext $context ) {
311 $moduleNames = self::getStartupModules();
313 // Get the latest version
314 $loader = $context->getResourceLoader();
315 $version = 1;
316 foreach ( $moduleNames as $moduleName ) {
317 $version = max( $version,
318 $loader->getModule( $moduleName )->getModifiedTime( $context )
322 $query = array(
323 'modules' => ResourceLoader::makePackedModulesString( $moduleNames ),
324 'only' => 'scripts',
325 'lang' => $context->getLanguage(),
326 'skin' => $context->getSkin(),
327 'debug' => $context->getDebug() ? 'true' : 'false',
328 'version' => wfTimestamp( TS_ISO_8601_BASIC, $version )
330 // Ensure uniform query order
331 ksort( $query );
332 return wfAppendQuery( wfScript( 'load' ), $query );
336 * @param ResourceLoaderContext $context
337 * @return string
339 public function getScript( ResourceLoaderContext $context ) {
340 global $IP;
342 $out = file_get_contents( "$IP/resources/src/startup.js" );
343 if ( $context->getOnly() === 'scripts' ) {
345 // Startup function
346 $configuration = $this->getConfigSettings( $context );
347 $registrations = $this->getModuleRegistrations( $context );
348 // Fix indentation
349 $registrations = str_replace( "\n", "\n\t", trim( $registrations ) );
350 $mwMapJsCall = Xml::encodeJsCall(
351 'mw.Map',
352 array( $this->getConfig()->get( 'LegacyJavaScriptGlobals' ) )
354 $mwConfigSetJsCall = Xml::encodeJsCall(
355 'mw.config.set',
356 array( $configuration ),
357 ResourceLoader::inDebugMode()
360 $out .= "var startUp = function () {\n" .
361 "\tmw.config = new " .
362 $mwMapJsCall . "\n" .
363 "\t$registrations\n" .
364 "\t" . $mwConfigSetJsCall .
365 "};\n";
367 // Conditional script injection
368 $scriptTag = Html::linkedScript( self::getStartupModulesUrl( $context ) );
369 $out .= "if ( isCompatible() ) {\n" .
370 "\t" . Xml::encodeJsCall( 'document.write', array( $scriptTag ) ) .
371 "\n}";
374 return $out;
378 * @return bool
380 public function supportsURLLoading() {
381 return false;
385 * @param ResourceLoaderContext $context
386 * @return array|mixed
388 public function getModifiedTime( ResourceLoaderContext $context ) {
389 global $IP;
391 $hash = $context->getHash();
392 if ( isset( $this->modifiedTime[$hash] ) ) {
393 return $this->modifiedTime[$hash];
396 // Call preloadModuleInfo() on ALL modules as we're about
397 // to call getModifiedTime() on all of them
398 $loader = $context->getResourceLoader();
399 $loader->preloadModuleInfo( $loader->getModuleNames(), $context );
401 $time = max(
402 wfTimestamp( TS_UNIX, $this->getConfig()->get( 'CacheEpoch' ) ),
403 filemtime( "$IP/resources/src/startup.js" ),
404 $this->getHashMtime( $context )
407 // ATTENTION!: Because of the line below, this is not going to cause
408 // infinite recursion - think carefully before making changes to this
409 // code!
410 // Pre-populate modifiedTime with something because the loop over
411 // all modules below includes the startup module (this module).
412 $this->modifiedTime[$hash] = 1;
414 foreach ( $loader->getModuleNames() as $name ) {
415 $module = $loader->getModule( $name );
416 $time = max( $time, $module->getModifiedTime( $context ) );
419 $this->modifiedTime[$hash] = $time;
420 return $this->modifiedTime[$hash];
424 * Hash of all dynamic data embedded in getScript().
426 * Detect changes to mw.config settings embedded in #getScript (bug 28899).
428 * @param ResourceLoaderContext $context
429 * @return string Hash
431 public function getModifiedHash( ResourceLoaderContext $context ) {
432 $data = array(
433 'vars' => $this->getConfigSettings( $context ),
434 'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
437 return md5( serialize( $data ) );
441 * @return string
443 public function getGroup() {
444 return 'startup';