Merge "ApiCSPReport: Log user ID instead of name, and limit urls to origin"
[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 'wgLoadScript' => $conf->get( 'LoadScript' ),
74 'debug' => $context->getDebug(),
75 'skin' => $skin,
76 'stylepath' => $conf->get( 'StylePath' ),
77 'wgUrlProtocols' => wfUrlProtocols(),
78 'wgArticlePath' => $conf->get( 'ArticlePath' ),
79 'wgScriptPath' => $conf->get( 'ScriptPath' ),
80 'wgScript' => $conf->get( 'Script' ),
81 'wgSearchType' => $conf->get( 'SearchType' ),
82 'wgVariantArticlePath' => $conf->get( 'VariantArticlePath' ),
83 // Force object to avoid "empty" associative array from
84 // becoming [] instead of {} in JS (T36604)
85 'wgActionPaths' => (object)$conf->get( 'ActionPaths' ),
86 'wgServer' => $conf->get( 'Server' ),
87 'wgServerName' => $conf->get( 'ServerName' ),
88 'wgUserLanguage' => $context->getLanguage(),
89 'wgContentLanguage' => $contLang->getCode(),
90 'wgTranslateNumerals' => $conf->get( 'TranslateNumerals' ),
91 'wgVersion' => $conf->get( 'Version' ),
92 'wgEnableAPI' => true, // Deprecated since MW 1.32
93 'wgEnableWriteAPI' => true, // Deprecated since MW 1.32
94 'wgFormattedNamespaces' => $contLang->getFormattedNamespaces(),
95 'wgNamespaceIds' => $namespaceIds,
96 'wgContentNamespaces' => $nsInfo->getContentNamespaces(),
97 'wgSiteName' => $conf->get( 'Sitename' ),
98 'wgDBname' => $conf->get( 'DBname' ),
99 'wgExtraSignatureNamespaces' => $conf->get( 'ExtraSignatureNamespaces' ),
100 'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
101 // MediaWiki sets cookies to have this prefix by default
102 'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
103 'wgCookieDomain' => $conf->get( 'CookieDomain' ),
104 'wgCookiePath' => $conf->get( 'CookiePath' ),
105 'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
106 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
107 'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass( Title::legalChars() ),
108 'wgIllegalFileChars' => Title::convertByteClassToUnicodeClass( $illegalFileChars ),
109 'wgResourceLoaderStorageVersion' => $conf->get( 'ResourceLoaderStorageVersion' ),
110 'wgResourceLoaderStorageEnabled' => $conf->get( 'ResourceLoaderStorageEnabled' ),
111 'wgForeignUploadTargets' => $conf->get( 'ForeignUploadTargets' ),
112 'wgEnableUploads' => $conf->get( 'EnableUploads' ),
113 'wgCommentByteLimit' => null,
114 'wgCommentCodePointLimit' => CommentStore::COMMENT_CHARACTER_LIMIT,
115 ];
116
117 Hooks::run( 'ResourceLoaderGetConfigVars', [ &$vars, $skin ] );
118
119 return $vars;
120 }
121
122 /**
123 * Recursively get all explicit and implicit dependencies for to the given module.
124 *
125 * @param array $registryData
126 * @param string $moduleName
127 * @return array
128 */
129 protected static function getImplicitDependencies( array $registryData, $moduleName ) {
130 static $dependencyCache = [];
131
132 // The list of implicit dependencies won't be altered, so we can
133 // cache them without having to worry.
134 if ( !isset( $dependencyCache[$moduleName] ) ) {
135 if ( !isset( $registryData[$moduleName] ) ) {
136 // Dependencies may not exist
137 $dependencyCache[$moduleName] = [];
138 } else {
139 $data = $registryData[$moduleName];
140 $dependencyCache[$moduleName] = $data['dependencies'];
141
142 foreach ( $data['dependencies'] as $dependency ) {
143 // Recursively get the dependencies of the dependencies
144 $dependencyCache[$moduleName] = array_merge(
145 $dependencyCache[$moduleName],
146 self::getImplicitDependencies( $registryData, $dependency )
147 );
148 }
149 }
150 }
151
152 return $dependencyCache[$moduleName];
153 }
154
155 /**
156 * Optimize the dependency tree in $this->modules.
157 *
158 * The optimization basically works like this:
159 * Given we have module A with the dependencies B and C
160 * and module B with the dependency C.
161 * Now we don't have to tell the client to explicitly fetch module
162 * C as that's already included in module B.
163 *
164 * This way we can reasonably reduce the amount of module registration
165 * data send to the client.
166 *
167 * @param array &$registryData Modules keyed by name with properties:
168 * - string 'version'
169 * - array 'dependencies'
170 * - string|null 'group'
171 * - string 'source'
172 */
173 public static function compileUnresolvedDependencies( array &$registryData ) {
174 foreach ( $registryData as $name => &$data ) {
175 $dependencies = $data['dependencies'];
176 foreach ( $data['dependencies'] as $dependency ) {
177 $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
178 $dependencies = array_diff( $dependencies, $implicitDependencies );
179 }
180 // Rebuild keys
181 $data['dependencies'] = array_values( $dependencies );
182 }
183 }
184
185 /**
186 * Get registration code for all modules.
187 *
188 * @param ResourceLoaderContext $context
189 * @return string JavaScript code for registering all modules with the client loader
190 */
191 public function getModuleRegistrations( ResourceLoaderContext $context ) {
192 $resourceLoader = $context->getResourceLoader();
193 // Future developers: Use WebRequest::getRawVal() instead getVal().
194 // The getVal() method performs slow Language+UTF logic. (f303bb9360)
195 $target = $context->getRequest()->getRawVal( 'target', 'desktop' );
196 $safemode = $context->getRequest()->getRawVal( 'safemode' ) === '1';
197 // Bypass target filter if this request is Special:JavaScriptTest.
198 // To prevent misuse in production, this is only allowed if testing is enabled server-side.
199 $byPassTargetFilter = $this->getConfig()->get( 'EnableJavaScriptTest' ) && $target === 'test';
200
201 $out = '';
202 $states = [];
203 $registryData = [];
204 $moduleNames = $resourceLoader->getModuleNames();
205
206 // Preload with a batch so that the below calls to getVersionHash() for each module
207 // don't require on-demand loading of more information.
208 try {
209 $resourceLoader->preloadModuleInfo( $moduleNames, $context );
210 } catch ( Exception $e ) {
211 // Don't fail the request (T152266)
212 // Also print the error in the main output
213 $resourceLoader->outputErrorAndLog( $e,
214 'Preloading module info from startup failed: {exception}',
215 [ 'exception' => $e ]
216 );
217 }
218
219 // Get registry data
220 foreach ( $moduleNames as $name ) {
221 $module = $resourceLoader->getModule( $name );
222 $moduleTargets = $module->getTargets();
223 if (
224 ( !$byPassTargetFilter && !in_array( $target, $moduleTargets ) )
225 || ( $safemode && $module->getOrigin() > ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL )
226 ) {
227 continue;
228 }
229
230 if ( $module->isRaw() ) {
231 // Don't register "raw" modules (like 'startup') client-side because depending on them
232 // is illegal anyway and would only lead to them being loaded a second time,
233 // causing any state to be lost.
234
235 // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
236 // Think carefully before making changes to this code!
237 // The below code is going to call ResourceLoaderModule::getVersionHash() for every module.
238 // For StartUpModule (this module) the hash is computed based on the manifest content,
239 // which is the very thing we are computing right here. As such, this must skip iterating
240 // over 'startup' itself.
241 continue;
242 }
243
244 try {
245 $versionHash = $module->getVersionHash( $context );
246 } catch ( Exception $e ) {
247 // Don't fail the request (T152266)
248 // Also print the error in the main output
249 $resourceLoader->outputErrorAndLog( $e,
250 'Calculating version for "{module}" failed: {exception}',
251 [
252 'module' => $name,
253 'exception' => $e,
254 ]
255 );
256 $versionHash = '';
257 $states[$name] = 'error';
258 }
259
260 if ( $versionHash !== '' && strlen( $versionHash ) !== 7 ) {
261 $this->getLogger()->warning(
262 "Module '{module}' produced an invalid version hash: '{version}'.",
263 [
264 'module' => $name,
265 'version' => $versionHash,
266 ]
267 );
268 // Module implementation either broken or deviated from ResourceLoader::makeHash
269 // Asserted by tests/phpunit/structure/ResourcesTest.
270 $versionHash = ResourceLoader::makeHash( $versionHash );
271 }
272
273 $skipFunction = $module->getSkipFunction();
274 if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
275 $skipFunction = ResourceLoader::filter( 'minify-js', $skipFunction );
276 }
277
278 $registryData[$name] = [
279 'version' => $versionHash,
280 'dependencies' => $module->getDependencies( $context ),
281 'group' => $module->getGroup(),
282 'source' => $module->getSource(),
283 'skip' => $skipFunction,
284 ];
285 }
286
287 self::compileUnresolvedDependencies( $registryData );
288
289 // Register sources
290 $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
291
292 // Figure out the different call signatures for mw.loader.register
293 $registrations = [];
294 foreach ( $registryData as $name => $data ) {
295 // Call mw.loader.register(name, version, dependencies, group, source, skip)
296 $registrations[] = [
297 $name,
298 $data['version'],
299 $data['dependencies'],
300 $data['group'],
301 // Swap default (local) for null
302 $data['source'] === 'local' ? null : $data['source'],
303 $data['skip']
304 ];
305 }
306
307 // Register modules
308 $out .= "\n" . ResourceLoader::makeLoaderRegisterScript( $registrations );
309
310 if ( $states ) {
311 $out .= "\n" . ResourceLoader::makeLoaderStateScript( $states );
312 }
313
314 return $out;
315 }
316
317 /**
318 * @return bool
319 */
320 public function isRaw() {
321 return true;
322 }
323
324 /**
325 * @private For internal use by SpecialJavaScriptTest
326 * @since 1.32
327 * @return array
328 */
329 public function getBaseModulesInternal() {
330 return $this->getBaseModules();
331 }
332
333 /**
334 * Base modules implicitly available to all modules.
335 *
336 * @return array
337 */
338 private function getBaseModules() {
339 global $wgIncludeLegacyJavaScript;
340
341 $baseModules = [ 'jquery', 'mediawiki.base' ];
342 if ( $wgIncludeLegacyJavaScript ) {
343 $baseModules[] = 'mediawiki.legacy.wikibits';
344 }
345
346 return $baseModules;
347 }
348
349 /**
350 * @param ResourceLoaderContext $context
351 * @return string JavaScript code
352 */
353 public function getScript( ResourceLoaderContext $context ) {
354 global $IP;
355 $conf = $this->getConfig();
356
357 if ( $context->getOnly() !== 'scripts' ) {
358 return '/* Requires only=script */';
359 }
360
361 $startupCode = file_get_contents( "$IP/resources/src/startup/startup.js" );
362
363 // The files read here MUST be kept in sync with maintenance/jsduck/eg-iframe.html,
364 // and MUST be considered by 'fileHashes' in StartUpModule::getDefinitionSummary().
365 $mwLoaderCode = file_get_contents( "$IP/resources/src/startup/mediawiki.js" ) .
366 file_get_contents( "$IP/resources/src/startup/mediawiki.requestIdleCallback.js" );
367 if ( $context->getDebug() ) {
368 $mwLoaderCode .= file_get_contents( "$IP/resources/src/startup/mediawiki.log.js" );
369 }
370 if ( $conf->get( 'ResourceLoaderEnableJSProfiler' ) ) {
371 $mwLoaderCode .= file_get_contents( "$IP/resources/src/startup/profiler.js" );
372 }
373
374 // Perform replacements for mediawiki.js
375 $mwLoaderPairs = [
376 '$VARS.baseModules' => ResourceLoader::encodeJsonForScript( $this->getBaseModules() ),
377 '$VARS.maxQueryLength' => ResourceLoader::encodeJsonForScript(
378 $conf->get( 'ResourceLoaderMaxQueryLength' )
379 ),
380 ];
381 $profilerStubs = [
382 '$CODE.profileExecuteStart();' => 'mw.loader.profiler.onExecuteStart( module );',
383 '$CODE.profileExecuteEnd();' => 'mw.loader.profiler.onExecuteEnd( module );',
384 '$CODE.profileScriptStart();' => 'mw.loader.profiler.onScriptStart( module );',
385 '$CODE.profileScriptEnd();' => 'mw.loader.profiler.onScriptEnd( module );',
386 ];
387 if ( $conf->get( 'ResourceLoaderEnableJSProfiler' ) ) {
388 // When profiling is enabled, insert the calls.
389 $mwLoaderPairs += $profilerStubs;
390 } else {
391 // When disabled (by default), insert nothing.
392 $mwLoaderPairs += array_fill_keys( array_keys( $profilerStubs ), '' );
393 }
394 $mwLoaderCode = strtr( $mwLoaderCode, $mwLoaderPairs );
395
396 // Perform string replacements for startup.js
397 $pairs = [
398 '$VARS.wgLegacyJavaScriptGlobals' => ResourceLoader::encodeJsonForScript(
399 $conf->get( 'LegacyJavaScriptGlobals' )
400 ),
401 '$VARS.configuration' => ResourceLoader::encodeJsonForScript(
402 $this->getConfigSettings( $context )
403 ),
404 // Raw JavaScript code (not JSON)
405 '$CODE.registrations();' => trim( $this->getModuleRegistrations( $context ) ),
406 '$CODE.defineLoader();' => $mwLoaderCode,
407 ];
408 $startupCode = strtr( $startupCode, $pairs );
409
410 return $startupCode;
411 }
412
413 /**
414 * @return bool
415 */
416 public function supportsURLLoading() {
417 return false;
418 }
419
420 /**
421 * @return bool
422 */
423 public function enableModuleContentVersion() {
424 // Enabling this means that ResourceLoader::getVersionHash will simply call getScript()
425 // and hash it to determine the version (as used by E-Tag HTTP response header).
426 return true;
427 }
428
429 /**
430 * @return string
431 */
432 public function getGroup() {
433 return 'startup';
434 }
435 }