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