MediaWiki  1.30.0
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  $hash = $context->getHash();
37  if ( isset( $this->configVars[$hash] ) ) {
38  return $this->configVars[$hash];
39  }
40 
42  $conf = $this->getConfig();
43 
44  // We can't use Title::newMainPage() if 'mainpage' is in
45  // $wgForceUIMsgAsContentMsg because that will try to use the session
46  // user's language and we have no session user. This does the
47  // equivalent but falling back to our ResourceLoaderContext language
48  // instead.
49  $mainPage = Title::newFromText( $context->msg( 'mainpage' )->inContentLanguage()->text() );
50  if ( !$mainPage ) {
51  $mainPage = Title::newFromText( 'Main Page' );
52  }
53 
59  $namespaceIds = $wgContLang->getNamespaceIds();
60  $caseSensitiveNamespaces = [];
61  foreach ( MWNamespace::getCanonicalNamespaces() as $index => $name ) {
62  $namespaceIds[$wgContLang->lc( $name )] = $index;
63  if ( !MWNamespace::isCapitalized( $index ) ) {
64  $caseSensitiveNamespaces[] = $index;
65  }
66  }
67 
68  $illegalFileChars = $conf->get( 'IllegalFileChars' );
69 
70  // Build list of variables
71  $vars = [
72  'wgLoadScript' => wfScript( 'load' ),
73  'debug' => $context->getDebug(),
74  'skin' => $context->getSkin(),
75  'stylepath' => $conf->get( 'StylePath' ),
76  'wgUrlProtocols' => wfUrlProtocols(),
77  'wgArticlePath' => $conf->get( 'ArticlePath' ),
78  'wgScriptPath' => $conf->get( 'ScriptPath' ),
79  'wgScriptExtension' => '.php',
80  'wgScript' => wfScript(),
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' => $wgContLang->getCode(),
90  'wgTranslateNumerals' => $conf->get( 'TranslateNumerals' ),
91  'wgVersion' => $conf->get( 'Version' ),
92  'wgEnableAPI' => $conf->get( 'EnableAPI' ),
93  'wgEnableWriteAPI' => $conf->get( 'EnableWriteAPI' ),
94  'wgMainPageTitle' => $mainPage->getPrefixedText(),
95  'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
96  'wgNamespaceIds' => $namespaceIds,
97  'wgContentNamespaces' => MWNamespace::getContentNamespaces(),
98  'wgSiteName' => $conf->get( 'Sitename' ),
99  'wgDBname' => $conf->get( 'DBname' ),
100  'wgExtraSignatureNamespaces' => $conf->get( 'ExtraSignatureNamespaces' ),
101  'wgAvailableSkins' => Skin::getSkinNames(),
102  'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
103  // MediaWiki sets cookies to have this prefix by default
104  'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
105  'wgCookieDomain' => $conf->get( 'CookieDomain' ),
106  'wgCookiePath' => $conf->get( 'CookiePath' ),
107  'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
108  'wgResourceLoaderMaxQueryLength' => $conf->get( 'ResourceLoaderMaxQueryLength' ),
109  'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
110  'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass( Title::legalChars() ),
111  'wgIllegalFileChars' => Title::convertByteClassToUnicodeClass( $illegalFileChars ),
112  'wgResourceLoaderStorageVersion' => $conf->get( 'ResourceLoaderStorageVersion' ),
113  'wgResourceLoaderStorageEnabled' => $conf->get( 'ResourceLoaderStorageEnabled' ),
114  'wgForeignUploadTargets' => $conf->get( 'ForeignUploadTargets' ),
115  'wgEnableUploads' => $conf->get( 'EnableUploads' ),
116  ];
117 
118  Hooks::run( 'ResourceLoaderGetConfigVars', [ &$vars ] );
119 
120  $this->configVars[$hash] = $vars;
121  return $this->configVars[$hash];
122  }
123 
131  protected static function getImplicitDependencies( array $registryData, $moduleName ) {
132  static $dependencyCache = [];
133 
134  // The list of implicit dependencies won't be altered, so we can
135  // cache them without having to worry.
136  if ( !isset( $dependencyCache[$moduleName] ) ) {
137  if ( !isset( $registryData[$moduleName] ) ) {
138  // Dependencies may not exist
139  $dependencyCache[$moduleName] = [];
140  } else {
141  $data = $registryData[$moduleName];
142  $dependencyCache[$moduleName] = $data['dependencies'];
143 
144  foreach ( $data['dependencies'] as $dependency ) {
145  // Recursively get the dependencies of the dependencies
146  $dependencyCache[$moduleName] = array_merge(
147  $dependencyCache[$moduleName],
148  self::getImplicitDependencies( $registryData, $dependency )
149  );
150  }
151  }
152  }
153 
154  return $dependencyCache[$moduleName];
155  }
156 
175  public static function compileUnresolvedDependencies( array &$registryData ) {
176  foreach ( $registryData as $name => &$data ) {
177  $dependencies = $data['dependencies'];
178  foreach ( $data['dependencies'] as $dependency ) {
179  $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
180  $dependencies = array_diff( $dependencies, $implicitDependencies );
181  }
182  // Rebuild keys
183  $data['dependencies'] = array_values( $dependencies );
184  }
185  }
186 
194  $resourceLoader = $context->getResourceLoader();
195  $target = $context->getRequest()->getVal( 'target', 'desktop' );
196  // Bypass target filter if this request is Special:JavaScriptTest.
197  // To prevent misuse in production, this is only allowed if testing is enabled server-side.
198  $byPassTargetFilter = $this->getConfig()->get( 'EnableJavaScriptTest' ) && $target === 'test';
199 
200  $out = '';
201  $states = [];
202  $registryData = [];
203 
204  // Get registry data
205  foreach ( $resourceLoader->getModuleNames() as $name ) {
206  $module = $resourceLoader->getModule( $name );
207  $moduleTargets = $module->getTargets();
208  if ( !$byPassTargetFilter && !in_array( $target, $moduleTargets ) ) {
209  continue;
210  }
211 
212  if ( $module->isRaw() ) {
213  // Don't register "raw" modules (like 'jquery' and 'mediawiki') client-side because
214  // depending on them is illegal anyway and would only lead to them being reloaded
215  // causing any state to be lost (like jQuery plugins, mw.config etc.)
216  continue;
217  }
218 
219  try {
220  $versionHash = $module->getVersionHash( $context );
221  } catch ( Exception $e ) {
222  // See also T152266 and ResourceLoader::getCombinedVersion()
224  $context->getLogger()->warning(
225  'Calculating version for "{module}" failed: {exception}',
226  [
227  'module' => $name,
228  'exception' => $e,
229  ]
230  );
231  $versionHash = '';
232  $states[$name] = 'error';
233  }
234 
235  if ( $versionHash !== '' && strlen( $versionHash ) !== 7 ) {
236  $context->getLogger()->warning(
237  "Module '{module}' produced an invalid version hash: '{version}'.",
238  [
239  'module' => $name,
240  'version' => $versionHash,
241  ]
242  );
243  // Module implementation either broken or deviated from ResourceLoader::makeHash
244  // Asserted by tests/phpunit/structure/ResourcesTest.
245  $versionHash = ResourceLoader::makeHash( $versionHash );
246  }
247 
248  $skipFunction = $module->getSkipFunction();
249  if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
250  $skipFunction = ResourceLoader::filter( 'minify-js', $skipFunction );
251  }
252 
253  $registryData[$name] = [
254  'version' => $versionHash,
255  'dependencies' => $module->getDependencies( $context ),
256  'group' => $module->getGroup(),
257  'source' => $module->getSource(),
258  'skip' => $skipFunction,
259  ];
260  }
261 
262  self::compileUnresolvedDependencies( $registryData );
263 
264  // Register sources
265  $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
266 
267  // Figure out the different call signatures for mw.loader.register
268  $registrations = [];
269  foreach ( $registryData as $name => $data ) {
270  // Call mw.loader.register(name, version, dependencies, group, source, skip)
271  $registrations[] = [
272  $name,
273  $data['version'],
274  $data['dependencies'],
275  $data['group'],
276  // Swap default (local) for null
277  $data['source'] === 'local' ? null : $data['source'],
278  $data['skip']
279  ];
280  }
281 
282  // Register modules
283  $out .= "\n" . ResourceLoader::makeLoaderRegisterScript( $registrations );
284 
285  if ( $states ) {
286  $out .= "\n" . ResourceLoader::makeLoaderStateScript( $states );
287  }
288 
289  return $out;
290  }
291 
295  public function isRaw() {
296  return true;
297  }
298 
305  return [
306  $url => [ 'as' => 'script' ]
307  ];
308  }
309 
315  public static function getStartupModules() {
316  return [ 'jquery', 'mediawiki' ];
317  }
318 
319  public static function getLegacyModules() {
321 
322  $legacyModules = [];
324  $legacyModules[] = 'mediawiki.legacy.wikibits';
325  }
326 
327  return $legacyModules;
328  }
329 
340  $rl = $context->getResourceLoader();
341  $derivative = new DerivativeResourceLoaderContext( $context );
342  $derivative->setModules( array_merge(
343  self::getStartupModules(),
344  self::getLegacyModules()
345  ) );
346  $derivative->setOnly( 'scripts' );
347  // Must setModules() before makeVersionQuery()
348  $derivative->setVersion( $rl->makeVersionQuery( $derivative ) );
349 
350  return $rl->createLoaderURL( 'local', $derivative );
351  }
352 
358  global $IP;
359  if ( $context->getOnly() !== 'scripts' ) {
360  return '/* Requires only=script */';
361  }
362 
363  $out = file_get_contents( "$IP/resources/src/startup.js" );
364 
365  $pairs = array_map( function ( $value ) {
366  $value = FormatJson::encode( $value, ResourceLoader::inDebugMode(), FormatJson::ALL_OK );
367  // Fix indentation
368  $value = str_replace( "\n", "\n\t", $value );
369  return $value;
370  }, [
371  '$VARS.wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
372  '$VARS.configuration' => $this->getConfigSettings( $context ),
373  // This url may be preloaded. See getPreloadLinks().
374  '$VARS.baseModulesUri' => self::getStartupModulesUrl( $context ),
375  ] );
376  $pairs['$CODE.registrations()'] = str_replace(
377  "\n",
378  "\n\t",
379  trim( $this->getModuleRegistrations( $context ) )
380  );
381 
382  return strtr( $out, $pairs );
383  }
384 
388  public function supportsURLLoading() {
389  return false;
390  }
391 
399  global $IP;
400  $summary = parent::getDefinitionSummary( $context );
401  $summary[] = [
402  // Detect changes to variables exposed in mw.config (T30899).
403  'vars' => $this->getConfigSettings( $context ),
404  // Changes how getScript() creates mw.Map for mw.config
405  'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
406  // Detect changes to the module registrations
407  'moduleHashes' => $this->getAllModuleHashes( $context ),
408 
409  'fileMtimes' => [
410  filemtime( "$IP/resources/src/startup.js" ),
411  ],
412  ];
413  return $summary;
414  }
415 
423  $rl = $context->getResourceLoader();
424  // Preload for getCombinedVersion()
425  $rl->preloadModuleInfo( $rl->getModuleNames(), $context );
426 
427  // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
428  // Think carefully before making changes to this code!
429  // Pre-populate versionHash with something because the loop over all modules below includes
430  // the startup module (this module).
431  // See ResourceLoaderModule::getVersionHash() for usage of this cache.
432  $this->versionHash[$context->getHash()] = null;
433 
434  return $rl->getCombinedVersion( $context, $rl->getModuleNames() );
435  }
436 
440  public function getGroup() {
441  return 'startup';
442  }
443 }
ResourceLoaderStartUpModule\$targets
$targets
Definition: ResourceLoaderStartUpModule.php:29
ResourceLoaderContext
Object passed around to modules which contains information about the state of a specific loader reque...
Definition: ResourceLoaderContext.php:32
object
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:25
Title\newFromText
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:268
$wgIncludeLegacyJavaScript
$wgIncludeLegacyJavaScript
Whether to ensure the mediawiki.legacy library is loaded before other modules.
Definition: DefaultSettings.php:3697
ResourceLoaderStartUpModule\getDefinitionSummary
getDefinitionSummary(ResourceLoaderContext $context)
Get the definition summary for this module.
Definition: ResourceLoaderStartUpModule.php:398
$context
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:2581
ResourceLoaderStartUpModule\getModuleRegistrations
getModuleRegistrations(ResourceLoaderContext $context)
Get registration code for all modules.
Definition: ResourceLoaderStartUpModule.php:193
ResourceLoaderStartUpModule\getAllModuleHashes
getAllModuleHashes(ResourceLoaderContext $context)
Helper method for getDefinitionSummary().
Definition: ResourceLoaderStartUpModule.php:422
ResourceLoaderModule\$versionHash
$versionHash
Definition: ResourceLoaderModule.php:78
ResourceLoaderStartUpModule\getStartupModules
static getStartupModules()
Base modules required for the base environment of ResourceLoader.
Definition: ResourceLoaderStartUpModule.php:315
ResourceLoaderStartUpModule\$configVars
$configVars
Definition: ResourceLoaderStartUpModule.php:28
ResourceLoaderStartUpModule\getStartupModulesUrl
static getStartupModulesUrl(ResourceLoaderContext $context)
Get the load URL of the startup modules.
Definition: ResourceLoaderStartUpModule.php:339
$resourceLoader
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:2581
MWNamespace\getContentNamespaces
static getContentNamespaces()
Get a list of all namespace indices which are considered to contain content.
Definition: MWNamespace.php:353
Title\convertByteClassToUnicodeClass
static convertByteClassToUnicodeClass( $byteClass)
Utility method for converting a character sequence from bytes to Unicode.
Definition: Title.php:646
FormatJson\ALL_OK
const ALL_OK
Skip escaping as many characters as reasonably possible.
Definition: FormatJson.php:55
php
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:35
ResourceLoaderStartUpModule\getImplicitDependencies
static getImplicitDependencies(array $registryData, $moduleName)
Recursively get all explicit and implicit dependencies for to the given module.
Definition: ResourceLoaderStartUpModule.php:131
Skin\getSkinNames
static getSkinNames()
Fetch the set of available skins.
Definition: Skin.php:51
ResourceLoaderStartUpModule\getLegacyModules
static getLegacyModules()
Definition: ResourceLoaderStartUpModule.php:319
FormatJson\encode
static encode( $value, $pretty=false, $escaping=0)
Returns the JSON representation of a value.
Definition: FormatJson.php:127
ResourceLoaderStartUpModule\supportsURLLoading
supportsURLLoading()
Definition: ResourceLoaderStartUpModule.php:388
wfScript
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
Definition: GlobalFunctions.php:2934
$IP
$IP
Definition: update.php:3
ResourceLoaderStartUpModule\isRaw
isRaw()
Definition: ResourceLoaderStartUpModule.php:295
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
$vars
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition: hooks.txt:2198
ResourceLoaderStartUpModule\getScript
getScript(ResourceLoaderContext $context)
Definition: ResourceLoaderStartUpModule.php:357
wfUrlProtocols
wfUrlProtocols( $includeProtocolRelative=true)
Returns a regular expression of url protocols.
Definition: GlobalFunctions.php:792
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2141
$value
$value
Definition: styleTest.css.php:45
ResourceLoaderStartUpModule\getGroup
getGroup()
Definition: ResourceLoaderStartUpModule.php:440
ResourceLoaderStartUpModule
Definition: ResourceLoaderStartUpModule.php:25
DerivativeResourceLoaderContext
Allows changing specific properties of a context object, without changing the main one.
Definition: DerivativeResourceLoaderContext.php:30
ResourceLoaderModule\$name
$name
Definition: ResourceLoaderModule.php:70
ResourceLoaderModule
Abstraction for ResourceLoader modules, with name registration and maxage functionality.
Definition: ResourceLoaderModule.php:34
ResourceLoaderStartUpModule\getPreloadLinks
getPreloadLinks(ResourceLoaderContext $context)
Definition: ResourceLoaderStartUpModule.php:303
as
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
Definition: distributors.txt:9
MWNamespace\getCanonicalNamespaces
static getCanonicalNamespaces( $rebuild=false)
Returns array of all defined namespaces with their canonical (English) names.
Definition: MWNamespace.php:207
MWNamespace\isCapitalized
static isCapitalized( $index)
Is the namespace first-letter capitalized?
Definition: MWNamespace.php:397
ResourceLoaderStartUpModule\getConfigSettings
getConfigSettings( $context)
Definition: ResourceLoaderStartUpModule.php:35
Title\legalChars
static legalChars()
Get a regex character class describing the legal characters in a link.
Definition: Title.php:618
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:203
ResourceLoaderStartUpModule\compileUnresolvedDependencies
static compileUnresolvedDependencies(array &$registryData)
Optimize the dependency tree in $this->modules.
Definition: ResourceLoaderStartUpModule.php:175
ResourceLoaderModule\getConfig
getConfig()
Definition: ResourceLoaderModule.php:188
array
the array() calling protocol came about after MediaWiki 1.4rc1.
MWExceptionHandler\logException
static logException( $e, $catcher=self::CAUGHT_BY_OTHER)
Log an exception to the exception log (if enabled).
Definition: MWExceptionHandler.php:613
$wgContLang
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 content language as $wgContLang
Definition: design.txt:56
$out
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:781