3 * Abstraction for ResourceLoader modules.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @author Trevor Parscal
22 * @author Roan Kattouw
25 use MediaWiki\MediaWikiServices
;
26 use Psr\Log\LoggerAwareInterface
;
27 use Psr\Log\LoggerInterface
;
28 use Psr\Log\NullLogger
;
29 use Wikimedia\ScopedCallback
;
32 * Abstraction for ResourceLoader modules, with name registration and maxage functionality.
34 abstract class ResourceLoaderModule
implements LoggerAwareInterface
{
36 const TYPE_SCRIPTS
= 'scripts';
37 const TYPE_STYLES
= 'styles';
38 const TYPE_COMBINED
= 'combined';
41 // Module only has styles (loaded via <style> or <link rel=stylesheet>)
42 const LOAD_STYLES
= 'styles';
43 // Module may have other resources (loaded via mw.loader from a script)
44 const LOAD_GENERAL
= 'general';
46 # sitewide core module like a skin file or jQuery component
47 const ORIGIN_CORE_SITEWIDE
= 1;
49 # per-user module generated by the software
50 const ORIGIN_CORE_INDIVIDUAL
= 2;
52 # sitewide module generated from user-editable files, like MediaWiki:Common.js, or
53 # modules accessible to multiple users, such as those generated by the Gadgets extension.
54 const ORIGIN_USER_SITEWIDE
= 3;
56 # per-user module generated from user-editable files, like User:Me/vector.js
57 const ORIGIN_USER_INDIVIDUAL
= 4;
59 # an access constant; make sure this is kept as the largest number in this group
60 const ORIGIN_ALL
= 10;
62 # script and style modules form a hierarchy of trustworthiness, with core modules like
63 # skins and jQuery as most trustworthy, and user scripts as least trustworthy. We can
64 # limit the types of scripts and styles we allow to load on, say, sensitive special
65 # pages like Special:UserLogin and Special:Preferences
66 protected $origin = self
::ORIGIN_CORE_SITEWIDE
;
68 /* Protected Members */
70 protected $name = null;
71 protected $targets = [ 'desktop' ];
73 // In-object cache for file dependencies
74 protected $fileDeps = [];
75 // In-object cache for message blob (keyed by language)
76 protected $msgBlobs = [];
77 // In-object cache for version hash
78 protected $versionHash = [];
79 // In-object cache for module content
80 protected $contents = [];
90 protected $deprecated = false;
93 * @var LoggerInterface
100 * Get this module's name. This is set when the module is registered
101 * with ResourceLoader::register()
103 * @return string|null Name (string) or null if no name was set
105 public function getName() {
110 * Set this module's name. This is called by ResourceLoader::register()
111 * when registering the module. Other code should not call this.
113 * @param string $name Name
115 public function setName( $name ) {
120 * Get this module's origin. This is set when the module is registered
121 * with ResourceLoader::register()
123 * @return int ResourceLoaderModule class constant, the subclass default
124 * if not set manually
126 public function getOrigin() {
127 return $this->origin
;
131 * @param ResourceLoaderContext $context
134 public function getFlip( $context ) {
137 return $wgContLang->getDir() !== $context->getDirection();
141 * Get JS representing deprecation information for the current module if available
143 * @return string JavaScript code
145 protected function getDeprecationInformation() {
146 $deprecationInfo = $this->deprecated
;
147 if ( $deprecationInfo ) {
148 $name = $this->getName();
149 $warning = 'This page is using the deprecated ResourceLoader module "' . $name . '".';
150 if ( is_string( $deprecationInfo ) ) {
151 $warning .= "\n" . $deprecationInfo;
153 return Xml
::encodeJsCall(
163 * Get all JS for this module for a given language and skin.
164 * Includes all relevant JS except loader scripts.
166 * @param ResourceLoaderContext $context
167 * @return string JavaScript code
169 public function getScript( ResourceLoaderContext
$context ) {
170 // Stub, override expected
175 * Takes named templates by the module and returns an array mapping.
177 * @return array of templates mapping template alias to content
179 public function getTemplates() {
180 // Stub, override expected.
188 public function getConfig() {
189 if ( $this->config
=== null ) {
190 // Ugh, fall back to default
191 $this->config
= MediaWikiServices
::getInstance()->getMainConfig();
194 return $this->config
;
198 * @param Config $config
201 public function setConfig( Config
$config ) {
202 $this->config
= $config;
207 * @param LoggerInterface $logger
210 public function setLogger( LoggerInterface
$logger ) {
211 $this->logger
= $logger;
216 * @return LoggerInterface
218 protected function getLogger() {
219 if ( !$this->logger
) {
220 $this->logger
= new NullLogger();
222 return $this->logger
;
226 * Get the URL or URLs to load for this module's JS in debug mode.
227 * The default behavior is to return a load.php?only=scripts URL for
228 * the module, but file-based modules will want to override this to
229 * load the files directly.
231 * This function is called only when 1) we're in debug mode, 2) there
232 * is no only= parameter and 3) supportsURLLoading() returns true.
233 * #2 is important to prevent an infinite loop, therefore this function
234 * MUST return either an only= URL or a non-load.php URL.
236 * @param ResourceLoaderContext $context
237 * @return array Array of URLs
239 public function getScriptURLsForDebug( ResourceLoaderContext
$context ) {
240 $resourceLoader = $context->getResourceLoader();
241 $derivative = new DerivativeResourceLoaderContext( $context );
242 $derivative->setModules( [ $this->getName() ] );
243 $derivative->setOnly( 'scripts' );
244 $derivative->setDebug( true );
246 $url = $resourceLoader->createLoaderURL(
255 * Whether this module supports URL loading. If this function returns false,
256 * getScript() will be used even in cases (debug mode, no only param) where
257 * getScriptURLsForDebug() would normally be used instead.
260 public function supportsURLLoading() {
265 * Get all CSS for this module for a given skin.
267 * @param ResourceLoaderContext $context
268 * @return array List of CSS strings or array of CSS strings keyed by media type.
269 * like [ 'screen' => '.foo { width: 0 }' ];
270 * or [ 'screen' => [ '.foo { width: 0 }' ] ];
272 public function getStyles( ResourceLoaderContext
$context ) {
273 // Stub, override expected
278 * Get the URL or URLs to load for this module's CSS in debug mode.
279 * The default behavior is to return a load.php?only=styles URL for
280 * the module, but file-based modules will want to override this to
281 * load the files directly. See also getScriptURLsForDebug()
283 * @param ResourceLoaderContext $context
284 * @return array [ mediaType => [ URL1, URL2, ... ], ... ]
286 public function getStyleURLsForDebug( ResourceLoaderContext
$context ) {
287 $resourceLoader = $context->getResourceLoader();
288 $derivative = new DerivativeResourceLoaderContext( $context );
289 $derivative->setModules( [ $this->getName() ] );
290 $derivative->setOnly( 'styles' );
291 $derivative->setDebug( true );
293 $url = $resourceLoader->createLoaderURL(
298 return [ 'all' => [ $url ] ];
302 * Get the messages needed for this module.
304 * To get a JSON blob with messages, use MessageBlobStore::get()
306 * @return array List of message keys. Keys may occur more than once
308 public function getMessages() {
309 // Stub, override expected
314 * Get the group this module is in.
316 * @return string Group name
318 public function getGroup() {
319 // Stub, override expected
324 * Get the origin of this module. Should only be overridden for foreign modules.
326 * @return string Origin name, 'local' for local modules
328 public function getSource() {
329 // Stub, override expected
334 * From where in the page HTML should this module be loaded?
336 * @deprecated since 1.29 Obsolete. All modules load async from `<head>`.
339 public function getPosition() {
344 * Whether this module's JS expects to work without the client-side ResourceLoader module.
345 * Returning true from this function will prevent mw.loader.state() call from being
346 * appended to the bottom of the script.
350 public function isRaw() {
355 * Get a list of modules this module depends on.
357 * Dependency information is taken into account when loading a module
358 * on the client side.
360 * Note: It is expected that $context will be made non-optional in the near
363 * @param ResourceLoaderContext $context
364 * @return array List of module names as strings
366 public function getDependencies( ResourceLoaderContext
$context = null ) {
367 // Stub, override expected
372 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
374 * @return array Array of strings
376 public function getTargets() {
377 return $this->targets
;
381 * Get the module's load type.
384 * @return string ResourceLoaderModule LOAD_* constant
386 public function getType() {
387 return self
::LOAD_GENERAL
;
391 * Get the skip function.
393 * Modules that provide fallback functionality can provide a "skip function". This
394 * function, if provided, will be passed along to the module registry on the client.
395 * When this module is loaded (either directly or as a dependency of another module),
396 * then this function is executed first. If the function returns true, the module will
397 * instantly be considered "ready" without requesting the associated module resources.
399 * The value returned here must be valid javascript for execution in a private function.
400 * It must not contain the "function () {" and "}" wrapper though.
402 * @return string|null A JavaScript function body returning a boolean value, or null
404 public function getSkipFunction() {
409 * Get the files this module depends on indirectly for a given skin.
411 * These are only image files referenced by the module's stylesheet.
413 * @param ResourceLoaderContext $context
414 * @return array List of files
416 protected function getFileDependencies( ResourceLoaderContext
$context ) {
417 $vary = $context->getSkin() . '|' . $context->getLanguage();
419 // Try in-object cache first
420 if ( !isset( $this->fileDeps
[$vary] ) ) {
421 $dbr = wfGetDB( DB_REPLICA
);
422 $deps = $dbr->selectField( 'module_deps',
425 'md_module' => $this->getName(),
431 if ( !is_null( $deps ) ) {
432 $this->fileDeps
[$vary] = self
::expandRelativePaths(
433 (array)FormatJson
::decode( $deps, true )
436 $this->fileDeps
[$vary] = [];
439 return $this->fileDeps
[$vary];
443 * Set in-object cache for file dependencies.
445 * This is used to retrieve data in batches. See ResourceLoader::preloadModuleInfo().
446 * To save the data, use saveFileDependencies().
448 * @param ResourceLoaderContext $context
449 * @param string[] $files Array of file names
451 public function setFileDependencies( ResourceLoaderContext
$context, $files ) {
452 $vary = $context->getSkin() . '|' . $context->getLanguage();
453 $this->fileDeps
[$vary] = $files;
457 * Set the files this module depends on indirectly for a given skin.
460 * @param ResourceLoaderContext $context
461 * @param array $localFileRefs List of files
463 protected function saveFileDependencies( ResourceLoaderContext
$context, $localFileRefs ) {
465 // Related bugs and performance considerations:
466 // 1. Don't needlessly change the database value with the same list in a
467 // different order or with duplicates.
468 // 2. Use relative paths to avoid ghost entries when $IP changes. (T111481)
469 // 3. Don't needlessly replace the database with the same value
470 // just because $IP changed (e.g. when upgrading a wiki).
471 // 4. Don't create an endless replace loop on every request for this
472 // module when '../' is used anywhere. Even though both are expanded
473 // (one expanded by getFileDependencies from the DB, the other is
474 // still raw as originally read by RL), the latter has not
475 // been normalized yet.
478 $localFileRefs = array_values( array_unique( $localFileRefs ) );
479 sort( $localFileRefs );
480 $localPaths = self
::getRelativePaths( $localFileRefs );
482 $storedPaths = self
::getRelativePaths( $this->getFileDependencies( $context ) );
483 // If the list has been modified since last time we cached it, update the cache
484 if ( $localPaths !== $storedPaths ) {
485 $vary = $context->getSkin() . '|' . $context->getLanguage();
486 $cache = ObjectCache
::getLocalClusterInstance();
487 $key = $cache->makeKey( __METHOD__
, $this->getName(), $vary );
488 $scopeLock = $cache->getScopedLock( $key, 0 );
490 return; // T124649; avoid write slams
493 $deps = FormatJson
::encode( $localPaths );
494 $dbw = wfGetDB( DB_MASTER
);
495 $dbw->upsert( 'module_deps',
497 'md_module' => $this->getName(),
501 [ 'md_module', 'md_skin' ],
507 if ( $dbw->trxLevel() ) {
508 $dbw->onTransactionResolution(
509 function () use ( &$scopeLock ) {
510 ScopedCallback
::consume( $scopeLock ); // release after commit
516 } catch ( Exception
$e ) {
517 wfDebugLog( 'resourceloader', __METHOD__
. ": failed to update DB: $e" );
522 * Make file paths relative to MediaWiki directory.
524 * This is used to make file paths safe for storing in a database without the paths
525 * becoming stale or incorrect when MediaWiki is moved or upgraded (T111481).
528 * @param array $filePaths
531 public static function getRelativePaths( array $filePaths ) {
533 return array_map( function ( $path ) use ( $IP ) {
534 return RelPath\
getRelativePath( $path, $IP );
539 * Expand directories relative to $IP.
542 * @param array $filePaths
545 public static function expandRelativePaths( array $filePaths ) {
547 return array_map( function ( $path ) use ( $IP ) {
548 return RelPath\
joinPath( $IP, $path );
553 * Get the hash of the message blob.
556 * @param ResourceLoaderContext $context
557 * @return string|null JSON blob or null if module has no messages
559 protected function getMessageBlob( ResourceLoaderContext
$context ) {
560 if ( !$this->getMessages() ) {
561 // Don't bother consulting MessageBlobStore
564 // Message blobs may only vary language, not by context keys
565 $lang = $context->getLanguage();
566 if ( !isset( $this->msgBlobs
[$lang] ) ) {
567 $this->getLogger()->warning( 'Message blob for {module} should have been preloaded', [
568 'module' => $this->getName(),
570 $store = $context->getResourceLoader()->getMessageBlobStore();
571 $this->msgBlobs
[$lang] = $store->getBlob( $this, $lang );
573 return $this->msgBlobs
[$lang];
577 * Set in-object cache for message blobs.
579 * Used to allow fetching of message blobs in batches. See ResourceLoader::preloadModuleInfo().
582 * @param string|null $blob JSON blob or null
583 * @param string $lang Language code
585 public function setMessageBlob( $blob, $lang ) {
586 $this->msgBlobs
[$lang] = $blob;
590 * Get headers to send as part of a module web response.
592 * It is not supported to send headers through this method that are
593 * required to be unique or otherwise sent once in an HTTP response
594 * because clients may make batch requests for multiple modules (as
595 * is the default behaviour for ResourceLoader clients).
597 * For exclusive or aggregated headers, see ResourceLoader::sendResponseHeaders().
600 * @param ResourceLoaderContext $context
601 * @return string[] Array of HTTP response headers
603 final public function getHeaders( ResourceLoaderContext
$context ) {
606 $formattedLinks = [];
607 foreach ( $this->getPreloadLinks( $context ) as $url => $attribs ) {
608 $link = "<{$url}>;rel=preload";
609 foreach ( $attribs as $key => $val ) {
610 $link .= ";{$key}={$val}";
612 $formattedLinks[] = $link;
614 if ( $formattedLinks ) {
615 $headers[] = 'Link: ' . implode( ',', $formattedLinks );
622 * Get a list of resources that web browsers may preload.
624 * Behaviour of rel=preload link is specified at <https://www.w3.org/TR/preload/>.
626 * Use case for ResourceLoader originally part of T164299.
630 * protected function getPreloadLinks() {
632 * 'https://example.org/script.js' => [ 'as' => 'script' ],
633 * 'https://example.org/image.png' => [ 'as' => 'image' ],
638 * @par Example using HiDPI image variants
640 * protected function getPreloadLinks() {
642 * 'https://example.org/logo.png' => [
644 * 'media' => 'not all and (min-resolution: 2dppx)',
646 * 'https://example.org/logo@2x.png' => [
648 * 'media' => '(min-resolution: 2dppx)',
654 * @see ResourceLoaderModule::getHeaders
656 * @param ResourceLoaderContext $context
657 * @return array Keyed by url, values must be an array containing
658 * at least an 'as' key. Optionally a 'media' key as well.
660 protected function getPreloadLinks( ResourceLoaderContext
$context ) {
665 * Get module-specific LESS variables, if any.
668 * @param ResourceLoaderContext $context
669 * @return array Module-specific LESS variables.
671 protected function getLessVars( ResourceLoaderContext
$context ) {
676 * Get an array of this module's resources. Ready for serving to the web.
679 * @param ResourceLoaderContext $context
682 public function getModuleContent( ResourceLoaderContext
$context ) {
683 $contextHash = $context->getHash();
684 // Cache this expensive operation. This calls builds the scripts, styles, and messages
685 // content which typically involves filesystem and/or database access.
686 if ( !array_key_exists( $contextHash, $this->contents
) ) {
687 $this->contents
[$contextHash] = $this->buildContent( $context );
689 return $this->contents
[$contextHash];
693 * Bundle all resources attached to this module into an array.
696 * @param ResourceLoaderContext $context
699 final protected function buildContent( ResourceLoaderContext
$context ) {
700 $rl = $context->getResourceLoader();
701 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
702 $statStart = microtime( true );
704 // Only include properties that are relevant to this context (e.g. only=scripts)
705 // and that are non-empty (e.g. don't include "templates" for modules without
706 // templates). This helps prevent invalidating cache for all modules when new
707 // optional properties are introduced.
711 if ( $context->shouldIncludeScripts() ) {
712 // If we are in debug mode, we'll want to return an array of URLs if possible
713 // However, we can't do this if the module doesn't support it
714 // We also can't do this if there is an only= parameter, because we have to give
715 // the module a way to return a load.php URL without causing an infinite loop
716 if ( $context->getDebug() && !$context->getOnly() && $this->supportsURLLoading() ) {
717 $scripts = $this->getScriptURLsForDebug( $context );
719 $scripts = $this->getScript( $context );
720 // Make the script safe to concatenate by making sure there is at least one
721 // trailing new line at the end of the content. Previously, this looked for
722 // a semi-colon instead, but that breaks concatenation if the semicolon
723 // is inside a comment like "// foo();". Instead, simply use a
724 // line break as separator which matches JavaScript native logic for implicitly
725 // ending statements even if a semi-colon is missing.
726 // Bugs: T29054, T162719.
727 if ( is_string( $scripts )
728 && strlen( $scripts )
729 && substr( $scripts, -1 ) !== "\n"
734 $content['scripts'] = $scripts;
738 if ( $context->shouldIncludeStyles() ) {
740 // Don't create empty stylesheets like [ '' => '' ] for modules
741 // that don't *have* any stylesheets (T40024).
742 $stylePairs = $this->getStyles( $context );
743 if ( count( $stylePairs ) ) {
744 // If we are in debug mode without &only= set, we'll want to return an array of URLs
745 // See comment near shouldIncludeScripts() for more details
746 if ( $context->getDebug() && !$context->getOnly() && $this->supportsURLLoading() ) {
748 'url' => $this->getStyleURLsForDebug( $context )
751 // Minify CSS before embedding in mw.loader.implement call
752 // (unless in debug mode)
753 if ( !$context->getDebug() ) {
754 foreach ( $stylePairs as $media => $style ) {
755 // Can be either a string or an array of strings.
756 if ( is_array( $style ) ) {
757 $stylePairs[$media] = [];
758 foreach ( $style as $cssText ) {
759 if ( is_string( $cssText ) ) {
760 $stylePairs[$media][] =
761 ResourceLoader
::filter( 'minify-css', $cssText );
764 } elseif ( is_string( $style ) ) {
765 $stylePairs[$media] = ResourceLoader
::filter( 'minify-css', $style );
769 // Wrap styles into @media groups as needed and flatten into a numerical array
771 'css' => $rl->makeCombinedStyles( $stylePairs )
775 $content['styles'] = $styles;
779 $blob = $this->getMessageBlob( $context );
781 $content['messagesBlob'] = $blob;
784 $templates = $this->getTemplates();
786 $content['templates'] = $templates;
789 $headers = $this->getHeaders( $context );
791 $content['headers'] = $headers;
794 $statTiming = microtime( true ) - $statStart;
795 $statName = strtr( $this->getName(), '.', '_' );
796 $stats->timing( "resourceloader_build.all", 1000 * $statTiming );
797 $stats->timing( "resourceloader_build.$statName", 1000 * $statTiming );
803 * Get a string identifying the current version of this module in a given context.
805 * Whenever anything happens that changes the module's response (e.g. scripts, styles, and
806 * messages) this value must change. This value is used to store module responses in cache.
807 * (Both client-side and server-side.)
809 * It is not recommended to override this directly. Use getDefinitionSummary() instead.
810 * If overridden, one must call the parent getVersionHash(), append data and re-hash.
812 * This method should be quick because it is frequently run by ResourceLoaderStartUpModule to
813 * propagate changes to the client and effectively invalidate cache.
815 * For backward-compatibility, the following optional data providers are automatically included:
817 * - getModifiedTime()
818 * - getModifiedHash()
821 * @param ResourceLoaderContext $context
822 * @return string Hash (should use ResourceLoader::makeHash)
824 public function getVersionHash( ResourceLoaderContext
$context ) {
825 // The startup module produces a manifest with versions representing the entire module.
826 // Typically, the request for the startup module itself has only=scripts. That must apply
827 // only to the startup module content, and not to the module version computed here.
828 $context = new DerivativeResourceLoaderContext( $context );
829 $context->setModules( [] );
830 // Version hash must cover all resources, regardless of startup request itself.
831 $context->setOnly( null );
832 // Compute version hash based on content, not debug urls.
833 $context->setDebug( false );
835 // Cache this somewhat expensive operation. Especially because some classes
836 // (e.g. startup module) iterate more than once over all modules to get versions.
837 $contextHash = $context->getHash();
838 if ( !array_key_exists( $contextHash, $this->versionHash
) ) {
839 if ( $this->enableModuleContentVersion() ) {
840 // Detect changes directly
841 $str = json_encode( $this->getModuleContent( $context ) );
843 // Infer changes based on definition and other metrics
844 $summary = $this->getDefinitionSummary( $context );
845 if ( !isset( $summary['_cacheEpoch'] ) ) {
846 throw new LogicException( 'getDefinitionSummary must call parent method' );
848 $str = json_encode( $summary );
850 $mtime = $this->getModifiedTime( $context );
851 if ( $mtime !== null ) {
852 // Support: MediaWiki 1.25 and earlier
853 $str .= strval( $mtime );
856 $mhash = $this->getModifiedHash( $context );
857 if ( $mhash !== null ) {
858 // Support: MediaWiki 1.25 and earlier
859 $str .= strval( $mhash );
863 $this->versionHash
[$contextHash] = ResourceLoader
::makeHash( $str );
865 return $this->versionHash
[$contextHash];
869 * Whether to generate version hash based on module content.
871 * If a module requires database or file system access to build the module
872 * content, consider disabling this in favour of manually tracking relevant
873 * aspects in getDefinitionSummary(). See getVersionHash() for how this is used.
877 public function enableModuleContentVersion() {
882 * Get the definition summary for this module.
884 * This is the method subclasses are recommended to use to track values in their
885 * version hash. Call this in getVersionHash() and pass it to e.g. json_encode.
887 * Subclasses must call the parent getDefinitionSummary() and build on that.
888 * It is recommended that each subclass appends its own new array. This prevents
889 * clashes or accidental overwrites of existing keys and gives each subclass
890 * its own scope for simple array keys.
893 * $summary = parent::getDefinitionSummary( $context );
901 * Return an array containing values from all significant properties of this
902 * module's definition.
904 * Be careful not to normalise too much. Especially preserve the order of things
905 * that carry significance in getScript and getStyles (T39812).
907 * Avoid including things that are insiginificant (e.g. order of message keys is
908 * insignificant and should be sorted to avoid unnecessary cache invalidation).
910 * This data structure must exclusively contain arrays and scalars as values (avoid
911 * object instances) to allow simple serialisation using json_encode.
913 * If modules have a hash or timestamp from another source, that may be incuded as-is.
915 * A number of utility methods are available to help you gather data. These are not
916 * called by default and must be included by the subclass' getDefinitionSummary().
921 * @param ResourceLoaderContext $context
924 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
926 '_class' => static::class,
927 '_cacheEpoch' => $this->getConfig()->get( 'CacheEpoch' ),
932 * Get this module's last modification timestamp for a given context.
934 * @deprecated since 1.26 Use getDefinitionSummary() instead
935 * @param ResourceLoaderContext $context Context object
936 * @return int|null UNIX timestamp
938 public function getModifiedTime( ResourceLoaderContext
$context ) {
943 * Helper method for providing a version hash to getVersionHash().
945 * @deprecated since 1.26 Use getDefinitionSummary() instead
946 * @param ResourceLoaderContext $context
947 * @return string|null Hash
949 public function getModifiedHash( ResourceLoaderContext
$context ) {
954 * Back-compat dummy for old subclass implementations of getModifiedTime().
956 * This method used to use ObjectCache to track when a hash was first seen. That principle
957 * stems from a time that ResourceLoader could only identify module versions by timestamp.
958 * That is no longer the case. Use getDefinitionSummary() directly.
960 * @deprecated since 1.26 Superseded by getVersionHash()
961 * @param ResourceLoaderContext $context
962 * @return int UNIX timestamp
964 public function getHashMtime( ResourceLoaderContext
$context ) {
965 if ( !is_string( $this->getModifiedHash( $context ) ) ) {
973 * Back-compat dummy for old subclass implementations of getModifiedTime().
976 * @deprecated since 1.26 Superseded by getVersionHash()
977 * @param ResourceLoaderContext $context
978 * @return int UNIX timestamp
980 public function getDefinitionMtime( ResourceLoaderContext
$context ) {
981 if ( $this->getDefinitionSummary( $context ) === null ) {
989 * Check whether this module is known to be empty. If a child class
990 * has an easy and cheap way to determine that this module is
991 * definitely going to be empty, it should override this method to
992 * return true in that case. Callers may optimize the request for this
993 * module away if this function returns true.
994 * @param ResourceLoaderContext $context
997 public function isKnownEmpty( ResourceLoaderContext
$context ) {
1002 * Check whether this module should be embeded rather than linked
1004 * Modules returning true here will be embedded rather than loaded by
1005 * ResourceLoaderClientHtml.
1008 * @param ResourceLoaderContext $context
1011 public function shouldEmbedModule( ResourceLoaderContext
$context ) {
1012 return $this->getGroup() === 'private';
1015 /** @var JSParser Lazy-initialized; use self::javaScriptParser() */
1016 private static $jsParser;
1017 private static $parseCacheVersion = 1;
1020 * Validate a given script file; if valid returns the original source.
1021 * If invalid, returns replacement JS source that throws an exception.
1023 * @param string $fileName
1024 * @param string $contents
1025 * @return string JS with the original, or a replacement error
1027 protected function validateScriptFile( $fileName, $contents ) {
1028 if ( !$this->getConfig()->get( 'ResourceLoaderValidateJS' ) ) {
1031 $cache = ObjectCache
::getMainWANInstance();
1032 return $cache->getWithSetCallback(
1033 $cache->makeGlobalKey(
1036 self
::$parseCacheVersion,
1041 function () use ( $contents, $fileName ) {
1042 $parser = self
::javaScriptParser();
1044 $parser->parse( $contents, $fileName, 1 );
1045 $result = $contents;
1046 } catch ( Exception
$e ) {
1047 // We'll save this to cache to avoid having to re-validate broken JS
1048 $err = $e->getMessage();
1049 $result = "mw.log.error(" .
1050 Xml
::encodeJsVar( "JavaScript parse error: $err" ) . ");";
1060 protected static function javaScriptParser() {
1061 if ( !self
::$jsParser ) {
1062 self
::$jsParser = new JSParser();
1064 return self
::$jsParser;
1068 * Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist.
1071 * @param string $filePath File path
1072 * @return int UNIX timestamp
1074 protected static function safeFilemtime( $filePath ) {
1075 MediaWiki\
suppressWarnings();
1076 $mtime = filemtime( $filePath ) ?
: 1;
1077 MediaWiki\restoreWarnings
();
1082 * Compute a non-cryptographic string hash of a file's contents.
1083 * If the file does not exist or cannot be read, returns an empty string.
1085 * @since 1.26 Uses MD4 instead of SHA1.
1086 * @param string $filePath File path
1087 * @return string Hash
1089 protected static function safeFileHash( $filePath ) {
1090 return FileContentsHasher
::getFileContentsHash( $filePath );