resourceloader: Move remaining module registrations to ServiceWiring
[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 foreach ( MWNamespace::getCanonicalNamespaces() as $index => $name ) {
61 $namespaceIds[$contLang->lc( $name )] = $index;
62 if ( !MWNamespace::isCapitalized( $index ) ) {
63 $caseSensitiveNamespaces[] = $index;
64 }
65 }
66
67 $illegalFileChars = $conf->get( 'IllegalFileChars' );
68
69 // Build list of variables
70 $skin = $context->getSkin();
71 $vars = [
72 'wgLoadScript' => wfScript( 'load' ),
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' => wfScript(),
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' => MWNamespace::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 * @return array
127 */
128 protected static function getImplicitDependencies( array $registryData, $moduleName ) {
129 static $dependencyCache = [];
130
131 // The list of implicit dependencies won't be altered, so we can
132 // cache them without having to worry.
133 if ( !isset( $dependencyCache[$moduleName] ) ) {
134 if ( !isset( $registryData[$moduleName] ) ) {
135 // Dependencies may not exist
136 $dependencyCache[$moduleName] = [];
137 } else {
138 $data = $registryData[$moduleName];
139 $dependencyCache[$moduleName] = $data['dependencies'];
140
141 foreach ( $data['dependencies'] as $dependency ) {
142 // Recursively get the dependencies of the dependencies
143 $dependencyCache[$moduleName] = array_merge(
144 $dependencyCache[$moduleName],
145 self::getImplicitDependencies( $registryData, $dependency )
146 );
147 }
148 }
149 }
150
151 return $dependencyCache[$moduleName];
152 }
153
154 /**
155 * Optimize the dependency tree in $this->modules.
156 *
157 * The optimization basically works like this:
158 * Given we have module A with the dependencies B and C
159 * and module B with the dependency C.
160 * Now we don't have to tell the client to explicitly fetch module
161 * C as that's already included in module B.
162 *
163 * This way we can reasonably reduce the amount of module registration
164 * data send to the client.
165 *
166 * @param array &$registryData Modules keyed by name with properties:
167 * - string 'version'
168 * - array 'dependencies'
169 * - string|null 'group'
170 * - string 'source'
171 */
172 public static function compileUnresolvedDependencies( array &$registryData ) {
173 foreach ( $registryData as $name => &$data ) {
174 $dependencies = $data['dependencies'];
175 foreach ( $data['dependencies'] as $dependency ) {
176 $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
177 $dependencies = array_diff( $dependencies, $implicitDependencies );
178 }
179 // Rebuild keys
180 $data['dependencies'] = array_values( $dependencies );
181 }
182 }
183
184 /**
185 * Get registration code for all modules.
186 *
187 * @param ResourceLoaderContext $context
188 * @return string JavaScript code for registering all modules with the client loader
189 */
190 public function getModuleRegistrations( ResourceLoaderContext $context ) {
191 $resourceLoader = $context->getResourceLoader();
192 // Future developers: Use WebRequest::getRawVal() instead getVal().
193 // The getVal() method performs slow Language+UTF logic. (f303bb9360)
194 $target = $context->getRequest()->getRawVal( 'target', 'desktop' );
195 $safemode = $context->getRequest()->getRawVal( 'safemode' ) === '1';
196 // Bypass target filter if this request is Special:JavaScriptTest.
197 // To prevent misuse in production, this is only allowed if testing is enabled server-side.
198 $byPassTargetFilter = $this->getConfig()->get( 'EnableJavaScriptTest' ) && $target === 'test';
199
200 $out = '';
201 $states = [];
202 $registryData = [];
203 $moduleNames = $resourceLoader->getModuleNames();
204
205 // Preload with a batch so that the below calls to getVersionHash() for each module
206 // don't require on-demand loading of more information.
207 try {
208 $resourceLoader->preloadModuleInfo( $moduleNames, $context );
209 } catch ( Exception $e ) {
210 // Don't fail the request (T152266)
211 // Also print the error in the main output
212 $resourceLoader->outputErrorAndLog( $e,
213 'Preloading module info from startup failed: {exception}',
214 [ 'exception' => $e ]
215 );
216 }
217
218 // Get registry data
219 foreach ( $moduleNames as $name ) {
220 $module = $resourceLoader->getModule( $name );
221 $moduleTargets = $module->getTargets();
222 if (
223 ( !$byPassTargetFilter && !in_array( $target, $moduleTargets ) )
224 || ( $safemode && $module->getOrigin() > ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL )
225 ) {
226 continue;
227 }
228
229 if ( $module->isRaw() ) {
230 // Don't register "raw" modules (like 'startup') client-side because depending on them
231 // is illegal anyway and would only lead to them being loaded a second time,
232 // causing any state to be lost.
233
234 // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
235 // Think carefully before making changes to this code!
236 // The below code is going to call ResourceLoaderModule::getVersionHash() for every module.
237 // For StartUpModule (this module) the hash is computed based on the manifest content,
238 // which is the very thing we are computing right here. As such, this must skip iterating
239 // over 'startup' itself.
240 continue;
241 }
242
243 try {
244 $versionHash = $module->getVersionHash( $context );
245 } catch ( Exception $e ) {
246 // Don't fail the request (T152266)
247 // Also print the error in the main output
248 $resourceLoader->outputErrorAndLog( $e,
249 'Calculating version for "{module}" failed: {exception}',
250 [
251 'module' => $name,
252 'exception' => $e,
253 ]
254 );
255 $versionHash = '';
256 $states[$name] = 'error';
257 }
258
259 if ( $versionHash !== '' && strlen( $versionHash ) !== 7 ) {
260 $context->getLogger()->warning(
261 "Module '{module}' produced an invalid version hash: '{version}'.",
262 [
263 'module' => $name,
264 'version' => $versionHash,
265 ]
266 );
267 // Module implementation either broken or deviated from ResourceLoader::makeHash
268 // Asserted by tests/phpunit/structure/ResourcesTest.
269 $versionHash = ResourceLoader::makeHash( $versionHash );
270 }
271
272 $skipFunction = $module->getSkipFunction();
273 if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
274 $skipFunction = ResourceLoader::filter( 'minify-js', $skipFunction );
275 }
276
277 $registryData[$name] = [
278 'version' => $versionHash,
279 'dependencies' => $module->getDependencies( $context ),
280 'group' => $module->getGroup(),
281 'source' => $module->getSource(),
282 'skip' => $skipFunction,
283 ];
284 }
285
286 self::compileUnresolvedDependencies( $registryData );
287
288 // Register sources
289 $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
290
291 // Figure out the different call signatures for mw.loader.register
292 $registrations = [];
293 foreach ( $registryData as $name => $data ) {
294 // Call mw.loader.register(name, version, dependencies, group, source, skip)
295 $registrations[] = [
296 $name,
297 $data['version'],
298 $data['dependencies'],
299 $data['group'],
300 // Swap default (local) for null
301 $data['source'] === 'local' ? null : $data['source'],
302 $data['skip']
303 ];
304 }
305
306 // Register modules
307 $out .= "\n" . ResourceLoader::makeLoaderRegisterScript( $registrations );
308
309 if ( $states ) {
310 $out .= "\n" . ResourceLoader::makeLoaderStateScript( $states );
311 }
312
313 return $out;
314 }
315
316 /**
317 * @return bool
318 */
319 public function isRaw() {
320 return true;
321 }
322
323 /**
324 * Internal modules used by ResourceLoader that cannot be depended on.
325 *
326 * These module(s) should have isRaw() return true, and are not
327 * legal dependencies (enforced by structure/ResourcesTest).
328 *
329 * @deprecated since 1.32 No longer used.
330 * @return array
331 */
332 public static function getStartupModules() {
333 wfDeprecated( __METHOD__, '1.32' );
334 return [];
335 }
336
337 /**
338 * @deprecated since 1.32 No longer used.
339 * @return array
340 */
341 public static function getLegacyModules() {
342 wfDeprecated( __METHOD__, '1.32' );
343 return [];
344 }
345
346 /**
347 * @private For internal use by SpecialJavaScriptTest
348 * @since 1.32
349 * @return array
350 */
351 public function getBaseModulesInternal() {
352 return $this->getBaseModules();
353 }
354
355 /**
356 * Base modules implicitly available to all modules.
357 *
358 * @return array
359 */
360 private function getBaseModules() {
361 global $wgIncludeLegacyJavaScript;
362
363 $baseModules = [ 'jquery', 'mediawiki.base' ];
364 if ( $wgIncludeLegacyJavaScript ) {
365 $baseModules[] = 'mediawiki.legacy.wikibits';
366 }
367
368 return $baseModules;
369 }
370
371 /**
372 * @param ResourceLoaderContext $context
373 * @return string JavaScript code
374 */
375 public function getScript( ResourceLoaderContext $context ) {
376 global $IP;
377 $conf = $this->getConfig();
378
379 if ( $context->getOnly() !== 'scripts' ) {
380 return '/* Requires only=script */';
381 }
382
383 $startupCode = file_get_contents( "$IP/resources/src/startup/startup.js" );
384
385 // The files read here MUST be kept in sync with maintenance/jsduck/eg-iframe.html,
386 // and MUST be considered by 'fileHashes' in StartUpModule::getDefinitionSummary().
387 $mwLoaderCode = file_get_contents( "$IP/resources/src/startup/mediawiki.js" ) .
388 file_get_contents( "$IP/resources/src/startup/mediawiki.requestIdleCallback.js" );
389 if ( $context->getDebug() ) {
390 $mwLoaderCode .= file_get_contents( "$IP/resources/src/startup/mediawiki.log.js" );
391 }
392 if ( $conf->get( 'ResourceLoaderEnableJSProfiler' ) ) {
393 $mwLoaderCode .= file_get_contents( "$IP/resources/src/startup/profiler.js" );
394 }
395
396 // Perform replacements for mediawiki.js
397 $mwLoaderPairs = [
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
451 /**
452 * @return string
453 */
454 public function getGroup() {
455 return 'startup';
456 }
457 }