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 Psr\Log\LoggerAwareInterface
;
26 use Psr\Log\LoggerInterface
;
27 use Psr\Log\NullLogger
;
30 * Abstraction for ResourceLoader modules, with name registration and maxage functionality.
32 abstract class ResourceLoaderModule
implements LoggerAwareInterface
{
34 const TYPE_SCRIPTS
= 'scripts';
35 const TYPE_STYLES
= 'styles';
36 const TYPE_COMBINED
= 'combined';
38 # sitewide core module like a skin file or jQuery component
39 const ORIGIN_CORE_SITEWIDE
= 1;
41 # per-user module generated by the software
42 const ORIGIN_CORE_INDIVIDUAL
= 2;
44 # sitewide module generated from user-editable files, like MediaWiki:Common.js, or
45 # modules accessible to multiple users, such as those generated by the Gadgets extension.
46 const ORIGIN_USER_SITEWIDE
= 3;
48 # per-user module generated from user-editable files, like User:Me/vector.js
49 const ORIGIN_USER_INDIVIDUAL
= 4;
51 # an access constant; make sure this is kept as the largest number in this group
52 const ORIGIN_ALL
= 10;
54 # script and style modules form a hierarchy of trustworthiness, with core modules like
55 # skins and jQuery as most trustworthy, and user scripts as least trustworthy. We can
56 # limit the types of scripts and styles we allow to load on, say, sensitive special
57 # pages like Special:UserLogin and Special:Preferences
58 protected $origin = self
::ORIGIN_CORE_SITEWIDE
;
60 /* Protected Members */
62 protected $name = null;
63 protected $targets = [ 'desktop' ];
65 // In-object cache for file dependencies
66 protected $fileDeps = [];
67 // In-object cache for message blob (keyed by language)
68 protected $msgBlobs = [];
69 // In-object cache for version hash
70 protected $versionHash = [];
71 // In-object cache for module content
72 protected $contents = [];
80 * @var LoggerInterface
87 * Get this module's name. This is set when the module is registered
88 * with ResourceLoader::register()
90 * @return string|null Name (string) or null if no name was set
92 public function getName() {
97 * Set this module's name. This is called by ResourceLoader::register()
98 * when registering the module. Other code should not call this.
100 * @param string $name Name
102 public function setName( $name ) {
107 * Get this module's origin. This is set when the module is registered
108 * with ResourceLoader::register()
110 * @return int ResourceLoaderModule class constant, the subclass default
111 * if not set manually
113 public function getOrigin() {
114 return $this->origin
;
118 * Set this module's origin. This is called by ResourceLoader::register()
119 * when registering the module. Other code should not call this.
121 * @param int $origin Origin
123 public function setOrigin( $origin ) {
124 $this->origin
= $origin;
128 * @param ResourceLoaderContext $context
131 public function getFlip( $context ) {
134 return $wgContLang->getDir() !== $context->getDirection();
138 * Get all JS for this module for a given language and skin.
139 * Includes all relevant JS except loader scripts.
141 * @param ResourceLoaderContext $context
142 * @return string JavaScript code
144 public function getScript( ResourceLoaderContext
$context ) {
145 // Stub, override expected
150 * Takes named templates by the module and returns an array mapping.
152 * @return array of templates mapping template alias to content
154 public function getTemplates() {
155 // Stub, override expected.
163 public function getConfig() {
164 if ( $this->config
=== null ) {
165 // Ugh, fall back to default
166 $this->config
= ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
169 return $this->config
;
173 * @param Config $config
176 public function setConfig( Config
$config ) {
177 $this->config
= $config;
182 * @param LoggerInterface $logger
185 public function setLogger( LoggerInterface
$logger ) {
186 $this->logger
= $logger;
191 * @return LoggerInterface
193 protected function getLogger() {
194 if ( !$this->logger
) {
195 $this->logger
= new NullLogger();
197 return $this->logger
;
201 * Get the URL or URLs to load for this module's JS in debug mode.
202 * The default behavior is to return a load.php?only=scripts URL for
203 * the module, but file-based modules will want to override this to
204 * load the files directly.
206 * This function is called only when 1) we're in debug mode, 2) there
207 * is no only= parameter and 3) supportsURLLoading() returns true.
208 * #2 is important to prevent an infinite loop, therefore this function
209 * MUST return either an only= URL or a non-load.php URL.
211 * @param ResourceLoaderContext $context
212 * @return array Array of URLs
214 public function getScriptURLsForDebug( ResourceLoaderContext
$context ) {
215 $resourceLoader = $context->getResourceLoader();
216 $derivative = new DerivativeResourceLoaderContext( $context );
217 $derivative->setModules( [ $this->getName() ] );
218 $derivative->setOnly( 'scripts' );
219 $derivative->setDebug( true );
221 $url = $resourceLoader->createLoaderURL(
230 * Whether this module supports URL loading. If this function returns false,
231 * getScript() will be used even in cases (debug mode, no only param) where
232 * getScriptURLsForDebug() would normally be used instead.
235 public function supportsURLLoading() {
240 * Get all CSS for this module for a given skin.
242 * @param ResourceLoaderContext $context
243 * @return array List of CSS strings or array of CSS strings keyed by media type.
244 * like array( 'screen' => '.foo { width: 0 }' );
245 * or array( 'screen' => array( '.foo { width: 0 }' ) );
247 public function getStyles( ResourceLoaderContext
$context ) {
248 // Stub, override expected
253 * Get the URL or URLs to load for this module's CSS in debug mode.
254 * The default behavior is to return a load.php?only=styles URL for
255 * the module, but file-based modules will want to override this to
256 * load the files directly. See also getScriptURLsForDebug()
258 * @param ResourceLoaderContext $context
259 * @return array Array( mediaType => array( URL1, URL2, ... ), ... )
261 public function getStyleURLsForDebug( ResourceLoaderContext
$context ) {
262 $resourceLoader = $context->getResourceLoader();
263 $derivative = new DerivativeResourceLoaderContext( $context );
264 $derivative->setModules( [ $this->getName() ] );
265 $derivative->setOnly( 'styles' );
266 $derivative->setDebug( true );
268 $url = $resourceLoader->createLoaderURL(
273 return [ 'all' => [ $url ] ];
277 * Get the messages needed for this module.
279 * To get a JSON blob with messages, use MessageBlobStore::get()
281 * @return array List of message keys. Keys may occur more than once
283 public function getMessages() {
284 // Stub, override expected
289 * Get the group this module is in.
291 * @return string Group name
293 public function getGroup() {
294 // Stub, override expected
299 * Get the origin of this module. Should only be overridden for foreign modules.
301 * @return string Origin name, 'local' for local modules
303 public function getSource() {
304 // Stub, override expected
309 * Where on the HTML page should this module's JS be loaded?
310 * - 'top': in the "<head>"
311 * - 'bottom': at the bottom of the "<body>"
315 public function getPosition() {
320 * Whether this module's JS expects to work without the client-side ResourceLoader module.
321 * Returning true from this function will prevent mw.loader.state() call from being
322 * appended to the bottom of the script.
326 public function isRaw() {
331 * Get a list of modules this module depends on.
333 * Dependency information is taken into account when loading a module
334 * on the client side.
336 * Note: It is expected that $context will be made non-optional in the near
339 * @param ResourceLoaderContext $context
340 * @return array List of module names as strings
342 public function getDependencies( ResourceLoaderContext
$context = null ) {
343 // Stub, override expected
348 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
350 * @return array Array of strings
352 public function getTargets() {
353 return $this->targets
;
357 * Get the skip function.
359 * Modules that provide fallback functionality can provide a "skip function". This
360 * function, if provided, will be passed along to the module registry on the client.
361 * When this module is loaded (either directly or as a dependency of another module),
362 * then this function is executed first. If the function returns true, the module will
363 * instantly be considered "ready" without requesting the associated module resources.
365 * The value returned here must be valid javascript for execution in a private function.
366 * It must not contain the "function () {" and "}" wrapper though.
368 * @return string|null A JavaScript function body returning a boolean value, or null
370 public function getSkipFunction() {
375 * Get the files this module depends on indirectly for a given skin.
377 * These are only image files referenced by the module's stylesheet.
379 * @param ResourceLoaderContext $context
380 * @return array List of files
382 protected function getFileDependencies( ResourceLoaderContext
$context ) {
383 $vary = $context->getSkin() . '|' . $context->getLanguage();
385 // Try in-object cache first
386 if ( !isset( $this->fileDeps
[$vary] ) ) {
387 $dbr = wfGetDB( DB_SLAVE
);
388 $deps = $dbr->selectField( 'module_deps',
391 'md_module' => $this->getName(),
397 if ( !is_null( $deps ) ) {
398 $this->fileDeps
[$vary] = self
::expandRelativePaths(
399 (array)FormatJson
::decode( $deps, true )
402 $this->fileDeps
[$vary] = [];
405 return $this->fileDeps
[$vary];
409 * Set in-object cache for file dependencies.
411 * This is used to retrieve data in batches. See ResourceLoader::preloadModuleInfo().
412 * To save the data, use saveFileDependencies().
414 * @param ResourceLoaderContext $context
415 * @param string[] $files Array of file names
417 public function setFileDependencies( ResourceLoaderContext
$context, $files ) {
418 $vary = $context->getSkin() . '|' . $context->getLanguage();
419 $this->fileDeps
[$vary] = $files;
423 * Set the files this module depends on indirectly for a given skin.
426 * @param ResourceLoaderContext $context
427 * @param array $localFileRefs List of files
429 protected function saveFileDependencies( ResourceLoaderContext
$context, $localFileRefs ) {
431 $localFileRefs = array_values( array_unique( $localFileRefs ) );
432 sort( $localFileRefs );
435 // If the list has been modified since last time we cached it, update the cache
436 if ( $localFileRefs !== $this->getFileDependencies( $context ) ) {
437 $cache = ObjectCache
::getLocalClusterInstance();
438 $key = $cache->makeKey( __METHOD__
, $this->getName() );
439 $scopeLock = $cache->getScopedLock( $key, 0 );
441 return; // T124649; avoid write slams
444 $vary = $context->getSkin() . '|' . $context->getLanguage();
445 $dbw = wfGetDB( DB_MASTER
);
446 $dbw->replace( 'module_deps',
447 [ [ 'md_module', 'md_skin' ] ],
449 'md_module' => $this->getName(),
451 // Use relative paths to avoid ghost entries when $IP changes (T111481)
452 'md_deps' => FormatJson
::encode( self
::getRelativePaths( $localFileRefs ) ),
456 $dbw->onTransactionIdle( function () use ( &$scopeLock ) {
457 ScopedCallback
::consume( $scopeLock ); // release after commit
460 } catch ( Exception
$e ) {
461 wfDebugLog( 'resourceloader', __METHOD__
. ": failed to update DB: $e" );
466 * Make file paths relative to MediaWiki directory.
468 * This is used to make file paths safe for storing in a database without the paths
469 * becoming stale or incorrect when MediaWiki is moved or upgraded (T111481).
472 * @param array $filePaths
475 public static function getRelativePaths( array $filePaths ) {
477 return array_map( function ( $path ) use ( $IP ) {
478 return RelPath\
getRelativePath( $path, $IP );
483 * Expand directories relative to $IP.
486 * @param array $filePaths
489 public static function expandRelativePaths( array $filePaths ) {
491 return array_map( function ( $path ) use ( $IP ) {
492 return RelPath\
joinPath( $IP, $path );
497 * Get the hash of the message blob.
500 * @param ResourceLoaderContext $context
501 * @return string|null JSON blob or null if module has no messages
503 protected function getMessageBlob( ResourceLoaderContext
$context ) {
504 if ( !$this->getMessages() ) {
505 // Don't bother consulting MessageBlobStore
508 // Message blobs may only vary language, not by context keys
509 $lang = $context->getLanguage();
510 if ( !isset( $this->msgBlobs
[$lang] ) ) {
511 $this->getLogger()->warning( 'Message blob for {module} should have been preloaded', [
512 'module' => $this->getName(),
514 $store = $context->getResourceLoader()->getMessageBlobStore();
515 $this->msgBlobs
[$lang] = $store->getBlob( $this, $lang );
517 return $this->msgBlobs
[$lang];
521 * Set in-object cache for message blobs.
523 * Used to allow fetching of message blobs in batches. See ResourceLoader::preloadModuleInfo().
526 * @param string|null $blob JSON blob or null
527 * @param string $lang Language code
529 public function setMessageBlob( $blob, $lang ) {
530 $this->msgBlobs
[$lang] = $blob;
534 * Get module-specific LESS variables, if any.
537 * @param ResourceLoaderContext $context
538 * @return array Module-specific LESS variables.
540 protected function getLessVars( ResourceLoaderContext
$context ) {
545 * Get an array of this module's resources. Ready for serving to the web.
548 * @param ResourceLoaderContext $context
551 public function getModuleContent( ResourceLoaderContext
$context ) {
552 $contextHash = $context->getHash();
553 // Cache this expensive operation. This calls builds the scripts, styles, and messages
554 // content which typically involves filesystem and/or database access.
555 if ( !array_key_exists( $contextHash, $this->contents
) ) {
556 $this->contents
[$contextHash] = $this->buildContent( $context );
558 return $this->contents
[$contextHash];
562 * Bundle all resources attached to this module into an array.
565 * @param ResourceLoaderContext $context
568 final protected function buildContent( ResourceLoaderContext
$context ) {
569 $rl = $context->getResourceLoader();
570 $stats = RequestContext
::getMain()->getStats();
571 $statStart = microtime( true );
573 // Only include properties that are relevant to this context (e.g. only=scripts)
574 // and that are non-empty (e.g. don't include "templates" for modules without
575 // templates). This helps prevent invalidating cache for all modules when new
576 // optional properties are introduced.
580 if ( $context->shouldIncludeScripts() ) {
581 // If we are in debug mode, we'll want to return an array of URLs if possible
582 // However, we can't do this if the module doesn't support it
583 // We also can't do this if there is an only= parameter, because we have to give
584 // the module a way to return a load.php URL without causing an infinite loop
585 if ( $context->getDebug() && !$context->getOnly() && $this->supportsURLLoading() ) {
586 $scripts = $this->getScriptURLsForDebug( $context );
588 $scripts = $this->getScript( $context );
589 // rtrim() because there are usually a few line breaks
590 // after the last ';'. A new line at EOF, a new line
591 // added by ResourceLoaderFileModule::readScriptFiles, etc.
592 if ( is_string( $scripts )
593 && strlen( $scripts )
594 && substr( rtrim( $scripts ), -1 ) !== ';'
596 // Append semicolon to prevent weird bugs caused by files not
597 // terminating their statements right (bug 27054)
601 $content['scripts'] = $scripts;
605 if ( $context->shouldIncludeStyles() ) {
607 // Don't create empty stylesheets like array( '' => '' ) for modules
608 // that don't *have* any stylesheets (bug 38024).
609 $stylePairs = $this->getStyles( $context );
610 if ( count( $stylePairs ) ) {
611 // If we are in debug mode without &only= set, we'll want to return an array of URLs
612 // See comment near shouldIncludeScripts() for more details
613 if ( $context->getDebug() && !$context->getOnly() && $this->supportsURLLoading() ) {
615 'url' => $this->getStyleURLsForDebug( $context )
618 // Minify CSS before embedding in mw.loader.implement call
619 // (unless in debug mode)
620 if ( !$context->getDebug() ) {
621 foreach ( $stylePairs as $media => $style ) {
622 // Can be either a string or an array of strings.
623 if ( is_array( $style ) ) {
624 $stylePairs[$media] = [];
625 foreach ( $style as $cssText ) {
626 if ( is_string( $cssText ) ) {
627 $stylePairs[$media][] =
628 ResourceLoader
::filter( 'minify-css', $cssText );
631 } elseif ( is_string( $style ) ) {
632 $stylePairs[$media] = ResourceLoader
::filter( 'minify-css', $style );
636 // Wrap styles into @media groups as needed and flatten into a numerical array
638 'css' => $rl->makeCombinedStyles( $stylePairs )
642 $content['styles'] = $styles;
646 $blob = $this->getMessageBlob( $context );
648 $content['messagesBlob'] = $blob;
651 $templates = $this->getTemplates();
653 $content['templates'] = $templates;
656 $statTiming = microtime( true ) - $statStart;
657 $statName = strtr( $this->getName(), '.', '_' );
658 $stats->timing( "resourceloader_build.all", 1000 * $statTiming );
659 $stats->timing( "resourceloader_build.$statName", 1000 * $statTiming );
665 * Get a string identifying the current version of this module in a given context.
667 * Whenever anything happens that changes the module's response (e.g. scripts, styles, and
668 * messages) this value must change. This value is used to store module responses in cache.
669 * (Both client-side and server-side.)
671 * It is not recommended to override this directly. Use getDefinitionSummary() instead.
672 * If overridden, one must call the parent getVersionHash(), append data and re-hash.
674 * This method should be quick because it is frequently run by ResourceLoaderStartUpModule to
675 * propagate changes to the client and effectively invalidate cache.
677 * For backward-compatibility, the following optional data providers are automatically included:
679 * - getModifiedTime()
680 * - getModifiedHash()
683 * @param ResourceLoaderContext $context
684 * @return string Hash (should use ResourceLoader::makeHash)
686 public function getVersionHash( ResourceLoaderContext
$context ) {
687 // The startup module produces a manifest with versions representing the entire module.
688 // Typically, the request for the startup module itself has only=scripts. That must apply
689 // only to the startup module content, and not to the module version computed here.
690 $context = new DerivativeResourceLoaderContext( $context );
691 $context->setModules( [] );
692 // Version hash must cover all resources, regardless of startup request itself.
693 $context->setOnly( null );
694 // Compute version hash based on content, not debug urls.
695 $context->setDebug( false );
697 // Cache this somewhat expensive operation. Especially because some classes
698 // (e.g. startup module) iterate more than once over all modules to get versions.
699 $contextHash = $context->getHash();
700 if ( !array_key_exists( $contextHash, $this->versionHash
) ) {
702 if ( $this->enableModuleContentVersion() ) {
703 // Detect changes directly
704 $str = json_encode( $this->getModuleContent( $context ) );
706 // Infer changes based on definition and other metrics
707 $summary = $this->getDefinitionSummary( $context );
708 if ( !isset( $summary['_cacheEpoch'] ) ) {
709 throw new LogicException( 'getDefinitionSummary must call parent method' );
711 $str = json_encode( $summary );
713 $mtime = $this->getModifiedTime( $context );
714 if ( $mtime !== null ) {
715 // Support: MediaWiki 1.25 and earlier
716 $str .= strval( $mtime );
719 $mhash = $this->getModifiedHash( $context );
720 if ( $mhash !== null ) {
721 // Support: MediaWiki 1.25 and earlier
722 $str .= strval( $mhash );
726 $this->versionHash
[$contextHash] = ResourceLoader
::makeHash( $str );
728 return $this->versionHash
[$contextHash];
732 * Whether to generate version hash based on module content.
734 * If a module requires database or file system access to build the module
735 * content, consider disabling this in favour of manually tracking relevant
736 * aspects in getDefinitionSummary(). See getVersionHash() for how this is used.
740 public function enableModuleContentVersion() {
745 * Get the definition summary for this module.
747 * This is the method subclasses are recommended to use to track values in their
748 * version hash. Call this in getVersionHash() and pass it to e.g. json_encode.
750 * Subclasses must call the parent getDefinitionSummary() and build on that.
751 * It is recommended that each subclass appends its own new array. This prevents
752 * clashes or accidental overwrites of existing keys and gives each subclass
753 * its own scope for simple array keys.
756 * $summary = parent::getDefinitionSummary( $context );
757 * $summary[] = array(
764 * Return an array containing values from all significant properties of this
765 * module's definition.
767 * Be careful not to normalise too much. Especially preserve the order of things
768 * that carry significance in getScript and getStyles (T39812).
770 * Avoid including things that are insiginificant (e.g. order of message keys is
771 * insignificant and should be sorted to avoid unnecessary cache invalidation).
773 * This data structure must exclusively contain arrays and scalars as values (avoid
774 * object instances) to allow simple serialisation using json_encode.
776 * If modules have a hash or timestamp from another source, that may be incuded as-is.
778 * A number of utility methods are available to help you gather data. These are not
779 * called by default and must be included by the subclass' getDefinitionSummary().
784 * @param ResourceLoaderContext $context
787 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
789 '_class' => get_class( $this ),
790 '_cacheEpoch' => $this->getConfig()->get( 'CacheEpoch' ),
795 * Get this module's last modification timestamp for a given context.
797 * @deprecated since 1.26 Use getDefinitionSummary() instead
798 * @param ResourceLoaderContext $context Context object
799 * @return int|null UNIX timestamp
801 public function getModifiedTime( ResourceLoaderContext
$context ) {
806 * Helper method for providing a version hash to getVersionHash().
808 * @deprecated since 1.26 Use getDefinitionSummary() instead
809 * @param ResourceLoaderContext $context
810 * @return string|null Hash
812 public function getModifiedHash( ResourceLoaderContext
$context ) {
817 * Back-compat dummy for old subclass implementations of getModifiedTime().
819 * This method used to use ObjectCache to track when a hash was first seen. That principle
820 * stems from a time that ResourceLoader could only identify module versions by timestamp.
821 * That is no longer the case. Use getDefinitionSummary() directly.
823 * @deprecated since 1.26 Superseded by getVersionHash()
824 * @param ResourceLoaderContext $context
825 * @return int UNIX timestamp
827 public function getHashMtime( ResourceLoaderContext
$context ) {
828 if ( !is_string( $this->getModifiedHash( $context ) ) ) {
836 * Back-compat dummy for old subclass implementations of getModifiedTime().
839 * @deprecated since 1.26 Superseded by getVersionHash()
840 * @param ResourceLoaderContext $context
841 * @return int UNIX timestamp
843 public function getDefinitionMtime( ResourceLoaderContext
$context ) {
844 if ( $this->getDefinitionSummary( $context ) === null ) {
852 * Check whether this module is known to be empty. If a child class
853 * has an easy and cheap way to determine that this module is
854 * definitely going to be empty, it should override this method to
855 * return true in that case. Callers may optimize the request for this
856 * module away if this function returns true.
857 * @param ResourceLoaderContext $context
860 public function isKnownEmpty( ResourceLoaderContext
$context ) {
864 /** @var JSParser Lazy-initialized; use self::javaScriptParser() */
865 private static $jsParser;
866 private static $parseCacheVersion = 1;
869 * Validate a given script file; if valid returns the original source.
870 * If invalid, returns replacement JS source that throws an exception.
872 * @param string $fileName
873 * @param string $contents
874 * @return string JS with the original, or a replacement error
876 protected function validateScriptFile( $fileName, $contents ) {
877 if ( $this->getConfig()->get( 'ResourceLoaderValidateJS' ) ) {
879 $cache = ObjectCache
::getMainWANInstance();
880 $key = $cache->makeKey(
883 self
::$parseCacheVersion,
886 $cacheEntry = $cache->get( $key );
887 if ( is_string( $cacheEntry ) ) {
891 $parser = self
::javaScriptParser();
893 $parser->parse( $contents, $fileName, 1 );
895 } catch ( Exception
$e ) {
896 // We'll save this to cache to avoid having to validate broken JS over and over...
897 $err = $e->getMessage();
898 $result = "mw.log.error(" .
899 Xml
::encodeJsVar( "JavaScript parse error: $err" ) . ");";
902 $cache->set( $key, $result );
912 protected static function javaScriptParser() {
913 if ( !self
::$jsParser ) {
914 self
::$jsParser = new JSParser();
916 return self
::$jsParser;
920 * Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist.
923 * @param string $filePath File path
924 * @return int UNIX timestamp
926 protected static function safeFilemtime( $filePath ) {
927 MediaWiki\
suppressWarnings();
928 $mtime = filemtime( $filePath ) ?
: 1;
929 MediaWiki\restoreWarnings
();
934 * Compute a non-cryptographic string hash of a file's contents.
935 * If the file does not exist or cannot be read, returns an empty string.
937 * @since 1.26 Uses MD4 instead of SHA1.
938 * @param string $filePath File path
939 * @return string Hash
941 protected static function safeFileHash( $filePath ) {
942 return FileContentsHasher
::getFileContentsHash( $filePath );