26use Psr\Log\LoggerAwareInterface;
27use Psr\Log\LoggerInterface;
28use Psr\Log\NullLogger;
29use WrappedString\WrappedString;
93 const FILTER_NOMIN =
'/*@nomin*/';
110 if ( !$moduleNames ) {
119 $vary =
"$skin|$lang";
120 $res =
$dbr->select(
'module_deps', [
'md_module',
'md_deps' ], [
121 'md_module' => $moduleNames,
127 $modulesWithDeps = [];
128 foreach (
$res as $row ) {
129 $module = $this->
getModule( $row->md_module );
132 FormatJson::decode( $row->md_deps,
true )
134 $modulesWithDeps[] = $row->md_module;
138 foreach ( array_diff( $moduleNames, $modulesWithDeps )
as $name ) {
150 foreach ( $moduleNames
as $name ) {
152 if ( $module && $module->getMessages() ) {
181 if ( strpos( $data, ResourceLoader::FILTER_NOMIN ) !==
false ) {
189 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
192 $key =
$cache->makeGlobalKey(
196 self::$filterCacheVersion, md5( $data )
201 $stats->increment(
"resourceloader_cache.$filter.miss" );
205 $stats->increment(
"resourceloader_cache.$filter.hit" );
216 $data = trim( $data );
219 $data = ( $filter ===
'minify-css' )
222 }
catch ( Exception
$e ) {
223 MWExceptionHandler::logException(
$e );
240 $this->logger =
$logger ?:
new NullLogger();
243 $this->logger->debug( __METHOD__ .
' was called without providing a Config instance' );
244 $config = MediaWikiServices::getInstance()->getMainConfig();
255 $this->
register( include
"$IP/resources/Resources.php" );
256 $this->
register( include
"$IP/resources/ResourcesOOUI.php" );
258 $this->
register(
$config->get(
'ResourceModules' ) );
262 Hooks::run(
'ResourceLoaderRegisterModules', [ &$rl ] );
264 if (
$config->get(
'EnableJavaScriptTest' ) ===
true ) {
323 public function register(
$name, $info = null ) {
324 $moduleSkinStyles = $this->config->
get(
'ResourceModuleSkinStyles' );
328 foreach ( $registrations
as $name => $info ) {
330 if ( isset( $this->moduleInfos[
$name] ) ) {
332 $this->logger->warning(
333 'ResourceLoader duplicate registration warning. ' .
334 'Another module has already been registered as ' .
$name
339 if ( !self::isValidModuleName(
$name ) ) {
340 throw new MWException(
"ResourceLoader module name '$name' is invalid, "
341 .
"see ResourceLoader::isValidModuleName()" );
346 $this->moduleInfos[
$name] = [
'object' => $info ];
347 $info->setName(
$name );
348 $this->modules[
$name] = $info;
349 } elseif ( is_array( $info ) ) {
351 $this->moduleInfos[
$name] = $info;
354 'ResourceLoader module info type error for module \'' .
$name .
359 // Last-minute changes
361 // Apply custom skin-defined styles to existing modules.
362 if ( $this->isFileModule( $name ) ) {
363 foreach ( $moduleSkinStyles as $skinName => $skinStyles ) {
364 // If this module already defines skinStyles for this skin, ignore $wgResourceModuleSkinStyles.
365 if ( isset( $this->moduleInfos[$name]['skinStyles
'][$skinName] ) ) {
369 // If $name is preceded with a '+
', the defined style files will be added to 'default'
370 // skinStyles, otherwise 'default' will be ignored as it normally would be.
371 if ( isset( $skinStyles[$name] ) ) {
372 $paths = (array)$skinStyles[$name];
374 } elseif ( isset( $skinStyles['+
' . $name] ) ) {
375 $paths = (array)$skinStyles['+
' . $name];
376 $styleFiles = isset( $this->moduleInfos[$name]['skinStyles
']['default'] ) ?
377 (array)$this->moduleInfos[$name]['skinStyles
']['default'] :
383 // Add new file paths, remapping them to refer to our directories and not use settings
384 // from the module we're modifying, which come
from the base
definition.
385 list( $localBasePath, $remoteBasePath ) =
392 $this->moduleInfos[
$name][
'skinStyles'][$skinName] = $styleFiles;
401 if ( $this->config->get(
'EnableJavaScriptTest' ) !==
true ) {
402 throw new MWException(
'Attempt to register JavaScript test modules '
403 .
'but <code>$wgEnableJavaScriptTest</code> is false. '
404 .
'Edit your <code>LocalSettings.php</code> to enable it.' );
409 $testModules[
'qunit'] = [];
413 Hooks::run(
'ResourceLoaderTestModules', [ &$testModules, &$rl ] );
417 foreach ( $testModules[
'qunit']
as &$module ) {
421 $module[
'position'] =
'top';
422 $module[
'dependencies'][] =
'test.mediawiki.qunit.testrunner';
425 $testModules[
'qunit'] =
426 ( include
"$IP/tests/qunit/QUnitTestResources.php" ) + $testModules[
'qunit'];
428 foreach ( $testModules
as $id => $names ) {
430 $this->
register( $testModules[$id] );
433 $this->testModuleNames[$id] = array_keys( $testModules[$id] );
449 if ( is_array( $id ) ) {
451 $this->addSource( $key,
$value );
457 if ( isset( $this->sources[$id] ) ) {
459 'ResourceLoader duplicate source addition error. ' .
460 'Another source has already been registered as ' . $id
465 if ( is_array( $loadUrl ) ) {
466 if ( !isset( $loadUrl[
'loadScript'] ) ) {
468 __METHOD__ .
' was passed an array with no "loadScript" key.'
472 $loadUrl = $loadUrl[
'loadScript'];
475 $this->sources[$id] = $loadUrl;
484 return array_keys( $this->moduleInfos );
499 if ( $framework ==
'all' ) {
500 return $this->testModuleNames;
501 } elseif ( isset( $this->testModuleNames[$framework] )
502 && is_array( $this->testModuleNames[$framework] )
504 return $this->testModuleNames[$framework];
518 return isset( $this->moduleInfos[
$name] );
533 if ( !isset( $this->modules[
$name] ) ) {
534 if ( !isset( $this->moduleInfos[
$name] ) ) {
539 $info = $this->moduleInfos[
$name];
541 if ( isset( $info[
'object'] ) ) {
543 $object = $info[
'object'];
545 if ( !isset( $info[
'class'] ) ) {
546 $class =
'ResourceLoaderFileModule';
548 $class = $info[
'class'];
551 $object =
new $class( $info );
552 $object->setConfig( $this->getConfig() );
553 $object->setLogger( $this->logger );
555 $object->setName(
$name );
556 $this->modules[
$name] = $object;
559 return $this->modules[
$name];
569 if ( !isset( $this->moduleInfos[
$name] ) ) {
572 $info = $this->moduleInfos[
$name];
573 if ( isset( $info[
'object'] ) || isset( $info[
'class'] ) ) {
585 return $this->sources;
598 if ( !isset( $this->sources[
$source] ) ) {
599 throw new MWException(
"The $source source was never registered in ResourceLoader." );
601 return $this->sources[
$source];
610 $hash = hash(
'fnv132',
$value );
611 return Wikimedia\base_convert( $hash, 16, 36, 7 );
625 MWExceptionHandler::logException(
$e );
626 $this->logger->warning(
630 $this->
errors[] = self::formatExceptionNoComment(
$e );
642 if ( !$moduleNames ) {
647 return $this->getModule( $module )->getVersionHash(
$context );
648 }
catch ( Exception
$e ) {
652 $this->outputErrorAndLog(
$e,
653 'Calculating version for "{module}" failed: {exception}',
661 return self::makeHash( implode(
'',
$hashes ) );
686 if ( !$this->getModule(
$name ) ) {
691 $moduleNames[] =
$name;
693 return $this->getCombinedVersion(
$context, $moduleNames );
715 $module = $this->getModule(
$name );
719 if ( $module->getGroup() ===
'private' ) {
720 $this->logger->debug(
"Request for private module '$name' denied" );
721 $this->
errors[] =
"Cannot show private module \"$name\"";
733 }
catch ( Exception
$e ) {
734 $this->outputErrorAndLog(
$e,
'Preloading module info failed: {exception}' );
740 $versionHash = $this->getCombinedVersion(
$context, array_keys(
$modules ) );
741 }
catch ( Exception
$e ) {
742 $this->outputErrorAndLog(
$e,
'Calculating version hash failed: {exception}' );
747 $etag =
'W/"' . $versionHash .
'"';
750 if ( $this->tryRespondNotModified(
$context, $etag ) ) {
755 if ( $this->config->get(
'UseFileCache' ) ) {
757 if ( $this->tryRespondFromFileCache( $fileCache,
$context, $etag ) ) {
768 $warnings = ob_get_contents();
769 if ( strlen( $warnings ) ) {
770 $this->
errors[] = $warnings;
775 if ( isset( $fileCache ) && !$this->
errors && !count( $missing ) ) {
778 if ( $fileCache->isCacheWorthy() ) {
786 $this->sendResponseHeaders(
$context, $etag, (
bool)$this->
errors );
791 if (
$context->getImageObj() && $this->errors ) {
793 $response = implode(
"\n\n", $this->errors );
794 } elseif ( $this->errors ) {
795 $errorText = implode(
"\n\n", $this->errors );
796 $errorResponse = self::makeComment( $errorText );
797 if (
$context->shouldIncludeScripts() ) {
798 $errorResponse .=
'if (window.console && console.error) {'
799 . Xml::encodeJsCall(
'console.error', [ $errorText ] )
822 \MediaWiki\HeaderCallback::warnIfHeadersSent();
823 $rlMaxage = $this->config->get(
'ResourceLoaderMaxage' );
828 if ( is_null(
$context->getVersion() )
832 $maxage = $rlMaxage[
'unversioned'][
'client'];
833 $smaxage = $rlMaxage[
'unversioned'][
'server'];
837 $maxage = $rlMaxage[
'versioned'][
'client'];
838 $smaxage = $rlMaxage[
'versioned'][
'server'];
843 header(
'Content-Type: text/plain; charset=utf-8' );
847 } elseif (
$context->getOnly() ===
'styles' ) {
848 header(
'Content-Type: text/css; charset=utf-8' );
849 header(
'Access-Control-Allow-Origin: *' );
851 header(
'Content-Type: text/javascript; charset=utf-8' );
855 header(
'ETag: ' . $etag );
858 header(
'Cache-Control: private, no-cache, must-revalidate' );
859 header(
'Pragma: no-cache' );
861 header(
"Cache-Control: public, max-age=$maxage, s-maxage=$smaxage" );
862 $exp = min( $maxage, $smaxage );
863 header(
'Expires: ' .
wfTimestamp( TS_RFC2822, $exp + time() ) );
880 $clientKeys =
$context->
getRequest()->getHeader(
'If-None-Match', WebRequest::GETHEADER_LIST );
882 if ( $clientKeys !==
false && !
$context->getDebug() && in_array( $etag, $clientKeys ) ) {
896 $this->sendResponseHeaders(
$context, $etag,
false );
915 $rlMaxage = $this->config->get(
'ResourceLoaderMaxage' );
919 $maxage = is_null(
$context->getVersion() )
920 ? $rlMaxage[
'unversioned'][
'server']
921 : $rlMaxage[
'versioned'][
'server'];
934 $this->sendResponseHeaders(
$context, $etag,
false );
939 $warnings = ob_get_contents();
940 if ( strlen( $warnings ) ) {
964 $encText = str_replace(
'*/',
'* /', $text );
965 return "/*\n$encText\n*/\n";
975 return self::makeComment( self::formatExceptionNoComment(
$e ) );
989 return MWExceptionHandler::getPublicLogMessage(
$e );
992 return MWExceptionHandler::getLogMessage(
$e ) .
994 MWExceptionHandler::getRedactedTraceAsString(
$e );
1011 if ( !count(
$modules ) && !count( $missing ) ) {
1022 if ( $data ===
false ) {
1024 $this->
errors[] =
'Image generation failed';
1029 foreach ( $missing
as $name ) {
1030 $states[
$name] =
'missing';
1036 $filter =
$context->getOnly() ===
'styles' ?
'minify-css' :
'minify-js';
1041 $implementKey =
$name .
'@' . $module->getVersionHash(
$context );
1048 if ( is_string( $scripts ) ) {
1050 $strContent = $scripts;
1051 } elseif ( is_array( $scripts ) ) {
1053 $strContent = self::makeLoaderImplementScript( $implementKey, $scripts, [], [], [] );
1061 $strContent = isset( $styles[
'css'] ) ? implode(
'', $styles[
'css'] ) :
'';
1065 if ( is_string( $scripts ) ) {
1066 if (
$name ===
'site' ||
$name ===
'user' ) {
1072 $scripts = self::filter(
'minify-js', $scripts );
1078 $strContent = self::makeLoaderImplementScript(
1089 $strContent = self::filter( $filter, $strContent );
1092 $out .= $strContent;
1094 }
catch ( Exception
$e ) {
1095 $this->outputErrorAndLog(
$e,
'Generating module package failed: {exception}' );
1098 $states[
$name] =
'error';
1101 $isRaw |= $module->isRaw();
1105 if (
$context->shouldIncludeScripts() && !
$context->getRaw() && !$isRaw ) {
1110 $states[
$name] =
'ready';
1115 if ( count( $states ) ) {
1116 $stateScript = self::makeLoaderStateScript( $states );
1118 $stateScript = self::filter(
'minify-js', $stateScript );
1120 $out .= $stateScript;
1123 if ( count( $states ) ) {
1124 $this->
errors[] =
'Problematic modules: ' .
1138 public function getModulesByMessage( $messageKey ) {
1140 foreach ( $this->getModuleNames() as $moduleName ) {
1141 $module = $this->getModule( $moduleName );
1142 if ( in_array( $messageKey, $module->getMessages() ) ) {
1143 $moduleNames[] = $moduleName;
1146 return $moduleNames;
1167 protected static function makeLoaderImplementScript(
1168 $name, $scripts, $styles,
$messages, $templates
1171 $scripts =
new XmlJsCode(
"function ( $, jQuery, require, module ) {\n{$scripts->value}\n}" );
1172 } elseif ( !is_string( $scripts ) && !is_array( $scripts ) ) {
1173 throw new MWException(
'Invalid scripts error. Array of URLs or string of code expected.' );
1185 self::trimArray( $module );
1197 public static function makeMessageSetScript(
$messages ) {
1212 public static function makeCombinedStyles(
array $stylePairs ) {
1214 foreach ( $stylePairs as $media => $styles ) {
1218 $styles = (
array)$styles;
1219 foreach ( $styles as $style ) {
1220 $style = trim( $style );
1222 if ( $style !==
'' ) {
1227 if ( $media ===
'' || $media ==
'all' ) {
1229 } elseif ( is_string( $media ) ) {
1230 $out[] =
"@media $media {\n" . str_replace(
"\n",
"\n\t",
"\t" . $style ) .
"}";
1253 public static function makeLoaderStateScript( $name, $state =
null ) {
1254 if ( is_array( $name ) ) {
1283 public static function makeCustomLoaderScript( $name, $version, $dependencies,
1286 $script = str_replace(
"\n",
"\n\t", trim( $script ) );
1288 "( function ( name, version, dependencies, group, source ) {\n\t$script\n} )",
1289 [ $name, $version, $dependencies, $group,
$source ],
1294 private static function isEmptyObject( stdClass $obj ) {
1295 foreach ( $obj
as $key =>
$value ) {
1313 private static function trimArray(
array &$array ) {
1314 $i = count( $array );
1316 if ( $array[$i] ===
null
1317 || $array[$i] === []
1318 || ( $array[$i] instanceof
XmlJsCode && $array[$i]->value ===
'{}' )
1319 || ( $array[$i] instanceof stdClass && self::isEmptyObject( $array[$i] ) )
1321 unset( $array[$i] );
1355 public static function makeLoaderRegisterScript( $name, $version =
null,
1356 $dependencies =
null, $group =
null,
$source =
null, $skip =
null
1358 if ( is_array( $name ) ) {
1361 foreach ( $name as $i => &$module ) {
1362 $index[$module[0]] = $i;
1367 foreach ( $name as &$module ) {
1368 if ( isset( $module[2] ) ) {
1369 foreach ( $module[2] as &$dependency ) {
1370 if ( isset( $index[$dependency] ) ) {
1371 $dependency = $index[$dependency];
1377 array_walk( $name, [
'self',
'trimArray' ] );
1380 'mw.loader.register',
1385 $registration = [
$name, $version, $dependencies, $group,
$source, $skip ];
1386 self::trimArray( $registration );
1388 'mw.loader.register',
1409 public static function makeLoaderSourcesScript( $id, $loadUrl =
null ) {
1410 if ( is_array( $id ) ) {
1412 'mw.loader.addSource',
1418 'mw.loader.addSource',
1433 public static function makeLoaderConditionalScript( $script ) {
1434 return '(window.RLQ=window.RLQ||[]).push(function(){' .
1435 trim( $script ) .
'});';
1447 public static function makeInlineScript( $script ) {
1448 $js = self::makeLoaderConditionalScript( $script );
1449 return new WrappedString(
1450 Html::inlineScript( $js ),
1451 '<script>(window.RLQ=window.RLQ||[]).push(function(){',
1463 public static function makeConfigSetScript(
array $configuration ) {
1479 public static function makePackedModulesString(
$modules ) {
1482 $pos = strrpos( $module,
'.' );
1483 $prefix = $pos ===
false ?
'' : substr( $module, 0, $pos );
1484 $suffix = $pos ===
false ? $module : substr( $module, $pos + 1 );
1485 $groups[$prefix][] = $suffix;
1489 foreach ( $groups as $prefix => $suffixes ) {
1490 $p = $prefix ===
'' ?
'' : $prefix .
'.';
1491 $arr[] = $p . implode(
',', $suffixes );
1493 $str = implode(
'|', $arr );
1502 public static function inDebugMode() {
1503 if ( self::$debugMode ===
null ) {
1505 self::$debugMode =
$wgRequest->getFuzzyBool(
'debug',
1509 return self::$debugMode;
1519 public static function clearCache() {
1520 self::$debugMode =
null;
1536 $script = $this->getLoadScript(
$source );
1551 return self::makeLoaderQuery(
1582 public static function makeLoaderQuery(
$modules,
$lang, $skin, $user =
null,
1583 $version =
null,
$debug =
false, $only =
null, $printable =
false,
1584 $handheld =
false, $extraQuery = []
1587 'modules' => self::makePackedModulesString(
$modules ),
1590 'debug' =>
$debug ?
'true' :
'false',
1592 if ( $user !==
null ) {
1595 if ( $version !==
null ) {
1596 $query[
'version'] = $version;
1598 if ( $only !==
null ) {
1623 public static function isValidModuleName( $moduleName ) {
1624 return strcspn( $moduleName,
'!,|', 0, 255 ) === strlen( $moduleName );
1636 public function getLessCompiler( $extraVars = [] ) {
1640 if ( !class_exists(
'Less_Parser' ) ) {
1641 throw new MWException(
'MediaWiki requires the less.php parser' );
1645 $parser->ModifyVars( array_merge( $this->getLessVars(), $extraVars ) );
1647 array_fill_keys( $this->config->get(
'ResourceLoaderLESSImportPaths' ),
'' )
1649 $parser->SetOption(
'relativeUrls',
false );
1660 public function getLessVars() {
1661 if ( !$this->lessVars ) {
1662 $lessVars = $this->config->get(
'ResourceLoaderLESSVars' );
1663 Hooks::run(
'ResourceLoaderGetLessVars', [ &$lessVars ] );
1664 $this->lessVars = $lessVars;
1666 return $this->lessVars;
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for and distribution as defined by Sections through of this document Licensor shall mean the copyright owner or entity authorized by the copyright owner that is granting the License Legal Entity shall mean the union of the acting entity and all other entities that control are controlled by or are under common control with that entity For the purposes of this definition control direct or to cause the direction or management of such whether by contract or including but not limited to software source documentation and configuration files Object form shall mean any form resulting from mechanical transformation or translation of a Source including but not limited to compiled object generated and conversions to other media types Work shall mean the work of whether in Source or Object made available under the as indicated by a copyright notice that is included in or attached to the whether in Source or Object that is based or other modifications as a an original work of authorship For the purposes of this Derivative Works shall not include works that remain separable or merely the Work and Derivative Works thereof Contribution shall mean any work of including the original version of the Work and any modifications or additions to that Work or Derivative Works that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner For the purposes of this definition
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for and distribution as defined by Sections through of this document Licensor shall mean the copyright owner or entity authorized by the copyright owner that is granting the License Legal Entity shall mean the union of the acting entity and all other entities that control are controlled by or are under common control with that entity For the purposes of this definition control direct or to cause the direction or management of such whether by contract or including but not limited to software source documentation and configuration files Object form shall mean any form resulting from mechanical transformation or translation of a Source including but not limited to compiled object generated and conversions to other media types Work shall mean the work of whether in Source or Object made available under the as indicated by a copyright notice that is included in or attached to the whether in Source or Object that is based or other modifications as a an original work of authorship For the purposes of this Derivative Works shall not include works that remain separable from
$wgResourceLoaderDebug
The default debug mode (on/off) for of ResourceLoader requests.
$wgShowExceptionDetails
If set to true, uncaught exceptions will print a complete stack trace to output.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfResetOutputBuffers( $resetGzipEncoding=true)
Clear away any user-level output buffers, discarding contents.
if(! $wgDBerrorLogTZ) $wgRequest
static minify( $css)
Removes whitespace from CSS data.
getSkin()
Get the Skin object.
getUser()
Get the User object.
getRequest()
Get the WebRequest object.
getLanguage()
Get the Language object.
isCacheGood( $timestamp='')
Check if up to date cache file exists.
fetchText()
Get the uncompressed text from the cache.
cacheTimestamp()
Get the last-modified timestamp of the cache file.
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
static header( $code)
Output an HTTP status code header.
static minify( $s, $statementsOnOwnLine=false, $maxLineLength=1000)
Returns minified JavaScript code.
This class generates message blobs for use by ResourceLoader modules.
get(ResourceLoader $resourceLoader, $modules, $lang)
static transformCssMedia( $media)
Transform "media" attribute based on request parameters.
ResourceLoader request result caching in the file system.
static useFileCache(ResourceLoaderContext $context)
Check if an RL request can be cached.
static newFromContext(ResourceLoaderContext $context)
Construct an ResourceFileCache from a context.
Object passed around to modules which contains information about the state of a specific loader reque...
static extractBasePaths( $options=[], $localBasePath=null, $remoteBasePath=null)
Extract a pair of local and remote base paths from module definition information.
An object to represent a path to a JavaScript/CSS file, along with a remote and local base path,...
Abstraction for ResourceLoader modules, with name registration and maxage functionality.
static expandRelativePaths(array $filePaths)
Expand directories relative to $IP.
static preloadTitleInfo(ResourceLoaderContext $context, IDatabase $db, array $moduleNames)
Dynamic JavaScript and CSS resource loading system.
__construct(Config $config=null, LoggerInterface $logger=null)
Register core modules and runs registration hooks.
static formatExceptionNoComment( $e)
Handle exception display.
tryRespondFromFileCache(ResourceFileCache $fileCache, ResourceLoaderContext $context, $etag)
Send out code for a response from file cache if possible.
isFileModule( $name)
Return whether the definition of a module corresponds to a simple ResourceLoaderFileModule.
getModuleNames()
Get a list of module names.
setMessageBlobStore(MessageBlobStore $blobStore)
static inDebugMode()
Determine whether debug mode was requested Order of priority is 1) request param, 2) cookie,...
makeModuleResponse(ResourceLoaderContext $context, array $modules, array $missing=[])
Generate code for a response.
setLogger(LoggerInterface $logger)
getTestModuleNames( $framework='all')
Get a list of test module names for one (or all) frameworks.
getLoadScript( $source)
Get the URL to the load.php endpoint for the given ResourceLoader source.
tryRespondNotModified(ResourceLoaderContext $context, $etag)
Respond with HTTP 304 Not Modified if appropiate.
static int $filterCacheVersion
getSources()
Get the list of sources.
addSource( $id, $loadUrl=null)
Add a foreign source of modules.
array $moduleInfos
Associative array mapping module name to info associative array.
sendResponseHeaders(ResourceLoaderContext $context, $etag, $errors)
Send main response headers to the client.
outputErrorAndLog(Exception $e, $msg, array $context=[])
Add an error to the 'errors' array and log it.
array $testModuleNames
Associative array mapping framework ids to a list of names of test suite modules like [ 'qunit' => [ ...
makeVersionQuery(ResourceLoaderContext $context)
Get the expected value of the 'version' query parameter.
getModule( $name)
Get the ResourceLoaderModule object for a given module name.
array $modules
Module name/ResourceLoaderModule object pairs.
isModuleRegistered( $name)
Check whether a ResourceLoader module is registered.
static applyFilter( $filter, $data)
static formatException( $e)
Handle exception display.
MessageBlobStore $blobStore
array $errors
Errors accumulated during current respond() call.
static makeComment( $text)
Generate a CSS or JS comment block.
getCombinedVersion(ResourceLoaderContext $context, array $moduleNames)
Helper method to get and combine versions of multiple modules.
respond(ResourceLoaderContext $context)
Output a response to a load request, including the content-type header.
static filter( $filter, $data, array $options=[])
Run JavaScript or CSS data through a filter, caching the filtered result for future calls.
preloadModuleInfo(array $moduleNames, ResourceLoaderContext $context)
Load information stored in the database about modules.
A wrapper class which causes Xml::encodeJsVar() and Xml::encodeJsCall() to interpret a given string a...
static encodeJsCall( $name, $args, $pretty=false)
Create a call to a JavaScript function.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
when a variable name is used in a it is silently declared as a new local masking the global
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
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
the array() calling protocol came about after MediaWiki 1.4rc1.
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
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
do that in ParserLimitReportFormat instead $parser
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
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 modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check $image
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content $content
if the prop value should be in the metadata multi language array can modify can modify indexed by page_id indexed by prefixed DB keys can modify can modify can modify this should be populated with an alert message to that effect to be fed to an HTMLForm object and populate $result with the reason in the form of error messages should be plain text with no special etc to show that they re errors
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
Allows to change the fields on the form that will be generated $name
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
this hook is for auditing only $response
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
returning false will NOT prevent logging $e
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
if(!isset( $args[0])) $lang