Remove JavaScript global variable wgLoadScript
[lhc/web/wiklou.git] / includes / resourceloader / ResourceLoaderStartUpModule.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @author Trevor Parscal
20 * @author Roan Kattouw
21 */
22
23 use MediaWiki\MediaWikiServices;
24
25 /**
26 * Module for ResourceLoader initialization.
27 *
28 * See also <https://www.mediawiki.org/wiki/ResourceLoader/Features#Startup_Module>
29 *
30 * The startup module, as being called only from ResourceLoaderClientHtml, has
31 * the ability to vary based extra query parameters, in addition to those
32 * from ResourceLoaderContext:
33 *
34 * - target: Only register modules in the client intended for this target.
35 * Default: "desktop".
36 * See also: OutputPage::setTarget(), ResourceLoaderModule::getTargets().
37 *
38 * - safemode: Only register modules that have ORIGIN_CORE as their origin.
39 * This effectively disables ORIGIN_USER modules. (T185303)
40 * See also: OutputPage::disallowUserJs()
41 */
42 class ResourceLoaderStartUpModule extends ResourceLoaderModule {
43 protected $targets = [ 'desktop', 'mobile' ];
44
45 /**
46 * @param ResourceLoaderContext $context
47 * @return array
48 */
49 private function getConfigSettings( $context ) {
50 $conf = $this->getConfig();
51
52 /**
53 * Namespace related preparation
54 * - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces.
55 * - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive.
56 */
57 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
58 $namespaceIds = $contLang->getNamespaceIds();
59 $caseSensitiveNamespaces = [];
60 $nsInfo = MediaWikiServices::getInstance()->getNamespaceInfo();
61 foreach ( $nsInfo->getCanonicalNamespaces() as $index => $name ) {
62 $namespaceIds[$contLang->lc( $name )] = $index;
63 if ( !$nsInfo->isCapitalized( $index ) ) {
64 $caseSensitiveNamespaces[] = $index;
65 }
66 }
67
68 $illegalFileChars = $conf->get( 'IllegalFileChars' );
69
70 // Build list of variables
71 $skin = $context->getSkin();
72 $vars = [
73 'debug' => $context->getDebug(),
74 'skin' => $skin,
75 'stylepath' => $conf->get( 'StylePath' ),
76 'wgUrlProtocols' => wfUrlProtocols(),
77 'wgArticlePath' => $conf->get( 'ArticlePath' ),
78 'wgScriptPath' => $conf->get( 'ScriptPath' ),
79 'wgScript' => $conf->get( 'Script' ),
80 'wgSearchType' => $conf->get( 'SearchType' ),
81 'wgVariantArticlePath' => $conf->get( 'VariantArticlePath' ),
82 // Force object to avoid "empty" associative array from
83 // becoming [] instead of {} in JS (T36604)
84 'wgActionPaths' => (object)$conf->get( 'ActionPaths' ),
85 'wgServer' => $conf->get( 'Server' ),
86 'wgServerName' => $conf->get( 'ServerName' ),
87 'wgUserLanguage' => $context->getLanguage(),
88 'wgContentLanguage' => $contLang->getCode(),
89 'wgTranslateNumerals' => $conf->get( 'TranslateNumerals' ),
90 'wgVersion' => $conf->get( 'Version' ),
91 'wgEnableAPI' => true, // Deprecated since MW 1.32
92 'wgEnableWriteAPI' => true, // Deprecated since MW 1.32
93 'wgFormattedNamespaces' => $contLang->getFormattedNamespaces(),
94 'wgNamespaceIds' => $namespaceIds,
95 'wgContentNamespaces' => $nsInfo->getContentNamespaces(),
96 'wgSiteName' => $conf->get( 'Sitename' ),
97 'wgDBname' => $conf->get( 'DBname' ),
98 'wgExtraSignatureNamespaces' => $conf->get( 'ExtraSignatureNamespaces' ),
99 'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
100 // MediaWiki sets cookies to have this prefix by default
101 'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
102 'wgCookieDomain' => $conf->get( 'CookieDomain' ),
103 'wgCookiePath' => $conf->get( 'CookiePath' ),
104 'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
105 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
106 'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass( Title::legalChars() ),
107 'wgIllegalFileChars' => Title::convertByteClassToUnicodeClass( $illegalFileChars ),
108 'wgResourceLoaderStorageVersion' => $conf->get( 'ResourceLoaderStorageVersion' ),
109 'wgResourceLoaderStorageEnabled' => $conf->get( 'ResourceLoaderStorageEnabled' ),
110 'wgForeignUploadTargets' => $conf->get( 'ForeignUploadTargets' ),
111 'wgEnableUploads' => $conf->get( 'EnableUploads' ),
112 'wgCommentByteLimit' => null,
113 'wgCommentCodePointLimit' => CommentStore::COMMENT_CHARACTER_LIMIT,
114 ];
115
116 Hooks::run( 'ResourceLoaderGetConfigVars', [ &$vars, $skin ] );
117
118 return $vars;
119 }
120
121 /**
122 * Recursively get all explicit and implicit dependencies for to the given module.
123 *
124 * @param array $registryData
125 * @param string $moduleName
126 * @param string[] $handled Internal parameter for recursion. (Optional)
127 * @return array
128 * @throws ResourceLoaderCircularDependencyError
129 */
130 protected static function getImplicitDependencies(
131 array $registryData,
132 $moduleName,
133 array $handled = []
134 ) {
135 static $dependencyCache = [];
136
137 // No modules will be added or changed server-side after this point,
138 // so we can safely cache parts of the tree for re-use.
139 if ( !isset( $dependencyCache[$moduleName] ) ) {
140 if ( !isset( $registryData[$moduleName] ) ) {
141 // Unknown module names are allowed here, this is only an optimisation.
142 // Checks for illegal and unknown dependencies happen as PHPUnit structure tests,
143 // and also client-side at run-time.
144 $flat = [];
145 } else {
146 $data = $registryData[$moduleName];
147 $flat = $data['dependencies'];
148
149 // Prevent recursion
150 $handled[] = $moduleName;
151 foreach ( $data['dependencies'] as $dependency ) {
152 if ( in_array( $dependency, $handled, true ) ) {
153 // If we encounter a circular dependency, then stop the optimiser and leave the
154 // original dependencies array unmodified. Circular dependencies are not
155 // supported in ResourceLoader. Awareness of them exists here so that we can
156 // optimise the registry when it isn't broken, and otherwise transport the
157 // registry unchanged. The client will handle this further.
158 throw new ResourceLoaderCircularDependencyError();
159 } else {
160 // Recursively add the dependencies of the dependencies
161 $flat = array_merge(
162 $flat,
163 self::getImplicitDependencies( $registryData, $dependency, $handled )
164 );
165 }
166 }
167 }
168
169 $dependencyCache[$moduleName] = $flat;
170 }
171
172 return $dependencyCache[$moduleName];
173 }
174
175 /**
176 * Optimize the dependency tree in $this->modules.
177 *
178 * The optimization basically works like this:
179 * Given we have module A with the dependencies B and C
180 * and module B with the dependency C.
181 * Now we don't have to tell the client to explicitly fetch module
182 * C as that's already included in module B.
183 *
184 * This way we can reasonably reduce the amount of module registration
185 * data send to the client.
186 *
187 * @param array &$registryData Modules keyed by name with properties:
188 * - string 'version'
189 * - array 'dependencies'
190 * - string|null 'group'
191 * - string 'source'
192 */
193 public static function compileUnresolvedDependencies( array &$registryData ) {
194 foreach ( $registryData as $name => &$data ) {
195 $dependencies = $data['dependencies'];
196 try {
197 foreach ( $data['dependencies'] as $dependency ) {
198 $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
199 $dependencies = array_diff( $dependencies, $implicitDependencies );
200 }
201 } catch ( ResourceLoaderCircularDependencyError $err ) {
202 // Leave unchanged
203 $dependencies = $data['dependencies'];
204 }
205
206 // Rebuild keys
207 $data['dependencies'] = array_values( $dependencies );
208 }
209 }
210
211 /**
212 * Get registration code for all modules.
213 *
214 * @param ResourceLoaderContext $context
215 * @return string JavaScript code for registering all modules with the client loader
216 */
217 public function getModuleRegistrations( ResourceLoaderContext $context ) {
218 $resourceLoader = $context->getResourceLoader();
219 // Future developers: Use WebRequest::getRawVal() instead getVal().
220 // The getVal() method performs slow Language+UTF logic. (f303bb9360)
221 $target = $context->getRequest()->getRawVal( 'target', 'desktop' );
222 $safemode = $context->getRequest()->getRawVal( 'safemode' ) === '1';
223 // Bypass target filter if this request is Special:JavaScriptTest.
224 // To prevent misuse in production, this is only allowed if testing is enabled server-side.
225 $byPassTargetFilter = $this->getConfig()->get( 'EnableJavaScriptTest' ) && $target === 'test';
226
227 $out = '';
228 $states = [];
229 $registryData = [];
230 $moduleNames = $resourceLoader->getModuleNames();
231
232 // Preload with a batch so that the below calls to getVersionHash() for each module
233 // don't require on-demand loading of more information.
234 try {
235 $resourceLoader->preloadModuleInfo( $moduleNames, $context );
236 } catch ( Exception $e ) {
237 // Don't fail the request (T152266)
238 // Also print the error in the main output
239 $resourceLoader->outputErrorAndLog( $e,
240 'Preloading module info from startup failed: {exception}',
241 [ 'exception' => $e ]
242 );
243 }
244
245 // Get registry data
246 foreach ( $moduleNames as $name ) {
247 $module = $resourceLoader->getModule( $name );
248 $moduleTargets = $module->getTargets();
249 if (
250 ( !$byPassTargetFilter && !in_array( $target, $moduleTargets ) )
251 || ( $safemode && $module->getOrigin() > ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL )
252 ) {
253 continue;
254 }
255
256 if ( $module instanceof ResourceLoaderStartUpModule ) {
257 // Don't register 'startup' to the client because loading it lazily or depending
258 // on it doesn't make sense, because the startup module *is* the client.
259 // Registering would be a waste of bandwidth and memory and risks somehow causing
260 // it to load a second time.
261
262 // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
263 // Think carefully before making changes to this code!
264 // The below code is going to call ResourceLoaderModule::getVersionHash() for every module.
265 // For StartUpModule (this module) the hash is computed based on the manifest content,
266 // which is the very thing we are computing right here. As such, this must skip iterating
267 // over 'startup' itself.
268 continue;
269 }
270
271 try {
272 $versionHash = $module->getVersionHash( $context );
273 } catch ( Exception $e ) {
274 // Don't fail the request (T152266)
275 // Also print the error in the main output
276 $resourceLoader->outputErrorAndLog( $e,
277 'Calculating version for "{module}" failed: {exception}',
278 [
279 'module' => $name,
280 'exception' => $e,
281 ]
282 );
283 $versionHash = '';
284 $states[$name] = 'error';
285 }
286
287 if ( $versionHash !== '' && strlen( $versionHash ) !== 7 ) {
288 $this->getLogger()->warning(
289 "Module '{module}' produced an invalid version hash: '{version}'.",
290 [
291 'module' => $name,
292 'version' => $versionHash,
293 ]
294 );
295 // Module implementation either broken or deviated from ResourceLoader::makeHash
296 // Asserted by tests/phpunit/structure/ResourcesTest.
297 $versionHash = ResourceLoader::makeHash( $versionHash );
298 }
299
300 $skipFunction = $module->getSkipFunction();
301 if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
302 $skipFunction = ResourceLoader::filter( 'minify-js', $skipFunction );
303 }
304
305 $registryData[$name] = [
306 'version' => $versionHash,
307 'dependencies' => $module->getDependencies( $context ),
308 'group' => $module->getGroup(),
309 'source' => $module->getSource(),
310 'skip' => $skipFunction,
311 ];
312 }
313
314 self::compileUnresolvedDependencies( $registryData );
315
316 // Register sources
317 $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
318
319 // Figure out the different call signatures for mw.loader.register
320 $registrations = [];
321 foreach ( $registryData as $name => $data ) {
322 // Call mw.loader.register(name, version, dependencies, group, source, skip)
323 $registrations[] = [
324 $name,
325 $data['version'],
326 $data['dependencies'],
327 $data['group'],
328 // Swap default (local) for null
329 $data['source'] === 'local' ? null : $data['source'],
330 $data['skip']
331 ];
332 }
333
334 // Register modules
335 $out .= "\n" . ResourceLoader::makeLoaderRegisterScript( $registrations );
336
337 if ( $states ) {
338 $out .= "\n" . ResourceLoader::makeLoaderStateScript( $states );
339 }
340
341 return $out;
342 }
343
344 /**
345 * @private For internal use by SpecialJavaScriptTest
346 * @since 1.32
347 * @return array
348 * @codeCoverageIgnore
349 */
350 public function getBaseModulesInternal() {
351 return $this->getBaseModules();
352 }
353
354 /**
355 * Base modules implicitly available to all modules.
356 *
357 * @return array
358 */
359 private function getBaseModules() {
360 global $wgIncludeLegacyJavaScript;
361
362 $baseModules = [ 'jquery', 'mediawiki.base' ];
363 if ( $wgIncludeLegacyJavaScript ) {
364 $baseModules[] = 'mediawiki.legacy.wikibits';
365 }
366
367 return $baseModules;
368 }
369
370 /**
371 * @param ResourceLoaderContext $context
372 * @return string JavaScript code
373 */
374 public function getScript( ResourceLoaderContext $context ) {
375 global $IP;
376 $conf = $this->getConfig();
377
378 if ( $context->getOnly() !== 'scripts' ) {
379 return '/* Requires only=script */';
380 }
381
382 $startupCode = file_get_contents( "$IP/resources/src/startup/startup.js" );
383
384 // The files read here MUST be kept in sync with maintenance/jsduck/eg-iframe.html,
385 // and MUST be considered by 'fileHashes' in StartUpModule::getDefinitionSummary().
386 $mwLoaderCode = file_get_contents( "$IP/resources/src/startup/mediawiki.js" ) .
387 file_get_contents( "$IP/resources/src/startup/mediawiki.requestIdleCallback.js" );
388 if ( $context->getDebug() ) {
389 $mwLoaderCode .= file_get_contents( "$IP/resources/src/startup/mediawiki.log.js" );
390 }
391 if ( $conf->get( 'ResourceLoaderEnableJSProfiler' ) ) {
392 $mwLoaderCode .= file_get_contents( "$IP/resources/src/startup/profiler.js" );
393 }
394
395 // Perform replacements for mediawiki.js
396 $mwLoaderPairs = [
397 '$VARS.reqBase' => ResourceLoader::encodeJsonForScript( $context->getReqBase() ),
398 '$VARS.baseModules' => ResourceLoader::encodeJsonForScript( $this->getBaseModules() ),
399 '$VARS.maxQueryLength' => ResourceLoader::encodeJsonForScript(
400 $conf->get( 'ResourceLoaderMaxQueryLength' )
401 ),
402 ];
403 $profilerStubs = [
404 '$CODE.profileExecuteStart();' => 'mw.loader.profiler.onExecuteStart( module );',
405 '$CODE.profileExecuteEnd();' => 'mw.loader.profiler.onExecuteEnd( module );',
406 '$CODE.profileScriptStart();' => 'mw.loader.profiler.onScriptStart( module );',
407 '$CODE.profileScriptEnd();' => 'mw.loader.profiler.onScriptEnd( module );',
408 ];
409 if ( $conf->get( 'ResourceLoaderEnableJSProfiler' ) ) {
410 // When profiling is enabled, insert the calls.
411 $mwLoaderPairs += $profilerStubs;
412 } else {
413 // When disabled (by default), insert nothing.
414 $mwLoaderPairs += array_fill_keys( array_keys( $profilerStubs ), '' );
415 }
416 $mwLoaderCode = strtr( $mwLoaderCode, $mwLoaderPairs );
417
418 // Perform string replacements for startup.js
419 $pairs = [
420 '$VARS.wgLegacyJavaScriptGlobals' => ResourceLoader::encodeJsonForScript(
421 $conf->get( 'LegacyJavaScriptGlobals' )
422 ),
423 '$VARS.configuration' => ResourceLoader::encodeJsonForScript(
424 $this->getConfigSettings( $context )
425 ),
426 // Raw JavaScript code (not JSON)
427 '$CODE.registrations();' => trim( $this->getModuleRegistrations( $context ) ),
428 '$CODE.defineLoader();' => $mwLoaderCode,
429 ];
430 $startupCode = strtr( $startupCode, $pairs );
431
432 return $startupCode;
433 }
434
435 /**
436 * @return bool
437 */
438 public function supportsURLLoading() {
439 return false;
440 }
441
442 /**
443 * @return bool
444 */
445 public function enableModuleContentVersion() {
446 // Enabling this means that ResourceLoader::getVersionHash will simply call getScript()
447 // and hash it to determine the version (as used by E-Tag HTTP response header).
448 return true;
449 }
450 }