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