d4a34f3352d4306ff58940bf3788b6df51fa1057
[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 private $groupIds = [
46 // These reserved numbers MUST start at 0 and not skip any. These are preset
47 // for forward compatiblity so that they can be safely referenced by mediawiki.js,
48 // even when the code is cached and the order of registrations (and implicit
49 // group ids) changes between versions of the software.
50 'user' => 0,
51 'private' => 1,
52 ];
53
54 /**
55 * @param ResourceLoaderContext $context
56 * @return array
57 */
58 private function getConfigSettings( $context ) {
59 $conf = $this->getConfig();
60
61 /**
62 * Namespace related preparation
63 * - wgNamespaceIds: Key-value pairs of all localized, canonical and aliases for namespaces.
64 * - wgCaseSensitiveNamespaces: Array of namespaces that are case-sensitive.
65 */
66 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
67 $namespaceIds = $contLang->getNamespaceIds();
68 $caseSensitiveNamespaces = [];
69 $nsInfo = MediaWikiServices::getInstance()->getNamespaceInfo();
70 foreach ( $nsInfo->getCanonicalNamespaces() as $index => $name ) {
71 $namespaceIds[$contLang->lc( $name )] = $index;
72 if ( !$nsInfo->isCapitalized( $index ) ) {
73 $caseSensitiveNamespaces[] = $index;
74 }
75 }
76
77 $illegalFileChars = $conf->get( 'IllegalFileChars' );
78
79 // Build list of variables
80 $skin = $context->getSkin();
81 $vars = [
82 'debug' => $context->getDebug(),
83 'skin' => $skin,
84 'stylepath' => $conf->get( 'StylePath' ),
85 'wgUrlProtocols' => wfUrlProtocols(),
86 'wgArticlePath' => $conf->get( 'ArticlePath' ),
87 'wgScriptPath' => $conf->get( 'ScriptPath' ),
88 'wgScript' => $conf->get( 'Script' ),
89 'wgSearchType' => $conf->get( 'SearchType' ),
90 'wgVariantArticlePath' => $conf->get( 'VariantArticlePath' ),
91 // Force object to avoid "empty" associative array from
92 // becoming [] instead of {} in JS (T36604)
93 'wgActionPaths' => (object)$conf->get( 'ActionPaths' ),
94 'wgServer' => $conf->get( 'Server' ),
95 'wgServerName' => $conf->get( 'ServerName' ),
96 'wgUserLanguage' => $context->getLanguage(),
97 'wgContentLanguage' => $contLang->getCode(),
98 'wgTranslateNumerals' => $conf->get( 'TranslateNumerals' ),
99 'wgVersion' => $conf->get( 'Version' ),
100 'wgEnableAPI' => true, // Deprecated since MW 1.32
101 'wgEnableWriteAPI' => true, // Deprecated since MW 1.32
102 'wgFormattedNamespaces' => $contLang->getFormattedNamespaces(),
103 'wgNamespaceIds' => $namespaceIds,
104 'wgContentNamespaces' => $nsInfo->getContentNamespaces(),
105 'wgSiteName' => $conf->get( 'Sitename' ),
106 'wgDBname' => $conf->get( 'DBname' ),
107 'wgWikiID' => WikiMap::getWikiIdFromDbDomain( WikiMap::getCurrentWikiDbDomain() ),
108 'wgExtraSignatureNamespaces' => $conf->get( 'ExtraSignatureNamespaces' ),
109 'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
110 // MediaWiki sets cookies to have this prefix by default
111 'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
112 'wgCookieDomain' => $conf->get( 'CookieDomain' ),
113 'wgCookiePath' => $conf->get( 'CookiePath' ),
114 'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
115 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
116 'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass( Title::legalChars() ),
117 'wgIllegalFileChars' => Title::convertByteClassToUnicodeClass( $illegalFileChars ),
118 'wgForeignUploadTargets' => $conf->get( 'ForeignUploadTargets' ),
119 'wgEnableUploads' => $conf->get( 'EnableUploads' ),
120 'wgCommentByteLimit' => null,
121 'wgCommentCodePointLimit' => CommentStore::COMMENT_CHARACTER_LIMIT,
122 ];
123
124 Hooks::run( 'ResourceLoaderGetConfigVars', [ &$vars, $skin ] );
125
126 return $vars;
127 }
128
129 /**
130 * Recursively get all explicit and implicit dependencies for to the given module.
131 *
132 * @param array $registryData
133 * @param string $moduleName
134 * @param string[] $handled Internal parameter for recursion. (Optional)
135 * @return array
136 * @throws ResourceLoaderCircularDependencyError
137 */
138 protected static function getImplicitDependencies(
139 array $registryData,
140 $moduleName,
141 array $handled = []
142 ) {
143 static $dependencyCache = [];
144
145 // No modules will be added or changed server-side after this point,
146 // so we can safely cache parts of the tree for re-use.
147 if ( !isset( $dependencyCache[$moduleName] ) ) {
148 if ( !isset( $registryData[$moduleName] ) ) {
149 // Unknown module names are allowed here, this is only an optimisation.
150 // Checks for illegal and unknown dependencies happen as PHPUnit structure tests,
151 // and also client-side at run-time.
152 $flat = [];
153 } else {
154 $data = $registryData[$moduleName];
155 $flat = $data['dependencies'];
156
157 // Prevent recursion
158 $handled[] = $moduleName;
159 foreach ( $data['dependencies'] as $dependency ) {
160 if ( in_array( $dependency, $handled, true ) ) {
161 // If we encounter a circular dependency, then stop the optimiser and leave the
162 // original dependencies array unmodified. Circular dependencies are not
163 // supported in ResourceLoader. Awareness of them exists here so that we can
164 // optimise the registry when it isn't broken, and otherwise transport the
165 // registry unchanged. The client will handle this further.
166 throw new ResourceLoaderCircularDependencyError();
167 } else {
168 // Recursively add the dependencies of the dependencies
169 $flat = array_merge(
170 $flat,
171 self::getImplicitDependencies( $registryData, $dependency, $handled )
172 );
173 }
174 }
175 }
176
177 $dependencyCache[$moduleName] = $flat;
178 }
179
180 return $dependencyCache[$moduleName];
181 }
182
183 /**
184 * Optimize the dependency tree in $this->modules.
185 *
186 * The optimization basically works like this:
187 * Given we have module A with the dependencies B and C
188 * and module B with the dependency C.
189 * Now we don't have to tell the client to explicitly fetch module
190 * C as that's already included in module B.
191 *
192 * This way we can reasonably reduce the amount of module registration
193 * data send to the client.
194 *
195 * @param array &$registryData Modules keyed by name with properties:
196 * - string 'version'
197 * - array 'dependencies'
198 * - string|null 'group'
199 * - string 'source'
200 */
201 public static function compileUnresolvedDependencies( array &$registryData ) {
202 foreach ( $registryData as $name => &$data ) {
203 $dependencies = $data['dependencies'];
204 try {
205 foreach ( $data['dependencies'] as $dependency ) {
206 $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
207 $dependencies = array_diff( $dependencies, $implicitDependencies );
208 }
209 } catch ( ResourceLoaderCircularDependencyError $err ) {
210 // Leave unchanged
211 $dependencies = $data['dependencies'];
212 }
213
214 // Rebuild keys
215 $data['dependencies'] = array_values( $dependencies );
216 }
217 }
218
219 /**
220 * Get registration code for all modules.
221 *
222 * @param ResourceLoaderContext $context
223 * @return string JavaScript code for registering all modules with the client loader
224 */
225 public function getModuleRegistrations( ResourceLoaderContext $context ) {
226 $resourceLoader = $context->getResourceLoader();
227 // Future developers: Use WebRequest::getRawVal() instead getVal().
228 // The getVal() method performs slow Language+UTF logic. (f303bb9360)
229 $target = $context->getRequest()->getRawVal( 'target', 'desktop' );
230 $safemode = $context->getRequest()->getRawVal( 'safemode' ) === '1';
231 // Bypass target filter if this request is Special:JavaScriptTest.
232 // To prevent misuse in production, this is only allowed if testing is enabled server-side.
233 $byPassTargetFilter = $this->getConfig()->get( 'EnableJavaScriptTest' ) && $target === 'test';
234
235 $out = '';
236 $states = [];
237 $registryData = [];
238 $moduleNames = $resourceLoader->getModuleNames();
239
240 // Preload with a batch so that the below calls to getVersionHash() for each module
241 // don't require on-demand loading of more information.
242 try {
243 $resourceLoader->preloadModuleInfo( $moduleNames, $context );
244 } catch ( Exception $e ) {
245 // Don't fail the request (T152266)
246 // Also print the error in the main output
247 $resourceLoader->outputErrorAndLog( $e,
248 'Preloading module info from startup failed: {exception}',
249 [ 'exception' => $e ]
250 );
251 }
252
253 // Get registry data
254 foreach ( $moduleNames as $name ) {
255 $module = $resourceLoader->getModule( $name );
256 $moduleTargets = $module->getTargets();
257 if (
258 ( !$byPassTargetFilter && !in_array( $target, $moduleTargets ) )
259 || ( $safemode && $module->getOrigin() > ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL )
260 ) {
261 continue;
262 }
263
264 if ( $module instanceof ResourceLoaderStartUpModule ) {
265 // Don't register 'startup' to the client because loading it lazily or depending
266 // on it doesn't make sense, because the startup module *is* the client.
267 // Registering would be a waste of bandwidth and memory and risks somehow causing
268 // it to load a second time.
269
270 // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
271 // Think carefully before making changes to this code!
272 // The below code is going to call ResourceLoaderModule::getVersionHash() for every module.
273 // For StartUpModule (this module) the hash is computed based on the manifest content,
274 // which is the very thing we are computing right here. As such, this must skip iterating
275 // over 'startup' itself.
276 continue;
277 }
278
279 try {
280 $versionHash = $module->getVersionHash( $context );
281 } catch ( Exception $e ) {
282 // Don't fail the request (T152266)
283 // Also print the error in the main output
284 $resourceLoader->outputErrorAndLog( $e,
285 'Calculating version for "{module}" failed: {exception}',
286 [
287 'module' => $name,
288 'exception' => $e,
289 ]
290 );
291 $versionHash = '';
292 $states[$name] = 'error';
293 }
294
295 if ( $versionHash !== '' && strlen( $versionHash ) !== ResourceLoader::HASH_LENGTH ) {
296 $e = new RuntimeException( "Badly formatted module version hash" );
297 $resourceLoader->outputErrorAndLog( $e,
298 "Module '{module}' produced an invalid version hash: '{version}'.",
299 [
300 'module' => $name,
301 'version' => $versionHash,
302 ]
303 );
304 // Module implementation either broken or deviated from ResourceLoader::makeHash
305 // Asserted by tests/phpunit/structure/ResourcesTest.
306 $versionHash = ResourceLoader::makeHash( $versionHash );
307 }
308
309 $skipFunction = $module->getSkipFunction();
310 if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
311 $skipFunction = ResourceLoader::filter( 'minify-js', $skipFunction );
312 }
313
314 $registryData[$name] = [
315 'version' => $versionHash,
316 'dependencies' => $module->getDependencies( $context ),
317 'group' => $this->getGroupId( $module->getGroup() ),
318 'source' => $module->getSource(),
319 'skip' => $skipFunction,
320 ];
321 }
322
323 self::compileUnresolvedDependencies( $registryData );
324
325 // Register sources
326 $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
327
328 // Figure out the different call signatures for mw.loader.register
329 $registrations = [];
330 foreach ( $registryData as $name => $data ) {
331 // Call mw.loader.register(name, version, dependencies, group, source, skip)
332 $registrations[] = [
333 $name,
334 $data['version'],
335 $data['dependencies'],
336 $data['group'],
337 // Swap default (local) for null
338 $data['source'] === 'local' ? null : $data['source'],
339 $data['skip']
340 ];
341 }
342
343 // Register modules
344 $out .= "\n" . ResourceLoader::makeLoaderRegisterScript( $registrations );
345
346 if ( $states ) {
347 $out .= "\n" . ResourceLoader::makeLoaderStateScript( $states );
348 }
349
350 return $out;
351 }
352
353 private function getGroupId( $groupName ) {
354 if ( $groupName === null ) {
355 return null;
356 }
357
358 if ( !array_key_exists( $groupName, $this->groupIds ) ) {
359 $this->groupIds[$groupName] = count( $this->groupIds );
360 }
361
362 return $this->groupIds[$groupName];
363 }
364
365 /**
366 * Base modules implicitly available to all modules.
367 *
368 * @return array
369 */
370 private function getBaseModules() {
371 $baseModules = [ 'jquery', 'mediawiki.base' ];
372 return $baseModules;
373 }
374
375 /**
376 * Get the localStorage key for the entire module store. The key references
377 * $wgDBname to prevent clashes between wikis under the same web domain.
378 *
379 * @return string localStorage item key for JavaScript
380 */
381 private function getStoreKey() {
382 return 'MediaWikiModuleStore:' . $this->getConfig()->get( 'DBname' );
383 }
384
385 /**
386 * Get the key on which the JavaScript module cache (mw.loader.store) will vary.
387 *
388 * @param ResourceLoaderContext $context
389 * @return string String of concatenated vary conditions
390 */
391 private function getStoreVary( ResourceLoaderContext $context ) {
392 return implode( ':', [
393 $context->getSkin(),
394 $this->getConfig()->get( 'ResourceLoaderStorageVersion' ),
395 $context->getLanguage(),
396 ] );
397 }
398
399 /**
400 * @param ResourceLoaderContext $context
401 * @return string JavaScript code
402 */
403 public function getScript( ResourceLoaderContext $context ) {
404 global $IP;
405 $conf = $this->getConfig();
406
407 if ( $context->getOnly() !== 'scripts' ) {
408 return '/* Requires only=script */';
409 }
410
411 $startupCode = file_get_contents( "$IP/resources/src/startup/startup.js" );
412
413 // The files read here MUST be kept in sync with maintenance/jsduck/eg-iframe.html,
414 // and MUST be considered by 'fileHashes' in StartUpModule::getDefinitionSummary().
415 $mwLoaderCode = file_get_contents( "$IP/resources/src/startup/mediawiki.js" ) .
416 file_get_contents( "$IP/resources/src/startup/mediawiki.requestIdleCallback.js" );
417 if ( $context->getDebug() ) {
418 $mwLoaderCode .= file_get_contents( "$IP/resources/src/startup/mediawiki.log.js" );
419 }
420 if ( $conf->get( 'ResourceLoaderEnableJSProfiler' ) ) {
421 $mwLoaderCode .= file_get_contents( "$IP/resources/src/startup/profiler.js" );
422 }
423
424 // Perform replacements for mediawiki.js
425 $mwLoaderPairs = [
426 '$VARS.reqBase' => ResourceLoader::encodeJsonForScript( $context->getReqBase() ),
427 '$VARS.baseModules' => ResourceLoader::encodeJsonForScript( $this->getBaseModules() ),
428 '$VARS.maxQueryLength' => ResourceLoader::encodeJsonForScript(
429 $conf->get( 'ResourceLoaderMaxQueryLength' )
430 ),
431 // The client-side module cache can be disabled by site configuration.
432 // It is also always disabled in debug mode.
433 '$VARS.storeEnabled' => ResourceLoader::encodeJsonForScript(
434 $conf->get( 'ResourceLoaderStorageEnabled' ) && !$context->getDebug()
435 ),
436 '$VARS.wgLegacyJavaScriptGlobals' => ResourceLoader::encodeJsonForScript(
437 $conf->get( 'LegacyJavaScriptGlobals' )
438 ),
439 '$VARS.storeKey' => ResourceLoader::encodeJsonForScript( $this->getStoreKey() ),
440 '$VARS.storeVary' => ResourceLoader::encodeJsonForScript( $this->getStoreVary( $context ) ),
441 '$VARS.groupUser' => ResourceLoader::encodeJsonForScript( $this->getGroupId( 'user' ) ),
442 '$VARS.groupPrivate' => ResourceLoader::encodeJsonForScript( $this->getGroupId( 'private' ) ),
443 ];
444 $profilerStubs = [
445 '$CODE.profileExecuteStart();' => 'mw.loader.profiler.onExecuteStart( module );',
446 '$CODE.profileExecuteEnd();' => 'mw.loader.profiler.onExecuteEnd( module );',
447 '$CODE.profileScriptStart();' => 'mw.loader.profiler.onScriptStart( module );',
448 '$CODE.profileScriptEnd();' => 'mw.loader.profiler.onScriptEnd( module );',
449 ];
450 if ( $conf->get( 'ResourceLoaderEnableJSProfiler' ) ) {
451 // When profiling is enabled, insert the calls.
452 $mwLoaderPairs += $profilerStubs;
453 } else {
454 // When disabled (by default), insert nothing.
455 $mwLoaderPairs += array_fill_keys( array_keys( $profilerStubs ), '' );
456 }
457 $mwLoaderCode = strtr( $mwLoaderCode, $mwLoaderPairs );
458
459 // Perform string replacements for startup.js
460 $pairs = [
461 '$VARS.configuration' => ResourceLoader::encodeJsonForScript(
462 $this->getConfigSettings( $context )
463 ),
464 // Raw JavaScript code (not JSON)
465 '$CODE.registrations();' => trim( $this->getModuleRegistrations( $context ) ),
466 '$CODE.defineLoader();' => $mwLoaderCode,
467 ];
468 $startupCode = strtr( $startupCode, $pairs );
469
470 return $startupCode;
471 }
472
473 /**
474 * @return bool
475 */
476 public function supportsURLLoading() {
477 return false;
478 }
479
480 /**
481 * @return bool
482 */
483 public function enableModuleContentVersion() {
484 // Enabling this means that ResourceLoader::getVersionHash will simply call getScript()
485 // and hash it to determine the version (as used by E-Tag HTTP response header).
486 return true;
487 }
488 }