Fixed spacing
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoaderStartUpModule.php
1 <?php
2 /**
3 * Module for resource loader initialization.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @author Trevor Parscal
22 * @author Roan Kattouw
23 */
24
25 class ResourceLoaderStartUpModule extends ResourceLoaderModule {
26
27 // Cache for getConfigSettings() as it's called by multiple methods
28 protected $configVars = array();
29 protected $targets = array( 'desktop', 'mobile' );
30
31 /**
32 * @param ResourceLoaderContext $context
33 * @return array
34 */
35 protected function getConfigSettings( $context ) {
36
37 $hash = $context->getHash();
38 if ( isset( $this->configVars[$hash] ) ) {
39 return $this->configVars[$hash];
40 }
41
42 global $wgContLang;
43
44 $mainPage = Title::newMainPage();
45
46 /**
47 * Namespace related preparation
48 * - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces.
49 * - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive.
50 */
51 $namespaceIds = $wgContLang->getNamespaceIds();
52 $caseSensitiveNamespaces = array();
53 foreach ( MWNamespace::getCanonicalNamespaces() as $index => $name ) {
54 $namespaceIds[$wgContLang->lc( $name )] = $index;
55 if ( !MWNamespace::isCapitalized( $index ) ) {
56 $caseSensitiveNamespaces[] = $index;
57 }
58 }
59
60 $conf = $this->getConfig();
61 // Build list of variables
62 $vars = array(
63 'wgLoadScript' => wfScript( 'load' ),
64 'debug' => $context->getDebug(),
65 'skin' => $context->getSkin(),
66 'stylepath' => $conf->get( 'StylePath' ),
67 'wgUrlProtocols' => wfUrlProtocols(),
68 'wgArticlePath' => $conf->get( 'ArticlePath' ),
69 'wgScriptPath' => $conf->get( 'ScriptPath' ),
70 'wgScriptExtension' => $conf->get( 'ScriptExtension' ),
71 'wgScript' => wfScript(),
72 'wgSearchType' => $conf->get( 'SearchType' ),
73 'wgVariantArticlePath' => $conf->get( 'VariantArticlePath' ),
74 // Force object to avoid "empty" associative array from
75 // becoming [] instead of {} in JS (bug 34604)
76 'wgActionPaths' => (object)$conf->get( 'ActionPaths' ),
77 'wgServer' => $conf->get( 'Server' ),
78 'wgServerName' => $conf->get( 'ServerName' ),
79 'wgUserLanguage' => $context->getLanguage(),
80 'wgContentLanguage' => $wgContLang->getCode(),
81 'wgTranslateNumerals' => $conf->get( 'TranslateNumerals' ),
82 'wgVersion' => $conf->get( 'Version' ),
83 'wgEnableAPI' => $conf->get( 'EnableAPI' ),
84 'wgEnableWriteAPI' => $conf->get( 'EnableWriteAPI' ),
85 'wgMainPageTitle' => $mainPage->getPrefixedText(),
86 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
87 'wgNamespaceIds' => $namespaceIds,
88 'wgContentNamespaces' => MWNamespace::getContentNamespaces(),
89 'wgSiteName' => $conf->get( 'Sitename' ),
90 'wgDBname' => $conf->get( 'DBname' ),
91 'wgAvailableSkins' => Skin::getSkinNames(),
92 'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
93 // MediaWiki sets cookies to have this prefix by default
94 'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
95 'wgCookieDomain' => $conf->get( 'CookieDomain' ),
96 'wgCookiePath' => $conf->get( 'CookiePath' ),
97 'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
98 'wgResourceLoaderMaxQueryLength' => $conf->get( 'ResourceLoaderMaxQueryLength' ),
99 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
100 'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass( Title::legalChars() ),
101 'wgResourceLoaderStorageVersion' => $conf->get( 'ResourceLoaderStorageVersion' ),
102 'wgResourceLoaderStorageEnabled' => $conf->get( 'ResourceLoaderStorageEnabled' ),
103 );
104
105 Hooks::run( 'ResourceLoaderGetConfigVars', array( &$vars ) );
106
107 $this->configVars[$hash] = $vars;
108 return $this->configVars[$hash];
109 }
110
111 /**
112 * Recursively get all explicit and implicit dependencies for to the given module.
113 *
114 * @param array $registryData
115 * @param string $moduleName
116 * @return array
117 */
118 protected static function getImplicitDependencies( array $registryData, $moduleName ) {
119 static $dependencyCache = array();
120
121 // The list of implicit dependencies won't be altered, so we can
122 // cache them without having to worry.
123 if ( !isset( $dependencyCache[$moduleName] ) ) {
124
125 if ( !isset( $registryData[$moduleName] ) ) {
126 // Dependencies may not exist
127 $dependencyCache[$moduleName] = array();
128 } else {
129 $data = $registryData[$moduleName];
130 $dependencyCache[$moduleName] = $data['dependencies'];
131
132 foreach ( $data['dependencies'] as $dependency ) {
133 // Recursively get the dependencies of the dependencies
134 $dependencyCache[$moduleName] = array_merge(
135 $dependencyCache[$moduleName],
136 self::getImplicitDependencies( $registryData, $dependency )
137 );
138 }
139 }
140 }
141
142 return $dependencyCache[$moduleName];
143 }
144
145 /**
146 * Optimize the dependency tree in $this->modules.
147 *
148 * The optimization basically works like this:
149 * Given we have module A with the dependencies B and C
150 * and module B with the dependency C.
151 * Now we don't have to tell the client to explicitly fetch module
152 * C as that's already included in module B.
153 *
154 * This way we can reasonably reduce the amount of module registration
155 * data send to the client.
156 *
157 * @param array &$registryData Modules keyed by name with properties:
158 * - string 'version'
159 * - array 'dependencies'
160 * - string|null 'group'
161 * - string 'source'
162 * - string|false 'loader'
163 */
164 public static function compileUnresolvedDependencies( array &$registryData ) {
165 foreach ( $registryData as $name => &$data ) {
166 if ( $data['loader'] !== false ) {
167 continue;
168 }
169 $dependencies = $data['dependencies'];
170 foreach ( $data['dependencies'] as $dependency ) {
171 $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
172 $dependencies = array_diff( $dependencies, $implicitDependencies );
173 }
174 // Rebuild keys
175 $data['dependencies'] = array_values( $dependencies );
176 }
177 }
178
179
180 /**
181 * Get registration code for all modules.
182 *
183 * @param ResourceLoaderContext $context
184 * @return string JavaScript code for registering all modules with the client loader
185 */
186 public function getModuleRegistrations( ResourceLoaderContext $context ) {
187
188 $resourceLoader = $context->getResourceLoader();
189 $target = $context->getRequest()->getVal( 'target', 'desktop' );
190
191 $out = '';
192 $registryData = array();
193
194 // Get registry data
195 foreach ( $resourceLoader->getModuleNames() as $name ) {
196 $module = $resourceLoader->getModule( $name );
197 $moduleTargets = $module->getTargets();
198 if ( !in_array( $target, $moduleTargets ) ) {
199 continue;
200 }
201
202 if ( $module->isRaw() ) {
203 // Don't register "raw" modules (like 'jquery' and 'mediawiki') client-side because
204 // depending on them is illegal anyway and would only lead to them being reloaded
205 // causing any state to be lost (like jQuery plugins, mw.config etc.)
206 continue;
207 }
208
209 $versionHash = $module->getVersionHash( $context );
210 if ( strlen( $versionHash ) !== 8 ) {
211 // Module implementation either broken or deviated from ResourceLoader::makeHash
212 // Asserted by tests/phpunit/structure/ResourcesTest.
213 $versionHash = ResourceLoader::makeHash( $versionHash );
214 }
215
216 $skipFunction = $module->getSkipFunction();
217 if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
218 $skipFunction = $resourceLoader->filter( 'minify-js',
219 $skipFunction,
220 // There will potentially be lots of these little strings in the registrations
221 // manifest, we don't want to blow up the startup module with
222 // "/* cache key: ... */" all over it.
223 /* cacheReport = */ false
224 );
225 }
226
227 $registryData[$name] = array(
228 'version' => $versionHash,
229 'dependencies' => $module->getDependencies( $context ),
230 'group' => $module->getGroup(),
231 'source' => $module->getSource(),
232 'loader' => $module->getLoaderScript(),
233 'skip' => $skipFunction,
234 );
235 }
236
237 self::compileUnresolvedDependencies( $registryData );
238
239 // Register sources
240 $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
241
242 // Concatenate module loader scripts and figure out the different call
243 // signatures for mw.loader.register
244 $registrations = array();
245 foreach ( $registryData as $name => $data ) {
246 if ( $data['loader'] !== false ) {
247 $out .= ResourceLoader::makeCustomLoaderScript(
248 $name,
249 $data['version'],
250 $data['dependencies'],
251 $data['group'],
252 $data['source'],
253 $data['loader']
254 );
255 continue;
256 }
257
258 // Call mw.loader.register(name, version, dependencies, group, source, skip)
259 $registrations[] = array(
260 $name,
261 $data['version'],
262 $data['dependencies'],
263 $data['group'],
264 // Swap default (local) for null
265 $data['source'] === 'local' ? null : $data['source'],
266 $data['skip']
267 );
268 }
269
270 // Register modules
271 $out .= ResourceLoader::makeLoaderRegisterScript( $registrations );
272
273 return $out;
274 }
275
276 /**
277 * @return bool
278 */
279 public function isRaw() {
280 return true;
281 }
282
283 /**
284 * Base modules required for the base environment of ResourceLoader
285 *
286 * @return array
287 */
288 public static function getStartupModules() {
289 return array( 'jquery', 'mediawiki' );
290 }
291
292 /**
293 * Get the load URL of the startup modules.
294 *
295 * This is a helper for getScript(), but can also be called standalone, such
296 * as when generating an AppCache manifest.
297 *
298 * @param ResourceLoaderContext $context
299 * @return string
300 */
301 public static function getStartupModulesUrl( ResourceLoaderContext $context ) {
302 $rl = $context->getResourceLoader();
303 $moduleNames = self::getStartupModules();
304
305 $query = array(
306 'modules' => ResourceLoader::makePackedModulesString( $moduleNames ),
307 'only' => 'scripts',
308 'lang' => $context->getLanguage(),
309 'skin' => $context->getSkin(),
310 'debug' => $context->getDebug() ? 'true' : 'false',
311 'version' => $rl->getCombinedVersion( $context, $moduleNames ),
312 );
313 // Ensure uniform query order
314 ksort( $query );
315 return wfAppendQuery( wfScript( 'load' ), $query );
316 }
317
318 /**
319 * @param ResourceLoaderContext $context
320 * @return string
321 */
322 public function getScript( ResourceLoaderContext $context ) {
323 global $IP;
324
325 $out = file_get_contents( "$IP/resources/src/startup.js" );
326 if ( $context->getOnly() === 'scripts' ) {
327
328 // Startup function
329 $configuration = $this->getConfigSettings( $context );
330 $registrations = $this->getModuleRegistrations( $context );
331 // Fix indentation
332 $registrations = str_replace( "\n", "\n\t", trim( $registrations ) );
333 $mwMapJsCall = Xml::encodeJsCall(
334 'mw.Map',
335 array( $this->getConfig()->get( 'LegacyJavaScriptGlobals' ) )
336 );
337 $mwConfigSetJsCall = Xml::encodeJsCall(
338 'mw.config.set',
339 array( $configuration ),
340 ResourceLoader::inDebugMode()
341 );
342
343 $out .= "var startUp = function () {\n" .
344 "\tmw.config = new " .
345 $mwMapJsCall . "\n" .
346 "\t$registrations\n" .
347 "\t" . $mwConfigSetJsCall .
348 "};\n";
349
350 // Conditional script injection
351 $scriptTag = Html::linkedScript( self::getStartupModulesUrl( $context ) );
352 $out .= "if ( isCompatible() ) {\n" .
353 "\t" . Xml::encodeJsCall( 'document.write', array( $scriptTag ) ) .
354 "\n}";
355 }
356
357 return $out;
358 }
359
360 /**
361 * @return bool
362 */
363 public function supportsURLLoading() {
364 return false;
365 }
366
367 /**
368 * Get the definition summary for this module.
369 *
370 * @param ResourceLoaderContext $context
371 * @return array
372 */
373 public function getDefinitionSummary( ResourceLoaderContext $context ) {
374 global $IP;
375 $summary = parent::getDefinitionSummary( $context );
376 $summary[] = array(
377 // Detect changes to variables exposed in mw.config (T30899).
378 'vars' => $this->getConfigSettings( $context ),
379 // Changes how getScript() creates mw.Map for mw.config
380 'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
381 // Detect changes to the module registrations
382 'moduleHashes' => $this->getAllModuleHashes( $context ),
383
384 'fileMtimes' => array(
385 filemtime( "$IP/resources/src/startup.js" ),
386 ),
387 );
388 return $summary;
389 }
390
391 /**
392 * Helper method for getDefinitionSummary().
393 *
394 * @param ResourceLoaderContext $context
395 * @return string SHA-1
396 */
397 protected function getAllModuleHashes( ResourceLoaderContext $context ) {
398 $rl = $context->getResourceLoader();
399 // Preload for getCombinedVersion()
400 $rl->preloadModuleInfo( $rl->getModuleNames(), $context );
401
402 // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
403 // Think carefully before making changes to this code!
404 // Pre-populate versionHash with something because the loop over all modules below includes
405 // the startup module (this module).
406 // See ResourceLoaderModule::getVersionHash() for usage of this cache.
407 $this->versionHash[$context->getHash()] = null;
408
409 return $rl->getCombinedVersion( $context, $rl->getModuleNames() );
410 }
411
412 /**
413 * @return string
414 */
415 public function getGroup() {
416 return 'startup';
417 }
418 }