Merge "Http::getProxy() method to get proxy configuration"
[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 = [];
29 protected $targets = [ '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 = [];
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 = [
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 ];
108
109 Hooks::run( 'ResourceLoaderGetConfigVars', [ &$vars ] );
110
111 $this->configVars[$hash] = $vars;
112 return $this->configVars[$hash];
113 }
114
115 /**
116 * Recursively get all explicit and implicit dependencies for to the given module.
117 *
118 * @param array $registryData
119 * @param string $moduleName
120 * @return array
121 */
122 protected static function getImplicitDependencies( array $registryData, $moduleName ) {
123 static $dependencyCache = [];
124
125 // The list of implicit dependencies won't be altered, so we can
126 // cache them without having to worry.
127 if ( !isset( $dependencyCache[$moduleName] ) ) {
128
129 if ( !isset( $registryData[$moduleName] ) ) {
130 // Dependencies may not exist
131 $dependencyCache[$moduleName] = [];
132 } else {
133 $data = $registryData[$moduleName];
134 $dependencyCache[$moduleName] = $data['dependencies'];
135
136 foreach ( $data['dependencies'] as $dependency ) {
137 // Recursively get the dependencies of the dependencies
138 $dependencyCache[$moduleName] = array_merge(
139 $dependencyCache[$moduleName],
140 self::getImplicitDependencies( $registryData, $dependency )
141 );
142 }
143 }
144 }
145
146 return $dependencyCache[$moduleName];
147 }
148
149 /**
150 * Optimize the dependency tree in $this->modules.
151 *
152 * The optimization basically works like this:
153 * Given we have module A with the dependencies B and C
154 * and module B with the dependency C.
155 * Now we don't have to tell the client to explicitly fetch module
156 * C as that's already included in module B.
157 *
158 * This way we can reasonably reduce the amount of module registration
159 * data send to the client.
160 *
161 * @param array &$registryData Modules keyed by name with properties:
162 * - string 'version'
163 * - array 'dependencies'
164 * - string|null 'group'
165 * - string 'source'
166 */
167 public static function compileUnresolvedDependencies( array &$registryData ) {
168 foreach ( $registryData as $name => &$data ) {
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 * Get registration code for all modules.
181 *
182 * @param ResourceLoaderContext $context
183 * @return string JavaScript code for registering all modules with the client loader
184 */
185 public function getModuleRegistrations( ResourceLoaderContext $context ) {
186
187 $resourceLoader = $context->getResourceLoader();
188 $target = $context->getRequest()->getVal( 'target', 'desktop' );
189 // Bypass target filter if this request is Special:JavaScriptTest.
190 // To prevent misuse in production, this is only allowed if testing is enabled server-side.
191 $byPassTargetFilter = $this->getConfig()->get( 'EnableJavaScriptTest' ) && $target === 'test';
192
193 $out = '';
194 $registryData = [];
195
196 // Get registry data
197 foreach ( $resourceLoader->getModuleNames() as $name ) {
198 $module = $resourceLoader->getModule( $name );
199 $moduleTargets = $module->getTargets();
200 if ( !$byPassTargetFilter && !in_array( $target, $moduleTargets ) ) {
201 continue;
202 }
203
204 if ( $module->isRaw() ) {
205 // Don't register "raw" modules (like 'jquery' and 'mediawiki') client-side because
206 // depending on them is illegal anyway and would only lead to them being reloaded
207 // causing any state to be lost (like jQuery plugins, mw.config etc.)
208 continue;
209 }
210
211 $versionHash = $module->getVersionHash( $context );
212 if ( strlen( $versionHash ) !== 8 ) {
213 $context->getLogger()->warning(
214 "Module '{module}' produced an invalid version hash: '{version}'.",
215 [
216 'module' => $name,
217 'version' => $versionHash,
218 ]
219 );
220 // Module implementation either broken or deviated from ResourceLoader::makeHash
221 // Asserted by tests/phpunit/structure/ResourcesTest.
222 $versionHash = ResourceLoader::makeHash( $versionHash );
223 }
224
225 $skipFunction = $module->getSkipFunction();
226 if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
227 $skipFunction = ResourceLoader::filter( 'minify-js', $skipFunction );
228 }
229
230 $registryData[$name] = [
231 'version' => $versionHash,
232 'dependencies' => $module->getDependencies( $context ),
233 'group' => $module->getGroup(),
234 'source' => $module->getSource(),
235 'skip' => $skipFunction,
236 ];
237 }
238
239 self::compileUnresolvedDependencies( $registryData );
240
241 // Register sources
242 $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
243
244 // Figure out the different call signatures for mw.loader.register
245 $registrations = [];
246 foreach ( $registryData as $name => $data ) {
247 // Call mw.loader.register(name, version, dependencies, group, source, skip)
248 $registrations[] = [
249 $name,
250 $data['version'],
251 $data['dependencies'],
252 $data['group'],
253 // Swap default (local) for null
254 $data['source'] === 'local' ? null : $data['source'],
255 $data['skip']
256 ];
257 }
258
259 // Register modules
260 $out .= "\n" . ResourceLoader::makeLoaderRegisterScript( $registrations );
261
262 return $out;
263 }
264
265 /**
266 * @return bool
267 */
268 public function isRaw() {
269 return true;
270 }
271
272 /**
273 * Base modules required for the base environment of ResourceLoader
274 *
275 * @return array
276 */
277 public static function getStartupModules() {
278 return [ 'jquery', 'mediawiki' ];
279 }
280
281 public static function getLegacyModules() {
282 global $wgIncludeLegacyJavaScript;
283
284 $legacyModules = [];
285 if ( $wgIncludeLegacyJavaScript ) {
286 $legacyModules[] = 'mediawiki.legacy.wikibits';
287 }
288
289 return $legacyModules;
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 = [
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 if ( $context->getOnly() !== 'scripts' ) {
325 return '/* Requires only=script */';
326 }
327
328 $out = file_get_contents( "$IP/resources/src/startup.js" );
329
330 $pairs = array_map( function ( $value ) {
331 $value = FormatJson::encode( $value, ResourceLoader::inDebugMode(), FormatJson::ALL_OK );
332 // Fix indentation
333 $value = str_replace( "\n", "\n\t", $value );
334 return $value;
335 }, [
336 '$VARS.wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
337 '$VARS.configuration' => $this->getConfigSettings( $context ),
338 '$VARS.baseModulesUri' => self::getStartupModulesUrl( $context ),
339 ] );
340 $pairs['$CODE.registrations()'] = str_replace(
341 "\n",
342 "\n\t",
343 trim( $this->getModuleRegistrations( $context ) )
344 );
345
346 return strtr( $out, $pairs );
347 }
348
349 /**
350 * @return bool
351 */
352 public function supportsURLLoading() {
353 return false;
354 }
355
356 /**
357 * Get the definition summary for this module.
358 *
359 * @param ResourceLoaderContext $context
360 * @return array
361 */
362 public function getDefinitionSummary( ResourceLoaderContext $context ) {
363 global $IP;
364 $summary = parent::getDefinitionSummary( $context );
365 $summary[] = [
366 // Detect changes to variables exposed in mw.config (T30899).
367 'vars' => $this->getConfigSettings( $context ),
368 // Changes how getScript() creates mw.Map for mw.config
369 'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
370 // Detect changes to the module registrations
371 'moduleHashes' => $this->getAllModuleHashes( $context ),
372
373 'fileMtimes' => [
374 filemtime( "$IP/resources/src/startup.js" ),
375 ],
376 ];
377 return $summary;
378 }
379
380 /**
381 * Helper method for getDefinitionSummary().
382 *
383 * @param ResourceLoaderContext $context
384 * @return string SHA-1
385 */
386 protected function getAllModuleHashes( ResourceLoaderContext $context ) {
387 $rl = $context->getResourceLoader();
388 // Preload for getCombinedVersion()
389 $rl->preloadModuleInfo( $rl->getModuleNames(), $context );
390
391 // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
392 // Think carefully before making changes to this code!
393 // Pre-populate versionHash with something because the loop over all modules below includes
394 // the startup module (this module).
395 // See ResourceLoaderModule::getVersionHash() for usage of this cache.
396 $this->versionHash[$context->getHash()] = null;
397
398 return $rl->getCombinedVersion( $context, $rl->getModuleNames() );
399 }
400
401 /**
402 * @return string
403 */
404 public function getGroup() {
405 return 'startup';
406 }
407 }