MediaWiki  master
ResourceLoaderStartUpModule.php
Go to the documentation of this file.
1 <?php
24 
43  protected $targets = [ 'desktop', 'mobile' ];
44 
45  private $groupIds = [
46  // These reserved numbers MUST start at 0 and not skip any. These are preset
47  // for forward compatiblity so that they can be safely referenced by mediawiki.js,
48  // even when the code is cached and the order of registrations (and implicit
49  // group ids) changes between versions of the software.
50  'user' => 0,
51  'private' => 1,
52  ];
53 
58  private function getConfigSettings( $context ) {
59  $conf = $this->getConfig();
60 
66  $contLang = MediaWikiServices::getInstance()->getContentLanguage();
67  $namespaceIds = $contLang->getNamespaceIds();
68  $caseSensitiveNamespaces = [];
69  $nsInfo = MediaWikiServices::getInstance()->getNamespaceInfo();
70  foreach ( $nsInfo->getCanonicalNamespaces() as $index => $name ) {
71  $namespaceIds[$contLang->lc( $name )] = $index;
72  if ( !$nsInfo->isCapitalized( $index ) ) {
73  $caseSensitiveNamespaces[] = $index;
74  }
75  }
76 
77  $illegalFileChars = $conf->get( 'IllegalFileChars' );
78 
79  // Build list of variables
80  $skin = $context->getSkin();
81  $vars = [
82  'debug' => $context->getDebug(),
83  'skin' => $skin,
84  'stylepath' => $conf->get( 'StylePath' ),
85  'wgUrlProtocols' => wfUrlProtocols(),
86  'wgArticlePath' => $conf->get( 'ArticlePath' ),
87  'wgScriptPath' => $conf->get( 'ScriptPath' ),
88  'wgScript' => $conf->get( 'Script' ),
89  'wgSearchType' => $conf->get( 'SearchType' ),
90  'wgVariantArticlePath' => $conf->get( 'VariantArticlePath' ),
91  // Force object to avoid "empty" associative array from
92  // becoming [] instead of {} in JS (T36604)
93  'wgActionPaths' => (object)$conf->get( 'ActionPaths' ),
94  'wgServer' => $conf->get( 'Server' ),
95  'wgServerName' => $conf->get( 'ServerName' ),
96  'wgUserLanguage' => $context->getLanguage(),
97  'wgContentLanguage' => $contLang->getCode(),
98  'wgTranslateNumerals' => $conf->get( 'TranslateNumerals' ),
99  'wgVersion' => $conf->get( 'Version' ),
100  'wgEnableAPI' => true, // Deprecated since MW 1.32
101  'wgEnableWriteAPI' => true, // Deprecated since MW 1.32
102  'wgFormattedNamespaces' => $contLang->getFormattedNamespaces(),
103  'wgNamespaceIds' => $namespaceIds,
104  'wgContentNamespaces' => $nsInfo->getContentNamespaces(),
105  'wgSiteName' => $conf->get( 'Sitename' ),
106  'wgDBname' => $conf->get( 'DBname' ),
107  'wgExtraSignatureNamespaces' => $conf->get( 'ExtraSignatureNamespaces' ),
108  'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
109  // MediaWiki sets cookies to have this prefix by default
110  'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
111  'wgCookieDomain' => $conf->get( 'CookieDomain' ),
112  'wgCookiePath' => $conf->get( 'CookiePath' ),
113  'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
114  'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
115  'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass( Title::legalChars() ),
116  'wgIllegalFileChars' => Title::convertByteClassToUnicodeClass( $illegalFileChars ),
117  'wgForeignUploadTargets' => $conf->get( 'ForeignUploadTargets' ),
118  'wgEnableUploads' => $conf->get( 'EnableUploads' ),
119  'wgCommentByteLimit' => null,
120  'wgCommentCodePointLimit' => CommentStore::COMMENT_CHARACTER_LIMIT,
121  ];
122 
123  Hooks::run( 'ResourceLoaderGetConfigVars', [ &$vars, $skin ] );
124 
125  return $vars;
126  }
127 
137  protected static function getImplicitDependencies(
138  array $registryData,
139  $moduleName,
140  array $handled = []
141  ) {
142  static $dependencyCache = [];
143 
144  // No modules will be added or changed server-side after this point,
145  // so we can safely cache parts of the tree for re-use.
146  if ( !isset( $dependencyCache[$moduleName] ) ) {
147  if ( !isset( $registryData[$moduleName] ) ) {
148  // Unknown module names are allowed here, this is only an optimisation.
149  // Checks for illegal and unknown dependencies happen as PHPUnit structure tests,
150  // and also client-side at run-time.
151  $flat = [];
152  } else {
153  $data = $registryData[$moduleName];
154  $flat = $data['dependencies'];
155 
156  // Prevent recursion
157  $handled[] = $moduleName;
158  foreach ( $data['dependencies'] as $dependency ) {
159  if ( in_array( $dependency, $handled, true ) ) {
160  // If we encounter a circular dependency, then stop the optimiser and leave the
161  // original dependencies array unmodified. Circular dependencies are not
162  // supported in ResourceLoader. Awareness of them exists here so that we can
163  // optimise the registry when it isn't broken, and otherwise transport the
164  // registry unchanged. The client will handle this further.
166  } else {
167  // Recursively add the dependencies of the dependencies
168  $flat = array_merge(
169  $flat,
170  self::getImplicitDependencies( $registryData, $dependency, $handled )
171  );
172  }
173  }
174  }
175 
176  $dependencyCache[$moduleName] = $flat;
177  }
178 
179  return $dependencyCache[$moduleName];
180  }
181 
200  public static function compileUnresolvedDependencies( array &$registryData ) {
201  foreach ( $registryData as $name => &$data ) {
202  $dependencies = $data['dependencies'];
203  try {
204  foreach ( $data['dependencies'] as $dependency ) {
205  $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
206  $dependencies = array_diff( $dependencies, $implicitDependencies );
207  }
208  } catch ( ResourceLoaderCircularDependencyError $err ) {
209  // Leave unchanged
210  $dependencies = $data['dependencies'];
211  }
212 
213  // Rebuild keys
214  $data['dependencies'] = array_values( $dependencies );
215  }
216  }
217 
225  $resourceLoader = $context->getResourceLoader();
226  // Future developers: Use WebRequest::getRawVal() instead getVal().
227  // The getVal() method performs slow Language+UTF logic. (f303bb9360)
228  $target = $context->getRequest()->getRawVal( 'target', 'desktop' );
229  $safemode = $context->getRequest()->getRawVal( 'safemode' ) === '1';
230  // Bypass target filter if this request is Special:JavaScriptTest.
231  // To prevent misuse in production, this is only allowed if testing is enabled server-side.
232  $byPassTargetFilter = $this->getConfig()->get( 'EnableJavaScriptTest' ) && $target === 'test';
233 
234  $out = '';
235  $states = [];
236  $registryData = [];
237  $moduleNames = $resourceLoader->getModuleNames();
238 
239  // Preload with a batch so that the below calls to getVersionHash() for each module
240  // don't require on-demand loading of more information.
241  try {
242  $resourceLoader->preloadModuleInfo( $moduleNames, $context );
243  } catch ( Exception $e ) {
244  // Don't fail the request (T152266)
245  // Also print the error in the main output
246  $resourceLoader->outputErrorAndLog( $e,
247  'Preloading module info from startup failed: {exception}',
248  [ 'exception' => $e ]
249  );
250  }
251 
252  // Get registry data
253  foreach ( $moduleNames as $name ) {
254  $module = $resourceLoader->getModule( $name );
255  $moduleTargets = $module->getTargets();
256  if (
257  ( !$byPassTargetFilter && !in_array( $target, $moduleTargets ) )
258  || ( $safemode && $module->getOrigin() > ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL )
259  ) {
260  continue;
261  }
262 
263  if ( $module instanceof ResourceLoaderStartUpModule ) {
264  // Don't register 'startup' to the client because loading it lazily or depending
265  // on it doesn't make sense, because the startup module *is* the client.
266  // Registering would be a waste of bandwidth and memory and risks somehow causing
267  // it to load a second time.
268 
269  // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
270  // Think carefully before making changes to this code!
271  // The below code is going to call ResourceLoaderModule::getVersionHash() for every module.
272  // For StartUpModule (this module) the hash is computed based on the manifest content,
273  // which is the very thing we are computing right here. As such, this must skip iterating
274  // over 'startup' itself.
275  continue;
276  }
277 
278  try {
279  $versionHash = $module->getVersionHash( $context );
280  } catch ( Exception $e ) {
281  // Don't fail the request (T152266)
282  // Also print the error in the main output
283  $resourceLoader->outputErrorAndLog( $e,
284  'Calculating version for "{module}" failed: {exception}',
285  [
286  'module' => $name,
287  'exception' => $e,
288  ]
289  );
290  $versionHash = '';
291  $states[$name] = 'error';
292  }
293 
294  if ( $versionHash !== '' && strlen( $versionHash ) !== 7 ) {
295  $e = new RuntimeException( "Badly formatted module version hash" );
296  $resourceLoader->outputErrorAndLog( $e,
297  "Module '{module}' produced an invalid version hash: '{version}'.",
298  [
299  'module' => $name,
300  'version' => $versionHash,
301  ]
302  );
303  // Module implementation either broken or deviated from ResourceLoader::makeHash
304  // Asserted by tests/phpunit/structure/ResourcesTest.
306  }
307 
308  $skipFunction = $module->getSkipFunction();
309  if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
310  $skipFunction = ResourceLoader::filter( 'minify-js', $skipFunction );
311  }
312 
313  $registryData[$name] = [
314  'version' => $versionHash,
315  'dependencies' => $module->getDependencies( $context ),
316  'group' => $this->getGroupId( $module->getGroup() ),
317  'source' => $module->getSource(),
318  'skip' => $skipFunction,
319  ];
320  }
321 
322  self::compileUnresolvedDependencies( $registryData );
323 
324  // Register sources
326 
327  // Figure out the different call signatures for mw.loader.register
328  $registrations = [];
329  foreach ( $registryData as $name => $data ) {
330  // Call mw.loader.register(name, version, dependencies, group, source, skip)
331  $registrations[] = [
332  $name,
333  $data['version'],
334  $data['dependencies'],
335  $data['group'],
336  // Swap default (local) for null
337  $data['source'] === 'local' ? null : $data['source'],
338  $data['skip']
339  ];
340  }
341 
342  // Register modules
343  $out .= "\n" . ResourceLoader::makeLoaderRegisterScript( $registrations );
344 
345  if ( $states ) {
346  $out .= "\n" . ResourceLoader::makeLoaderStateScript( $states );
347  }
348 
349  return $out;
350  }
351 
352  private function getGroupId( $groupName ) {
353  if ( $groupName === null ) {
354  return null;
355  }
356 
357  if ( !array_key_exists( $groupName, $this->groupIds ) ) {
358  $this->groupIds[$groupName] = count( $this->groupIds );
359  }
360 
361  return $this->groupIds[$groupName];
362  }
363 
369  private function getBaseModules() {
370  $baseModules = [ 'jquery', 'mediawiki.base' ];
371  return $baseModules;
372  }
373 
380  private function getStoreKey() {
381  return 'MediaWikiModuleStore:' . $this->getConfig()->get( 'DBname' );
382  }
383 
391  return implode( ':', [
392  $context->getSkin(),
393  $this->getConfig()->get( 'ResourceLoaderStorageVersion' ),
394  $context->getLanguage(),
395  ] );
396  }
397 
403  global $IP;
404  $conf = $this->getConfig();
405 
406  if ( $context->getOnly() !== 'scripts' ) {
407  return '/* Requires only=script */';
408  }
409 
410  $startupCode = file_get_contents( "$IP/resources/src/startup/startup.js" );
411 
412  // The files read here MUST be kept in sync with maintenance/jsduck/eg-iframe.html,
413  // and MUST be considered by 'fileHashes' in StartUpModule::getDefinitionSummary().
414  $mwLoaderCode = file_get_contents( "$IP/resources/src/startup/mediawiki.js" ) .
415  file_get_contents( "$IP/resources/src/startup/mediawiki.requestIdleCallback.js" );
416  if ( $context->getDebug() ) {
417  $mwLoaderCode .= file_get_contents( "$IP/resources/src/startup/mediawiki.log.js" );
418  }
419  if ( $conf->get( 'ResourceLoaderEnableJSProfiler' ) ) {
420  $mwLoaderCode .= file_get_contents( "$IP/resources/src/startup/profiler.js" );
421  }
422 
423  // Perform replacements for mediawiki.js
424  $mwLoaderPairs = [
425  '$VARS.reqBase' => ResourceLoader::encodeJsonForScript( $context->getReqBase() ),
426  '$VARS.baseModules' => ResourceLoader::encodeJsonForScript( $this->getBaseModules() ),
427  '$VARS.maxQueryLength' => ResourceLoader::encodeJsonForScript(
428  $conf->get( 'ResourceLoaderMaxQueryLength' )
429  ),
430  // The client-side module cache can be disabled by site configuration.
431  // It is also always disabled in debug mode.
432  '$VARS.storeEnabled' => ResourceLoader::encodeJsonForScript(
433  $conf->get( 'ResourceLoaderStorageEnabled' ) && !$context->getDebug()
434  ),
435  '$VARS.wgLegacyJavaScriptGlobals' => ResourceLoader::encodeJsonForScript(
436  $conf->get( 'LegacyJavaScriptGlobals' )
437  ),
438  '$VARS.storeKey' => ResourceLoader::encodeJsonForScript( $this->getStoreKey() ),
439  '$VARS.storeVary' => ResourceLoader::encodeJsonForScript( $this->getStoreVary( $context ) ),
440  '$VARS.groupUser' => ResourceLoader::encodeJsonForScript( $this->getGroupId( 'user' ) ),
441  '$VARS.groupPrivate' => ResourceLoader::encodeJsonForScript( $this->getGroupId( 'private' ) ),
442  ];
443  $profilerStubs = [
444  '$CODE.profileExecuteStart();' => 'mw.loader.profiler.onExecuteStart( module );',
445  '$CODE.profileExecuteEnd();' => 'mw.loader.profiler.onExecuteEnd( module );',
446  '$CODE.profileScriptStart();' => 'mw.loader.profiler.onScriptStart( module );',
447  '$CODE.profileScriptEnd();' => 'mw.loader.profiler.onScriptEnd( module );',
448  ];
449  if ( $conf->get( 'ResourceLoaderEnableJSProfiler' ) ) {
450  // When profiling is enabled, insert the calls.
451  $mwLoaderPairs += $profilerStubs;
452  } else {
453  // When disabled (by default), insert nothing.
454  $mwLoaderPairs += array_fill_keys( array_keys( $profilerStubs ), '' );
455  }
456  $mwLoaderCode = strtr( $mwLoaderCode, $mwLoaderPairs );
457 
458  // Perform string replacements for startup.js
459  $pairs = [
460  '$VARS.configuration' => ResourceLoader::encodeJsonForScript(
461  $this->getConfigSettings( $context )
462  ),
463  // Raw JavaScript code (not JSON)
464  '$CODE.registrations();' => trim( $this->getModuleRegistrations( $context ) ),
465  '$CODE.defineLoader();' => $mwLoaderCode,
466  ];
467  $startupCode = strtr( $startupCode, $pairs );
468 
469  return $startupCode;
470  }
471 
475  public function supportsURLLoading() {
476  return false;
477  }
478 
482  public function enableModuleContentVersion() {
483  // Enabling this means that ResourceLoader::getVersionHash will simply call getScript()
484  // and hash it to determine the version (as used by E-Tag HTTP response header).
485  return true;
486  }
487 }
wfUrlProtocols( $includeProtocolRelative=true)
Returns a regular expression of url protocols.
static filter( $filter, $data, array $options=[])
Run JavaScript or CSS data through a filter, caching the filtered result for future calls...
Abstraction for ResourceLoader modules, with name registration and maxage functionality.
$IP
Definition: WebStart.php:41
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:2632
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2158
static compileUnresolvedDependencies(array &$registryData)
Optimize the dependency tree in $this->modules.
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 $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
getModuleRegistrations(ResourceLoaderContext $context)
Get registration code for all modules.
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 MediaWikiServices
Definition: injection.txt:23
array $versionHash
Map of (context hash => cached module version hash)
const COMMENT_CHARACTER_LIMIT
Maximum length of a comment in UTF-8 characters.
static convertByteClassToUnicodeClass( $byteClass)
Utility method for converting a character sequence from bytes to Unicode.
Definition: Title.php:717
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password 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:773
static makeHash( $value)
getReqBase()
Get the request base parameters, omitting any defaults.
static encodeJsonForScript( $data)
Wrapper around json_encode that avoids needless escapes, and pretty-prints in debug mode...
static makeLoaderStateScript( $states, $state=null)
Returns a JS call to mw.loader.state, which sets the state of one ore more modules to a given value...
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:773
getStoreKey()
Get the localStorage key for the entire module store.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned $skin
Definition: hooks.txt:1983
getStoreVary(ResourceLoaderContext $context)
Get the key on which the JavaScript module cache (mw.loader.store) will vary.
Module for ResourceLoader initialization.
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
getBaseModules()
Base modules implicitly available to all modules.
getScript(ResourceLoaderContext $context)
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
static inDebugMode()
Determine whether debug mode was requested Order of priority is 1) request param, 2) cookie...
static getImplicitDependencies(array $registryData, $moduleName, array $handled=[])
Recursively get all explicit and implicit dependencies for to the given module.
static makeLoaderSourcesScript( $sources, $loadUrl=null)
Returns JS code which calls mw.loader.addSource() with the given parameters.
string null $name
Module name.
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:2632
static makeLoaderRegisterScript(array $modules)
Returns JS code which calls mw.loader.register with the given parameter.
static legalChars()
Get a regex character class describing the legal characters in a link.
Definition: Title.php:703
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition: hooks.txt:2216
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
Object passed around to modules which contains information about the state of a specific loader reque...