MediaWiki REL1_31
ResourceLoaderStartUpModule.php
Go to the documentation of this file.
1<?php
37
38 // Cache for getConfigSettings() as it's called by multiple methods
39 protected $configVars = [];
40 protected $targets = [ 'desktop', 'mobile' ];
41
46 protected function getConfigSettings( $context ) {
47 $hash = $context->getHash();
48 if ( isset( $this->configVars[$hash] ) ) {
49 return $this->configVars[$hash];
50 }
51
52 global $wgContLang;
53 $conf = $this->getConfig();
54
55 // We can't use Title::newMainPage() if 'mainpage' is in
56 // $wgForceUIMsgAsContentMsg because that will try to use the session
57 // user's language and we have no session user. This does the
58 // equivalent but falling back to our ResourceLoaderContext language
59 // instead.
60 $mainPage = Title::newFromText( $context->msg( 'mainpage' )->inContentLanguage()->text() );
61 if ( !$mainPage ) {
62 $mainPage = Title::newFromText( 'Main Page' );
63 }
64
70 $namespaceIds = $wgContLang->getNamespaceIds();
71 $caseSensitiveNamespaces = [];
72 foreach ( MWNamespace::getCanonicalNamespaces() as $index => $name ) {
73 $namespaceIds[$wgContLang->lc( $name )] = $index;
74 if ( !MWNamespace::isCapitalized( $index ) ) {
75 $caseSensitiveNamespaces[] = $index;
76 }
77 }
78
79 $illegalFileChars = $conf->get( 'IllegalFileChars' );
80 $oldCommentSchema = $conf->get( 'CommentTableSchemaMigrationStage' ) === MIGRATION_OLD;
81
82 // Build list of variables
83 $vars = [
84 'wgLoadScript' => wfScript( 'load' ),
85 'debug' => $context->getDebug(),
86 'skin' => $context->getSkin(),
87 'stylepath' => $conf->get( 'StylePath' ),
88 'wgUrlProtocols' => wfUrlProtocols(),
89 'wgArticlePath' => $conf->get( 'ArticlePath' ),
90 'wgScriptPath' => $conf->get( 'ScriptPath' ),
91 'wgScript' => wfScript(),
92 'wgSearchType' => $conf->get( 'SearchType' ),
93 'wgVariantArticlePath' => $conf->get( 'VariantArticlePath' ),
94 // Force object to avoid "empty" associative array from
95 // becoming [] instead of {} in JS (T36604)
96 'wgActionPaths' => (object)$conf->get( 'ActionPaths' ),
97 'wgServer' => $conf->get( 'Server' ),
98 'wgServerName' => $conf->get( 'ServerName' ),
99 'wgUserLanguage' => $context->getLanguage(),
100 'wgContentLanguage' => $wgContLang->getCode(),
101 'wgTranslateNumerals' => $conf->get( 'TranslateNumerals' ),
102 'wgVersion' => $conf->get( 'Version' ),
103 'wgEnableAPI' => $conf->get( 'EnableAPI' ),
104 'wgEnableWriteAPI' => $conf->get( 'EnableWriteAPI' ),
105 'wgMainPageTitle' => $mainPage->getPrefixedText(),
106 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
107 'wgNamespaceIds' => $namespaceIds,
108 'wgContentNamespaces' => MWNamespace::getContentNamespaces(),
109 'wgSiteName' => $conf->get( 'Sitename' ),
110 'wgDBname' => $conf->get( 'DBname' ),
111 'wgExtraSignatureNamespaces' => $conf->get( 'ExtraSignatureNamespaces' ),
112 'wgAvailableSkins' => Skin::getSkinNames(),
113 'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
114 // MediaWiki sets cookies to have this prefix by default
115 'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
116 'wgCookieDomain' => $conf->get( 'CookieDomain' ),
117 'wgCookiePath' => $conf->get( 'CookiePath' ),
118 'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
119 'wgResourceLoaderMaxQueryLength' => $conf->get( 'ResourceLoaderMaxQueryLength' ),
120 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
121 'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass( Title::legalChars() ),
122 'wgIllegalFileChars' => Title::convertByteClassToUnicodeClass( $illegalFileChars ),
123 'wgResourceLoaderStorageVersion' => $conf->get( 'ResourceLoaderStorageVersion' ),
124 'wgResourceLoaderStorageEnabled' => $conf->get( 'ResourceLoaderStorageEnabled' ),
125 'wgForeignUploadTargets' => $conf->get( 'ForeignUploadTargets' ),
126 'wgEnableUploads' => $conf->get( 'EnableUploads' ),
127 'wgCommentByteLimit' => $oldCommentSchema ? 255 : null,
128 'wgCommentCodePointLimit' => $oldCommentSchema ? null : CommentStore::COMMENT_CHARACTER_LIMIT,
129 ];
130
131 Hooks::run( 'ResourceLoaderGetConfigVars', [ &$vars ] );
132
133 $this->configVars[$hash] = $vars;
134 return $this->configVars[$hash];
135 }
136
144 protected static function getImplicitDependencies( array $registryData, $moduleName ) {
145 static $dependencyCache = [];
146
147 // The list of implicit dependencies won't be altered, so we can
148 // cache them without having to worry.
149 if ( !isset( $dependencyCache[$moduleName] ) ) {
150 if ( !isset( $registryData[$moduleName] ) ) {
151 // Dependencies may not exist
152 $dependencyCache[$moduleName] = [];
153 } else {
154 $data = $registryData[$moduleName];
155 $dependencyCache[$moduleName] = $data['dependencies'];
156
157 foreach ( $data['dependencies'] as $dependency ) {
158 // Recursively get the dependencies of the dependencies
159 $dependencyCache[$moduleName] = array_merge(
160 $dependencyCache[$moduleName],
161 self::getImplicitDependencies( $registryData, $dependency )
162 );
163 }
164 }
165 }
166
167 return $dependencyCache[$moduleName];
168 }
169
188 public static function compileUnresolvedDependencies( array &$registryData ) {
189 foreach ( $registryData as $name => &$data ) {
190 $dependencies = $data['dependencies'];
191 foreach ( $data['dependencies'] as $dependency ) {
192 $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
193 $dependencies = array_diff( $dependencies, $implicitDependencies );
194 }
195 // Rebuild keys
196 $data['dependencies'] = array_values( $dependencies );
197 }
198 }
199
207 $resourceLoader = $context->getResourceLoader();
208 // Future developers: Use WebRequest::getRawVal() instead getVal().
209 // The getVal() method performs slow Language+UTF logic. (f303bb9360)
210 $target = $context->getRequest()->getRawVal( 'target', 'desktop' );
211 // Bypass target filter if this request is Special:JavaScriptTest.
212 // To prevent misuse in production, this is only allowed if testing is enabled server-side.
213 $byPassTargetFilter = $this->getConfig()->get( 'EnableJavaScriptTest' ) && $target === 'test';
214
215 $out = '';
216 $states = [];
217 $registryData = [];
218
219 // Get registry data
220 foreach ( $resourceLoader->getModuleNames() as $name ) {
221 $module = $resourceLoader->getModule( $name );
222 $moduleTargets = $module->getTargets();
223 if ( !$byPassTargetFilter && !in_array( $target, $moduleTargets ) ) {
224 continue;
225 }
226
227 if ( $module->isRaw() ) {
228 // Don't register "raw" modules (like 'jquery' and 'mediawiki') client-side because
229 // depending on them is illegal anyway and would only lead to them being reloaded
230 // causing any state to be lost (like jQuery plugins, mw.config etc.)
231 continue;
232 }
233
234 try {
235 $versionHash = $module->getVersionHash( $context );
236 } catch ( Exception $e ) {
237 // See also T152266 and ResourceLoader::getCombinedVersion()
238 MWExceptionHandler::logException( $e );
239 $context->getLogger()->warning(
240 'Calculating version for "{module}" failed: {exception}',
241 [
242 'module' => $name,
243 'exception' => $e,
244 ]
245 );
246 $versionHash = '';
247 $states[$name] = 'error';
248 }
249
250 if ( $versionHash !== '' && strlen( $versionHash ) !== 7 ) {
251 $context->getLogger()->warning(
252 "Module '{module}' produced an invalid version hash: '{version}'.",
253 [
254 'module' => $name,
255 'version' => $versionHash,
256 ]
257 );
258 // Module implementation either broken or deviated from ResourceLoader::makeHash
259 // Asserted by tests/phpunit/structure/ResourcesTest.
261 }
262
263 $skipFunction = $module->getSkipFunction();
264 if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
265 $skipFunction = ResourceLoader::filter( 'minify-js', $skipFunction );
266 }
267
268 $registryData[$name] = [
269 'version' => $versionHash,
270 'dependencies' => $module->getDependencies( $context ),
271 'group' => $module->getGroup(),
272 'source' => $module->getSource(),
273 'skip' => $skipFunction,
274 ];
275 }
276
278
279 // Register sources
281
282 // Figure out the different call signatures for mw.loader.register
283 $registrations = [];
284 foreach ( $registryData as $name => $data ) {
285 // Call mw.loader.register(name, version, dependencies, group, source, skip)
286 $registrations[] = [
287 $name,
288 $data['version'],
289 $data['dependencies'],
290 $data['group'],
291 // Swap default (local) for null
292 $data['source'] === 'local' ? null : $data['source'],
293 $data['skip']
294 ];
295 }
296
297 // Register modules
298 $out .= "\n" . ResourceLoader::makeLoaderRegisterScript( $registrations );
299
300 if ( $states ) {
301 $out .= "\n" . ResourceLoader::makeLoaderStateScript( $states );
302 }
303
304 return $out;
305 }
306
310 public function isRaw() {
311 return true;
312 }
313
320 return [
321 $url => [ 'as' => 'script' ]
322 ];
323 }
324
330 public static function getStartupModules() {
331 return [ 'jquery', 'mediawiki' ];
332 }
333
334 public static function getLegacyModules() {
336
337 $legacyModules = [];
339 $legacyModules[] = 'mediawiki.legacy.wikibits';
340 }
341
342 return $legacyModules;
343 }
344
355 $rl = $context->getResourceLoader();
356 $derivative = new DerivativeResourceLoaderContext( $context );
357 $derivative->setModules( array_merge(
358 self::getStartupModules(),
359 self::getLegacyModules()
360 ) );
361 $derivative->setOnly( 'scripts' );
362 // Must setModules() before makeVersionQuery()
363 $derivative->setVersion( $rl->makeVersionQuery( $derivative ) );
364
365 return $rl->createLoaderURL( 'local', $derivative );
366 }
367
373 global $IP;
374 if ( $context->getOnly() !== 'scripts' ) {
375 return '/* Requires only=script */';
376 }
377
378 $out = file_get_contents( "$IP/resources/src/startup.js" );
379
380 $pairs = array_map( function ( $value ) {
381 $value = FormatJson::encode( $value, ResourceLoader::inDebugMode(), FormatJson::ALL_OK );
382 // Fix indentation
383 $value = str_replace( "\n", "\n\t", $value );
384 return $value;
385 }, [
386 '$VARS.wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
387 '$VARS.configuration' => $this->getConfigSettings( $context ),
388 // This url may be preloaded. See getPreloadLinks().
389 '$VARS.baseModulesUri' => self::getStartupModulesUrl( $context ),
390 ] );
391 $pairs['$CODE.registrations()'] = str_replace(
392 "\n",
393 "\n\t",
394 trim( $this->getModuleRegistrations( $context ) )
395 );
396
397 return strtr( $out, $pairs );
398 }
399
403 public function supportsURLLoading() {
404 return false;
405 }
406
414 global $IP;
415 $summary = parent::getDefinitionSummary( $context );
416 $summary[] = [
417 // Detect changes to variables exposed in mw.config (T30899).
418 'vars' => $this->getConfigSettings( $context ),
419 // Changes how getScript() creates mw.Map for mw.config
420 'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
421 // Detect changes to the module registrations
422 'moduleHashes' => $this->getAllModuleHashes( $context ),
423
424 'fileMtimes' => [
425 filemtime( "$IP/resources/src/startup.js" ),
426 ],
427 ];
428 return $summary;
429 }
430
438 $rl = $context->getResourceLoader();
439 // Preload for getCombinedVersion()
440 $rl->preloadModuleInfo( $rl->getModuleNames(), $context );
441
442 // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
443 // Think carefully before making changes to this code!
444 // Pre-populate versionHash with something because the loop over all modules below includes
445 // the startup module (this module).
446 // See ResourceLoaderModule::getVersionHash() for usage of this cache.
447 $this->versionHash[$context->getHash()] = null;
448
449 return $rl->getCombinedVersion( $context, $rl->getModuleNames() );
450 }
451
455 public function getGroup() {
456 return 'startup';
457 }
458}
$wgIncludeLegacyJavaScript
Whether to ensure the mediawiki.legacy library is loaded before other modules.
wfUrlProtocols( $includeProtocolRelative=true)
Returns a regular expression of url protocols.
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
Allows changing specific properties of a context object, without changing the main one.
Object passed around to modules which contains information about the state of a specific loader reque...
Abstraction for ResourceLoader modules, with name registration and maxage functionality.
Module for ResourceLoader initialization.
getScript(ResourceLoaderContext $context)
static getImplicitDependencies(array $registryData, $moduleName)
Recursively get all explicit and implicit dependencies for to the given module.
static getStartupModules()
Base modules required for the base environment of ResourceLoader.
getPreloadLinks(ResourceLoaderContext $context)
getDefinitionSummary(ResourceLoaderContext $context)
Get the definition summary for this module.
getAllModuleHashes(ResourceLoaderContext $context)
Helper method for getDefinitionSummary().
static compileUnresolvedDependencies(array &$registryData)
Optimize the dependency tree in $this->modules.
static getStartupModulesUrl(ResourceLoaderContext $context)
Get the load URL of the startup modules.
getModuleRegistrations(ResourceLoaderContext $context)
Get registration code for all modules.
static makeLoaderStateScript( $name, $state=null)
Returns a JS call to mw.loader.state, which sets the state of a module or modules to a given value.
static inDebugMode()
Determine whether debug mode was requested Order of priority is 1) request param, 2) cookie,...
static makeLoaderSourcesScript( $id, $loadUrl=null)
Returns JS code which calls mw.loader.addSource() with the given parameters.
static makeLoaderRegisterScript( $name, $version=null, $dependencies=null, $group=null, $source=null, $skip=null)
Returns JS code which calls mw.loader.register with the given parameters.
static makeHash( $value)
static filter( $filter, $data, array $options=[])
Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
Definition design.txt:57
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition hooks.txt:2228
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition hooks.txt:2811
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition hooks.txt:864
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext such as when responding to a resource loader request or generating HTML output & $resourceLoader
Definition hooks.txt:2818
returning false will NOT prevent logging $e
Definition hooks.txt:2176
$IP
Definition update.php:3
globals will be eliminated from MediaWiki replaced by an application object which would be passed to constructors Whether that would be an convenient solution remains to be but certainly PHP makes such object oriented programming models easier than they were in previous versions For the time being MediaWiki programmers will have to work in an environment with some global context At the time of globals were initialised on startup by MediaWiki of these were configuration which are documented in DefaultSettings php There is no comprehensive documentation for the remaining however some of the most important ones are listed below They are typically initialised either in index php or in Setup php For a description of the see design txt $wgTitle Title object created from the request URL $wgOut OutputPage object for HTTP response $wgUser User object for the user associated with the current request $wgLang Language object selected by user preferences $wgContLang Language object associated with the wiki being viewed $wgParser Parser object Parser extensions register their hooks here $wgRequest WebRequest object
Definition globals.txt:64
const MIGRATION_OLD
Definition Defines.php:302