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 $name = null;
69 protected $targets = [ 'desktop' ];
71 // In-object cache for file dependencies
72 protected $fileDeps = [];
73 // In-object cache for message blob (keyed by language)
74 protected $msgBlobs = [];
75 // In-object cache for version hash
76 protected $versionHash = [];
77 // In-object cache for module content
78 protected $contents = [];
88 protected $deprecated = false;
91 * @var LoggerInterface
96 * Get this module's name. This is set when the module is registered
97 * with ResourceLoader::register()
99 * @return string|null Name (string) or null if no name was set
101 public function getName() {
106 * Set this module's name. This is called by ResourceLoader::register()
107 * when registering the module. Other code should not call this.
109 * @param string $name Name
111 public function setName( $name ) {
116 * Get this module's origin. This is set when the module is registered
117 * with ResourceLoader::register()
119 * @return int ResourceLoaderModule class constant, the subclass default
120 * if not set manually
122 public function getOrigin() {
123 return $this->origin
;
127 * @param ResourceLoaderContext $context
130 public function getFlip( $context ) {
133 return $wgContLang->getDir() !== $context->getDirection();
137 * Get JS representing deprecation information for the current module if available
139 * @return string JavaScript code
141 protected function getDeprecationInformation() {
142 $deprecationInfo = $this->deprecated
;
143 if ( $deprecationInfo ) {
144 $name = $this->getName();
145 $warning = 'This page is using the deprecated ResourceLoader module "' . $name . '".';
146 if ( is_string( $deprecationInfo ) ) {
147 $warning .= "\n" . $deprecationInfo;
149 return Xml
::encodeJsCall(
159 * Get all JS for this module for a given language and skin.
160 * Includes all relevant JS except loader scripts.
162 * @param ResourceLoaderContext $context
163 * @return string JavaScript code
165 public function getScript( ResourceLoaderContext
$context ) {
166 // Stub, override expected
171 * Takes named templates by the module and returns an array mapping.
173 * @return array of templates mapping template alias to content
175 public function getTemplates() {
176 // Stub, override expected.
184 public function getConfig() {
185 if ( $this->config
=== null ) {
186 // Ugh, fall back to default
187 $this->config
= MediaWikiServices
::getInstance()->getMainConfig();
190 return $this->config
;
194 * @param Config $config
197 public function setConfig( Config
$config ) {
198 $this->config
= $config;
203 * @param LoggerInterface $logger
206 public function setLogger( LoggerInterface
$logger ) {
207 $this->logger
= $logger;
212 * @return LoggerInterface
214 protected function getLogger() {
215 if ( !$this->logger
) {
216 $this->logger
= new NullLogger();
218 return $this->logger
;
222 * Get the URL or URLs to load for this module's JS in debug mode.
223 * The default behavior is to return a load.php?only=scripts URL for
224 * the module, but file-based modules will want to override this to
225 * load the files directly.
227 * This function is called only when 1) we're in debug mode, 2) there
228 * is no only= parameter and 3) supportsURLLoading() returns true.
229 * #2 is important to prevent an infinite loop, therefore this function
230 * MUST return either an only= URL or a non-load.php URL.
232 * @param ResourceLoaderContext $context
233 * @return array Array of URLs
235 public function getScriptURLsForDebug( ResourceLoaderContext
$context ) {
236 $resourceLoader = $context->getResourceLoader();
237 $derivative = new DerivativeResourceLoaderContext( $context );
238 $derivative->setModules( [ $this->getName() ] );
239 $derivative->setOnly( 'scripts' );
240 $derivative->setDebug( true );
242 $url = $resourceLoader->createLoaderURL(
251 * Whether this module supports URL loading. If this function returns false,
252 * getScript() will be used even in cases (debug mode, no only param) where
253 * getScriptURLsForDebug() would normally be used instead.
256 public function supportsURLLoading() {
261 * Get all CSS for this module for a given skin.
263 * @param ResourceLoaderContext $context
264 * @return array List of CSS strings or array of CSS strings keyed by media type.
265 * like [ 'screen' => '.foo { width: 0 }' ];
266 * or [ 'screen' => [ '.foo { width: 0 }' ] ];
268 public function getStyles( ResourceLoaderContext
$context ) {
269 // Stub, override expected
274 * Get the URL or URLs to load for this module's CSS in debug mode.
275 * The default behavior is to return a load.php?only=styles URL for
276 * the module, but file-based modules will want to override this to
277 * load the files directly. See also getScriptURLsForDebug()
279 * @param ResourceLoaderContext $context
280 * @return array [ mediaType => [ URL1, URL2, ... ], ... ]
282 public function getStyleURLsForDebug( ResourceLoaderContext
$context ) {
283 $resourceLoader = $context->getResourceLoader();
284 $derivative = new DerivativeResourceLoaderContext( $context );
285 $derivative->setModules( [ $this->getName() ] );
286 $derivative->setOnly( 'styles' );
287 $derivative->setDebug( true );
289 $url = $resourceLoader->createLoaderURL(
294 return [ 'all' => [ $url ] ];
298 * Get the messages needed for this module.
300 * To get a JSON blob with messages, use MessageBlobStore::get()
302 * @return array List of message keys. Keys may occur more than once
304 public function getMessages() {
305 // Stub, override expected
310 * Get the group this module is in.
312 * @return string Group name
314 public function getGroup() {
315 // Stub, override expected
320 * Get the origin of this module. Should only be overridden for foreign modules.
322 * @return string Origin name, 'local' for local modules
324 public function getSource() {
325 // Stub, override expected
330 * From where in the page HTML should this module be loaded?
332 * @deprecated since 1.29 Obsolete. All modules load async from `<head>`.
335 public function getPosition() {
340 * Whether this module's JS expects to work without the client-side ResourceLoader module.
341 * Returning true from this function will prevent mw.loader.state() call from being
342 * appended to the bottom of the script.
346 public function isRaw() {
351 * Get a list of modules this module depends on.
353 * Dependency information is taken into account when loading a module
354 * on the client side.
356 * Note: It is expected that $context will be made non-optional in the near
359 * @param ResourceLoaderContext $context
360 * @return array List of module names as strings
362 public function getDependencies( ResourceLoaderContext
$context = null ) {
363 // Stub, override expected
368 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
370 * @return array Array of strings
372 public function getTargets() {
373 return $this->targets
;
377 * Get the module's load type.
380 * @return string ResourceLoaderModule LOAD_* constant
382 public function getType() {
383 return self
::LOAD_GENERAL
;
387 * Get the skip function.
389 * Modules that provide fallback functionality can provide a "skip function". This
390 * function, if provided, will be passed along to the module registry on the client.
391 * When this module is loaded (either directly or as a dependency of another module),
392 * then this function is executed first. If the function returns true, the module will
393 * instantly be considered "ready" without requesting the associated module resources.
395 * The value returned here must be valid javascript for execution in a private function.
396 * It must not contain the "function () {" and "}" wrapper though.
398 * @return string|null A JavaScript function body returning a boolean value, or null
400 public function getSkipFunction() {
405 * Get the files this module depends on indirectly for a given skin.
407 * These are only image files referenced by the module's stylesheet.
409 * @param ResourceLoaderContext $context
410 * @return array List of files
412 protected function getFileDependencies( ResourceLoaderContext
$context ) {
413 $vary = $context->getSkin() . '|' . $context->getLanguage();
415 // Try in-object cache first
416 if ( !isset( $this->fileDeps
[$vary] ) ) {
417 $dbr = wfGetDB( DB_REPLICA
);
418 $deps = $dbr->selectField( 'module_deps',
421 'md_module' => $this->getName(),
427 if ( !is_null( $deps ) ) {
428 $this->fileDeps
[$vary] = self
::expandRelativePaths(
429 (array)FormatJson
::decode( $deps, true )
432 $this->fileDeps
[$vary] = [];
435 return $this->fileDeps
[$vary];
439 * Set in-object cache for file dependencies.
441 * This is used to retrieve data in batches. See ResourceLoader::preloadModuleInfo().
442 * To save the data, use saveFileDependencies().
444 * @param ResourceLoaderContext $context
445 * @param string[] $files Array of file names
447 public function setFileDependencies( ResourceLoaderContext
$context, $files ) {
448 $vary = $context->getSkin() . '|' . $context->getLanguage();
449 $this->fileDeps
[$vary] = $files;
453 * Set the files this module depends on indirectly for a given skin.
456 * @param ResourceLoaderContext $context
457 * @param array $localFileRefs List of files
459 protected function saveFileDependencies( ResourceLoaderContext
$context, $localFileRefs ) {
461 // Related bugs and performance considerations:
462 // 1. Don't needlessly change the database value with the same list in a
463 // different order or with duplicates.
464 // 2. Use relative paths to avoid ghost entries when $IP changes. (T111481)
465 // 3. Don't needlessly replace the database with the same value
466 // just because $IP changed (e.g. when upgrading a wiki).
467 // 4. Don't create an endless replace loop on every request for this
468 // module when '../' is used anywhere. Even though both are expanded
469 // (one expanded by getFileDependencies from the DB, the other is
470 // still raw as originally read by RL), the latter has not
471 // been normalized yet.
474 $localFileRefs = array_values( array_unique( $localFileRefs ) );
475 sort( $localFileRefs );
476 $localPaths = self
::getRelativePaths( $localFileRefs );
478 $storedPaths = self
::getRelativePaths( $this->getFileDependencies( $context ) );
479 // If the list has been modified since last time we cached it, update the cache
480 if ( $localPaths !== $storedPaths ) {
481 $vary = $context->getSkin() . '|' . $context->getLanguage();
482 $cache = ObjectCache
::getLocalClusterInstance();
483 $key = $cache->makeKey( __METHOD__
, $this->getName(), $vary );
484 $scopeLock = $cache->getScopedLock( $key, 0 );
486 return; // T124649; avoid write slams
489 $deps = FormatJson
::encode( $localPaths );
490 $dbw = wfGetDB( DB_MASTER
);
491 $dbw->upsert( 'module_deps',
493 'md_module' => $this->getName(),
497 [ 'md_module', 'md_skin' ],
503 if ( $dbw->trxLevel() ) {
504 $dbw->onTransactionResolution(
505 function () use ( &$scopeLock ) {
506 ScopedCallback
::consume( $scopeLock ); // release after commit
512 } catch ( Exception
$e ) {
513 wfDebugLog( 'resourceloader', __METHOD__
. ": failed to update DB: $e" );
518 * Make file paths relative to MediaWiki directory.
520 * This is used to make file paths safe for storing in a database without the paths
521 * becoming stale or incorrect when MediaWiki is moved or upgraded (T111481).
524 * @param array $filePaths
527 public static function getRelativePaths( array $filePaths ) {
529 return array_map( function ( $path ) use ( $IP ) {
530 return RelPath\
getRelativePath( $path, $IP );
535 * Expand directories relative to $IP.
538 * @param array $filePaths
541 public static function expandRelativePaths( array $filePaths ) {
543 return array_map( function ( $path ) use ( $IP ) {
544 return RelPath\
joinPath( $IP, $path );
549 * Get the hash of the message blob.
552 * @param ResourceLoaderContext $context
553 * @return string|null JSON blob or null if module has no messages
555 protected function getMessageBlob( ResourceLoaderContext
$context ) {
556 if ( !$this->getMessages() ) {
557 // Don't bother consulting MessageBlobStore
560 // Message blobs may only vary language, not by context keys
561 $lang = $context->getLanguage();
562 if ( !isset( $this->msgBlobs
[$lang] ) ) {
563 $this->getLogger()->warning( 'Message blob for {module} should have been preloaded', [
564 'module' => $this->getName(),
566 $store = $context->getResourceLoader()->getMessageBlobStore();
567 $this->msgBlobs
[$lang] = $store->getBlob( $this, $lang );
569 return $this->msgBlobs
[$lang];
573 * Set in-object cache for message blobs.
575 * Used to allow fetching of message blobs in batches. See ResourceLoader::preloadModuleInfo().
578 * @param string|null $blob JSON blob or null
579 * @param string $lang Language code
581 public function setMessageBlob( $blob, $lang ) {
582 $this->msgBlobs
[$lang] = $blob;
586 * Get headers to send as part of a module web response.
588 * It is not supported to send headers through this method that are
589 * required to be unique or otherwise sent once in an HTTP response
590 * because clients may make batch requests for multiple modules (as
591 * is the default behaviour for ResourceLoader clients).
593 * For exclusive or aggregated headers, see ResourceLoader::sendResponseHeaders().
596 * @param ResourceLoaderContext $context
597 * @return string[] Array of HTTP response headers
599 final public function getHeaders( ResourceLoaderContext
$context ) {
602 $formattedLinks = [];
603 foreach ( $this->getPreloadLinks( $context ) as $url => $attribs ) {
604 $link = "<{$url}>;rel=preload";
605 foreach ( $attribs as $key => $val ) {
606 $link .= ";{$key}={$val}";
608 $formattedLinks[] = $link;
610 if ( $formattedLinks ) {
611 $headers[] = 'Link: ' . implode( ',', $formattedLinks );
618 * Get a list of resources that web browsers may preload.
620 * Behaviour of rel=preload link is specified at <https://www.w3.org/TR/preload/>.
622 * Use case for ResourceLoader originally part of T164299.
626 * protected function getPreloadLinks() {
628 * 'https://example.org/script.js' => [ 'as' => 'script' ],
629 * 'https://example.org/image.png' => [ 'as' => 'image' ],
634 * @par Example using HiDPI image variants
636 * protected function getPreloadLinks() {
638 * 'https://example.org/logo.png' => [
640 * 'media' => 'not all and (min-resolution: 2dppx)',
642 * 'https://example.org/logo@2x.png' => [
644 * 'media' => '(min-resolution: 2dppx)',
650 * @see ResourceLoaderModule::getHeaders
652 * @param ResourceLoaderContext $context
653 * @return array Keyed by url, values must be an array containing
654 * at least an 'as' key. Optionally a 'media' key as well.
656 protected function getPreloadLinks( ResourceLoaderContext
$context ) {
661 * Get module-specific LESS variables, if any.
664 * @param ResourceLoaderContext $context
665 * @return array Module-specific LESS variables.
667 protected function getLessVars( ResourceLoaderContext
$context ) {
672 * Get an array of this module's resources. Ready for serving to the web.
675 * @param ResourceLoaderContext $context
678 public function getModuleContent( ResourceLoaderContext
$context ) {
679 $contextHash = $context->getHash();
680 // Cache this expensive operation. This calls builds the scripts, styles, and messages
681 // content which typically involves filesystem and/or database access.
682 if ( !array_key_exists( $contextHash, $this->contents
) ) {
683 $this->contents
[$contextHash] = $this->buildContent( $context );
685 return $this->contents
[$contextHash];
689 * Bundle all resources attached to this module into an array.
692 * @param ResourceLoaderContext $context
695 final protected function buildContent( ResourceLoaderContext
$context ) {
696 $rl = $context->getResourceLoader();
697 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
698 $statStart = microtime( true );
700 // Only include properties that are relevant to this context (e.g. only=scripts)
701 // and that are non-empty (e.g. don't include "templates" for modules without
702 // templates). This helps prevent invalidating cache for all modules when new
703 // optional properties are introduced.
707 if ( $context->shouldIncludeScripts() ) {
708 // If we are in debug mode, we'll want to return an array of URLs if possible
709 // However, we can't do this if the module doesn't support it
710 // We also can't do this if there is an only= parameter, because we have to give
711 // the module a way to return a load.php URL without causing an infinite loop
712 if ( $context->getDebug() && !$context->getOnly() && $this->supportsURLLoading() ) {
713 $scripts = $this->getScriptURLsForDebug( $context );
715 $scripts = $this->getScript( $context );
716 // Make the script safe to concatenate by making sure there is at least one
717 // trailing new line at the end of the content. Previously, this looked for
718 // a semi-colon instead, but that breaks concatenation if the semicolon
719 // is inside a comment like "// foo();". Instead, simply use a
720 // line break as separator which matches JavaScript native logic for implicitly
721 // ending statements even if a semi-colon is missing.
722 // Bugs: T29054, T162719.
723 if ( is_string( $scripts )
724 && strlen( $scripts )
725 && substr( $scripts, -1 ) !== "\n"
730 $content['scripts'] = $scripts;
734 if ( $context->shouldIncludeStyles() ) {
736 // Don't create empty stylesheets like [ '' => '' ] for modules
737 // that don't *have* any stylesheets (T40024).
738 $stylePairs = $this->getStyles( $context );
739 if ( count( $stylePairs ) ) {
740 // If we are in debug mode without &only= set, we'll want to return an array of URLs
741 // See comment near shouldIncludeScripts() for more details
742 if ( $context->getDebug() && !$context->getOnly() && $this->supportsURLLoading() ) {
744 'url' => $this->getStyleURLsForDebug( $context )
747 // Minify CSS before embedding in mw.loader.implement call
748 // (unless in debug mode)
749 if ( !$context->getDebug() ) {
750 foreach ( $stylePairs as $media => $style ) {
751 // Can be either a string or an array of strings.
752 if ( is_array( $style ) ) {
753 $stylePairs[$media] = [];
754 foreach ( $style as $cssText ) {
755 if ( is_string( $cssText ) ) {
756 $stylePairs[$media][] =
757 ResourceLoader
::filter( 'minify-css', $cssText );
760 } elseif ( is_string( $style ) ) {
761 $stylePairs[$media] = ResourceLoader
::filter( 'minify-css', $style );
765 // Wrap styles into @media groups as needed and flatten into a numerical array
767 'css' => $rl->makeCombinedStyles( $stylePairs )
771 $content['styles'] = $styles;
775 $blob = $this->getMessageBlob( $context );
777 $content['messagesBlob'] = $blob;
780 $templates = $this->getTemplates();
782 $content['templates'] = $templates;
785 $headers = $this->getHeaders( $context );
787 $content['headers'] = $headers;
790 $statTiming = microtime( true ) - $statStart;
791 $statName = strtr( $this->getName(), '.', '_' );
792 $stats->timing( "resourceloader_build.all", 1000 * $statTiming );
793 $stats->timing( "resourceloader_build.$statName", 1000 * $statTiming );
799 * Get a string identifying the current version of this module in a given context.
801 * Whenever anything happens that changes the module's response (e.g. scripts, styles, and
802 * messages) this value must change. This value is used to store module responses in cache.
803 * (Both client-side and server-side.)
805 * It is not recommended to override this directly. Use getDefinitionSummary() instead.
806 * If overridden, one must call the parent getVersionHash(), append data and re-hash.
808 * This method should be quick because it is frequently run by ResourceLoaderStartUpModule to
809 * propagate changes to the client and effectively invalidate cache.
811 * For backward-compatibility, the following optional data providers are automatically included:
813 * - getModifiedTime()
814 * - getModifiedHash()
817 * @param ResourceLoaderContext $context
818 * @return string Hash (should use ResourceLoader::makeHash)
820 public function getVersionHash( ResourceLoaderContext
$context ) {
821 // The startup module produces a manifest with versions representing the entire module.
822 // Typically, the request for the startup module itself has only=scripts. That must apply
823 // only to the startup module content, and not to the module version computed here.
824 $context = new DerivativeResourceLoaderContext( $context );
825 $context->setModules( [] );
826 // Version hash must cover all resources, regardless of startup request itself.
827 $context->setOnly( null );
828 // Compute version hash based on content, not debug urls.
829 $context->setDebug( false );
831 // Cache this somewhat expensive operation. Especially because some classes
832 // (e.g. startup module) iterate more than once over all modules to get versions.
833 $contextHash = $context->getHash();
834 if ( !array_key_exists( $contextHash, $this->versionHash
) ) {
835 if ( $this->enableModuleContentVersion() ) {
836 // Detect changes directly
837 $str = json_encode( $this->getModuleContent( $context ) );
839 // Infer changes based on definition and other metrics
840 $summary = $this->getDefinitionSummary( $context );
841 if ( !isset( $summary['_cacheEpoch'] ) ) {
842 throw new LogicException( 'getDefinitionSummary must call parent method' );
844 $str = json_encode( $summary );
846 $mtime = $this->getModifiedTime( $context );
847 if ( $mtime !== null ) {
848 // Support: MediaWiki 1.25 and earlier
849 $str .= strval( $mtime );
852 $mhash = $this->getModifiedHash( $context );
853 if ( $mhash !== null ) {
854 // Support: MediaWiki 1.25 and earlier
855 $str .= strval( $mhash );
859 $this->versionHash
[$contextHash] = ResourceLoader
::makeHash( $str );
861 return $this->versionHash
[$contextHash];
865 * Whether to generate version hash based on module content.
867 * If a module requires database or file system access to build the module
868 * content, consider disabling this in favour of manually tracking relevant
869 * aspects in getDefinitionSummary(). See getVersionHash() for how this is used.
873 public function enableModuleContentVersion() {
878 * Get the definition summary for this module.
880 * This is the method subclasses are recommended to use to track values in their
881 * version hash. Call this in getVersionHash() and pass it to e.g. json_encode.
883 * Subclasses must call the parent getDefinitionSummary() and build on that.
884 * It is recommended that each subclass appends its own new array. This prevents
885 * clashes or accidental overwrites of existing keys and gives each subclass
886 * its own scope for simple array keys.
889 * $summary = parent::getDefinitionSummary( $context );
897 * Return an array containing values from all significant properties of this
898 * module's definition.
900 * Be careful not to normalise too much. Especially preserve the order of things
901 * that carry significance in getScript and getStyles (T39812).
903 * Avoid including things that are insiginificant (e.g. order of message keys is
904 * insignificant and should be sorted to avoid unnecessary cache invalidation).
906 * This data structure must exclusively contain arrays and scalars as values (avoid
907 * object instances) to allow simple serialisation using json_encode.
909 * If modules have a hash or timestamp from another source, that may be incuded as-is.
911 * A number of utility methods are available to help you gather data. These are not
912 * called by default and must be included by the subclass' getDefinitionSummary().
917 * @param ResourceLoaderContext $context
920 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
922 '_class' => static::class,
923 '_cacheEpoch' => $this->getConfig()->get( 'CacheEpoch' ),
928 * Get this module's last modification timestamp for a given context.
930 * @deprecated since 1.26 Use getDefinitionSummary() instead
931 * @param ResourceLoaderContext $context Context object
932 * @return int|null UNIX timestamp
934 public function getModifiedTime( ResourceLoaderContext
$context ) {
939 * Helper method for providing a version hash to getVersionHash().
941 * @deprecated since 1.26 Use getDefinitionSummary() instead
942 * @param ResourceLoaderContext $context
943 * @return string|null Hash
945 public function getModifiedHash( ResourceLoaderContext
$context ) {
950 * Back-compat dummy for old subclass implementations of getModifiedTime().
952 * This method used to use ObjectCache to track when a hash was first seen. That principle
953 * stems from a time that ResourceLoader could only identify module versions by timestamp.
954 * That is no longer the case. Use getDefinitionSummary() directly.
956 * @deprecated since 1.26 Superseded by getVersionHash()
957 * @param ResourceLoaderContext $context
958 * @return int UNIX timestamp
960 public function getHashMtime( ResourceLoaderContext
$context ) {
961 if ( !is_string( $this->getModifiedHash( $context ) ) ) {
969 * Back-compat dummy for old subclass implementations of getModifiedTime().
972 * @deprecated since 1.26 Superseded by getVersionHash()
973 * @param ResourceLoaderContext $context
974 * @return int UNIX timestamp
976 public function getDefinitionMtime( ResourceLoaderContext
$context ) {
977 if ( $this->getDefinitionSummary( $context ) === null ) {
985 * Check whether this module is known to be empty. If a child class
986 * has an easy and cheap way to determine that this module is
987 * definitely going to be empty, it should override this method to
988 * return true in that case. Callers may optimize the request for this
989 * module away if this function returns true.
990 * @param ResourceLoaderContext $context
993 public function isKnownEmpty( ResourceLoaderContext
$context ) {
998 * Check whether this module should be embeded rather than linked
1000 * Modules returning true here will be embedded rather than loaded by
1001 * ResourceLoaderClientHtml.
1004 * @param ResourceLoaderContext $context
1007 public function shouldEmbedModule( ResourceLoaderContext
$context ) {
1008 return $this->getGroup() === 'private';
1011 /** @var JSParser Lazy-initialized; use self::javaScriptParser() */
1012 private static $jsParser;
1013 private static $parseCacheVersion = 1;
1016 * Validate a given script file; if valid returns the original source.
1017 * If invalid, returns replacement JS source that throws an exception.
1019 * @param string $fileName
1020 * @param string $contents
1021 * @return string JS with the original, or a replacement error
1023 protected function validateScriptFile( $fileName, $contents ) {
1024 if ( !$this->getConfig()->get( 'ResourceLoaderValidateJS' ) ) {
1027 $cache = ObjectCache
::getMainWANInstance();
1028 return $cache->getWithSetCallback(
1029 $cache->makeGlobalKey(
1032 self
::$parseCacheVersion,
1037 function () use ( $contents, $fileName ) {
1038 $parser = self
::javaScriptParser();
1040 $parser->parse( $contents, $fileName, 1 );
1041 $result = $contents;
1042 } catch ( Exception
$e ) {
1043 // We'll save this to cache to avoid having to re-validate broken JS
1044 $err = $e->getMessage();
1045 $result = "mw.log.error(" .
1046 Xml
::encodeJsVar( "JavaScript parse error: $err" ) . ");";
1056 protected static function javaScriptParser() {
1057 if ( !self
::$jsParser ) {
1058 self
::$jsParser = new JSParser();
1060 return self
::$jsParser;
1064 * Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist.
1067 * @param string $filePath File path
1068 * @return int UNIX timestamp
1070 protected static function safeFilemtime( $filePath ) {
1071 MediaWiki\
suppressWarnings();
1072 $mtime = filemtime( $filePath ) ?
: 1;
1073 MediaWiki\restoreWarnings
();
1078 * Compute a non-cryptographic string hash of a file's contents.
1079 * If the file does not exist or cannot be read, returns an empty string.
1081 * @since 1.26 Uses MD4 instead of SHA1.
1082 * @param string $filePath File path
1083 * @return string Hash
1085 protected static function safeFileHash( $filePath ) {
1086 return FileContentsHasher
::getFileContentsHash( $filePath );