MediaWiki  master
FileContentsHasher.php
Go to the documentation of this file.
1 <?php
23 
25  protected $cache;
26 
28  private static $instance;
29 
30  public function __construct() {
31  $this->cache = ObjectCache::getLocalServerInstance( 'hash' );
32  }
33 
39  public static function singleton() {
40  if ( !self::$instance ) {
41  self::$instance = new self;
42  }
43 
44  return self::$instance;
45  }
46 
55  private function getFileContentsHashInternal( $filePath, $algo = 'md4' ) {
56  $mtime = filemtime( $filePath );
57  if ( $mtime === false ) {
58  return false;
59  }
60 
61  $cacheKey = $this->cache->makeGlobalKey( __CLASS__, $filePath, $mtime, $algo );
62  $hash = $this->cache->get( $cacheKey );
63 
64  if ( $hash ) {
65  return $hash;
66  }
67 
68  $contents = file_get_contents( $filePath );
69  if ( $contents === false ) {
70  return false;
71  }
72 
73  $hash = hash( $algo, $contents );
74  $this->cache->set( $cacheKey, $hash, 60 * 60 * 24 ); // 24h
75 
76  return $hash;
77  }
78 
88  public static function getFileContentsHash( $filePaths, $algo = 'md4' ) {
90 
91  if ( !is_array( $filePaths ) ) {
92  $filePaths = (array)$filePaths;
93  }
94 
95  Wikimedia\suppressWarnings();
96 
97  if ( count( $filePaths ) === 1 ) {
98  $hash = $instance->getFileContentsHashInternal( $filePaths[0], $algo );
99  Wikimedia\restoreWarnings();
100  return $hash;
101  }
102 
103  sort( $filePaths );
104  $hashes = [];
105  foreach ( $filePaths as $filePath ) {
106  $hashes[] = $instance->getFileContentsHashInternal( $filePath, $algo ) ?: '';
107  }
108 
109  Wikimedia\restoreWarnings();
110 
111  $hashes = implode( '', $hashes );
112  return $hashes ? hash( $algo, $hashes ) : false;
113  }
114 }
FileContentsHasher
Definition: FileContentsHasher.php:22
FileContentsHasher\$cache
BagOStuff $cache
Definition: FileContentsHasher.php:25
BagOStuff
Class representing a cache/ephemeral data store.
Definition: BagOStuff.php:65
FileContentsHasher\getFileContentsHash
static getFileContentsHash( $filePaths, $algo='md4')
Get a hash of the combined contents of one or more files, either by retrieving a previously-computed ...
Definition: FileContentsHasher.php:88
FileContentsHasher\getFileContentsHashInternal
getFileContentsHashInternal( $filePath, $algo='md4')
Get a hash of a file's contents, either by retrieving a previously- computed hash from the cache,...
Definition: FileContentsHasher.php:55
FileContentsHasher\$instance
static FileContentsHasher $instance
Definition: FileContentsHasher.php:28
FileContentsHasher\__construct
__construct()
Definition: FileContentsHasher.php:30
$hashes
$hashes
Definition: testCompression.php:71
FileContentsHasher\singleton
static singleton()
Get the singleton instance of this class.
Definition: FileContentsHasher.php:39
ObjectCache\getLocalServerInstance
static getLocalServerInstance( $fallback=CACHE_NONE)
Factory function for CACHE_ACCEL (referenced from DefaultSettings.php)
Definition: ObjectCache.php:254