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