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