MediaWiki REL1_35
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}
Class representing a cache/ephemeral data store.
Definition BagOStuff.php:71
static FileContentsHasher $instance
static getFileContentsHash( $filePaths, $algo='md4')
Get a hash of the combined contents of one or more files, either by retrieving a previously-computed ...
getFileContentsHashInternal( $filePath, $algo='md4')
Get a hash of a file's contents, either by retrieving a previously- computed hash from the cache,...
static singleton()
Get the singleton instance of this class.