or ) const LOAD_STYLES = 'styles'; // Module may have other resources (loaded via mw.loader from a script) const LOAD_GENERAL = 'general'; # sitewide core module like a skin file or jQuery component const ORIGIN_CORE_SITEWIDE = 1; # per-user module generated by the software const ORIGIN_CORE_INDIVIDUAL = 2; # sitewide module generated from user-editable files, like MediaWiki:Common.js, or # modules accessible to multiple users, such as those generated by the Gadgets extension. const ORIGIN_USER_SITEWIDE = 3; # per-user module generated from user-editable files, like User:Me/vector.js const ORIGIN_USER_INDIVIDUAL = 4; # an access constant; make sure this is kept as the largest number in this group const ORIGIN_ALL = 10; # script and style modules form a hierarchy of trustworthiness, with core modules like # skins and jQuery as most trustworthy, and user scripts as least trustworthy. We can # limit the types of scripts and styles we allow to load on, say, sensitive special # pages like Special:UserLogin and Special:Preferences protected $origin = self::ORIGIN_CORE_SITEWIDE; protected $name = null; protected $targets = [ 'desktop' ]; // In-object cache for file dependencies protected $fileDeps = []; // In-object cache for message blob (keyed by language) protected $msgBlobs = []; // In-object cache for version hash protected $versionHash = []; // In-object cache for module content protected $contents = []; /** * @var Config */ protected $config; /** * @var array|bool */ protected $deprecated = false; /** * @var LoggerInterface */ protected $logger; /** * Get this module's name. This is set when the module is registered * with ResourceLoader::register() * * @return string|null Name (string) or null if no name was set */ public function getName() { return $this->name; } /** * Set this module's name. This is called by ResourceLoader::register() * when registering the module. Other code should not call this. * * @param string $name */ public function setName( $name ) { $this->name = $name; } /** * Get this module's origin. This is set when the module is registered * with ResourceLoader::register() * * @return int ResourceLoaderModule class constant, the subclass default * if not set manually */ public function getOrigin() { return $this->origin; } /** * @param ResourceLoaderContext $context * @return bool */ public function getFlip( $context ) { global $wgContLang; return $wgContLang->getDir() !== $context->getDirection(); } /** * Get JS representing deprecation information for the current module if available * * @return string JavaScript code */ protected function getDeprecationInformation() { $deprecationInfo = $this->deprecated; if ( $deprecationInfo ) { $name = $this->getName(); $warning = 'This page is using the deprecated ResourceLoader module "' . $name . '".'; if ( is_string( $deprecationInfo ) ) { $warning .= "\n" . $deprecationInfo; } return Xml::encodeJsCall( 'mw.log.warn', [ $warning ] ); } else { return ''; } } /** * Get all JS for this module for a given language and skin. * Includes all relevant JS except loader scripts. * * @param ResourceLoaderContext $context * @return string JavaScript code */ public function getScript( ResourceLoaderContext $context ) { // Stub, override expected return ''; } /** * Takes named templates by the module and returns an array mapping. * * @return array of templates mapping template alias to content */ public function getTemplates() { // Stub, override expected. return []; } /** * @return Config * @since 1.24 */ public function getConfig() { if ( $this->config === null ) { // Ugh, fall back to default $this->config = MediaWikiServices::getInstance()->getMainConfig(); } return $this->config; } /** * @param Config $config * @since 1.24 */ public function setConfig( Config $config ) { $this->config = $config; } /** * @since 1.27 * @param LoggerInterface $logger * @return null */ public function setLogger( LoggerInterface $logger ) { $this->logger = $logger; } /** * @since 1.27 * @return LoggerInterface */ protected function getLogger() { if ( !$this->logger ) { $this->logger = new NullLogger(); } return $this->logger; } /** * Get the URL or URLs to load for this module's JS in debug mode. * The default behavior is to return a load.php?only=scripts URL for * the module, but file-based modules will want to override this to * load the files directly. * * This function is called only when 1) we're in debug mode, 2) there * is no only= parameter and 3) supportsURLLoading() returns true. * #2 is important to prevent an infinite loop, therefore this function * MUST return either an only= URL or a non-load.php URL. * * @param ResourceLoaderContext $context * @return array Array of URLs */ public function getScriptURLsForDebug( ResourceLoaderContext $context ) { $resourceLoader = $context->getResourceLoader(); $derivative = new DerivativeResourceLoaderContext( $context ); $derivative->setModules( [ $this->getName() ] ); $derivative->setOnly( 'scripts' ); $derivative->setDebug( true ); $url = $resourceLoader->createLoaderURL( $this->getSource(), $derivative ); return [ $url ]; } /** * Whether this module supports URL loading. If this function returns false, * getScript() will be used even in cases (debug mode, no only param) where * getScriptURLsForDebug() would normally be used instead. * @return bool */ public function supportsURLLoading() { return true; } /** * Get all CSS for this module for a given skin. * * @param ResourceLoaderContext $context * @return array List of CSS strings or array of CSS strings keyed by media type. * like [ 'screen' => '.foo { width: 0 }' ]; * or [ 'screen' => [ '.foo { width: 0 }' ] ]; */ public function getStyles( ResourceLoaderContext $context ) { // Stub, override expected return []; } /** * Get the URL or URLs to load for this module's CSS in debug mode. * The default behavior is to return a load.php?only=styles URL for * the module, but file-based modules will want to override this to * load the files directly. See also getScriptURLsForDebug() * * @param ResourceLoaderContext $context * @return array [ mediaType => [ URL1, URL2, ... ], ... ] */ public function getStyleURLsForDebug( ResourceLoaderContext $context ) { $resourceLoader = $context->getResourceLoader(); $derivative = new DerivativeResourceLoaderContext( $context ); $derivative->setModules( [ $this->getName() ] ); $derivative->setOnly( 'styles' ); $derivative->setDebug( true ); $url = $resourceLoader->createLoaderURL( $this->getSource(), $derivative ); return [ 'all' => [ $url ] ]; } /** * Get the messages needed for this module. * * To get a JSON blob with messages, use MessageBlobStore::get() * * @return array List of message keys. Keys may occur more than once */ public function getMessages() { // Stub, override expected return []; } /** * Get the group this module is in. * * @return string Group name */ public function getGroup() { // Stub, override expected return null; } /** * Get the origin of this module. Should only be overridden for foreign modules. * * @return string Origin name, 'local' for local modules */ public function getSource() { // Stub, override expected return 'local'; } /** * From where in the page HTML should this module be loaded? * * @deprecated since 1.29 Obsolete. All modules load async from `
`. * @return string */ public function getPosition() { return 'top'; } /** * Whether this module's JS expects to work without the client-side ResourceLoader module. * Returning true from this function will prevent mw.loader.state() call from being * appended to the bottom of the script. * * @return bool */ public function isRaw() { return false; } /** * Get a list of modules this module depends on. * * Dependency information is taken into account when loading a module * on the client side. * * Note: It is expected that $context will be made non-optional in the near * future. * * @param ResourceLoaderContext $context * @return array List of module names as strings */ public function getDependencies( ResourceLoaderContext $context = null ) { // Stub, override expected return []; } /** * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile'] * * @return array Array of strings */ public function getTargets() { return $this->targets; } /** * Get the module's load type. * * @since 1.28 * @return string ResourceLoaderModule LOAD_* constant */ public function getType() { return self::LOAD_GENERAL; } /** * Get the skip function. * * Modules that provide fallback functionality can provide a "skip function". This * function, if provided, will be passed along to the module registry on the client. * When this module is loaded (either directly or as a dependency of another module), * then this function is executed first. If the function returns true, the module will * instantly be considered "ready" without requesting the associated module resources. * * The value returned here must be valid javascript for execution in a private function. * It must not contain the "function () {" and "}" wrapper though. * * @return string|null A JavaScript function body returning a boolean value, or null */ public function getSkipFunction() { return null; } /** * Get the files this module depends on indirectly for a given skin. * * These are only image files referenced by the module's stylesheet. * * @param ResourceLoaderContext $context * @return array List of files */ protected function getFileDependencies( ResourceLoaderContext $context ) { $vary = $context->getSkin() . '|' . $context->getLanguage(); // Try in-object cache first if ( !isset( $this->fileDeps[$vary] ) ) { $dbr = wfGetDB( DB_REPLICA ); $deps = $dbr->selectField( 'module_deps', 'md_deps', [ 'md_module' => $this->getName(), 'md_skin' => $vary, ], __METHOD__ ); if ( !is_null( $deps ) ) { $this->fileDeps[$vary] = self::expandRelativePaths( (array)FormatJson::decode( $deps, true ) ); } else { $this->fileDeps[$vary] = []; } } return $this->fileDeps[$vary]; } /** * Set in-object cache for file dependencies. * * This is used to retrieve data in batches. See ResourceLoader::preloadModuleInfo(). * To save the data, use saveFileDependencies(). * * @param ResourceLoaderContext $context * @param string[] $files Array of file names */ public function setFileDependencies( ResourceLoaderContext $context, $files ) { $vary = $context->getSkin() . '|' . $context->getLanguage(); $this->fileDeps[$vary] = $files; } /** * Set the files this module depends on indirectly for a given skin. * * @since 1.27 * @param ResourceLoaderContext $context * @param array $localFileRefs List of files */ protected function saveFileDependencies( ResourceLoaderContext $context, $localFileRefs ) { try { // Related bugs and performance considerations: // 1. Don't needlessly change the database value with the same list in a // different order or with duplicates. // 2. Use relative paths to avoid ghost entries when $IP changes. (T111481) // 3. Don't needlessly replace the database with the same value // just because $IP changed (e.g. when upgrading a wiki). // 4. Don't create an endless replace loop on every request for this // module when '../' is used anywhere. Even though both are expanded // (one expanded by getFileDependencies from the DB, the other is // still raw as originally read by RL), the latter has not // been normalized yet. // Normalise $localFileRefs = array_values( array_unique( $localFileRefs ) ); sort( $localFileRefs ); $localPaths = self::getRelativePaths( $localFileRefs ); $storedPaths = self::getRelativePaths( $this->getFileDependencies( $context ) ); // If the list has been modified since last time we cached it, update the cache if ( $localPaths !== $storedPaths ) { $vary = $context->getSkin() . '|' . $context->getLanguage(); $cache = ObjectCache::getLocalClusterInstance(); $key = $cache->makeKey( __METHOD__, $this->getName(), $vary ); $scopeLock = $cache->getScopedLock( $key, 0 ); if ( !$scopeLock ) { return; // T124649; avoid write slams } $deps = FormatJson::encode( $localPaths ); $dbw = wfGetDB( DB_MASTER ); $dbw->upsert( 'module_deps', [ 'md_module' => $this->getName(), 'md_skin' => $vary, 'md_deps' => $deps, ], [ 'md_module', 'md_skin' ], [ 'md_deps' => $deps, ] ); if ( $dbw->trxLevel() ) { $dbw->onTransactionResolution( function () use ( &$scopeLock ) { ScopedCallback::consume( $scopeLock ); // release after commit }, __METHOD__ ); } } } catch ( Exception $e ) { wfDebugLog( 'resourceloader', __METHOD__ . ": failed to update DB: $e" ); } } /** * Make file paths relative to MediaWiki directory. * * This is used to make file paths safe for storing in a database without the paths * becoming stale or incorrect when MediaWiki is moved or upgraded (T111481). * * @since 1.27 * @param array $filePaths * @return array */ public static function getRelativePaths( array $filePaths ) { global $IP; return array_map( function ( $path ) use ( $IP ) { return RelPath\getRelativePath( $path, $IP ); }, $filePaths ); } /** * Expand directories relative to $IP. * * @since 1.27 * @param array $filePaths * @return array */ public static function expandRelativePaths( array $filePaths ) { global $IP; return array_map( function ( $path ) use ( $IP ) { return RelPath\joinPath( $IP, $path ); }, $filePaths ); } /** * Get the hash of the message blob. * * @since 1.27 * @param ResourceLoaderContext $context * @return string|null JSON blob or null if module has no messages */ protected function getMessageBlob( ResourceLoaderContext $context ) { if ( !$this->getMessages() ) { // Don't bother consulting MessageBlobStore return null; } // Message blobs may only vary language, not by context keys $lang = $context->getLanguage(); if ( !isset( $this->msgBlobs[$lang] ) ) { $this->getLogger()->warning( 'Message blob for {module} should have been preloaded', [ 'module' => $this->getName(), ] ); $store = $context->getResourceLoader()->getMessageBlobStore(); $this->msgBlobs[$lang] = $store->getBlob( $this, $lang ); } return $this->msgBlobs[$lang]; } /** * Set in-object cache for message blobs. * * Used to allow fetching of message blobs in batches. See ResourceLoader::preloadModuleInfo(). * * @since 1.27 * @param string|null $blob JSON blob or null * @param string $lang Language code */ public function setMessageBlob( $blob, $lang ) { $this->msgBlobs[$lang] = $blob; } /** * Get headers to send as part of a module web response. * * It is not supported to send headers through this method that are * required to be unique or otherwise sent once in an HTTP response * because clients may make batch requests for multiple modules (as * is the default behaviour for ResourceLoader clients). * * For exclusive or aggregated headers, see ResourceLoader::sendResponseHeaders(). * * @since 1.30 * @param ResourceLoaderContext $context * @return string[] Array of HTTP response headers */ final public function getHeaders( ResourceLoaderContext $context ) { $headers = []; $formattedLinks = []; foreach ( $this->getPreloadLinks( $context ) as $url => $attribs ) { $link = "<{$url}>;rel=preload"; foreach ( $attribs as $key => $val ) { $link .= ";{$key}={$val}"; } $formattedLinks[] = $link; } if ( $formattedLinks ) { $headers[] = 'Link: ' . implode( ',', $formattedLinks ); } return $headers; } /** * Get a list of resources that web browsers may preload. * * Behaviour of rel=preload link is specified at