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';
39 // Module only has styles (loaded via <style> or <link rel=stylesheet>)
40 const LOAD_STYLES
= 'styles';
41 // Module may have other resources (loaded via mw.loader from a script)
42 const LOAD_GENERAL
= 'general';
44 # sitewide core module like a skin file or jQuery component
45 const ORIGIN_CORE_SITEWIDE
= 1;
47 # per-user module generated by the software
48 const ORIGIN_CORE_INDIVIDUAL
= 2;
50 # sitewide module generated from user-editable files, like MediaWiki:Common.js, or
51 # modules accessible to multiple users, such as those generated by the Gadgets extension.
52 const ORIGIN_USER_SITEWIDE
= 3;
54 # per-user module generated from user-editable files, like User:Me/vector.js
55 const ORIGIN_USER_INDIVIDUAL
= 4;
57 # an access constant; make sure this is kept as the largest number in this group
58 const ORIGIN_ALL
= 10;
60 # script and style modules form a hierarchy of trustworthiness, with core modules like
61 # skins and jQuery as most trustworthy, and user scripts as least trustworthy. We can
62 # limit the types of scripts and styles we allow to load on, say, sensitive special
63 # pages like Special:UserLogin and Special:Preferences
64 protected $origin = self
::ORIGIN_CORE_SITEWIDE
;
66 /* Protected Members */
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 = [];
86 * @var LoggerInterface
93 * Get this module's name. This is set when the module is registered
94 * with ResourceLoader::register()
96 * @return string|null Name (string) or null if no name was set
98 public function getName() {
103 * Set this module's name. This is called by ResourceLoader::register()
104 * when registering the module. Other code should not call this.
106 * @param string $name Name
108 public function setName( $name ) {
113 * Get this module's origin. This is set when the module is registered
114 * with ResourceLoader::register()
116 * @return int ResourceLoaderModule class constant, the subclass default
117 * if not set manually
119 public function getOrigin() {
120 return $this->origin
;
124 * @param ResourceLoaderContext $context
127 public function getFlip( $context ) {
130 return $wgContLang->getDir() !== $context->getDirection();
134 * Get all JS for this module for a given language and skin.
135 * Includes all relevant JS except loader scripts.
137 * @param ResourceLoaderContext $context
138 * @return string JavaScript code
140 public function getScript( ResourceLoaderContext
$context ) {
141 // Stub, override expected
146 * Takes named templates by the module and returns an array mapping.
148 * @return array of templates mapping template alias to content
150 public function getTemplates() {
151 // Stub, override expected.
159 public function getConfig() {
160 if ( $this->config
=== null ) {
161 // Ugh, fall back to default
162 $this->config
= ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
165 return $this->config
;
169 * @param Config $config
172 public function setConfig( Config
$config ) {
173 $this->config
= $config;
178 * @param LoggerInterface $logger
181 public function setLogger( LoggerInterface
$logger ) {
182 $this->logger
= $logger;
187 * @return LoggerInterface
189 protected function getLogger() {
190 if ( !$this->logger
) {
191 $this->logger
= new NullLogger();
193 return $this->logger
;
197 * Get the URL or URLs to load for this module's JS in debug mode.
198 * The default behavior is to return a load.php?only=scripts URL for
199 * the module, but file-based modules will want to override this to
200 * load the files directly.
202 * This function is called only when 1) we're in debug mode, 2) there
203 * is no only= parameter and 3) supportsURLLoading() returns true.
204 * #2 is important to prevent an infinite loop, therefore this function
205 * MUST return either an only= URL or a non-load.php URL.
207 * @param ResourceLoaderContext $context
208 * @return array Array of URLs
210 public function getScriptURLsForDebug( ResourceLoaderContext
$context ) {
211 $resourceLoader = $context->getResourceLoader();
212 $derivative = new DerivativeResourceLoaderContext( $context );
213 $derivative->setModules( [ $this->getName() ] );
214 $derivative->setOnly( 'scripts' );
215 $derivative->setDebug( true );
217 $url = $resourceLoader->createLoaderURL(
226 * Whether this module supports URL loading. If this function returns false,
227 * getScript() will be used even in cases (debug mode, no only param) where
228 * getScriptURLsForDebug() would normally be used instead.
231 public function supportsURLLoading() {
236 * Get all CSS for this module for a given skin.
238 * @param ResourceLoaderContext $context
239 * @return array List of CSS strings or array of CSS strings keyed by media type.
240 * like array( 'screen' => '.foo { width: 0 }' );
241 * or array( 'screen' => array( '.foo { width: 0 }' ) );
243 public function getStyles( ResourceLoaderContext
$context ) {
244 // Stub, override expected
249 * Get the URL or URLs to load for this module's CSS in debug mode.
250 * The default behavior is to return a load.php?only=styles URL for
251 * the module, but file-based modules will want to override this to
252 * load the files directly. See also getScriptURLsForDebug()
254 * @param ResourceLoaderContext $context
255 * @return array Array( mediaType => array( URL1, URL2, ... ), ... )
257 public function getStyleURLsForDebug( ResourceLoaderContext
$context ) {
258 $resourceLoader = $context->getResourceLoader();
259 $derivative = new DerivativeResourceLoaderContext( $context );
260 $derivative->setModules( [ $this->getName() ] );
261 $derivative->setOnly( 'styles' );
262 $derivative->setDebug( true );
264 $url = $resourceLoader->createLoaderURL(
269 return [ 'all' => [ $url ] ];
273 * Get the messages needed for this module.
275 * To get a JSON blob with messages, use MessageBlobStore::get()
277 * @return array List of message keys. Keys may occur more than once
279 public function getMessages() {
280 // Stub, override expected
285 * Get the group this module is in.
287 * @return string Group name
289 public function getGroup() {
290 // Stub, override expected
295 * Get the origin of this module. Should only be overridden for foreign modules.
297 * @return string Origin name, 'local' for local modules
299 public function getSource() {
300 // Stub, override expected
305 * Where on the HTML page should this module's JS be loaded?
306 * - 'top': in the "<head>"
307 * - 'bottom': at the bottom of the "<body>"
311 public function getPosition() {
316 * Whether this module's JS expects to work without the client-side ResourceLoader module.
317 * Returning true from this function will prevent mw.loader.state() call from being
318 * appended to the bottom of the script.
322 public function isRaw() {
327 * Get a list of modules this module depends on.
329 * Dependency information is taken into account when loading a module
330 * on the client side.
332 * Note: It is expected that $context will be made non-optional in the near
335 * @param ResourceLoaderContext $context
336 * @return array List of module names as strings
338 public function getDependencies( ResourceLoaderContext
$context = null ) {
339 // Stub, override expected
344 * Get target(s) for the module, eg ['desktop'] or ['desktop', 'mobile']
346 * @return array Array of strings
348 public function getTargets() {
349 return $this->targets
;
353 * Get the module's load type.
356 * @return string ResourceLoaderModule LOAD_* constant
358 public function getType() {
359 return self
::LOAD_GENERAL
;
363 * Get the skip function.
365 * Modules that provide fallback functionality can provide a "skip function". This
366 * function, if provided, will be passed along to the module registry on the client.
367 * When this module is loaded (either directly or as a dependency of another module),
368 * then this function is executed first. If the function returns true, the module will
369 * instantly be considered "ready" without requesting the associated module resources.
371 * The value returned here must be valid javascript for execution in a private function.
372 * It must not contain the "function () {" and "}" wrapper though.
374 * @return string|null A JavaScript function body returning a boolean value, or null
376 public function getSkipFunction() {
381 * Get the files this module depends on indirectly for a given skin.
383 * These are only image files referenced by the module's stylesheet.
385 * @param ResourceLoaderContext $context
386 * @return array List of files
388 protected function getFileDependencies( ResourceLoaderContext
$context ) {
389 $vary = $context->getSkin() . '|' . $context->getLanguage();
391 // Try in-object cache first
392 if ( !isset( $this->fileDeps
[$vary] ) ) {
393 $dbr = wfGetDB( DB_SLAVE
);
394 $deps = $dbr->selectField( 'module_deps',
397 'md_module' => $this->getName(),
403 if ( !is_null( $deps ) ) {
404 $this->fileDeps
[$vary] = self
::expandRelativePaths(
405 (array)FormatJson
::decode( $deps, true )
408 $this->fileDeps
[$vary] = [];
411 return $this->fileDeps
[$vary];
415 * Set in-object cache for file dependencies.
417 * This is used to retrieve data in batches. See ResourceLoader::preloadModuleInfo().
418 * To save the data, use saveFileDependencies().
420 * @param ResourceLoaderContext $context
421 * @param string[] $files Array of file names
423 public function setFileDependencies( ResourceLoaderContext
$context, $files ) {
424 $vary = $context->getSkin() . '|' . $context->getLanguage();
425 $this->fileDeps
[$vary] = $files;
429 * Set the files this module depends on indirectly for a given skin.
432 * @param ResourceLoaderContext $context
433 * @param array $localFileRefs List of files
435 protected function saveFileDependencies( ResourceLoaderContext
$context, $localFileRefs ) {
437 $localFileRefs = array_values( array_unique( $localFileRefs ) );
438 sort( $localFileRefs );
441 // If the list has been modified since last time we cached it, update the cache
442 if ( $localFileRefs !== $this->getFileDependencies( $context ) ) {
443 $cache = ObjectCache
::getLocalClusterInstance();
444 $key = $cache->makeKey( __METHOD__
, $this->getName() );
445 $scopeLock = $cache->getScopedLock( $key, 0 );
447 return; // T124649; avoid write slams
450 $vary = $context->getSkin() . '|' . $context->getLanguage();
451 $dbw = wfGetDB( DB_MASTER
);
452 $dbw->replace( 'module_deps',
453 [ [ 'md_module', 'md_skin' ] ],
455 'md_module' => $this->getName(),
457 // Use relative paths to avoid ghost entries when $IP changes (T111481)
458 'md_deps' => FormatJson
::encode( self
::getRelativePaths( $localFileRefs ) ),
462 $dbw->onTransactionResolution( function () use ( &$scopeLock ) {
463 ScopedCallback
::consume( $scopeLock ); // release after commit
466 } catch ( Exception
$e ) {
467 wfDebugLog( 'resourceloader', __METHOD__
. ": failed to update DB: $e" );
472 * Make file paths relative to MediaWiki directory.
474 * This is used to make file paths safe for storing in a database without the paths
475 * becoming stale or incorrect when MediaWiki is moved or upgraded (T111481).
478 * @param array $filePaths
481 public static function getRelativePaths( array $filePaths ) {
483 return array_map( function ( $path ) use ( $IP ) {
484 return RelPath\
getRelativePath( $path, $IP );
489 * Expand directories relative to $IP.
492 * @param array $filePaths
495 public static function expandRelativePaths( array $filePaths ) {
497 return array_map( function ( $path ) use ( $IP ) {
498 return RelPath\
joinPath( $IP, $path );
503 * Get the hash of the message blob.
506 * @param ResourceLoaderContext $context
507 * @return string|null JSON blob or null if module has no messages
509 protected function getMessageBlob( ResourceLoaderContext
$context ) {
510 if ( !$this->getMessages() ) {
511 // Don't bother consulting MessageBlobStore
514 // Message blobs may only vary language, not by context keys
515 $lang = $context->getLanguage();
516 if ( !isset( $this->msgBlobs
[$lang] ) ) {
517 $this->getLogger()->warning( 'Message blob for {module} should have been preloaded', [
518 'module' => $this->getName(),
520 $store = $context->getResourceLoader()->getMessageBlobStore();
521 $this->msgBlobs
[$lang] = $store->getBlob( $this, $lang );
523 return $this->msgBlobs
[$lang];
527 * Set in-object cache for message blobs.
529 * Used to allow fetching of message blobs in batches. See ResourceLoader::preloadModuleInfo().
532 * @param string|null $blob JSON blob or null
533 * @param string $lang Language code
535 public function setMessageBlob( $blob, $lang ) {
536 $this->msgBlobs
[$lang] = $blob;
540 * Get module-specific LESS variables, if any.
543 * @param ResourceLoaderContext $context
544 * @return array Module-specific LESS variables.
546 protected function getLessVars( ResourceLoaderContext
$context ) {
551 * Get an array of this module's resources. Ready for serving to the web.
554 * @param ResourceLoaderContext $context
557 public function getModuleContent( ResourceLoaderContext
$context ) {
558 $contextHash = $context->getHash();
559 // Cache this expensive operation. This calls builds the scripts, styles, and messages
560 // content which typically involves filesystem and/or database access.
561 if ( !array_key_exists( $contextHash, $this->contents
) ) {
562 $this->contents
[$contextHash] = $this->buildContent( $context );
564 return $this->contents
[$contextHash];
568 * Bundle all resources attached to this module into an array.
571 * @param ResourceLoaderContext $context
574 final protected function buildContent( ResourceLoaderContext
$context ) {
575 $rl = $context->getResourceLoader();
576 $stats = RequestContext
::getMain()->getStats();
577 $statStart = microtime( true );
579 // Only include properties that are relevant to this context (e.g. only=scripts)
580 // and that are non-empty (e.g. don't include "templates" for modules without
581 // templates). This helps prevent invalidating cache for all modules when new
582 // optional properties are introduced.
586 if ( $context->shouldIncludeScripts() ) {
587 // If we are in debug mode, we'll want to return an array of URLs if possible
588 // However, we can't do this if the module doesn't support it
589 // We also can't do this if there is an only= parameter, because we have to give
590 // the module a way to return a load.php URL without causing an infinite loop
591 if ( $context->getDebug() && !$context->getOnly() && $this->supportsURLLoading() ) {
592 $scripts = $this->getScriptURLsForDebug( $context );
594 $scripts = $this->getScript( $context );
595 // rtrim() because there are usually a few line breaks
596 // after the last ';'. A new line at EOF, a new line
597 // added by ResourceLoaderFileModule::readScriptFiles, etc.
598 if ( is_string( $scripts )
599 && strlen( $scripts )
600 && substr( rtrim( $scripts ), -1 ) !== ';'
602 // Append semicolon to prevent weird bugs caused by files not
603 // terminating their statements right (bug 27054)
607 $content['scripts'] = $scripts;
611 if ( $context->shouldIncludeStyles() ) {
613 // Don't create empty stylesheets like array( '' => '' ) for modules
614 // that don't *have* any stylesheets (bug 38024).
615 $stylePairs = $this->getStyles( $context );
616 if ( count( $stylePairs ) ) {
617 // If we are in debug mode without &only= set, we'll want to return an array of URLs
618 // See comment near shouldIncludeScripts() for more details
619 if ( $context->getDebug() && !$context->getOnly() && $this->supportsURLLoading() ) {
621 'url' => $this->getStyleURLsForDebug( $context )
624 // Minify CSS before embedding in mw.loader.implement call
625 // (unless in debug mode)
626 if ( !$context->getDebug() ) {
627 foreach ( $stylePairs as $media => $style ) {
628 // Can be either a string or an array of strings.
629 if ( is_array( $style ) ) {
630 $stylePairs[$media] = [];
631 foreach ( $style as $cssText ) {
632 if ( is_string( $cssText ) ) {
633 $stylePairs[$media][] =
634 ResourceLoader
::filter( 'minify-css', $cssText );
637 } elseif ( is_string( $style ) ) {
638 $stylePairs[$media] = ResourceLoader
::filter( 'minify-css', $style );
642 // Wrap styles into @media groups as needed and flatten into a numerical array
644 'css' => $rl->makeCombinedStyles( $stylePairs )
648 $content['styles'] = $styles;
652 $blob = $this->getMessageBlob( $context );
654 $content['messagesBlob'] = $blob;
657 $templates = $this->getTemplates();
659 $content['templates'] = $templates;
662 $statTiming = microtime( true ) - $statStart;
663 $statName = strtr( $this->getName(), '.', '_' );
664 $stats->timing( "resourceloader_build.all", 1000 * $statTiming );
665 $stats->timing( "resourceloader_build.$statName", 1000 * $statTiming );
671 * Get a string identifying the current version of this module in a given context.
673 * Whenever anything happens that changes the module's response (e.g. scripts, styles, and
674 * messages) this value must change. This value is used to store module responses in cache.
675 * (Both client-side and server-side.)
677 * It is not recommended to override this directly. Use getDefinitionSummary() instead.
678 * If overridden, one must call the parent getVersionHash(), append data and re-hash.
680 * This method should be quick because it is frequently run by ResourceLoaderStartUpModule to
681 * propagate changes to the client and effectively invalidate cache.
683 * For backward-compatibility, the following optional data providers are automatically included:
685 * - getModifiedTime()
686 * - getModifiedHash()
689 * @param ResourceLoaderContext $context
690 * @return string Hash (should use ResourceLoader::makeHash)
692 public function getVersionHash( ResourceLoaderContext
$context ) {
693 // The startup module produces a manifest with versions representing the entire module.
694 // Typically, the request for the startup module itself has only=scripts. That must apply
695 // only to the startup module content, and not to the module version computed here.
696 $context = new DerivativeResourceLoaderContext( $context );
697 $context->setModules( [] );
698 // Version hash must cover all resources, regardless of startup request itself.
699 $context->setOnly( null );
700 // Compute version hash based on content, not debug urls.
701 $context->setDebug( false );
703 // Cache this somewhat expensive operation. Especially because some classes
704 // (e.g. startup module) iterate more than once over all modules to get versions.
705 $contextHash = $context->getHash();
706 if ( !array_key_exists( $contextHash, $this->versionHash
) ) {
708 if ( $this->enableModuleContentVersion() ) {
709 // Detect changes directly
710 $str = json_encode( $this->getModuleContent( $context ) );
712 // Infer changes based on definition and other metrics
713 $summary = $this->getDefinitionSummary( $context );
714 if ( !isset( $summary['_cacheEpoch'] ) ) {
715 throw new LogicException( 'getDefinitionSummary must call parent method' );
717 $str = json_encode( $summary );
719 $mtime = $this->getModifiedTime( $context );
720 if ( $mtime !== null ) {
721 // Support: MediaWiki 1.25 and earlier
722 $str .= strval( $mtime );
725 $mhash = $this->getModifiedHash( $context );
726 if ( $mhash !== null ) {
727 // Support: MediaWiki 1.25 and earlier
728 $str .= strval( $mhash );
732 $this->versionHash
[$contextHash] = ResourceLoader
::makeHash( $str );
734 return $this->versionHash
[$contextHash];
738 * Whether to generate version hash based on module content.
740 * If a module requires database or file system access to build the module
741 * content, consider disabling this in favour of manually tracking relevant
742 * aspects in getDefinitionSummary(). See getVersionHash() for how this is used.
746 public function enableModuleContentVersion() {
751 * Get the definition summary for this module.
753 * This is the method subclasses are recommended to use to track values in their
754 * version hash. Call this in getVersionHash() and pass it to e.g. json_encode.
756 * Subclasses must call the parent getDefinitionSummary() and build on that.
757 * It is recommended that each subclass appends its own new array. This prevents
758 * clashes or accidental overwrites of existing keys and gives each subclass
759 * its own scope for simple array keys.
762 * $summary = parent::getDefinitionSummary( $context );
763 * $summary[] = array(
770 * Return an array containing values from all significant properties of this
771 * module's definition.
773 * Be careful not to normalise too much. Especially preserve the order of things
774 * that carry significance in getScript and getStyles (T39812).
776 * Avoid including things that are insiginificant (e.g. order of message keys is
777 * insignificant and should be sorted to avoid unnecessary cache invalidation).
779 * This data structure must exclusively contain arrays and scalars as values (avoid
780 * object instances) to allow simple serialisation using json_encode.
782 * If modules have a hash or timestamp from another source, that may be incuded as-is.
784 * A number of utility methods are available to help you gather data. These are not
785 * called by default and must be included by the subclass' getDefinitionSummary().
790 * @param ResourceLoaderContext $context
793 public function getDefinitionSummary( ResourceLoaderContext
$context ) {
795 '_class' => get_class( $this ),
796 '_cacheEpoch' => $this->getConfig()->get( 'CacheEpoch' ),
801 * Get this module's last modification timestamp for a given context.
803 * @deprecated since 1.26 Use getDefinitionSummary() instead
804 * @param ResourceLoaderContext $context Context object
805 * @return int|null UNIX timestamp
807 public function getModifiedTime( ResourceLoaderContext
$context ) {
812 * Helper method for providing a version hash to getVersionHash().
814 * @deprecated since 1.26 Use getDefinitionSummary() instead
815 * @param ResourceLoaderContext $context
816 * @return string|null Hash
818 public function getModifiedHash( ResourceLoaderContext
$context ) {
823 * Back-compat dummy for old subclass implementations of getModifiedTime().
825 * This method used to use ObjectCache to track when a hash was first seen. That principle
826 * stems from a time that ResourceLoader could only identify module versions by timestamp.
827 * That is no longer the case. Use getDefinitionSummary() directly.
829 * @deprecated since 1.26 Superseded by getVersionHash()
830 * @param ResourceLoaderContext $context
831 * @return int UNIX timestamp
833 public function getHashMtime( ResourceLoaderContext
$context ) {
834 if ( !is_string( $this->getModifiedHash( $context ) ) ) {
842 * Back-compat dummy for old subclass implementations of getModifiedTime().
845 * @deprecated since 1.26 Superseded by getVersionHash()
846 * @param ResourceLoaderContext $context
847 * @return int UNIX timestamp
849 public function getDefinitionMtime( ResourceLoaderContext
$context ) {
850 if ( $this->getDefinitionSummary( $context ) === null ) {
858 * Check whether this module is known to be empty. If a child class
859 * has an easy and cheap way to determine that this module is
860 * definitely going to be empty, it should override this method to
861 * return true in that case. Callers may optimize the request for this
862 * module away if this function returns true.
863 * @param ResourceLoaderContext $context
866 public function isKnownEmpty( ResourceLoaderContext
$context ) {
870 /** @var JSParser Lazy-initialized; use self::javaScriptParser() */
871 private static $jsParser;
872 private static $parseCacheVersion = 1;
875 * Validate a given script file; if valid returns the original source.
876 * If invalid, returns replacement JS source that throws an exception.
878 * @param string $fileName
879 * @param string $contents
880 * @return string JS with the original, or a replacement error
882 protected function validateScriptFile( $fileName, $contents ) {
883 if ( $this->getConfig()->get( 'ResourceLoaderValidateJS' ) ) {
885 $cache = ObjectCache
::getMainWANInstance();
886 $key = $cache->makeKey(
889 self
::$parseCacheVersion,
892 $cacheEntry = $cache->get( $key );
893 if ( is_string( $cacheEntry ) ) {
897 $parser = self
::javaScriptParser();
899 $parser->parse( $contents, $fileName, 1 );
901 } catch ( Exception
$e ) {
902 // We'll save this to cache to avoid having to validate broken JS over and over...
903 $err = $e->getMessage();
904 $result = "mw.log.error(" .
905 Xml
::encodeJsVar( "JavaScript parse error: $err" ) . ");";
908 $cache->set( $key, $result );
918 protected static function javaScriptParser() {
919 if ( !self
::$jsParser ) {
920 self
::$jsParser = new JSParser();
922 return self
::$jsParser;
926 * Safe version of filemtime(), which doesn't throw a PHP warning if the file doesn't exist.
929 * @param string $filePath File path
930 * @return int UNIX timestamp
932 protected static function safeFilemtime( $filePath ) {
933 MediaWiki\
suppressWarnings();
934 $mtime = filemtime( $filePath ) ?
: 1;
935 MediaWiki\restoreWarnings
();
940 * Compute a non-cryptographic string hash of a file's contents.
941 * If the file does not exist or cannot be read, returns an empty string.
943 * @since 1.26 Uses MD4 instead of SHA1.
944 * @param string $filePath File path
945 * @return string Hash
947 protected static function safeFileHash( $filePath ) {
948 return FileContentsHasher
::getFileContentsHash( $filePath );