MediaWiki REL1_28
ResourceLoaderStartUpModule.php
Go to the documentation of this file.
1<?php
26
27 // Cache for getConfigSettings() as it's called by multiple methods
28 protected $configVars = [];
29 protected $targets = [ 'desktop', 'mobile' ];
30
35 protected function getConfigSettings( $context ) {
36
37 $hash = $context->getHash();
38 if ( isset( $this->configVars[$hash] ) ) {
39 return $this->configVars[$hash];
40 }
41
43 $conf = $this->getConfig();
44
45 // We can't use Title::newMainPage() if 'mainpage' is in
46 // $wgForceUIMsgAsContentMsg because that will try to use the session
47 // user's language and we have no session user. This does the
48 // equivalent but falling back to our ResourceLoaderContext language
49 // instead.
50 $mainPage = Title::newFromText( $context->msg( 'mainpage' )->inContentLanguage()->text() );
51 if ( !$mainPage ) {
52 $mainPage = Title::newFromText( 'Main Page' );
53 }
54
60 $namespaceIds = $wgContLang->getNamespaceIds();
61 $caseSensitiveNamespaces = [];
62 foreach ( MWNamespace::getCanonicalNamespaces() as $index => $name ) {
63 $namespaceIds[$wgContLang->lc( $name )] = $index;
64 if ( !MWNamespace::isCapitalized( $index ) ) {
65 $caseSensitiveNamespaces[] = $index;
66 }
67 }
68
69 $illegalFileChars = $conf->get( 'IllegalFileChars' );
70
71 // Build list of variables
72 $vars = [
73 'wgLoadScript' => wfScript( 'load' ),
74 'debug' => $context->getDebug(),
75 'skin' => $context->getSkin(),
76 'stylepath' => $conf->get( 'StylePath' ),
77 'wgUrlProtocols' => wfUrlProtocols(),
78 'wgArticlePath' => $conf->get( 'ArticlePath' ),
79 'wgScriptPath' => $conf->get( 'ScriptPath' ),
80 'wgScriptExtension' => '.php',
81 'wgScript' => wfScript(),
82 'wgSearchType' => $conf->get( 'SearchType' ),
83 'wgVariantArticlePath' => $conf->get( 'VariantArticlePath' ),
84 // Force object to avoid "empty" associative array from
85 // becoming [] instead of {} in JS (bug 34604)
86 'wgActionPaths' => (object)$conf->get( 'ActionPaths' ),
87 'wgServer' => $conf->get( 'Server' ),
88 'wgServerName' => $conf->get( 'ServerName' ),
89 'wgUserLanguage' => $context->getLanguage(),
90 'wgContentLanguage' => $wgContLang->getCode(),
91 'wgTranslateNumerals' => $conf->get( 'TranslateNumerals' ),
92 'wgVersion' => $conf->get( 'Version' ),
93 'wgEnableAPI' => $conf->get( 'EnableAPI' ),
94 'wgEnableWriteAPI' => $conf->get( 'EnableWriteAPI' ),
95 'wgMainPageTitle' => $mainPage->getPrefixedText(),
96 'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
97 'wgNamespaceIds' => $namespaceIds,
98 'wgContentNamespaces' => MWNamespace::getContentNamespaces(),
99 'wgSiteName' => $conf->get( 'Sitename' ),
100 'wgDBname' => $conf->get( 'DBname' ),
101 'wgExtraSignatureNamespaces' => $conf->get( 'ExtraSignatureNamespaces' ),
102 'wgAvailableSkins' => Skin::getSkinNames(),
103 'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
104 // MediaWiki sets cookies to have this prefix by default
105 'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
106 'wgCookieDomain' => $conf->get( 'CookieDomain' ),
107 'wgCookiePath' => $conf->get( 'CookiePath' ),
108 'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
109 'wgResourceLoaderMaxQueryLength' => $conf->get( 'ResourceLoaderMaxQueryLength' ),
110 'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
111 'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass( Title::legalChars() ),
112 'wgIllegalFileChars' => Title::convertByteClassToUnicodeClass( $illegalFileChars ),
113 'wgResourceLoaderStorageVersion' => $conf->get( 'ResourceLoaderStorageVersion' ),
114 'wgResourceLoaderStorageEnabled' => $conf->get( 'ResourceLoaderStorageEnabled' ),
115 'wgResourceLoaderLegacyModules' => self::getLegacyModules(),
116 'wgForeignUploadTargets' => $conf->get( 'ForeignUploadTargets' ),
117 'wgEnableUploads' => $conf->get( 'EnableUploads' ),
118 ];
119
120 Hooks::run( 'ResourceLoaderGetConfigVars', [ &$vars ] );
121
122 $this->configVars[$hash] = $vars;
123 return $this->configVars[$hash];
124 }
125
133 protected static function getImplicitDependencies( array $registryData, $moduleName ) {
134 static $dependencyCache = [];
135
136 // The list of implicit dependencies won't be altered, so we can
137 // cache them without having to worry.
138 if ( !isset( $dependencyCache[$moduleName] ) ) {
139
140 if ( !isset( $registryData[$moduleName] ) ) {
141 // Dependencies may not exist
142 $dependencyCache[$moduleName] = [];
143 } else {
144 $data = $registryData[$moduleName];
145 $dependencyCache[$moduleName] = $data['dependencies'];
146
147 foreach ( $data['dependencies'] as $dependency ) {
148 // Recursively get the dependencies of the dependencies
149 $dependencyCache[$moduleName] = array_merge(
150 $dependencyCache[$moduleName],
151 self::getImplicitDependencies( $registryData, $dependency )
152 );
153 }
154 }
155 }
156
157 return $dependencyCache[$moduleName];
158 }
159
178 public static function compileUnresolvedDependencies( array &$registryData ) {
179 foreach ( $registryData as $name => &$data ) {
180 $dependencies = $data['dependencies'];
181 foreach ( $data['dependencies'] as $dependency ) {
182 $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
183 $dependencies = array_diff( $dependencies, $implicitDependencies );
184 }
185 // Rebuild keys
186 $data['dependencies'] = array_values( $dependencies );
187 }
188 }
189
197
198 $resourceLoader = $context->getResourceLoader();
199 $target = $context->getRequest()->getVal( 'target', 'desktop' );
200 // Bypass target filter if this request is Special:JavaScriptTest.
201 // To prevent misuse in production, this is only allowed if testing is enabled server-side.
202 $byPassTargetFilter = $this->getConfig()->get( 'EnableJavaScriptTest' ) && $target === 'test';
203
204 $out = '';
205 $registryData = [];
206
207 // Get registry data
208 foreach ( $resourceLoader->getModuleNames() as $name ) {
209 $module = $resourceLoader->getModule( $name );
210 $moduleTargets = $module->getTargets();
211 if ( !$byPassTargetFilter && !in_array( $target, $moduleTargets ) ) {
212 continue;
213 }
214
215 if ( $module->isRaw() ) {
216 // Don't register "raw" modules (like 'jquery' and 'mediawiki') client-side because
217 // depending on them is illegal anyway and would only lead to them being reloaded
218 // causing any state to be lost (like jQuery plugins, mw.config etc.)
219 continue;
220 }
221
222 $versionHash = $module->getVersionHash( $context );
223 if ( strlen( $versionHash ) !== 7 ) {
224 $context->getLogger()->warning(
225 "Module '{module}' produced an invalid version hash: '{version}'.",
226 [
227 'module' => $name,
228 'version' => $versionHash,
229 ]
230 );
231 // Module implementation either broken or deviated from ResourceLoader::makeHash
232 // Asserted by tests/phpunit/structure/ResourcesTest.
234 }
235
236 $skipFunction = $module->getSkipFunction();
237 if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
238 $skipFunction = ResourceLoader::filter( 'minify-js', $skipFunction );
239 }
240
241 $registryData[$name] = [
242 'version' => $versionHash,
243 'dependencies' => $module->getDependencies( $context ),
244 'group' => $module->getGroup(),
245 'source' => $module->getSource(),
246 'skip' => $skipFunction,
247 ];
248 }
249
251
252 // Register sources
254
255 // Figure out the different call signatures for mw.loader.register
256 $registrations = [];
257 foreach ( $registryData as $name => $data ) {
258 // Call mw.loader.register(name, version, dependencies, group, source, skip)
259 $registrations[] = [
260 $name,
261 $data['version'],
262 $data['dependencies'],
263 $data['group'],
264 // Swap default (local) for null
265 $data['source'] === 'local' ? null : $data['source'],
266 $data['skip']
267 ];
268 }
269
270 // Register modules
271 $out .= "\n" . ResourceLoader::makeLoaderRegisterScript( $registrations );
272
273 return $out;
274 }
275
279 public function isRaw() {
280 return true;
281 }
282
288 public static function getStartupModules() {
289 return [ 'jquery', 'mediawiki' ];
290 }
291
292 public static function getLegacyModules() {
294
295 $legacyModules = [];
297 $legacyModules[] = 'mediawiki.legacy.wikibits';
298 }
299
300 return $legacyModules;
301 }
302
313 $rl = $context->getResourceLoader();
314
315 $derivative = new DerivativeResourceLoaderContext( $context );
316 $derivative->setModules( self::getStartupModules() );
317 $derivative->setOnly( 'scripts' );
318 // Must setModules() before makeVersionQuery()
319 $derivative->setVersion( $rl->makeVersionQuery( $derivative ) );
320
321 return $rl->createLoaderURL( 'local', $derivative );
322 }
323
329 global $IP;
330 if ( $context->getOnly() !== 'scripts' ) {
331 return '/* Requires only=script */';
332 }
333
334 $out = file_get_contents( "$IP/resources/src/startup.js" );
335
336 $pairs = array_map( function ( $value ) {
337 $value = FormatJson::encode( $value, ResourceLoader::inDebugMode(), FormatJson::ALL_OK );
338 // Fix indentation
339 $value = str_replace( "\n", "\n\t", $value );
340 return $value;
341 }, [
342 '$VARS.wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
343 '$VARS.configuration' => $this->getConfigSettings( $context ),
344 '$VARS.baseModulesUri' => self::getStartupModulesUrl( $context ),
345 ] );
346 $pairs['$CODE.registrations()'] = str_replace(
347 "\n",
348 "\n\t",
349 trim( $this->getModuleRegistrations( $context ) )
350 );
351
352 return strtr( $out, $pairs );
353 }
354
358 public function supportsURLLoading() {
359 return false;
360 }
361
369 global $IP;
370 $summary = parent::getDefinitionSummary( $context );
371 $summary[] = [
372 // Detect changes to variables exposed in mw.config (T30899).
373 'vars' => $this->getConfigSettings( $context ),
374 // Changes how getScript() creates mw.Map for mw.config
375 'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
376 // Detect changes to the module registrations
377 'moduleHashes' => $this->getAllModuleHashes( $context ),
378
379 'fileMtimes' => [
380 filemtime( "$IP/resources/src/startup.js" ),
381 ],
382 ];
383 return $summary;
384 }
385
393 $rl = $context->getResourceLoader();
394 // Preload for getCombinedVersion()
395 $rl->preloadModuleInfo( $rl->getModuleNames(), $context );
396
397 // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
398 // Think carefully before making changes to this code!
399 // Pre-populate versionHash with something because the loop over all modules below includes
400 // the startup module (this module).
401 // See ResourceLoaderModule::getVersionHash() for usage of this cache.
402 $this->versionHash[$context->getHash()] = null;
403
404 return $rl->getCombinedVersion( $context, $rl->getModuleNames() );
405 }
406
410 public function getGroup() {
411 return 'startup';
412 }
413}
$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...
$IP
Definition WebStart.php:58
getRequest()
Get the WebRequest object.
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.
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.
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 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.
static getSkinNames()
Fetch the set of available skins.
Definition Skin.php:49
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
when a variable name is used in a it is silently declared as a new local masking the global
Definition design.txt:95
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
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
the array() calling protocol came about after MediaWiki 1.4rc1.
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition hooks.txt:2162
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:886
error also a ContextSource you ll probably need to make sure the header is varied on such as when responding to a resource loader request or generating HTML output & $resourceLoader
Definition hooks.txt:2692
$summary
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
$context
Definition load.php:50