Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 72
0.00% covered (danger)
0.00%
0 / 16
CRAP
0.00% covered (danger)
0.00%
0 / 1
FileCacheBase
0.00% covered (danger)
0.00%
0 / 71
0.00% covered (danger)
0.00%
0 / 16
930
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 baseCacheDirectory
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 cacheDirectory
n/a
0 / 0
n/a
0 / 0
0
 cachePath
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
12
 isCached
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 cacheTimestamp
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 isCacheGood
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 useGzip
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 fetchText
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 saveText
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
12
 clearCache
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 checkCacheDirs
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 typeSubdirectory
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 hashSubdirectory
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 incrMissesRecent
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
30
 getMissesRecent
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 cacheMissKey
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * Data storage in the file system.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Cache
22 */
23
24namespace MediaWiki\Cache;
25
26use BagOStuff;
27use MediaWiki\Config\ServiceOptions;
28use MediaWiki\MainConfigNames;
29use MediaWiki\MediaWikiServices;
30use MediaWiki\Request\WebRequest;
31use ObjectCache;
32use Wikimedia\AtEase\AtEase;
33use Wikimedia\IPUtils;
34
35/**
36 * Base class for data storage in the file system.
37 *
38 * @ingroup Cache
39 */
40abstract class FileCacheBase {
41    /** @var string[] */
42    private const CONSTRUCTOR_OPTIONS = [
43        MainConfigNames::CacheEpoch,
44        MainConfigNames::FileCacheDepth,
45        MainConfigNames::FileCacheDirectory,
46        MainConfigNames::MimeType,
47        MainConfigNames::UseGzip,
48    ];
49
50    protected $mKey;
51    protected $mType = 'object';
52    protected $mExt = 'cache';
53    protected $mFilePath;
54    protected $mUseGzip;
55    /** @var bool|null lazy loaded */
56    protected $mCached;
57    /** @var ServiceOptions */
58    protected $options;
59
60    /* @todo configurable? */
61    private const MISS_FACTOR = 15; // log 1 every MISS_FACTOR cache misses
62    private const MISS_TTL_SEC = 3600; // how many seconds ago is "recent"
63
64    protected function __construct() {
65        $this->options = new ServiceOptions(
66            self::CONSTRUCTOR_OPTIONS,
67            MediaWikiServices::getInstance()->getMainConfig()
68        );
69        $this->mUseGzip = (bool)$this->options->get( MainConfigNames::UseGzip );
70    }
71
72    /**
73     * Get the base file cache directory
74     * @return string
75     */
76    final protected function baseCacheDirectory() {
77        return $this->options->get( MainConfigNames::FileCacheDirectory );
78    }
79
80    /**
81     * Get the base cache directory (not specific to this file)
82     * @return string
83     */
84    abstract protected function cacheDirectory();
85
86    /**
87     * Get the path to the cache file
88     * @return string
89     */
90    protected function cachePath() {
91        if ( $this->mFilePath !== null ) {
92            return $this->mFilePath;
93        }
94
95        $dir = $this->cacheDirectory();
96        # Build directories (methods include the trailing "/")
97        $subDirs = $this->typeSubdirectory() . $this->hashSubdirectory();
98        # Avoid extension confusion
99        $key = str_replace( '.', '%2E', urlencode( $this->mKey ) );
100        # Build the full file path
101        $this->mFilePath = "{$dir}/{$subDirs}{$key}.{$this->mExt}";
102        if ( $this->useGzip() ) {
103            $this->mFilePath .= '.gz';
104        }
105
106        return $this->mFilePath;
107    }
108
109    /**
110     * Check if the cache file exists
111     * @return bool
112     */
113    public function isCached() {
114        $this->mCached ??= is_file( $this->cachePath() );
115
116        return $this->mCached;
117    }
118
119    /**
120     * Get the last-modified timestamp of the cache file
121     * @return string|bool TS_MW timestamp
122     */
123    public function cacheTimestamp() {
124        $timestamp = filemtime( $this->cachePath() );
125
126        return ( $timestamp !== false )
127            ? wfTimestamp( TS_MW, $timestamp )
128            : false;
129    }
130
131    /**
132     * Check if up to date cache file exists
133     * @param string $timestamp MW_TS timestamp
134     *
135     * @return bool
136     */
137    public function isCacheGood( $timestamp = '' ) {
138        $cacheEpoch = $this->options->get( MainConfigNames::CacheEpoch );
139
140        if ( !$this->isCached() ) {
141            return false;
142        }
143
144        $cachetime = $this->cacheTimestamp();
145        $good = ( $timestamp <= $cachetime && $cacheEpoch <= $cachetime );
146        wfDebug( __METHOD__ .
147            ": cachetime $cachetime, touched '{$timestamp}' epoch {$cacheEpoch}, good " . wfBoolToStr( $good ) );
148
149        return $good;
150    }
151
152    /**
153     * Check if the cache is gzipped
154     * @return bool
155     */
156    protected function useGzip() {
157        return $this->mUseGzip;
158    }
159
160    /**
161     * Get the uncompressed text from the cache
162     * @return string
163     */
164    public function fetchText() {
165        if ( $this->useGzip() ) {
166            $fh = gzopen( $this->cachePath(), 'rb' );
167
168            return stream_get_contents( $fh );
169        } else {
170            return file_get_contents( $this->cachePath() );
171        }
172    }
173
174    /**
175     * Save and compress text to the cache
176     * @param string $text
177     * @return string|false Compressed text
178     */
179    public function saveText( $text ) {
180        if ( $this->useGzip() ) {
181            $text = gzencode( $text );
182        }
183
184        $this->checkCacheDirs(); // build parent dir
185        if ( !file_put_contents( $this->cachePath(), $text, LOCK_EX ) ) {
186            wfDebug( __METHOD__ . "() failed saving " . $this->cachePath() );
187            $this->mCached = null;
188
189            return false;
190        }
191
192        $this->mCached = true;
193
194        return $text;
195    }
196
197    /**
198     * Clear the cache for this page
199     * @return void
200     */
201    public function clearCache() {
202        AtEase::suppressWarnings();
203        unlink( $this->cachePath() );
204        AtEase::restoreWarnings();
205        $this->mCached = false;
206    }
207
208    /**
209     * Create parent directors of $this->cachePath()
210     * @return void
211     */
212    protected function checkCacheDirs() {
213        wfMkdirParents( dirname( $this->cachePath() ), null, __METHOD__ );
214    }
215
216    /**
217     * Get the cache type subdirectory (with trailing slash)
218     * An extending class could use that method to alter the type -> directory
219     * mapping. @see HTMLFileCache::typeSubdirectory() for an example.
220     *
221     * @return string
222     */
223    protected function typeSubdirectory() {
224        return $this->mType . '/';
225    }
226
227    /**
228     * Return relative multi-level hash subdirectory (with trailing slash)
229     * or the empty string if not $wgFileCacheDepth
230     * @return string
231     */
232    protected function hashSubdirectory() {
233        $fileCacheDepth = $this->options->get( MainConfigNames::FileCacheDepth );
234
235        $subdir = '';
236        if ( $fileCacheDepth > 0 ) {
237            $hash = md5( $this->mKey );
238            for ( $i = 1; $i <= $fileCacheDepth; $i++ ) {
239                $subdir .= substr( $hash, 0, $i ) . '/';
240            }
241        }
242
243        return $subdir;
244    }
245
246    /**
247     * Roughly increments the cache misses in the last hour by unique visitors
248     * @param WebRequest $request
249     * @return void
250     */
251    public function incrMissesRecent( WebRequest $request ) {
252        if ( mt_rand( 0, self::MISS_FACTOR - 1 ) == 0 ) {
253            # Get a large IP range that should include the user  even if that
254            # person's IP address changes
255            $ip = $request->getIP();
256            if ( !IPUtils::isValid( $ip ) ) {
257                return;
258            }
259
260            $ip = IPUtils::isIPv6( $ip )
261                ? IPUtils::sanitizeRange( "$ip/32" )
262                : IPUtils::sanitizeRange( "$ip/16" );
263
264            # Bail out if a request already came from this range...
265            $cache = ObjectCache::getLocalClusterInstance();
266            $key = $cache->makeKey( static::class, 'attempt', $this->mType, $this->mKey, $ip );
267            if ( !$cache->add( $key, 1, self::MISS_TTL_SEC ) ) {
268                return; // possibly the same user
269            }
270
271            # Increment the number of cache misses...
272            $cache->incrWithInit( $this->cacheMissKey( $cache ), self::MISS_TTL_SEC );
273        }
274    }
275
276    /**
277     * Roughly gets the cache misses in the last hour by unique visitors
278     * @return int
279     */
280    public function getMissesRecent() {
281        $cache = ObjectCache::getLocalClusterInstance();
282
283        return self::MISS_FACTOR * $cache->get( $this->cacheMissKey( $cache ) );
284    }
285
286    /**
287     * @param BagOStuff $cache Instance that the key will be used with
288     * @return string
289     */
290    protected function cacheMissKey( BagOStuff $cache ) {
291        return $cache->makeKey( static::class, 'misses', $this->mType, $this->mKey );
292    }
293}
294
295/** @deprecated class alias since 1.42 */
296class_alias( FileCacheBase::class, 'FileCacheBase' );