MediaWiki  1.29.2
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 (T36604)
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  'wgForeignUploadTargets' => $conf->get( 'ForeignUploadTargets' ),
116  'wgEnableUploads' => $conf->get( 'EnableUploads' ),
117  ];
118 
119  Hooks::run( 'ResourceLoaderGetConfigVars', [ &$vars ] );
120 
121  $this->configVars[$hash] = $vars;
122  return $this->configVars[$hash];
123  }
124 
132  protected static function getImplicitDependencies( array $registryData, $moduleName ) {
133  static $dependencyCache = [];
134 
135  // The list of implicit dependencies won't be altered, so we can
136  // cache them without having to worry.
137  if ( !isset( $dependencyCache[$moduleName] ) ) {
138 
139  if ( !isset( $registryData[$moduleName] ) ) {
140  // Dependencies may not exist
141  $dependencyCache[$moduleName] = [];
142  } else {
143  $data = $registryData[$moduleName];
144  $dependencyCache[$moduleName] = $data['dependencies'];
145 
146  foreach ( $data['dependencies'] as $dependency ) {
147  // Recursively get the dependencies of the dependencies
148  $dependencyCache[$moduleName] = array_merge(
149  $dependencyCache[$moduleName],
150  self::getImplicitDependencies( $registryData, $dependency )
151  );
152  }
153  }
154  }
155 
156  return $dependencyCache[$moduleName];
157  }
158 
177  public static function compileUnresolvedDependencies( array &$registryData ) {
178  foreach ( $registryData as $name => &$data ) {
179  $dependencies = $data['dependencies'];
180  foreach ( $data['dependencies'] as $dependency ) {
181  $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
182  $dependencies = array_diff( $dependencies, $implicitDependencies );
183  }
184  // Rebuild keys
185  $data['dependencies'] = array_values( $dependencies );
186  }
187  }
188 
196  $resourceLoader = $context->getResourceLoader();
197  $target = $context->getRequest()->getVal( 'target', 'desktop' );
198  // Bypass target filter if this request is Special:JavaScriptTest.
199  // To prevent misuse in production, this is only allowed if testing is enabled server-side.
200  $byPassTargetFilter = $this->getConfig()->get( 'EnableJavaScriptTest' ) && $target === 'test';
201 
202  $out = '';
203  $states = [];
204  $registryData = [];
205 
206  // Get registry data
207  foreach ( $resourceLoader->getModuleNames() as $name ) {
208  $module = $resourceLoader->getModule( $name );
209  $moduleTargets = $module->getTargets();
210  if ( !$byPassTargetFilter && !in_array( $target, $moduleTargets ) ) {
211  continue;
212  }
213 
214  if ( $module->isRaw() ) {
215  // Don't register "raw" modules (like 'jquery' and 'mediawiki') client-side because
216  // depending on them is illegal anyway and would only lead to them being reloaded
217  // causing any state to be lost (like jQuery plugins, mw.config etc.)
218  continue;
219  }
220 
221  try {
222  $versionHash = $module->getVersionHash( $context );
223  } catch ( Exception $e ) {
224  // See also T152266 and ResourceLoader::getCombinedVersion()
226  $context->getLogger()->warning(
227  'Calculating version for "{module}" failed: {exception}',
228  [
229  'module' => $name,
230  'exception' => $e,
231  ]
232  );
233  $versionHash = '';
234  $states[$name] = 'error';
235  }
236 
237  if ( $versionHash !== '' && strlen( $versionHash ) !== 7 ) {
238  $context->getLogger()->warning(
239  "Module '{module}' produced an invalid version hash: '{version}'.",
240  [
241  'module' => $name,
242  'version' => $versionHash,
243  ]
244  );
245  // Module implementation either broken or deviated from ResourceLoader::makeHash
246  // Asserted by tests/phpunit/structure/ResourcesTest.
247  $versionHash = ResourceLoader::makeHash( $versionHash );
248  }
249 
250  $skipFunction = $module->getSkipFunction();
251  if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
252  $skipFunction = ResourceLoader::filter( 'minify-js', $skipFunction );
253  }
254 
255  $registryData[$name] = [
256  'version' => $versionHash,
257  'dependencies' => $module->getDependencies( $context ),
258  'group' => $module->getGroup(),
259  'source' => $module->getSource(),
260  'skip' => $skipFunction,
261  ];
262  }
263 
264  self::compileUnresolvedDependencies( $registryData );
265 
266  // Register sources
267  $out .= ResourceLoader::makeLoaderSourcesScript( $resourceLoader->getSources() );
268 
269  // Figure out the different call signatures for mw.loader.register
270  $registrations = [];
271  foreach ( $registryData as $name => $data ) {
272  // Call mw.loader.register(name, version, dependencies, group, source, skip)
273  $registrations[] = [
274  $name,
275  $data['version'],
276  $data['dependencies'],
277  $data['group'],
278  // Swap default (local) for null
279  $data['source'] === 'local' ? null : $data['source'],
280  $data['skip']
281  ];
282  }
283 
284  // Register modules
285  $out .= "\n" . ResourceLoader::makeLoaderRegisterScript( $registrations );
286 
287  if ( $states ) {
288  $out .= "\n" . ResourceLoader::makeLoaderStateScript( $states );
289  }
290 
291  return $out;
292  }
293 
297  public function isRaw() {
298  return true;
299  }
300 
306  public static function getStartupModules() {
307  return [ 'jquery', 'mediawiki' ];
308  }
309 
310  public static function getLegacyModules() {
311  global $wgIncludeLegacyJavaScript;
312 
313  $legacyModules = [];
314  if ( $wgIncludeLegacyJavaScript ) {
315  $legacyModules[] = 'mediawiki.legacy.wikibits';
316  }
317 
318  return $legacyModules;
319  }
320 
331  $rl = $context->getResourceLoader();
332  $derivative = new DerivativeResourceLoaderContext( $context );
333  $derivative->setModules( array_merge(
334  self::getStartupModules(),
335  self::getLegacyModules()
336  ) );
337  $derivative->setOnly( 'scripts' );
338  // Must setModules() before makeVersionQuery()
339  $derivative->setVersion( $rl->makeVersionQuery( $derivative ) );
340 
341  return $rl->createLoaderURL( 'local', $derivative );
342  }
343 
349  global $IP;
350  if ( $context->getOnly() !== 'scripts' ) {
351  return '/* Requires only=script */';
352  }
353 
354  $out = file_get_contents( "$IP/resources/src/startup.js" );
355 
356  $pairs = array_map( function ( $value ) {
357  $value = FormatJson::encode( $value, ResourceLoader::inDebugMode(), FormatJson::ALL_OK );
358  // Fix indentation
359  $value = str_replace( "\n", "\n\t", $value );
360  return $value;
361  }, [
362  '$VARS.wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
363  '$VARS.configuration' => $this->getConfigSettings( $context ),
364  '$VARS.baseModulesUri' => self::getStartupModulesUrl( $context ),
365  ] );
366  $pairs['$CODE.registrations()'] = str_replace(
367  "\n",
368  "\n\t",
369  trim( $this->getModuleRegistrations( $context ) )
370  );
371 
372  return strtr( $out, $pairs );
373  }
374 
378  public function supportsURLLoading() {
379  return false;
380  }
381 
389  global $IP;
390  $summary = parent::getDefinitionSummary( $context );
391  $summary[] = [
392  // Detect changes to variables exposed in mw.config (T30899).
393  'vars' => $this->getConfigSettings( $context ),
394  // Changes how getScript() creates mw.Map for mw.config
395  'wgLegacyJavaScriptGlobals' => $this->getConfig()->get( 'LegacyJavaScriptGlobals' ),
396  // Detect changes to the module registrations
397  'moduleHashes' => $this->getAllModuleHashes( $context ),
398 
399  'fileMtimes' => [
400  filemtime( "$IP/resources/src/startup.js" ),
401  ],
402  ];
403  return $summary;
404  }
405 
413  $rl = $context->getResourceLoader();
414  // Preload for getCombinedVersion()
415  $rl->preloadModuleInfo( $rl->getModuleNames(), $context );
416 
417  // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
418  // Think carefully before making changes to this code!
419  // Pre-populate versionHash with something because the loop over all modules below includes
420  // the startup module (this module).
421  // See ResourceLoaderModule::getVersionHash() for usage of this cache.
422  $this->versionHash[$context->getHash()] = null;
423 
424  return $rl->getCombinedVersion( $context, $rl->getModuleNames() );
425  }
426 
430  public function getGroup() {
431  return 'startup';
432  }
433 }
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
$context
error also a ContextSource you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition: hooks.txt:2612
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:265
ResourceLoaderStartUpModule\getDefinitionSummary
getDefinitionSummary(ResourceLoaderContext $context)
Get the definition summary for this module.
Definition: ResourceLoaderStartUpModule.php:388
ResourceLoaderStartUpModule\getModuleRegistrations
getModuleRegistrations(ResourceLoaderContext $context)
Get registration code for all modules.
Definition: ResourceLoaderStartUpModule.php:195
ContextSource\msg
msg()
Get a Message object with context set Parameters are the same as wfMessage()
Definition: ContextSource.php:187
ResourceLoaderStartUpModule\getAllModuleHashes
getAllModuleHashes(ResourceLoaderContext $context)
Helper method for getDefinitionSummary().
Definition: ResourceLoaderStartUpModule.php:412
ResourceLoaderModule\$versionHash
$versionHash
Definition: ResourceLoaderModule.php:78
ResourceLoaderStartUpModule\getStartupModules
static getStartupModules()
Base modules required for the base environment of ResourceLoader.
Definition: ResourceLoaderStartUpModule.php:306
ResourceLoaderStartUpModule\$configVars
$configVars
Definition: ResourceLoaderStartUpModule.php:28
ResourceLoaderStartUpModule\getStartupModulesUrl
static getStartupModulesUrl(ResourceLoaderContext $context)
Get the load URL of the startup modules.
Definition: ResourceLoaderStartUpModule.php:330
ContextSource\getRequest
getRequest()
Get the WebRequest object.
Definition: ContextSource.php:78
MWNamespace\getContentNamespaces
static getContentNamespaces()
Get a list of all namespace indices which are considered to contain content.
Definition: MWNamespace.php:339
Title\convertByteClassToUnicodeClass
static convertByteClassToUnicodeClass( $byteClass)
Utility method for converting a character sequence from bytes to Unicode.
Definition: Title.php:624
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:132
Skin\getSkinNames
static getSkinNames()
Fetch the set of available skins.
Definition: Skin.php:49
ContextSource\getLanguage
getLanguage()
Get the Language object.
Definition: ContextSource.php:143
ResourceLoaderStartUpModule\getLegacyModules
static getLegacyModules()
Definition: ResourceLoaderStartUpModule.php:310
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:378
wfScript
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
Definition: GlobalFunctions.php:3138
$IP
$IP
Definition: update.php:3
ContextSource\getSkin
getSkin()
Get the Skin object.
Definition: ContextSource.php:153
ResourceLoaderStartUpModule\isRaw
isRaw()
Definition: ResourceLoaderStartUpModule.php:297
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:2179
ResourceLoaderStartUpModule\getScript
getScript(ResourceLoaderContext $context)
Definition: ResourceLoaderStartUpModule.php:348
wfUrlProtocols
wfUrlProtocols( $includeProtocolRelative=true)
Returns a regular expression of url protocols.
Definition: GlobalFunctions.php:758
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2122
$value
$value
Definition: styleTest.css.php:45
ResourceLoaderStartUpModule\getGroup
getGroup()
Definition: ResourceLoaderStartUpModule.php:430
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
$resourceLoader
error also a ContextSource 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:2612
ResourceLoaderModule
Abstraction for ResourceLoader modules, with name registration and maxage functionality.
Definition: ResourceLoaderModule.php:34
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:383
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:596
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
ResourceLoaderStartUpModule\compileUnresolvedDependencies
static compileUnresolvedDependencies(array &$registryData)
Optimize the dependency tree in $this->modules.
Definition: ResourceLoaderStartUpModule.php:177
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:596
$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:783