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