summaryrefslogtreecommitdiff
path: root/includes/cache/FileCacheBase.php
blob: 4bf36114c96c989723f0c6393de2a977eae2e59a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
<?php
/**
 * Data storage in the file system.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @ingroup Cache
 */

/**
 * Base class for data storage in the file system.
 *
 * @ingroup Cache
 */
abstract class FileCacheBase {
	protected $mKey;
	protected $mType = 'object';
	protected $mExt = 'cache';
	protected $mFilePath;
	protected $mUseGzip;
	/* lazy loaded */
	protected $mCached;

	/* @todo configurable? */
	const MISS_FACTOR = 15; // log 1 every MISS_FACTOR cache misses
	const MISS_TTL_SEC = 3600; // how many seconds ago is "recent"

	protected function __construct() {
		global $wgUseGzip;

		$this->mUseGzip = (bool)$wgUseGzip;
	}

	/**
	 * Get the base file cache directory
	 * @return string
	 */
	final protected function baseCacheDirectory() {
		global $wgFileCacheDirectory;

		return $wgFileCacheDirectory;
	}

	/**
	 * Get the base cache directory (not specific to this file)
	 * @return string
	 */
	abstract protected function cacheDirectory();

	/**
	 * Get the path to the cache file
	 * @return string
	 */
	protected function cachePath() {
		if ( $this->mFilePath !== null ) {
			return $this->mFilePath;
		}

		$dir = $this->cacheDirectory();
		# Build directories (methods include the trailing "/")
		$subDirs = $this->typeSubdirectory() . $this->hashSubdirectory();
		# Avoid extension confusion
		$key = str_replace( '.', '%2E', urlencode( $this->mKey ) );
		# Build the full file path
		$this->mFilePath = "{$dir}/{$subDirs}{$key}.{$this->mExt}";
		if ( $this->useGzip() ) {
			$this->mFilePath .= '.gz';
		}

		return $this->mFilePath;
	}

	/**
	 * Check if the cache file exists
	 * @return bool
	 */
	public function isCached() {
		if ( $this->mCached === null ) {
			$this->mCached = file_exists( $this->cachePath() );
		}

		return $this->mCached;
	}

	/**
	 * Get the last-modified timestamp of the cache file
	 * @return string|bool TS_MW timestamp
	 */
	public function cacheTimestamp() {
		$timestamp = filemtime( $this->cachePath() );

		return ( $timestamp !== false )
			? wfTimestamp( TS_MW, $timestamp )
			: false;
	}

	/**
	 * Check if up to date cache file exists
	 * @param string $timestamp MW_TS timestamp
	 *
	 * @return bool
	 */
	public function isCacheGood( $timestamp = '' ) {
		global $wgCacheEpoch;

		if ( !$this->isCached() ) {
			return false;
		}

		$cachetime = $this->cacheTimestamp();
		$good = ( $timestamp <= $cachetime && $wgCacheEpoch <= $cachetime );
		wfDebug( __METHOD__ .
			": cachetime $cachetime, touched '{$timestamp}' epoch {$wgCacheEpoch}, good $good\n" );

		return $good;
	}

	/**
	 * Check if the cache is gzipped
	 * @return bool
	 */
	protected function useGzip() {
		return $this->mUseGzip;
	}

	/**
	 * Get the uncompressed text from the cache
	 * @return string
	 */
	public function fetchText() {
		if ( $this->useGzip() ) {
			$fh = gzopen( $this->cachePath(), 'rb' );

			return stream_get_contents( $fh );
		} else {
			return file_get_contents( $this->cachePath() );
		}
	}

	/**
	 * Save and compress text to the cache
	 * @param string $text
	 * @return string Compressed text
	 */
	public function saveText( $text ) {
		global $wgUseFileCache;

		if ( !$wgUseFileCache ) {
			return false;
		}

		if ( $this->useGzip() ) {
			$text = gzencode( $text );
		}

		$this->checkCacheDirs(); // build parent dir
		if ( !file_put_contents( $this->cachePath(), $text, LOCK_EX ) ) {
			wfDebug( __METHOD__ . "() failed saving " . $this->cachePath() . "\n" );
			$this->mCached = null;

			return false;
		}

		$this->mCached = true;

		return $text;
	}

	/**
	 * Clear the cache for this page
	 * @return void
	 */
	public function clearCache() {
		wfSuppressWarnings();
		unlink( $this->cachePath() );
		wfRestoreWarnings();
		$this->mCached = false;
	}

	/**
	 * Create parent directors of $this->cachePath()
	 * @return void
	 */
	protected function checkCacheDirs() {
		wfMkdirParents( dirname( $this->cachePath() ), null, __METHOD__ );
	}

	/**
	 * Get the cache type subdirectory (with trailing slash)
	 * An extending class could use that method to alter the type -> directory
	 * mapping. @see HTMLFileCache::typeSubdirectory() for an example.
	 *
	 * @return string
	 */
	protected function typeSubdirectory() {
		return $this->mType . '/';
	}

	/**
	 * Return relative multi-level hash subdirectory (with trailing slash)
	 * or the empty string if not $wgFileCacheDepth
	 * @return string
	 */
	protected function hashSubdirectory() {
		global $wgFileCacheDepth;

		$subdir = '';
		if ( $wgFileCacheDepth > 0 ) {
			$hash = md5( $this->mKey );
			for ( $i = 1; $i <= $wgFileCacheDepth; $i++ ) {
				$subdir .= substr( $hash, 0, $i ) . '/';
			}
		}

		return $subdir;
	}

	/**
	 * Roughly increments the cache misses in the last hour by unique visitors
	 * @param WebRequest $request
	 * @return void
	 */
	public function incrMissesRecent( WebRequest $request ) {
		global $wgMemc;
		if ( mt_rand( 0, self::MISS_FACTOR - 1 ) == 0 ) {
			# Get a large IP range that should include the user  even if that
			# person's IP address changes
			$ip = $request->getIP();
			if ( !IP::isValid( $ip ) ) {
				return;
			}
			$ip = IP::isIPv6( $ip )
				? IP::sanitizeRange( "$ip/32" )
				: IP::sanitizeRange( "$ip/16" );

			# Bail out if a request already came from this range...
			$key = wfMemcKey( get_class( $this ), 'attempt', $this->mType, $this->mKey, $ip );
			if ( $wgMemc->get( $key ) ) {
				return; // possibly the same user
			}
			$wgMemc->set( $key, 1, self::MISS_TTL_SEC );

			# Increment the number of cache misses...
			$key = $this->cacheMissKey();
			if ( $wgMemc->get( $key ) === false ) {
				$wgMemc->set( $key, 1, self::MISS_TTL_SEC );
			} else {
				$wgMemc->incr( $key );
			}
		}
	}

	/**
	 * Roughly gets the cache misses in the last hour by unique visitors
	 * @return int
	 */
	public function getMissesRecent() {
		global $wgMemc;

		return self::MISS_FACTOR * $wgMemc->get( $this->cacheMissKey() );
	}

	/**
	 * @return string
	 */
	protected function cacheMissKey() {
		return wfMemcKey( get_class( $this ), 'misses', $this->mType, $this->mKey );
	}
}