Merge "Documentation: Remove paragraph about not creating a 2nd WebRequest"
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoaderStartUpModule.php
1 <?php
2 /**
3 * Module for ResourceLoader 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' => '.php',
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 'wgExtraSignatureNamespaces' => $conf->get( 'ExtraSignatureNamespaces' ),
92 'wgAvailableSkins' => Skin::getSkinNames(),
93 'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
94 // MediaWiki sets cookies to have this prefix by default
95 'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
96 'wgCookieDomain' => $conf->get( 'CookieDomain' ),
97 'wgCookiePath' => $conf->get( 'CookiePath' ),
98 'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
99 'wgResourceLoaderMaxQueryLength' => $conf->get( 'ResourceLoaderMaxQueryLength' ),
100 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
101 'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass( Title::legalChars() ),
102 'wgResourceLoaderStorageVersion' => $conf->get( 'ResourceLoaderStorageVersion' ),
103 'wgResourceLoaderStorageEnabled' => $conf->get( 'ResourceLoaderStorageEnabled' ),
104 'wgResourceLoaderLegacyModules' => self::getLegacyModules(),
105 'wgForeignUploadTargets' => $conf->get( 'ForeignUploadTargets' ),
106 'wgEnableUploads' => $conf->get( 'EnableUploads' ),
107 'wgForeignUploadTestEnabled' => $conf->get( 'ForeignUploadTestEnabled' ),
108 'wgForeignUploadTestDefault' => $conf->get( 'ForeignUploadTestDefault' ),
109 );
110
111 Hooks::run( 'ResourceLoaderGetConfigVars', array( &$vars ) );
112
113 $this->configVars[$hash] = $vars;
114 return $this->configVars[$hash];
115 }
116
117 /**
118 * Recursively get all explicit and implicit dependencies for to the given module.
119 *
120 * @param array $registryData
121 * @param string $moduleName
122 * @return array
123 */
124 protected static function getImplicitDependencies( array $registryData, $moduleName ) {
125 static $dependencyCache = array();
126
127 // The list of implicit dependencies won't be altered, so we can
128 // cache them without having to worry.
129 if ( !isset( $dependencyCache[$moduleName] ) ) {
130
131 if ( !isset( $registryData[$moduleName] ) ) {
132 // Dependencies may not exist
133 $dependencyCache[$moduleName] = array();
134 } else {
135 $data = $registryData[$moduleName];
136 $dependencyCache[$moduleName] = $data['dependencies'];
137
138 foreach ( $data['dependencies'] as $dependency ) {
139 // Recursively get the dependencies of the dependencies
140 $dependencyCache[$moduleName] = array_merge(
141 $dependencyCache[$moduleName],
142 self::getImplicitDependencies( $registryData, $dependency )
143 );
144 }
145 }
146 }
147
148 return $dependencyCache[$moduleName];
149 }
150
151 /**
152 * Optimize the dependency tree in $this->modules.
153 *
154 * The optimization basically works like this:
155 * Given we have module A with the dependencies B and C
156 * and module B with the dependency C.
157 * Now we don't have to tell the client to explicitly fetch module
158 * C as that's already included in module B.
159 *
160 * This way we can reasonably reduce the amount of module registration
161 * data send to the client.
162 *
163 * @param array &$registryData Modules keyed by name with properties:
164 * - string 'version'
165 * - array 'dependencies'
166 * - string|null 'group'
167 * - string 'source'
168 */
169 public static function compileUnresolvedDependencies( array &$registryData ) {
170 foreach ( $registryData as $name => &$data ) {
171 $dependencies = $data['dependencies'];
172 foreach ( $data['dependencies'] as $dependency ) {
173 $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
174 $dependencies = array_diff( $dependencies, $implicitDependencies );
175 }
176 // Rebuild keys
177 $data['dependencies'] = array_values( $dependencies );
178 }
179 }
180
181 /**
182 * Get registration code for all modules.
183 *
184 * @param ResourceLoaderContext $context
185 * @return string JavaScript code for registering all modules with the client loader
186 */
187 public function getModuleRegistrations( ResourceLoaderContext $context ) {
188
189 $resourceLoader = $context->getResourceLoader();
190 $target = $context->getRequest()->getVal( 'target', 'desktop' );
191 // Bypass target filter if this request is Special:JavaScriptTest.
192 // To prevent misuse in production, this is only allowed if testing is enabled server-side.
193 $byPassTargetFilter = $this->getConfig()->get( 'EnableJavaScriptTest' ) && $target === 'test';
194
195 $out = '';
196 $registryData = array();
197
198 // Get registry data
199 foreach ( $resourceLoader->getModuleNames() as $name ) {
200 $module = $resourceLoader->getModule( $name );
201 $moduleTargets = $module->getTargets();
202 if ( !$byPassTargetFilter && !in_array( $target, $moduleTargets ) ) {
203 continue;
204 }
205
206 if ( $module->isRaw() ) {
207 // Don't register "raw" modules (like 'jquery' and 'mediawiki') client-side because
208 // depending on them is illegal anyway and would only lead to them being reloaded
209 // causing any state to be lost (like jQuery plugins, mw.config etc.)
210 continue;
211 }
212
213 $versionHash = $module->getVersionHash( $context );
214 if ( strlen( $versionHash ) !== 8 ) {
215 $context->getLogger()->warning(
216 "Module '{module}' produced an invalid version hash: '{version}'.",
217 array(
218 'module' => $name,
219 'version' => $versionHash,
220 )
221 );
222 // Module implementation either broken or deviated from ResourceLoader::makeHash
223 // Asserted by tests/phpunit/structure/ResourcesTest.
224 $versionHash = ResourceLoader::makeHash( $versionHash );
225 }
226
227 $skipFunction = $module->getSkipFunction();
228 if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
229 $skipFunction = ResourceLoader::filter( 'minify-js', $skipFunction );
230 }
231
232 $registryData[$name] = array(
233 'version' => $versionHash,
234 'dependencies' => $module->getDependencies( $context ),
235 'group' => $module->getGroup(),
236 'source' => $module->getSource(),
237 'skip' => $skipFunction,
238 );
239 }
240
241 self::compileUnresolvedDependencies( $registryData );
242
243 // Register sources
244 $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
245
246 // Figure out the different call signatures for mw.loader.register
247 $registrations = array();
248 foreach ( $registryData as $name => $data ) {
249 // Call mw.loader.register(name, version, dependencies, group, source, skip)
250 $registrations[] = array(
251 $name,
252 $data['version'],
253 $data['dependencies'],
254 $data['group'],
255 // Swap default (local) for null
256 $data['source'] === 'local' ? null : $data['source'],
257 $data['skip']
258 );
259 }
260
261 // Register modules
262 $out .= "\n" . ResourceLoader::makeLoaderRegisterScript( $registrations );
263
264 return $out;
265 }
266
267 /**
268 * @return bool
269 */
270 public function isRaw() {
271 return true;
272 }
273
274 /**
275 * Base modules required for the base environment of ResourceLoader
276 *
277 * @return array
278 */
279 public static function getStartupModules() {
280 return array( 'jquery', 'mediawiki' );
281 }
282
283 public static function getLegacyModules() {
284 global $wgIncludeLegacyJavaScript, $wgPreloadJavaScriptMwUtil;
285
286 $legacyModules = array();
287 if ( $wgIncludeLegacyJavaScript ) {
288 $legacyModules[] = 'mediawiki.legacy.wikibits';
289 }
290 if ( $wgPreloadJavaScriptMwUtil ) {
291 $legacyModules[] = 'mediawiki.util';
292 }
293
294 return $legacyModules;
295 }
296
297 /**
298 * Get the load URL of the startup modules.
299 *
300 * This is a helper for getScript(), but can also be called standalone, such
301 * as when generating an AppCache manifest.
302 *
303 * @param ResourceLoaderContext $context
304 * @return string
305 */
306 public static function getStartupModulesUrl( ResourceLoaderContext $context ) {
307 $rl = $context->getResourceLoader();
308 $moduleNames = self::getStartupModules();
309
310 $query = array(
311 'modules' => ResourceLoader::makePackedModulesString( $moduleNames ),
312 'only' => 'scripts',
313 'lang' => $context->getLanguage(),
314 'skin' => $context->getSkin(),
315 'debug' => $context->getDebug() ? 'true' : 'false',
316 'version' => $rl->getCombinedVersion( $context, $moduleNames ),
317 );
318 // Ensure uniform query order
319 ksort( $query );
320 return wfAppendQuery( wfScript( 'load' ), $query );
321 }
322
323 /**
324 * @param ResourceLoaderContext $context
325 * @return string
326 */
327 public function getScript( ResourceLoaderContext $context ) {
328 global $IP;
329 if ( $context->getOnly() !== 'scripts' ) {
330 return '/* Requires only=script */';
331 }
332
333 $out = file_get_contents( "$IP/resources/src/startup.js" );
334
335 $pairs = array_map( function ( $value ) {
336 $value = FormatJson::encode( $value, ResourceLoader::inDebugMode(), FormatJson::ALL_OK );
337 // Fix indentation
338 $value = str_replace( "\n", "\n\t", $value );
339 return $value;
340 }, array(
341 '$VARS.wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
342 '$VARS.configuration' => $this->getConfigSettings( $context ),
343 '$VARS.baseModulesUri' => self::getStartupModulesUrl( $context ),
344 ) );
345 $pairs['$CODE.registrations()'] = str_replace(
346 "\n",
347 "\n\t",
348 trim( $this->getModuleRegistrations( $context ) )
349 );
350
351 return strtr( $out, $pairs );
352 }
353
354 /**
355 * @return bool
356 */
357 public function supportsURLLoading() {
358 return false;
359 }
360
361 /**
362 * Get the definition summary for this module.
363 *
364 * @param ResourceLoaderContext $context
365 * @return array
366 */
367 public function getDefinitionSummary( ResourceLoaderContext $context ) {
368 global $IP;
369 $summary = parent::getDefinitionSummary( $context );
370 $summary[] = array(
371 // Detect changes to variables exposed in mw.config (T30899).
372 'vars' => $this->getConfigSettings( $context ),
373 // Changes how getScript() creates mw.Map for mw.config
374 'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
375 // Detect changes to the module registrations
376 'moduleHashes' => $this->getAllModuleHashes( $context ),
377
378 'fileMtimes' => array(
379 filemtime( "$IP/resources/src/startup.js" ),
380 ),
381 );
382 return $summary;
383 }
384
385 /**
386 * Helper method for getDefinitionSummary().
387 *
388 * @param ResourceLoaderContext $context
389 * @return string SHA-1
390 */
391 protected function getAllModuleHashes( ResourceLoaderContext $context ) {
392 $rl = $context->getResourceLoader();
393 // Preload for getCombinedVersion()
394 $rl->preloadModuleInfo( $rl->getModuleNames(), $context );
395
396 // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
397 // Think carefully before making changes to this code!
398 // Pre-populate versionHash with something because the loop over all modules below includes
399 // the startup module (this module).
400 // See ResourceLoaderModule::getVersionHash() for usage of this cache.
401 $this->versionHash[$context->getHash()] = null;
402
403 return $rl->getCombinedVersion( $context, $rl->getModuleNames() );
404 }
405
406 /**
407 * @return string
408 */
409 public function getGroup() {
410 return 'startup';
411 }
412 }