3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
19 * @author Trevor Parscal
20 * @author Roan Kattouw
23 use MediaWiki\MediaWikiServices
;
24 use Psr\Log\LoggerAwareInterface
;
25 use Psr\Log\LoggerInterface
;
26 use Psr\Log\NullLogger
;
27 use Wikimedia\AtEase\AtEase
;
28 use Wikimedia\RelPath
;
29 use Wikimedia\ScopedCallback
;
32 * Abstraction for ResourceLoader modules, with name registration and maxage functionality.
34 * @ingroup ResourceLoader
37 abstract class ResourceLoaderModule
implements LoggerAwareInterface
{
40 /** @var LoggerInterface */
44 * Script and style modules form a hierarchy of trustworthiness, with core modules
45 * like skins and jQuery as most trustworthy, and user scripts as least trustworthy. We can
46 * limit the types of scripts and styles we allow to load on, say, sensitive special
47 * pages like Special:UserLogin and Special:Preferences
50 protected $origin = self
::ORIGIN_CORE_SITEWIDE
;
52 /** @var string|null Module name */
53 protected $name = null;
54 /** @var string[] What client platforms the module targets (e.g. desktop, mobile) */
55 protected $targets = [ 'desktop' ];
57 /** @var array Map of (variant => indirect file dependencies) */
58 protected $fileDeps = [];
59 /** @var array Map of (language => in-object cache for message blob) */
60 protected $msgBlobs = [];
61 /** @var array Map of (context hash => cached module version hash) */
62 protected $versionHash = [];
63 /** @var array Map of (context hash => cached module content) */
64 protected $contents = [];
66 /** @var string|bool Deprecation string or true if deprecated; false otherwise */
67 protected $deprecated = false;
69 /** @var string Scripts only */
70 const TYPE_SCRIPTS
= 'scripts';
71 /** @var string Styles only */
72 const TYPE_STYLES
= 'styles';
73 /** @var string Scripts and styles */
74 const TYPE_COMBINED
= 'combined';
76 /** @var string Module only has styles (loaded via <style> or <link rel=stylesheet>) */
77 const LOAD_STYLES
= 'styles';
78 /** @var string Module may have other resources (loaded via mw.loader from a script) */
79 const LOAD_GENERAL
= 'general';
81 /** @var int Sitewide core module like a skin file or jQuery component */
82 const ORIGIN_CORE_SITEWIDE
= 1;
83 /** @var int Per-user module generated by the software */
84 const ORIGIN_CORE_INDIVIDUAL
= 2;
86 * Sitewide module generated from user-editable files, like MediaWiki:Common.js,
87 * or modules accessible to multiple users, such as those generated by the Gadgets extension.
90 const ORIGIN_USER_SITEWIDE
= 3;
91 /** @var int Per-user module generated from user-editable files, like User:Me/vector.js */
92 const ORIGIN_USER_INDIVIDUAL
= 4;
93 /** @var int An access constant; make sure this is kept as the largest number in this group */
94 const ORIGIN_ALL
= 10;
97 * Get this module's name. This is set when the module is registered
98 * with ResourceLoader::register()
100 * @return string|null Name (string) or null if no name was set
102 public function getName() {
107 * Set this module's name. This is called by ResourceLoader::register()
108 * when registering the module. Other code should not call this.
110 * @param string $name
112 public function setName( $name ) {
117 * Get this module's origin. This is set when the module is registered
118 * with ResourceLoader::register()
120 * @return int ResourceLoaderModule class constant, the subclass default
121 * if not set manually
123 public function getOrigin() {
124 return $this->origin
;
128 * @param ResourceLoaderContext $context
131 public function getFlip( $context ) {
132 return MediaWikiServices
::getInstance()->getContentLanguage()->getDir() !==
133 $context->getDirection();
137 * Get JS representing deprecation information for the current module if available
139 * @return string JavaScript code
141 public 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 'mw.log.warn(' . ResourceLoader
::encodeJsonForScript( $warning ) . ');';
156 * Get all JS for this module for a given language and skin.
157 * Includes all relevant JS except loader scripts.
159 * For "plain" script modules, this should return a string with JS code. For multi-file modules
160 * where require() is used to load one file from another file, this should return an array
161 * structured as follows:
164 * 'file1.js' => [ 'type' => 'script', 'content' => 'JS code' ],
165 * 'file2.js' => [ 'type' => 'script', 'content' => 'JS code' ],
166 * 'data.json' => [ 'type' => 'data', 'content' => array ]
168 * 'main' => 'file1.js'
171 * @param ResourceLoaderContext $context
172 * @return string|array JavaScript code (string), or multi-file structure described above (array)
174 public function getScript( ResourceLoaderContext
$context ) {
175 // Stub, override expected
180 * Takes named templates by the module and returns an array mapping.
182 * @return string[] Array of templates mapping template alias to content
184 public function getTemplates() {
185 // Stub, override expected.
193 public function getConfig() {
194 if ( $this->config
=== null ) {
195 // Ugh, fall back to default
196 $this->config
= MediaWikiServices
::getInstance()->getMainConfig();
199 return $this->config
;
203 * @param Config $config
206 public function setConfig( Config
$config ) {
207 $this->config
= $config;
212 * @param LoggerInterface $logger
214 public function setLogger( LoggerInterface
$logger ) {
215 $this->logger
= $logger;
220 * @return LoggerInterface
222 protected function getLogger() {
223 if ( !$this->logger
) {
224 $this->logger
= new NullLogger();
226 return $this->logger
;
230 * Get the URL or URLs to load for this module's JS in debug mode.
231 * The default behavior is to return a load.php?only=scripts URL for
232 * the module, but file-based modules will want to override this to
233 * load the files directly.
235 * This function is called only when 1) we're in debug mode, 2) there
236 * is no only= parameter and 3) supportsURLLoading() returns true.
237 * #2 is important to prevent an infinite loop, therefore this function
238 * MUST return either an only= URL or a non-load.php URL.
240 * @param ResourceLoaderContext $context
241 * @return array Array of URLs
243 public function getScriptURLsForDebug( ResourceLoaderContext
$context ) {
244 $resourceLoader = $context->getResourceLoader();
245 $derivative = new DerivativeResourceLoaderContext( $context );
246 $derivative->setModules( [ $this->getName() ] );
247 $derivative->setOnly( 'scripts' );
248 $derivative->setDebug( true );
250 $url = $resourceLoader->createLoaderURL(
259 * Whether this module supports URL loading. If this function returns false,
260 * getScript() will be used even in cases (debug mode, no only param) where
261 * getScriptURLsForDebug() would normally be used instead.
264 public function supportsURLLoading() {
269 * Get all CSS for this module for a given skin.
271 * @param ResourceLoaderContext $context
272 * @return array List of CSS strings or array of CSS strings keyed by media type.
273 * like [ 'screen' => '.foo { width: 0 }' ];
274 * or [ 'screen' => [ '.foo { width: 0 }' ] ];
276 public function getStyles( ResourceLoaderContext
$context ) {
277 // Stub, override expected
282 * Get the URL or URLs to load for this module's CSS in debug mode.
283 * The default behavior is to return a load.php?only=styles URL for
284 * the module, but file-based modules will want to override this to
285 * load the files directly. See also getScriptURLsForDebug()
287 * @param ResourceLoaderContext $context
288 * @return array [ mediaType => [ URL1, URL2, ... ], ... ]
290 public function getStyleURLsForDebug( ResourceLoaderContext
$context ) {
291 $resourceLoader = $context->getResourceLoader();
292 $derivative = new DerivativeResourceLoaderContext( $context );
293 $derivative->setModules( [ $this->getName() ] );
294 $derivative->setOnly( 'styles' );
295 $derivative->setDebug( true );
297 $url = $resourceLoader->createLoaderURL(
302 return [ 'all' => [ $url ] ];
306 * Get the messages needed for this module.
308 * To get a JSON blob with messages, use MessageBlobStore::get()
310 * @return array List of message keys. Keys may occur more than once
312 public function getMessages() {
313 // Stub, override expected
318 * Get the group this module is in.
320 * @return string Group name
322 public function getGroup() {
323 // Stub, override expected
328 * Get the source of this module. Should only be overridden for foreign modules.
330 * @return string Source name, 'local' for local modules
332 public function getSource() {
333 // Stub, override expected
338 * Get a list of modules this module depends on.
340 * Dependency information is taken into account when loading a module
341 * on the client side.
343 * Note: It is expected that $context will be made non-optional in the near
346 * @param ResourceLoaderContext|null $context
347 * @return array List of module names as strings
349 public function getDependencies( ResourceLoaderContext
$context = null ) {
350 // Stub, override expected
355 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
357 * @return array Array of strings
359 public function getTargets() {
360 return $this->targets
;
364 * Get the module's load type.
367 * @return string ResourceLoaderModule LOAD_* constant
369 public function getType() {
370 return self
::LOAD_GENERAL
;
374 * Get the skip function.
376 * Modules that provide fallback functionality can provide a "skip function". This
377 * function, if provided, will be passed along to the module registry on the client.
378 * When this module is loaded (either directly or as a dependency of another module),
379 * then this function is executed first. If the function returns true, the module will
380 * instantly be considered "ready" without requesting the associated module resources.
382 * The value returned here must be valid javascript for execution in a private function.
383 * It must not contain the "function () {" and "}" wrapper though.
385 * @return string|null A JavaScript function body returning a boolean value, or null
387 public function getSkipFunction() {
392 * Get the files this module depends on indirectly for a given skin.
394 * These are only image files referenced by the module's stylesheet.
396 * @param ResourceLoaderContext $context
397 * @return array List of files
399 protected function getFileDependencies( ResourceLoaderContext
$context ) {
400 $vary = self
::getVary( $context );
402 // Try in-object cache first
403 if ( !isset( $this->fileDeps
[$vary] ) ) {
404 $dbr = wfGetDB( DB_REPLICA
);
405 $deps = $dbr->selectField( 'module_deps',
408 'md_module' => $this->getName(),
414 if ( !is_null( $deps ) ) {
415 $this->fileDeps
[$vary] = self
::expandRelativePaths(
416 (array)json_decode( $deps, true )
419 $this->fileDeps
[$vary] = [];
422 return $this->fileDeps
[$vary];
426 * Set in-object cache for file dependencies.
428 * This is used to retrieve data in batches. See ResourceLoader::preloadModuleInfo().
429 * To save the data, use saveFileDependencies().
431 * @param ResourceLoaderContext $context
432 * @param string[] $files Array of file names
434 public function setFileDependencies( ResourceLoaderContext
$context, $files ) {
435 $vary = self
::getVary( $context );
436 $this->fileDeps
[$vary] = $files;
440 * Set the files this module depends on indirectly for a given skin.
443 * @param ResourceLoaderContext $context
444 * @param array $localFileRefs List of files
446 protected function saveFileDependencies( ResourceLoaderContext
$context, $localFileRefs ) {
448 // Related bugs and performance considerations:
449 // 1. Don't needlessly change the database value with the same list in a
450 // different order or with duplicates.
451 // 2. Use relative paths to avoid ghost entries when $IP changes. (T111481)
452 // 3. Don't needlessly replace the database with the same value
453 // just because $IP changed (e.g. when upgrading a wiki).
454 // 4. Don't create an endless replace loop on every request for this
455 // module when '../' is used anywhere. Even though both are expanded
456 // (one expanded by getFileDependencies from the DB, the other is
457 // still raw as originally read by RL), the latter has not
458 // been normalized yet.
461 $localFileRefs = array_values( array_unique( $localFileRefs ) );
462 sort( $localFileRefs );
463 $localPaths = self
::getRelativePaths( $localFileRefs );
464 $storedPaths = self
::getRelativePaths( $this->getFileDependencies( $context ) );
466 if ( $localPaths === $storedPaths ) {
467 // Unchanged. Avoid needless database query (especially master conn!).
471 // The file deps list has changed, we want to update it.
472 $vary = self
::getVary( $context );
473 $cache = ObjectCache
::getLocalClusterInstance();
474 $key = $cache->makeKey( __METHOD__
, $this->getName(), $vary );
475 $scopeLock = $cache->getScopedLock( $key, 0 );
477 // Another request appears to be doing this update already.
478 // Avoid write slams (T124649).
482 // No needless escaping as this isn't HTML output.
483 // Only stored in the database and parsed in PHP.
484 $deps = json_encode( $localPaths, JSON_UNESCAPED_SLASHES
);
485 $dbw = wfGetDB( DB_MASTER
);
486 $dbw->upsert( 'module_deps',
488 'md_module' => $this->getName(),
492 [ [ 'md_module', 'md_skin' ] ],
499 if ( $dbw->trxLevel() ) {
500 $dbw->onTransactionResolution(
501 function () use ( &$scopeLock ) {
502 ScopedCallback
::consume( $scopeLock ); // release after commit
507 } catch ( Exception
$e ) {
508 // Probably a DB failure. Either the read query from getFileDependencies(),
509 // or the write query above.
510 wfDebugLog( 'resourceloader', __METHOD__
. ": failed to update DB: $e" );
515 * Make file paths relative to MediaWiki directory.
517 * This is used to make file paths safe for storing in a database without the paths
518 * becoming stale or incorrect when MediaWiki is moved or upgraded (T111481).
521 * @param array $filePaths
524 public static function getRelativePaths( array $filePaths ) {
526 return array_map( function ( $path ) use ( $IP ) {
527 return RelPath
::getRelativePath( $path, $IP );
532 * Expand directories relative to $IP.
535 * @param array $filePaths
538 public static function expandRelativePaths( array $filePaths ) {
540 return array_map( function ( $path ) use ( $IP ) {
541 return RelPath
::joinPath( $IP, $path );
546 * Get the hash of the message blob.
549 * @param ResourceLoaderContext $context
550 * @return string|null JSON blob or null if module has no messages
552 protected function getMessageBlob( ResourceLoaderContext
$context ) {
553 if ( !$this->getMessages() ) {
554 // Don't bother consulting MessageBlobStore
557 // Message blobs may only vary language, not by context keys
558 $lang = $context->getLanguage();
559 if ( !isset( $this->msgBlobs
[$lang] ) ) {
560 $this->getLogger()->warning( 'Message blob for {module} should have been preloaded', [
561 'module' => $this->getName(),
563 $store = $context->getResourceLoader()->getMessageBlobStore();
564 $this->msgBlobs
[$lang] = $store->getBlob( $this, $lang );
566 return $this->msgBlobs
[$lang];
570 * Set in-object cache for message blobs.
572 * Used to allow fetching of message blobs in batches. See ResourceLoader::preloadModuleInfo().
575 * @param string|null $blob JSON blob or null
576 * @param string $lang Language code
578 public function setMessageBlob( $blob, $lang ) {
579 $this->msgBlobs
[$lang] = $blob;
583 * Get headers to send as part of a module web response.
585 * It is not supported to send headers through this method that are
586 * required to be unique or otherwise sent once in an HTTP response
587 * because clients may make batch requests for multiple modules (as
588 * is the default behaviour for ResourceLoader clients).
590 * For exclusive or aggregated headers, see ResourceLoader::sendResponseHeaders().
593 * @param ResourceLoaderContext $context
594 * @return string[] Array of HTTP response headers
596 final public function getHeaders( ResourceLoaderContext
$context ) {
599 $formattedLinks = [];
600 foreach ( $this->getPreloadLinks( $context ) as $url => $attribs ) {
601 $link = "<{$url}>;rel=preload";
602 foreach ( $attribs as $key => $val ) {
603 $link .= ";{$key}={$val}";
605 $formattedLinks[] = $link;
607 if ( $formattedLinks ) {
608 $headers[] = 'Link: ' . implode( ',', $formattedLinks );
615 * Get a list of resources that web browsers may preload.
617 * Behaviour of rel=preload link is specified at <https://www.w3.org/TR/preload/>.
619 * Use case for ResourceLoader originally part of T164299.
623 * protected function getPreloadLinks() {
625 * 'https://example.org/script.js' => [ 'as' => 'script' ],
626 * 'https://example.org/image.png' => [ 'as' => 'image' ],
631 * @par Example using HiDPI image variants
633 * protected function getPreloadLinks() {
635 * 'https://example.org/logo.png' => [
637 * 'media' => 'not all and (min-resolution: 2dppx)',
639 * 'https://example.org/logo@2x.png' => [
641 * 'media' => '(min-resolution: 2dppx)',
647 * @see ResourceLoaderModule::getHeaders
649 * @param ResourceLoaderContext $context
650 * @return array Keyed by url, values must be an array containing
651 * at least an 'as' key. Optionally a 'media' key as well.
653 protected function getPreloadLinks( ResourceLoaderContext
$context ) {
658 * Get module-specific LESS variables, if any.
661 * @param ResourceLoaderContext $context
662 * @return array Module-specific LESS variables.
664 protected function getLessVars( ResourceLoaderContext
$context ) {
669 * Get an array of this module's resources. Ready for serving to the web.
672 * @param ResourceLoaderContext $context
675 public function getModuleContent( ResourceLoaderContext
$context ) {
676 $contextHash = $context->getHash();
677 // Cache this expensive operation. This calls builds the scripts, styles, and messages
678 // content which typically involves filesystem and/or database access.
679 if ( !array_key_exists( $contextHash, $this->contents
) ) {
680 $this->contents
[$contextHash] = $this->buildContent( $context );
682 return $this->contents
[$contextHash];
686 * Bundle all resources attached to this module into an array.
689 * @param ResourceLoaderContext $context
692 final protected function buildContent( ResourceLoaderContext
$context ) {
693 $rl = $context->getResourceLoader();
694 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
695 $statStart = microtime( true );
697 // This MUST build both scripts and styles, regardless of whether $context->getOnly()
698 // is 'scripts' or 'styles' because the result is used by getVersionHash which
699 // must be consistent regardless of the 'only' filter on the current request.
700 // Also, when introducing new module content resources (e.g. templates, headers),
701 // these should only be included in the array when they are non-empty so that
702 // existing modules not using them do not get their cache invalidated.
706 // If we are in debug mode, we'll want to return an array of URLs if possible
707 // However, we can't do this if the module doesn't support it.
708 // We also can't do this if there is an only= parameter, because we have to give
709 // the module a way to return a load.php URL without causing an infinite loop
710 if ( $context->getDebug() && !$context->getOnly() && $this->supportsURLLoading() ) {
711 $scripts = $this->getScriptURLsForDebug( $context );
713 $scripts = $this->getScript( $context );
714 // Make the script safe to concatenate by making sure there is at least one
715 // trailing new line at the end of the content. Previously, this looked for
716 // a semi-colon instead, but that breaks concatenation if the semicolon
717 // is inside a comment like "// foo();". Instead, simply use a
718 // line break as separator which matches JavaScript native logic for implicitly
719 // ending statements even if a semi-colon is missing.
720 // Bugs: T29054, T162719.
721 if ( is_string( $scripts )
722 && strlen( $scripts )
723 && substr( $scripts, -1 ) !== "\n"
728 $content['scripts'] = $scripts;
731 // Don't create empty stylesheets like [ '' => '' ] for modules
732 // that don't *have* any stylesheets (T40024).
733 $stylePairs = $this->getStyles( $context );
734 if ( count( $stylePairs ) ) {
735 // If we are in debug mode without &only= set, we'll want to return an array of URLs
736 // See comment near shouldIncludeScripts() for more details
737 if ( $context->getDebug() && !$context->getOnly() && $this->supportsURLLoading() ) {
739 'url' => $this->getStyleURLsForDebug( $context )
742 // Minify CSS before embedding in mw.loader.implement call
743 // (unless in debug mode)
744 if ( !$context->getDebug() ) {
745 foreach ( $stylePairs as $media => $style ) {
746 // Can be either a string or an array of strings.
747 if ( is_array( $style ) ) {
748 $stylePairs[$media] = [];
749 foreach ( $style as $cssText ) {
750 if ( is_string( $cssText ) ) {
751 $stylePairs[$media][] =
752 ResourceLoader
::filter( 'minify-css', $cssText );
755 } elseif ( is_string( $style ) ) {
756 $stylePairs[$media] = ResourceLoader
::filter( 'minify-css', $style );
760 // Wrap styles into @media groups as needed and flatten into a numerical array
762 'css' => $rl->makeCombinedStyles( $stylePairs )
766 $content['styles'] = $styles;
769 $blob = $this->getMessageBlob( $context );
771 $content['messagesBlob'] = $blob;
774 $templates = $this->getTemplates();
776 $content['templates'] = $templates;
779 $headers = $this->getHeaders( $context );
781 $content['headers'] = $headers;
784 $statTiming = microtime( true ) - $statStart;
785 $statName = strtr( $this->getName(), '.', '_' );
786 $stats->timing( "resourceloader_build.all", 1000 * $statTiming );
787 $stats->timing( "resourceloader_build.$statName", 1000 * $statTiming );
793 * Get a string identifying the current version of this module in a given context.
795 * Whenever anything happens that changes the module's response (e.g. scripts, styles, and
796 * messages) this value must change. This value is used to store module responses in cache.
797 * (Both client-side and server-side.)
799 * It is not recommended to override this directly. Use getDefinitionSummary() instead.
800 * If overridden, one must call the parent getVersionHash(), append data and re-hash.
802 * This method should be quick because it is frequently run by ResourceLoaderStartUpModule to
803 * propagate changes to the client and effectively invalidate cache.
806 * @param ResourceLoaderContext $context
807 * @return string Hash (should use ResourceLoader::makeHash)
809 public function getVersionHash( ResourceLoaderContext
$context ) {
810 // Cache this somewhat expensive operation. Especially because some classes
811 // (e.g. startup module) iterate more than once over all modules to get versions.
812 $contextHash = $context->getHash();
813 if ( !array_key_exists( $contextHash, $this->versionHash
) ) {
814 if ( $this->enableModuleContentVersion() ) {
815 // Detect changes directly by hashing the module contents.
816 $str = json_encode( $this->getModuleContent( $context ) );
818 // Infer changes based on definition and other metrics
819 $summary = $this->getDefinitionSummary( $context );
820 if ( !isset( $summary['_class'] ) ) {
821 throw new LogicException( 'getDefinitionSummary must call parent method' );
823 $str = json_encode( $summary );
826 $this->versionHash
[$contextHash] = ResourceLoader
::makeHash( $str );
828 return $this->versionHash
[$contextHash];
832 * Whether to generate version hash based on module content.
834 * If a module requires database or file system access to build the module
835 * content, consider disabling this in favour of manually tracking relevant
836 * aspects in getDefinitionSummary(). See getVersionHash() for how this is used.
840 public function enableModuleContentVersion() {
845 * Get the definition summary for this module.
847 * This is the method subclasses are recommended to use to track values in their
848 * version hash. Call this in getVersionHash() and pass it to e.g. json_encode.
850 * Subclasses must call the parent getDefinitionSummary() and build on that.
851 * It is recommended that each subclass appends its own new array. This prevents
852 * clashes or accidental overwrites of existing keys and gives each subclass
853 * its own scope for simple array keys.
856 * $summary = parent::getDefinitionSummary( $context );
864 * Return an array containing values from all significant properties of this
865 * module's definition.
867 * Be careful not to normalise too much. Especially preserve the order of things
868 * that carry significance in getScript and getStyles (T39812).
870 * Avoid including things that are insiginificant (e.g. order of message keys is
871 * insignificant and should be sorted to avoid unnecessary cache invalidation).
873 * This data structure must exclusively contain arrays and scalars as values (avoid
874 * object instances) to allow simple serialisation using json_encode.
876 * If modules have a hash or timestamp from another source, that may be incuded as-is.
878 * A number of utility methods are available to help you gather data. These are not
879 * called by default and must be included by the subclass' getDefinitionSummary().
884 * @param ResourceLoaderContext $context
887 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
889 '_class' => static::class,
890 // Make sure that when filter cache for minification is invalidated,
891 // we also change the HTTP urls and mw.loader.store keys (T176884).
892 '_cacheVersion' => ResourceLoader
::CACHE_VERSION
,
897 * Check whether this module is known to be empty. If a child class
898 * has an easy and cheap way to determine that this module is
899 * definitely going to be empty, it should override this method to
900 * return true in that case. Callers may optimize the request for this
901 * module away if this function returns true.
902 * @param ResourceLoaderContext $context
905 public function isKnownEmpty( ResourceLoaderContext
$context ) {
910 * Check whether this module should be embeded rather than linked
912 * Modules returning true here will be embedded rather than loaded by
913 * ResourceLoaderClientHtml.
916 * @param ResourceLoaderContext $context
919 public function shouldEmbedModule( ResourceLoaderContext
$context ) {
920 return $this->getGroup() === 'private';
923 /** @var JSParser Lazy-initialized; use self::javaScriptParser() */
924 private static $jsParser;
925 private static $parseCacheVersion = 1;
928 * Validate a given script file; if valid returns the original source.
929 * If invalid, returns replacement JS source that throws an exception.
931 * @param string $fileName
932 * @param string $contents
933 * @return string JS with the original, or a replacement error
935 protected function validateScriptFile( $fileName, $contents ) {
936 if ( !$this->getConfig()->get( 'ResourceLoaderValidateJS' ) ) {
939 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
940 return $cache->getWithSetCallback(
941 $cache->makeGlobalKey(
942 'resourceloader-jsparse',
943 self
::$parseCacheVersion,
948 function () use ( $contents, $fileName ) {
949 $parser = self
::javaScriptParser();
952 AtEase
::suppressWarnings();
953 $parser->parse( $contents, $fileName, 1 );
954 } catch ( Exception
$e ) {
957 AtEase
::restoreWarnings();
960 // Send the error to the browser console client-side.
961 // By returning this as replacement for the actual script,
962 // we ensure modules are safe to load in a batch request,
963 // without causing other unrelated modules to break.
964 return 'mw.log.error(' .
965 Xml
::encodeJsVar( 'JavaScript parse error: ' . $err->getMessage() ) .
976 protected static function javaScriptParser() {
977 if ( !self
::$jsParser ) {
978 self
::$jsParser = new JSParser();
980 return self
::$jsParser;
984 * Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist.
987 * @param string $filePath File path
988 * @return int UNIX timestamp
990 protected static function safeFilemtime( $filePath ) {
991 AtEase
::suppressWarnings();
992 $mtime = filemtime( $filePath ) ?
: 1;
993 AtEase
::restoreWarnings();
998 * Compute a non-cryptographic string hash of a file's contents.
999 * If the file does not exist or cannot be read, returns an empty string.
1001 * @since 1.26 Uses MD4 instead of SHA1.
1002 * @param string $filePath File path
1003 * @return string Hash
1005 protected static function safeFileHash( $filePath ) {
1006 return FileContentsHasher
::getFileContentsHash( $filePath );
1012 * @internal For internal use only.
1013 * @param ResourceLoaderContext $context
1014 * @return string Vary string
1016 public static function getVary( ResourceLoaderContext
$context ) {
1017 return implode( '|', [
1018 $context->getSkin(),
1019 $context->getLanguage(),