MediaWiki  master
ResourceLoaderStartUpModule.php
Go to the documentation of this file.
1 <?php
24 
43  protected $targets = [ 'desktop', 'mobile' ];
44 
49  private function getConfigSettings( $context ) {
50  $conf = $this->getConfig();
51 
57  $contLang = MediaWikiServices::getInstance()->getContentLanguage();
58  $namespaceIds = $contLang->getNamespaceIds();
59  $caseSensitiveNamespaces = [];
60  foreach ( MWNamespace::getCanonicalNamespaces() as $index => $name ) {
61  $namespaceIds[$contLang->lc( $name )] = $index;
62  if ( !MWNamespace::isCapitalized( $index ) ) {
63  $caseSensitiveNamespaces[] = $index;
64  }
65  }
66 
67  $illegalFileChars = $conf->get( 'IllegalFileChars' );
68 
69  // Build list of variables
70  $skin = $context->getSkin();
71  $vars = [
72  'wgLoadScript' => wfScript( 'load' ),
73  'debug' => $context->getDebug(),
74  'skin' => $skin,
75  'stylepath' => $conf->get( 'StylePath' ),
76  'wgUrlProtocols' => wfUrlProtocols(),
77  'wgArticlePath' => $conf->get( 'ArticlePath' ),
78  'wgScriptPath' => $conf->get( 'ScriptPath' ),
79  'wgScript' => wfScript(),
80  'wgSearchType' => $conf->get( 'SearchType' ),
81  'wgVariantArticlePath' => $conf->get( 'VariantArticlePath' ),
82  // Force object to avoid "empty" associative array from
83  // becoming [] instead of {} in JS (T36604)
84  'wgActionPaths' => (object)$conf->get( 'ActionPaths' ),
85  'wgServer' => $conf->get( 'Server' ),
86  'wgServerName' => $conf->get( 'ServerName' ),
87  'wgUserLanguage' => $context->getLanguage(),
88  'wgContentLanguage' => $contLang->getCode(),
89  'wgTranslateNumerals' => $conf->get( 'TranslateNumerals' ),
90  'wgVersion' => $conf->get( 'Version' ),
91  'wgEnableAPI' => true, // Deprecated since MW 1.32
92  'wgEnableWriteAPI' => true, // Deprecated since MW 1.32
93  'wgFormattedNamespaces' => $contLang->getFormattedNamespaces(),
94  'wgNamespaceIds' => $namespaceIds,
95  'wgContentNamespaces' => MWNamespace::getContentNamespaces(),
96  'wgSiteName' => $conf->get( 'Sitename' ),
97  'wgDBname' => $conf->get( 'DBname' ),
98  'wgExtraSignatureNamespaces' => $conf->get( 'ExtraSignatureNamespaces' ),
99  'wgExtensionAssetsPath' => $conf->get( 'ExtensionAssetsPath' ),
100  // MediaWiki sets cookies to have this prefix by default
101  'wgCookiePrefix' => $conf->get( 'CookiePrefix' ),
102  'wgCookieDomain' => $conf->get( 'CookieDomain' ),
103  'wgCookiePath' => $conf->get( 'CookiePath' ),
104  'wgCookieExpiration' => $conf->get( 'CookieExpiration' ),
105  'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
106  'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass( Title::legalChars() ),
107  'wgIllegalFileChars' => Title::convertByteClassToUnicodeClass( $illegalFileChars ),
108  'wgResourceLoaderStorageVersion' => $conf->get( 'ResourceLoaderStorageVersion' ),
109  'wgResourceLoaderStorageEnabled' => $conf->get( 'ResourceLoaderStorageEnabled' ),
110  'wgForeignUploadTargets' => $conf->get( 'ForeignUploadTargets' ),
111  'wgEnableUploads' => $conf->get( 'EnableUploads' ),
112  'wgCommentByteLimit' => null,
113  'wgCommentCodePointLimit' => CommentStore::COMMENT_CHARACTER_LIMIT,
114  ];
115 
116  Hooks::run( 'ResourceLoaderGetConfigVars', [ &$vars, $skin ] );
117 
118  return $vars;
119  }
120 
128  protected static function getImplicitDependencies( array $registryData, $moduleName ) {
129  static $dependencyCache = [];
130 
131  // The list of implicit dependencies won't be altered, so we can
132  // cache them without having to worry.
133  if ( !isset( $dependencyCache[$moduleName] ) ) {
134  if ( !isset( $registryData[$moduleName] ) ) {
135  // Dependencies may not exist
136  $dependencyCache[$moduleName] = [];
137  } else {
138  $data = $registryData[$moduleName];
139  $dependencyCache[$moduleName] = $data['dependencies'];
140 
141  foreach ( $data['dependencies'] as $dependency ) {
142  // Recursively get the dependencies of the dependencies
143  $dependencyCache[$moduleName] = array_merge(
144  $dependencyCache[$moduleName],
145  self::getImplicitDependencies( $registryData, $dependency )
146  );
147  }
148  }
149  }
150 
151  return $dependencyCache[$moduleName];
152  }
153 
172  public static function compileUnresolvedDependencies( array &$registryData ) {
173  foreach ( $registryData as $name => &$data ) {
174  $dependencies = $data['dependencies'];
175  foreach ( $data['dependencies'] as $dependency ) {
176  $implicitDependencies = self::getImplicitDependencies( $registryData, $dependency );
177  $dependencies = array_diff( $dependencies, $implicitDependencies );
178  }
179  // Rebuild keys
180  $data['dependencies'] = array_values( $dependencies );
181  }
182  }
183 
191  $resourceLoader = $context->getResourceLoader();
192  // Future developers: Use WebRequest::getRawVal() instead getVal().
193  // The getVal() method performs slow Language+UTF logic. (f303bb9360)
194  $target = $context->getRequest()->getRawVal( 'target', 'desktop' );
195  $safemode = $context->getRequest()->getRawVal( 'safemode' ) === '1';
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  $moduleNames = $resourceLoader->getModuleNames();
204 
205  // Preload with a batch so that the below calls to getVersionHash() for each module
206  // don't require on-demand loading of more information.
207  try {
208  $resourceLoader->preloadModuleInfo( $moduleNames, $context );
209  } catch ( Exception $e ) {
210  // Don't fail the request (T152266)
211  // Also print the error in the main output
212  $resourceLoader->outputErrorAndLog( $e,
213  'Preloading module info from startup failed: {exception}',
214  [ 'exception' => $e ]
215  );
216  }
217 
218  // Get registry data
219  foreach ( $moduleNames as $name ) {
220  $module = $resourceLoader->getModule( $name );
221  $moduleTargets = $module->getTargets();
222  if (
223  ( !$byPassTargetFilter && !in_array( $target, $moduleTargets ) )
224  || ( $safemode && $module->getOrigin() > ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL )
225  ) {
226  continue;
227  }
228 
229  if ( $module->isRaw() ) {
230  // Don't register "raw" modules (like 'startup') client-side because depending on them
231  // is illegal anyway and would only lead to them being loaded a second time,
232  // causing any state to be lost.
233 
234  // ATTENTION: Because of the line below, this is not going to cause infinite recursion.
235  // Think carefully before making changes to this code!
236  // The below code is going to call ResourceLoaderModule::getVersionHash() for every module.
237  // For StartUpModule (this module) the hash is computed based on the manifest content,
238  // which is the very thing we are computing right here. As such, this must skip iterating
239  // over 'startup' itself.
240  continue;
241  }
242 
243  try {
244  $versionHash = $module->getVersionHash( $context );
245  } catch ( Exception $e ) {
246  // Don't fail the request (T152266)
247  // Also print the error in the main output
248  $resourceLoader->outputErrorAndLog( $e,
249  'Calculating version for "{module}" failed: {exception}',
250  [
251  'module' => $name,
252  'exception' => $e,
253  ]
254  );
255  $versionHash = '';
256  $states[$name] = 'error';
257  }
258 
259  if ( $versionHash !== '' && strlen( $versionHash ) !== 7 ) {
260  $context->getLogger()->warning(
261  "Module '{module}' produced an invalid version hash: '{version}'.",
262  [
263  'module' => $name,
264  'version' => $versionHash,
265  ]
266  );
267  // Module implementation either broken or deviated from ResourceLoader::makeHash
268  // Asserted by tests/phpunit/structure/ResourcesTest.
270  }
271 
272  $skipFunction = $module->getSkipFunction();
273  if ( $skipFunction !== null && !ResourceLoader::inDebugMode() ) {
274  $skipFunction = ResourceLoader::filter( 'minify-js', $skipFunction );
275  }
276 
277  $registryData[$name] = [
278  'version' => $versionHash,
279  'dependencies' => $module->getDependencies( $context ),
280  'group' => $module->getGroup(),
281  'source' => $module->getSource(),
282  'skip' => $skipFunction,
283  ];
284  }
285 
286  self::compileUnresolvedDependencies( $registryData );
287 
288  // Register sources
290 
291  // Figure out the different call signatures for mw.loader.register
292  $registrations = [];
293  foreach ( $registryData as $name => $data ) {
294  // Call mw.loader.register(name, version, dependencies, group, source, skip)
295  $registrations[] = [
296  $name,
297  $data['version'],
298  $data['dependencies'],
299  $data['group'],
300  // Swap default (local) for null
301  $data['source'] === 'local' ? null : $data['source'],
302  $data['skip']
303  ];
304  }
305 
306  // Register modules
307  $out .= "\n" . ResourceLoader::makeLoaderRegisterScript( $registrations );
308 
309  if ( $states ) {
310  $out .= "\n" . ResourceLoader::makeLoaderStateScript( $states );
311  }
312 
313  return $out;
314  }
315 
319  public function isRaw() {
320  return true;
321  }
322 
332  public static function getStartupModules() {
333  wfDeprecated( __METHOD__, '1.32' );
334  return [];
335  }
336 
341  public static function getLegacyModules() {
342  wfDeprecated( __METHOD__, '1.32' );
343  return [];
344  }
345 
351  public function getBaseModulesInternal() {
352  return $this->getBaseModules();
353  }
354 
360  private function getBaseModules() {
362 
363  $baseModules = [ 'jquery', 'mediawiki.base' ];
364  if ( $wgIncludeLegacyJavaScript ) {
365  $baseModules[] = 'mediawiki.legacy.wikibits';
366  }
367 
368  return $baseModules;
369  }
370 
376  global $IP;
377  $conf = $this->getConfig();
378 
379  if ( $context->getOnly() !== 'scripts' ) {
380  return '/* Requires only=script */';
381  }
382 
383  $startupCode = file_get_contents( "$IP/resources/src/startup/startup.js" );
384 
385  // The files read here MUST be kept in sync with maintenance/jsduck/eg-iframe.html,
386  // and MUST be considered by 'fileHashes' in StartUpModule::getDefinitionSummary().
387  $mwLoaderCode = file_get_contents( "$IP/resources/src/startup/mediawiki.js" ) .
388  file_get_contents( "$IP/resources/src/startup/mediawiki.requestIdleCallback.js" );
389  if ( $context->getDebug() ) {
390  $mwLoaderCode .= file_get_contents( "$IP/resources/src/startup/mediawiki.log.js" );
391  }
392  if ( $conf->get( 'ResourceLoaderEnableJSProfiler' ) ) {
393  $mwLoaderCode .= file_get_contents( "$IP/resources/src/startup/profiler.js" );
394  }
395 
396  // Perform replacements for mediawiki.js
397  $mwLoaderPairs = [
398  '$VARS.baseModules' => ResourceLoader::encodeJsonForScript( $this->getBaseModules() ),
399  '$VARS.maxQueryLength' => ResourceLoader::encodeJsonForScript(
400  $conf->get( 'ResourceLoaderMaxQueryLength' )
401  ),
402  ];
403  $profilerStubs = [
404  '$CODE.profileExecuteStart();' => 'mw.loader.profiler.onExecuteStart( module );',
405  '$CODE.profileExecuteEnd();' => 'mw.loader.profiler.onExecuteEnd( module );',
406  '$CODE.profileScriptStart();' => 'mw.loader.profiler.onScriptStart( module );',
407  '$CODE.profileScriptEnd();' => 'mw.loader.profiler.onScriptEnd( module );',
408  ];
409  if ( $conf->get( 'ResourceLoaderEnableJSProfiler' ) ) {
410  // When profiling is enabled, insert the calls.
411  $mwLoaderPairs += $profilerStubs;
412  } else {
413  // When disabled (by default), insert nothing.
414  $mwLoaderPairs += array_fill_keys( array_keys( $profilerStubs ), '' );
415  }
416  $mwLoaderCode = strtr( $mwLoaderCode, $mwLoaderPairs );
417 
418  // Perform string replacements for startup.js
419  $pairs = [
420  '$VARS.wgLegacyJavaScriptGlobals' => ResourceLoader::encodeJsonForScript(
421  $conf->get( 'LegacyJavaScriptGlobals' )
422  ),
423  '$VARS.configuration' => ResourceLoader::encodeJsonForScript(
424  $this->getConfigSettings( $context )
425  ),
426  // Raw JavaScript code (not JSON)
427  '$CODE.registrations();' => trim( $this->getModuleRegistrations( $context ) ),
428  '$CODE.defineLoader();' => $mwLoaderCode,
429  ];
430  $startupCode = strtr( $startupCode, $pairs );
431 
432  return $startupCode;
433  }
434 
438  public function supportsURLLoading() {
439  return false;
440  }
441 
445  public function enableModuleContentVersion() {
446  // Enabling this means that ResourceLoader::getVersionHash will simply call getScript()
447  // and hash it to determine the version (as used by E-Tag HTTP response header).
448  return true;
449  }
450 
454  public function getGroup() {
455  return 'startup';
456  }
457 }
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
wfUrlProtocols( $includeProtocolRelative=true)
Returns a regular expression of url protocols.
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
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.
static getImplicitDependencies(array $registryData, $moduleName)
Recursively get all explicit and implicit dependencies for to the given module.
$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:2633
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:2159
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.
static getCanonicalNamespaces()
Returns array of all defined namespaces with their canonical (English) names.
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
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:714
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
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:780
static makeHash( $value)
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...
static getContentNamespaces()
Get a list of all namespace indices which are considered to contain content.
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:780
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:1982
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
$wgIncludeLegacyJavaScript
Whether to ensure the mediawiki.legacy library is loaded before other modules.
getBaseModules()
Base modules implicitly available to all modules.
static getStartupModules()
Internal modules used by ResourceLoader that cannot be depended on.
getScript(ResourceLoaderContext $context)
static isCapitalized( $index)
Is the namespace first-letter capitalized?
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...
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
static makeLoaderSourcesScript( $sources, $loadUrl=null)
Returns JS code which calls mw.loader.addSource() with the given parameters.
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:2633
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:700
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition: hooks.txt:2217
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...