Merge "Remove parameter 'options' from hook 'SkinEditSectionLinks'"
[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' => wfScript( 'load' ),
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' => wfScript(),
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 $context->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 * Internal modules used by ResourceLoader that cannot be depended on.
326 *
327 * These module(s) should have isRaw() return true, and are not
328 * legal dependencies (enforced by structure/ResourcesTest).
329 *
330 * @deprecated since 1.32 No longer used.
331 * @return array
332 */
333 public static function getStartupModules() {
334 wfDeprecated( __METHOD__, '1.32' );
335 return [];
336 }
337
338 /**
339 * @deprecated since 1.32 No longer used.
340 * @return array
341 */
342 public static function getLegacyModules() {
343 wfDeprecated( __METHOD__, '1.32' );
344 return [];
345 }
346
347 /**
348 * @private For internal use by SpecialJavaScriptTest
349 * @since 1.32
350 * @return array
351 */
352 public function getBaseModulesInternal() {
353 return $this->getBaseModules();
354 }
355
356 /**
357 * Base modules implicitly available to all modules.
358 *
359 * @return array
360 */
361 private function getBaseModules() {
362 global $wgIncludeLegacyJavaScript;
363
364 $baseModules = [ 'jquery', 'mediawiki.base' ];
365 if ( $wgIncludeLegacyJavaScript ) {
366 $baseModules[] = 'mediawiki.legacy.wikibits';
367 }
368
369 return $baseModules;
370 }
371
372 /**
373 * @param ResourceLoaderContext $context
374 * @return string JavaScript code
375 */
376 public function getScript( ResourceLoaderContext $context ) {
377 global $IP;
378 $conf = $this->getConfig();
379
380 if ( $context->getOnly() !== 'scripts' ) {
381 return '/* Requires only=script */';
382 }
383
384 $startupCode = file_get_contents( "$IP/resources/src/startup/startup.js" );
385
386 // The files read here MUST be kept in sync with maintenance/jsduck/eg-iframe.html,
387 // and MUST be considered by 'fileHashes' in StartUpModule::getDefinitionSummary().
388 $mwLoaderCode = file_get_contents( "$IP/resources/src/startup/mediawiki.js" ) .
389 file_get_contents( "$IP/resources/src/startup/mediawiki.requestIdleCallback.js" );
390 if ( $context->getDebug() ) {
391 $mwLoaderCode .= file_get_contents( "$IP/resources/src/startup/mediawiki.log.js" );
392 }
393 if ( $conf->get( 'ResourceLoaderEnableJSProfiler' ) ) {
394 $mwLoaderCode .= file_get_contents( "$IP/resources/src/startup/profiler.js" );
395 }
396
397 // Perform replacements for mediawiki.js
398 $mwLoaderPairs = [
399 '$VARS.baseModules' => ResourceLoader::encodeJsonForScript( $this->getBaseModules() ),
400 '$VARS.maxQueryLength' => ResourceLoader::encodeJsonForScript(
401 $conf->get( 'ResourceLoaderMaxQueryLength' )
402 ),
403 ];
404 $profilerStubs = [
405 '$CODE.profileExecuteStart();' => 'mw.loader.profiler.onExecuteStart( module );',
406 '$CODE.profileExecuteEnd();' => 'mw.loader.profiler.onExecuteEnd( module );',
407 '$CODE.profileScriptStart();' => 'mw.loader.profiler.onScriptStart( module );',
408 '$CODE.profileScriptEnd();' => 'mw.loader.profiler.onScriptEnd( module );',
409 ];
410 if ( $conf->get( 'ResourceLoaderEnableJSProfiler' ) ) {
411 // When profiling is enabled, insert the calls.
412 $mwLoaderPairs += $profilerStubs;
413 } else {
414 // When disabled (by default), insert nothing.
415 $mwLoaderPairs += array_fill_keys( array_keys( $profilerStubs ), '' );
416 }
417 $mwLoaderCode = strtr( $mwLoaderCode, $mwLoaderPairs );
418
419 // Perform string replacements for startup.js
420 $pairs = [
421 '$VARS.wgLegacyJavaScriptGlobals' => ResourceLoader::encodeJsonForScript(
422 $conf->get( 'LegacyJavaScriptGlobals' )
423 ),
424 '$VARS.configuration' => ResourceLoader::encodeJsonForScript(
425 $this->getConfigSettings( $context )
426 ),
427 // Raw JavaScript code (not JSON)
428 '$CODE.registrations();' => trim( $this->getModuleRegistrations( $context ) ),
429 '$CODE.defineLoader();' => $mwLoaderCode,
430 ];
431 $startupCode = strtr( $startupCode, $pairs );
432
433 return $startupCode;
434 }
435
436 /**
437 * @return bool
438 */
439 public function supportsURLLoading() {
440 return false;
441 }
442
443 /**
444 * @return bool
445 */
446 public function enableModuleContentVersion() {
447 // Enabling this means that ResourceLoader::getVersionHash will simply call getScript()
448 // and hash it to determine the version (as used by E-Tag HTTP response header).
449 return true;
450 }
451
452 /**
453 * @return string
454 */
455 public function getGroup() {
456 return 'startup';
457 }
458 }