MediaWiki  1.23.8
ResourceLoaderStartUpModule.php
Go to the documentation of this file.
1 <?php
26 
27  /* Protected Members */
28 
29  protected $modifiedTime = array();
30  protected $configVars = array();
31  protected $targets = array( 'desktop', 'mobile' );
32 
33  /* Protected Methods */
34 
39  protected function getConfig( $context ) {
40 
41  $hash = $context->getHash();
42  if ( isset( $this->configVars[$hash] ) ) {
43  return $this->configVars[$hash];
44  }
45 
46  global $wgLoadScript, $wgScript, $wgStylePath, $wgScriptExtension,
47  $wgArticlePath, $wgScriptPath, $wgServer, $wgContLang,
48  $wgVariantArticlePath, $wgActionPaths, $wgVersion,
49  $wgEnableAPI, $wgEnableWriteAPI, $wgDBname,
50  $wgSitename, $wgFileExtensions, $wgExtensionAssetsPath,
51  $wgCookiePrefix, $wgResourceLoaderMaxQueryLength,
52  $wgResourceLoaderStorageEnabled, $wgResourceLoaderStorageVersion,
53  $wgSearchType;
54 
55  $mainPage = Title::newMainPage();
56 
62  $namespaceIds = $wgContLang->getNamespaceIds();
63  $caseSensitiveNamespaces = array();
64  foreach ( MWNamespace::getCanonicalNamespaces() as $index => $name ) {
65  $namespaceIds[$wgContLang->lc( $name )] = $index;
66  if ( !MWNamespace::isCapitalized( $index ) ) {
67  $caseSensitiveNamespaces[] = $index;
68  }
69  }
70 
71  // Build list of variables
72  $vars = array(
73  'wgLoadScript' => $wgLoadScript,
74  'debug' => $context->getDebug(),
75  'skin' => $context->getSkin(),
76  'stylepath' => $wgStylePath,
77  'wgUrlProtocols' => wfUrlProtocols(),
78  'wgArticlePath' => $wgArticlePath,
79  'wgScriptPath' => $wgScriptPath,
80  'wgScriptExtension' => $wgScriptExtension,
81  'wgScript' => $wgScript,
82  'wgSearchType' => $wgSearchType,
83  'wgVariantArticlePath' => $wgVariantArticlePath,
84  // Force object to avoid "empty" associative array from
85  // becoming [] instead of {} in JS (bug 34604)
86  'wgActionPaths' => (object)$wgActionPaths,
87  'wgServer' => $wgServer,
88  'wgUserLanguage' => $context->getLanguage(),
89  'wgContentLanguage' => $wgContLang->getCode(),
90  'wgVersion' => $wgVersion,
91  'wgEnableAPI' => $wgEnableAPI,
92  'wgEnableWriteAPI' => $wgEnableWriteAPI,
93  'wgMainPageTitle' => $mainPage->getPrefixedText(),
94  'wgFormattedNamespaces' => $wgContLang->getFormattedNamespaces(),
95  'wgNamespaceIds' => $namespaceIds,
96  'wgContentNamespaces' => MWNamespace::getContentNamespaces(),
97  'wgSiteName' => $wgSitename,
98  'wgFileExtensions' => array_values( array_unique( $wgFileExtensions ) ),
99  'wgDBname' => $wgDBname,
100  // This sucks, it is only needed on Special:Upload, but I could
101  // not find a way to add vars only for a certain module
102  'wgFileCanRotate' => BitmapHandler::canRotate(),
103  'wgAvailableSkins' => Skin::getSkinNames(),
104  'wgExtensionAssetsPath' => $wgExtensionAssetsPath,
105  // MediaWiki sets cookies to have this prefix by default
106  'wgCookiePrefix' => $wgCookiePrefix,
107  'wgResourceLoaderMaxQueryLength' => $wgResourceLoaderMaxQueryLength,
108  'wgCaseSensitiveNamespaces' => $caseSensitiveNamespaces,
109  'wgLegalTitleChars' => Title::convertByteClassToUnicodeClass( Title::legalChars() ),
110  'wgResourceLoaderStorageVersion' => $wgResourceLoaderStorageVersion,
111  'wgResourceLoaderStorageEnabled' => $wgResourceLoaderStorageEnabled,
112  );
113 
114  wfRunHooks( 'ResourceLoaderGetConfigVars', array( &$vars ) );
115 
116  $this->configVars[$hash] = $vars;
117  return $this->configVars[$hash];
118  }
119 
126  public static function getModuleRegistrations( ResourceLoaderContext $context ) {
127  global $wgCacheEpoch;
128  wfProfileIn( __METHOD__ );
129 
130  $resourceLoader = $context->getResourceLoader();
131  $target = $context->getRequest()->getVal( 'target', 'desktop' );
132 
133  $out = '';
134  $registryData = array();
135 
136  // Get registry data
137  foreach ( $resourceLoader->getModuleNames() as $name ) {
138  $module = $resourceLoader->getModule( $name );
139  $moduleTargets = $module->getTargets();
140  if ( !in_array( $target, $moduleTargets ) ) {
141  continue;
142  }
143 
144  // getModifiedTime() is supposed to return a UNIX timestamp, but it doesn't always
145  // seem to do that, and custom implementations might forget. Coerce it to TS_UNIX
146  $moduleMtime = wfTimestamp( TS_UNIX, $module->getModifiedTime( $context ) );
147  $mtime = max( $moduleMtime, wfTimestamp( TS_UNIX, $wgCacheEpoch ) );
148 
149  // FIXME: Convert to numbers, wfTimestamp always gives us stings, even for TS_UNIX
150 
151  $registryData[ $name ] = array(
152  'version' => $mtime,
153  'dependencies' => $module->getDependencies(),
154  'group' => $module->getGroup(),
155  'source' => $module->getSource(),
156  'loader' => $module->getLoaderScript(),
157  );
158  }
159 
160  // Register sources
162 
163  // Concatenate module loader scripts and figure out the different call
164  // signatures for mw.loader.register
165  $registrations = array();
166  foreach ( $registryData as $name => $data ) {
167  if ( $data['loader'] !== false ) {
169  $name,
170  wfTimestamp( TS_ISO_8601_BASIC, $data['version'] ),
171  $data['dependencies'],
172  $data['group'],
173  $data['source'],
174  $data['loader']
175  );
176  continue;
177  }
178 
179  if (
180  !count( $data['dependencies'] ) &&
181  $data['group'] === null &&
182  $data['source'] === 'local'
183  ) {
184  // Modules without dependencies, a group or a foreign source;
185  // call mw.loader.register(name, timestamp)
186  $registrations[] = array( $name, $data['version'] );
187  } elseif ( $data['group'] === null && $data['source'] === 'local' ) {
188  // Modules with dependencies but no group or foreign source;
189  // call mw.loader.register(name, timestamp, dependencies)
190  $registrations[] = array( $name, $data['version'], $data['dependencies'] );
191  } elseif ( $data['source'] === 'local' ) {
192  // Modules with a group but no foreign source;
193  // call mw.loader.register(name, timestamp, dependencies, group)
194  $registrations[] = array(
195  $name,
196  $data['version'],
197  $data['dependencies'],
198  $data['group']
199  );
200  } else {
201  // Modules with a foreign source;
202  // call mw.loader.register(name, timestamp, dependencies, group, source)
203  $registrations[] = array(
204  $name,
205  $data['version'],
206  $data['dependencies'],
207  $data['group'],
208  $data['source']
209  );
210  }
211  }
212 
213  // Register modules
214  $out .= ResourceLoader::makeLoaderRegisterScript( $registrations );
215 
216  wfProfileOut( __METHOD__ );
217  return $out;
218  }
219 
220  /* Methods */
221 
225  public function isRaw() {
226  return true;
227  }
228 
238  public static function getStartupModulesUrl( ResourceLoaderContext $context ) {
239  // The core modules:
240  $moduleNames = array( 'jquery', 'mediawiki' );
241  wfRunHooks( 'ResourceLoaderGetStartupModules', array( &$moduleNames ), '1.23' );
242 
243  // Get the latest version
244  $loader = $context->getResourceLoader();
245  $version = 0;
246  foreach ( $moduleNames as $moduleName ) {
247  $version = max( $version,
248  $loader->getModule( $moduleName )->getModifiedTime( $context )
249  );
250  }
251 
252  $query = array(
253  'modules' => ResourceLoader::makePackedModulesString( $moduleNames ),
254  'only' => 'scripts',
255  'lang' => $context->getLanguage(),
256  'skin' => $context->getSkin(),
257  'debug' => $context->getDebug() ? 'true' : 'false',
258  'version' => wfTimestamp( TS_ISO_8601_BASIC, $version )
259  );
260  // Ensure uniform query order
261  ksort( $query );
262  return wfAppendQuery( wfScript( 'load' ), $query );
263  }
264 
269  public function getScript( ResourceLoaderContext $context ) {
270  global $IP, $wgLegacyJavaScriptGlobals;
271 
272  $out = file_get_contents( "$IP/resources/src/startup.js" );
273  if ( $context->getOnly() === 'scripts' ) {
274 
275  // Startup function
276  $configuration = $this->getConfig( $context );
277  $registrations = self::getModuleRegistrations( $context );
278  // Fix indentation
279  $registrations = str_replace( "\n", "\n\t", trim( $registrations ) );
280  $out .= "var startUp = function () {\n" .
281  "\tmw.config = new " .
282  Xml::encodeJsCall( 'mw.Map', array( $wgLegacyJavaScriptGlobals ) ) . "\n" .
283  "\t$registrations\n" .
284  "\t" . Xml::encodeJsCall( 'mw.config.set', array( $configuration ) ) .
285  "};\n";
286 
287  // Conditional script injection
288  $scriptTag = Html::linkedScript( self::getStartupModulesUrl( $context ) );
289  $out .= "if ( isCompatible() ) {\n" .
290  "\t" . Xml::encodeJsCall( 'document.write', array( $scriptTag ) ) .
291  "}";
292  }
293 
294  return $out;
295  }
296 
300  public function supportsURLLoading() {
301  return false;
302  }
303 
308  public function getModifiedTime( ResourceLoaderContext $context ) {
309  global $IP, $wgCacheEpoch;
310 
311  $hash = $context->getHash();
312  if ( isset( $this->modifiedTime[$hash] ) ) {
313  return $this->modifiedTime[$hash];
314  }
315 
316  // Call preloadModuleInfo() on ALL modules as we're about
317  // to call getModifiedTime() on all of them
318  $loader = $context->getResourceLoader();
319  $loader->preloadModuleInfo( $loader->getModuleNames(), $context );
320 
321  $time = max(
322  wfTimestamp( TS_UNIX, $wgCacheEpoch ),
323  filemtime( "$IP/resources/src/startup.js" ),
324  $this->getHashMtime( $context )
325  );
326 
327  // ATTENTION!: Because of the line below, this is not going to cause
328  // infinite recursion - think carefully before making changes to this
329  // code!
330  // Pre-populate modifiedTime with something because the the loop over
331  // all modules below includes the the startup module (this module).
332  $this->modifiedTime[$hash] = 1;
333 
334  foreach ( $loader->getModuleNames() as $name ) {
335  $module = $loader->getModule( $name );
336  $time = max( $time, $module->getModifiedTime( $context ) );
337  }
338 
339  $this->modifiedTime[$hash] = $time;
340  return $this->modifiedTime[$hash];
341  }
342 
351  public function getModifiedHash( ResourceLoaderContext $context ) {
352  global $wgLegacyJavaScriptGlobals;
353 
354  $data = array(
355  'vars' => $this->getConfig( $context ),
356  'wgLegacyJavaScriptGlobals' => $wgLegacyJavaScriptGlobals,
357  );
358 
359  return md5( serialize( $data ) );
360  }
361 
365  public function getGroup() {
366  return 'startup';
367  }
368 }
ResourceLoaderStartUpModule\$targets
$targets
Definition: ResourceLoaderStartUpModule.php:31
ResourceLoaderContext
Object passed around to modules which contains information about the state of a specific loader reque...
Definition: ResourceLoaderContext.php:29
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
$time
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition: hooks.txt:1358
$wgActionPaths
$wgActionPaths
Definition: img_auth.php:49
php
skin txt MediaWiki includes four core it has been set as the default in MediaWiki since the replacing Monobook it had been been the default skin since before being replaced by Vector largely rewritten in while keeping its appearance Several legacy skins were removed in the as the burden of supporting them became too heavy to bear Those in etc for skin dependent CSS etc for skin dependent JavaScript These can also be customised on a per user by etc This feature has led to a wide variety of user styles becoming that gallery is a good place to ending in php
Definition: skin.txt:62
ResourceLoaderContext\getResourceLoader
getResourceLoader()
Definition: ResourceLoaderContext.php:122
ResourceLoader\makeLoaderSourcesScript
static makeLoaderSourcesScript( $id, $properties=null)
Returns JS code which calls mw.loader.addSource() with the given parameters.
Definition: ResourceLoader.php:1115
BitmapHandler\canRotate
static canRotate()
Returns whether the current scaler supports rotation (im and gd do)
Definition: Bitmap.php:743
ResourceLoaderModule\getHashMtime
getHashMtime(ResourceLoaderContext $context)
Helper method for calculating when the module's hash (if it has one) changed.
Definition: ResourceLoaderModule.php:404
Title\newMainPage
static newMainPage()
Create a new Title for the Main Page.
Definition: Title.php:441
ResourceLoader\makePackedModulesString
static makePackedModulesString( $modules)
Convert an array of module names to a packed query string.
Definition: ResourceLoader.php:1165
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:2483
ResourceLoaderStartUpModule\getModuleRegistrations
static getModuleRegistrations(ResourceLoaderContext $context)
Get registration code for all modules.
Definition: ResourceLoaderStartUpModule.php:126
ResourceLoaderStartUpModule\getConfig
getConfig( $context)
Definition: ResourceLoaderStartUpModule.php:39
ResourceLoaderStartUpModule\$configVars
$configVars
Definition: ResourceLoaderStartUpModule.php:30
wfProfileIn
wfProfileIn( $functionname)
Begin profiling of a function.
Definition: Profiler.php:33
ResourceLoaderStartUpModule\getStartupModulesUrl
static getStartupModulesUrl(ResourceLoaderContext $context)
Get the load URL of the startup modules.
Definition: ResourceLoaderStartUpModule.php:238
ResourceLoaderStartUpModule\$modifiedTime
$modifiedTime
Definition: ResourceLoaderStartUpModule.php:29
$wgCookiePrefix
if( $wgRCFilterByAge) if( $wgSkipSkin) if( $wgLocalInterwiki) if( $wgSharedPrefix===false) if(! $wgCookiePrefix) $wgCookiePrefix
Definition: Setup.php:286
ResourceLoaderStartUpModule\getModifiedTime
getModifiedTime(ResourceLoaderContext $context)
Definition: ResourceLoaderStartUpModule.php:308
$resourceLoader
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled also a ContextSource error or success such as when responding to a resource loader request or generating HTML output & $resourceLoader
Definition: hooks.txt:1956
$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
ResourceLoaderContext\getOnly
getOnly()
Definition: ResourceLoaderContext.php:189
MWNamespace\getContentNamespaces
static getContentNamespaces()
Get a list of all namespace indices which are considered to contain content.
Definition: Namespace.php:334
Title\convertByteClassToUnicodeClass
static convertByteClassToUnicodeClass( $byteClass)
Utility method for converting a character sequence from bytes to Unicode.
Definition: Title.php:572
Skin\getSkinNames
static getSkinNames()
Fetch the set of available skins.
Definition: Skin.php:44
wfAppendQuery
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
Definition: GlobalFunctions.php:459
ResourceLoader\makeLoaderRegisterScript
static makeLoaderRegisterScript( $name, $version=null, $dependencies=null, $group=null, $source=null)
Returns JS code which calls mw.loader.register with the given parameters.
Definition: ResourceLoader.php:1082
Xml\encodeJsCall
static encodeJsCall( $name, $args, $pretty=false)
Create a call to a JavaScript function.
Definition: Xml.php:665
ResourceLoaderStartUpModule\supportsURLLoading
supportsURLLoading()
Definition: ResourceLoaderStartUpModule.php:300
$out
$out
Definition: UtfNormalGenerate.php:167
$wgDBname
controlled by $wgMainCacheType controlled by $wgParserCacheType controlled by $wgMessageCacheType If you set CACHE_NONE to one of the three control default value for MediaWiki still create a but requests to it are no ops and we always fall through to the database If the cache daemon can t be it should also disable itself fairly smoothly By $wgMemc is used but when it is $parserMemc or $messageMemc this is mentioned $wgDBname
Definition: memcached.txt:96
ResourceLoaderContext\getRequest
getRequest()
Definition: ResourceLoaderContext.php:129
wfScript
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
Definition: GlobalFunctions.php:3739
Html\linkedScript
static linkedScript( $url)
Output a "<script>" tag linking to the given URL, e.g., "<script src=foo.js></script>".
Definition: Html.php:589
ResourceLoaderContext\getDebug
getDebug()
Definition: ResourceLoaderContext.php:182
wfProfileOut
wfProfileOut( $functionname='missing')
Stop profiling of a function.
Definition: Profiler.php:46
ResourceLoaderStartUpModule\isRaw
isRaw()
Definition: ResourceLoaderStartUpModule.php:225
wfRunHooks
wfRunHooks( $event, array $args=array(), $deprecatedVersion=null)
Call hook functions defined in $wgHooks.
Definition: GlobalFunctions.php:4010
array
the array() calling protocol came about after MediaWiki 1.4rc1.
List of Api Query prop modules.
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
$wgFileExtensions
if(! $wgHtml5Version && $wgAllowRdfaAttributes) $wgFileExtensions
Definition: Setup.php:362
ResourceLoaderContext\getLanguage
getLanguage()
Definition: ResourceLoaderContext.php:143
ResourceLoaderStartUpModule\getScript
getScript(ResourceLoaderContext $context)
Definition: ResourceLoaderStartUpModule.php:269
wfUrlProtocols
wfUrlProtocols( $includeProtocolRelative=true)
Returns a regular expression of url protocols.
Definition: GlobalFunctions.php:695
TS_ISO_8601_BASIC
const TS_ISO_8601_BASIC
ISO 8601 basic format with no timezone: 19860209T200000Z.
Definition: GlobalFunctions.php:2472
ResourceLoaderStartUpModule\getModifiedHash
getModifiedHash(ResourceLoaderContext $context)
Hash of all dynamic data embedded in getScript().
Definition: ResourceLoaderStartUpModule.php:351
ResourceLoaderStartUpModule\getGroup
getGroup()
Definition: ResourceLoaderStartUpModule.php:365
ResourceLoaderStartUpModule
Definition: ResourceLoaderStartUpModule.php:25
ResourceLoaderModule\$name
$name
Definition: ResourceLoaderModule.php:60
$version
$version
Definition: parserTests.php:86
ResourceLoaderContext\getSkin
getSkin()
Definition: ResourceLoaderContext.php:168
$hash
return false to override stock group addition can be modified try getUserPermissionsErrors userCan checks are continued by internal code can override on output return false to not delete it return false to override the default password checks & $hash
Definition: hooks.txt:2697
$wgArticlePath
$wgArticlePath
Definition: img_auth.php:48
ResourceLoaderModule
Abstraction for resource loader modules, with name registration and maxage functionality.
Definition: ResourceLoaderModule.php:28
TS_UNIX
const TS_UNIX
Unix time - the number of seconds since 1970-01-01 00:00:00 UTC.
Definition: GlobalFunctions.php:2426
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: Namespace.php:218
MWNamespace\isCapitalized
static isCapitalized( $index)
Is the namespace first-letter capitalized?
Definition: Namespace.php:378
ResourceLoader\makeCustomLoaderScript
static makeCustomLoaderScript( $name, $version, $dependencies, $group, $source, $script)
Returns JS code which calls the script given by $script.
Definition: ResourceLoader.php:1049
Title\legalChars
static legalChars()
Get a regex character class describing the legal characters in a link.
Definition: Title.php:529
ResourceLoaderContext\getHash
getHash()
Definition: ResourceLoaderContext.php:231
$vars
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition: hooks.txt:1679
$query
return true to allow those checks to and false if checking is done use this to change the tables headers temp or archived zone change it to an object instance and return false override the list derivative used the name of the old file when set the default code will be skipped add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition: hooks.txt:1105
$IP
$IP
Definition: WebStart.php:88