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