Merge "Selenium: replace UserLoginPage with BlankPage where possible"
[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 'wgResourceLoaderStorageEnabled' => $conf->get( 'ResourceLoaderStorageEnabled' ),
109 'wgForeignUploadTargets' => $conf->get( 'ForeignUploadTargets' ),
110 'wgEnableUploads' => $conf->get( 'EnableUploads' ),
111 'wgCommentByteLimit' => null,
112 'wgCommentCodePointLimit' => CommentStore::COMMENT_CHARACTER_LIMIT,
113 ];
114
115 Hooks::run( 'ResourceLoaderGetConfigVars', [ &$vars, $skin ] );
116
117 return $vars;
118 }
119
120 /**
121 * Recursively get all explicit and implicit dependencies for to the given module.
122 *
123 * @param array $registryData
124 * @param string $moduleName
125 * @param string[] $handled Internal parameter for recursion. (Optional)
126 * @return array
127 * @throws ResourceLoaderCircularDependencyError
128 */
129 protected static function getImplicitDependencies(
130 array $registryData,
131 $moduleName,
132 array $handled = []
133 ) {
134 static $dependencyCache = [];
135
136 // No modules will be added or changed server-side after this point,
137 // so we can safely cache parts of the tree for re-use.
138 if ( !isset( $dependencyCache[$moduleName] ) ) {
139 if ( !isset( $registryData[$moduleName] ) ) {
140 // Unknown module names are allowed here, this is only an optimisation.
141 // Checks for illegal and unknown dependencies happen as PHPUnit structure tests,
142 // and also client-side at run-time.
143 $flat = [];
144 } else {
145 $data = $registryData[$moduleName];
146 $flat = $data['dependencies'];
147
148 // Prevent recursion
149 $handled[] = $moduleName;
150 foreach ( $data['dependencies'] as $dependency ) {
151 if ( in_array( $dependency, $handled, true ) ) {
152 // If we encounter a circular dependency, then stop the optimiser and leave the
153 // original dependencies array unmodified. Circular dependencies are not
154 // supported in ResourceLoader. Awareness of them exists here so that we can
155 // optimise the registry when it isn't broken, and otherwise transport the
156 // registry unchanged. The client will handle this further.
157 throw new ResourceLoaderCircularDependencyError();
158 } else {
159 // Recursively add the dependencies of the dependencies
160 $flat = array_merge(
161 $flat,
162 self::getImplicitDependencies( $registryData, $dependency, $handled )
163 );
164 }
165 }
166 }
167
168 $dependencyCache[$moduleName] = $flat;
169 }
170
171 return $dependencyCache[$moduleName];
172 }
173
174 /**
175 * Optimize the dependency tree in $this->modules.
176 *
177 * The optimization basically works like this:
178 * Given we have module A with the dependencies B and C
179 * and module B with the dependency C.
180 * Now we don't have to tell the client to explicitly fetch module
181 * C as that's already included in module B.
182 *
183 * This way we can reasonably reduce the amount of module registration
184 * data send to the client.
185 *
186 * @param array &$registryData Modules keyed by name with properties:
187 * - string 'version'
188 * - array 'dependencies'
189 * - string|null 'group'
190 * - string 'source'
191 */
192 public static function compileUnresolvedDependencies( array &$registryData ) {
193 foreach ( $registryData as $name => &$data ) {
194 $dependencies = $data['dependencies'];
195 try {
196 foreach ( $data['dependencies'] as $dependency ) {
197 $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
198 $dependencies = array_diff( $dependencies, $implicitDependencies );
199 }
200 } catch ( ResourceLoaderCircularDependencyError $err ) {
201 // Leave unchanged
202 $dependencies = $data['dependencies'];
203 }
204
205 // Rebuild keys
206 $data['dependencies'] = array_values( $dependencies );
207 }
208 }
209
210 /**
211 * Get registration code for all modules.
212 *
213 * @param ResourceLoaderContext $context
214 * @return string JavaScript code for registering all modules with the client loader
215 */
216 public function getModuleRegistrations( ResourceLoaderContext $context ) {
217 $resourceLoader = $context->getResourceLoader();
218 // Future developers: Use WebRequest::getRawVal() instead getVal().
219 // The getVal() method performs slow Language+UTF logic. (f303bb9360)
220 $target = $context->getRequest()->getRawVal( 'target', 'desktop' );
221 $safemode = $context->getRequest()->getRawVal( 'safemode' ) === '1';
222 // Bypass target filter if this request is Special:JavaScriptTest.
223 // To prevent misuse in production, this is only allowed if testing is enabled server-side.
224 $byPassTargetFilter = $this->getConfig()->get( 'EnableJavaScriptTest' ) && $target === 'test';
225
226 $out = '';
227 $states = [];
228 $registryData = [];
229 $moduleNames = $resourceLoader->getModuleNames();
230
231 // Preload with a batch so that the below calls to getVersionHash() for each module
232 // don't require on-demand loading of more information.
233 try {
234 $resourceLoader->preloadModuleInfo( $moduleNames, $context );
235 } catch ( Exception $e ) {
236 // Don't fail the request (T152266)
237 // Also print the error in the main output
238 $resourceLoader->outputErrorAndLog( $e,
239 'Preloading module info from startup failed: {exception}',
240 [ 'exception' => $e ]
241 );
242 }
243
244 // Get registry data
245 foreach ( $moduleNames as $name ) {
246 $module = $resourceLoader->getModule( $name );
247 $moduleTargets = $module->getTargets();
248 if (
249 ( !$byPassTargetFilter && !in_array( $target, $moduleTargets ) )
250 || ( $safemode && $module->getOrigin() > ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL )
251 ) {
252 continue;
253 }
254
255 if ( $module instanceof ResourceLoaderStartUpModule ) {
256 // Don't register 'startup' to the client because loading it lazily or depending
257 // on it doesn't make sense, because the startup module *is* the client.
258 // Registering would be a waste of bandwidth and memory and risks somehow causing
259 // it to load a second time.
260
261 // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
262 // Think carefully before making changes to this code!
263 // The below code is going to call ResourceLoaderModule::getVersionHash() for every module.
264 // For StartUpModule (this module) the hash is computed based on the manifest content,
265 // which is the very thing we are computing right here. As such, this must skip iterating
266 // over 'startup' itself.
267 continue;
268 }
269
270 try {
271 $versionHash = $module->getVersionHash( $context );
272 } catch ( Exception $e ) {
273 // Don't fail the request (T152266)
274 // Also print the error in the main output
275 $resourceLoader->outputErrorAndLog( $e,
276 'Calculating version for "{module}" failed: {exception}',
277 [
278 'module' => $name,
279 'exception' => $e,
280 ]
281 );
282 $versionHash = '';
283 $states[$name] = 'error';
284 }
285
286 if ( $versionHash !== '' && strlen( $versionHash ) !== 7 ) {
287 $this->getLogger()->warning(
288 "Module '{module}' produced an invalid version hash: '{version}'.",
289 [
290 'module' => $name,
291 'version' => $versionHash,
292 ]
293 );
294 // Module implementation either broken or deviated from ResourceLoader::makeHash
295 // Asserted by tests/phpunit/structure/ResourcesTest.
296 $versionHash = ResourceLoader::makeHash( $versionHash );
297 }
298
299 $skipFunction = $module->getSkipFunction();
300 if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
301 $skipFunction = ResourceLoader::filter( 'minify-js', $skipFunction );
302 }
303
304 $registryData[$name] = [
305 'version' => $versionHash,
306 'dependencies' => $module->getDependencies( $context ),
307 'group' => $module->getGroup(),
308 'source' => $module->getSource(),
309 'skip' => $skipFunction,
310 ];
311 }
312
313 self::compileUnresolvedDependencies( $registryData );
314
315 // Register sources
316 $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
317
318 // Figure out the different call signatures for mw.loader.register
319 $registrations = [];
320 foreach ( $registryData as $name => $data ) {
321 // Call mw.loader.register(name, version, dependencies, group, source, skip)
322 $registrations[] = [
323 $name,
324 $data['version'],
325 $data['dependencies'],
326 $data['group'],
327 // Swap default (local) for null
328 $data['source'] === 'local' ? null : $data['source'],
329 $data['skip']
330 ];
331 }
332
333 // Register modules
334 $out .= "\n" . ResourceLoader::makeLoaderRegisterScript( $registrations );
335
336 if ( $states ) {
337 $out .= "\n" . ResourceLoader::makeLoaderStateScript( $states );
338 }
339
340 return $out;
341 }
342
343 /**
344 * @private For internal use by SpecialJavaScriptTest
345 * @since 1.32
346 * @return array
347 * @codeCoverageIgnore
348 */
349 public function getBaseModulesInternal() {
350 return $this->getBaseModules();
351 }
352
353 /**
354 * Base modules implicitly available to all modules.
355 *
356 * @return array
357 */
358 private function getBaseModules() {
359 global $wgIncludeLegacyJavaScript;
360
361 $baseModules = [ 'jquery', 'mediawiki.base' ];
362 if ( $wgIncludeLegacyJavaScript ) {
363 $baseModules[] = 'mediawiki.legacy.wikibits';
364 }
365
366 return $baseModules;
367 }
368
369 /**
370 * Get the localStorage key for the entire module store. The key references
371 * $wgDBname to prevent clashes between wikis under the same web domain.
372 *
373 * @return string localStorage item key for JavaScript
374 */
375 private function getStoreKey() {
376 return 'MediaWikiModuleStore:' . $this->getConfig()->get( 'DBname' );
377 }
378
379 /**
380 * Get the key on which the JavaScript module cache (mw.loader.store) will vary.
381 *
382 * @param ResourceLoaderContext $context
383 * @return string String of concatenated vary conditions
384 */
385 private function getStoreVary( ResourceLoaderContext $context ) {
386 return implode( ':', [
387 $context->getSkin(),
388 $this->getConfig()->get( 'ResourceLoaderStorageVersion' ),
389 $context->getLanguage(),
390 ] );
391 }
392
393 /**
394 * @param ResourceLoaderContext $context
395 * @return string JavaScript code
396 */
397 public function getScript( ResourceLoaderContext $context ) {
398 global $IP;
399 $conf = $this->getConfig();
400
401 if ( $context->getOnly() !== 'scripts' ) {
402 return '/* Requires only=script */';
403 }
404
405 $startupCode = file_get_contents( "$IP/resources/src/startup/startup.js" );
406
407 // The files read here MUST be kept in sync with maintenance/jsduck/eg-iframe.html,
408 // and MUST be considered by 'fileHashes' in StartUpModule::getDefinitionSummary().
409 $mwLoaderCode = file_get_contents( "$IP/resources/src/startup/mediawiki.js" ) .
410 file_get_contents( "$IP/resources/src/startup/mediawiki.requestIdleCallback.js" );
411 if ( $context->getDebug() ) {
412 $mwLoaderCode .= file_get_contents( "$IP/resources/src/startup/mediawiki.log.js" );
413 }
414 if ( $conf->get( 'ResourceLoaderEnableJSProfiler' ) ) {
415 $mwLoaderCode .= file_get_contents( "$IP/resources/src/startup/profiler.js" );
416 }
417
418 // Perform replacements for mediawiki.js
419 $mwLoaderPairs = [
420 '$VARS.reqBase' => ResourceLoader::encodeJsonForScript( $context->getReqBase() ),
421 '$VARS.baseModules' => ResourceLoader::encodeJsonForScript( $this->getBaseModules() ),
422 '$VARS.maxQueryLength' => ResourceLoader::encodeJsonForScript(
423 $conf->get( 'ResourceLoaderMaxQueryLength' )
424 ),
425 '$VARS.storeKey' => ResourceLoader::encodeJsonForScript( $this->getStoreKey() ),
426 '$VARS.storeVary' => ResourceLoader::encodeJsonForScript( $this->getStoreVary( $context ) ),
427 ];
428 $profilerStubs = [
429 '$CODE.profileExecuteStart();' => 'mw.loader.profiler.onExecuteStart( module );',
430 '$CODE.profileExecuteEnd();' => 'mw.loader.profiler.onExecuteEnd( module );',
431 '$CODE.profileScriptStart();' => 'mw.loader.profiler.onScriptStart( module );',
432 '$CODE.profileScriptEnd();' => 'mw.loader.profiler.onScriptEnd( module );',
433 ];
434 if ( $conf->get( 'ResourceLoaderEnableJSProfiler' ) ) {
435 // When profiling is enabled, insert the calls.
436 $mwLoaderPairs += $profilerStubs;
437 } else {
438 // When disabled (by default), insert nothing.
439 $mwLoaderPairs += array_fill_keys( array_keys( $profilerStubs ), '' );
440 }
441 $mwLoaderCode = strtr( $mwLoaderCode, $mwLoaderPairs );
442
443 // Perform string replacements for startup.js
444 $pairs = [
445 '$VARS.wgLegacyJavaScriptGlobals' => ResourceLoader::encodeJsonForScript(
446 $conf->get( 'LegacyJavaScriptGlobals' )
447 ),
448 '$VARS.configuration' => ResourceLoader::encodeJsonForScript(
449 $this->getConfigSettings( $context )
450 ),
451 // Raw JavaScript code (not JSON)
452 '$CODE.registrations();' => trim( $this->getModuleRegistrations( $context ) ),
453 '$CODE.defineLoader();' => $mwLoaderCode,
454 ];
455 $startupCode = strtr( $startupCode, $pairs );
456
457 return $startupCode;
458 }
459
460 /**
461 * @return bool
462 */
463 public function supportsURLLoading() {
464 return false;
465 }
466
467 /**
468 * @return bool
469 */
470 public function enableModuleContentVersion() {
471 // Enabling this means that ResourceLoader::getVersionHash will simply call getScript()
472 // and hash it to determine the version (as used by E-Tag HTTP response header).
473 return true;
474 }
475 }