FileCacheDriver.php 6.63 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
<?php
/*
	Question2Answer by Gideon Greenspan and contributors
	http://www.question2answer.org/

	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.

	More about this license: http://www.question2answer.org/license.php
*/

19 20
namespace Q2A\Storage;

21 22 23
/**
 * Caches data (typically from database queries) to the filesystem.
 */
24
class FileCacheDriver implements CacheDriver
25 26
{
	private $enabled = false;
27
	private $keyPrefix = '';
28 29 30
	private $error;
	private $cacheDir;

31 32
	private $phpProtect = '<?php header($_SERVER[\'SERVER_PROTOCOL\'].\' 404 Not Found\'); die; ?>';

33 34 35 36 37 38
	/**
	 * Creates a new FileCache instance and checks we can write to the cache directory.
	 * @param array $config Configuration data, including cache storage directory.
	 */
	public function __construct($config)
	{
Scott committed
39 40 41 42
		if (!$config['enabled']) {
			return;
		}

43 44 45 46
		if (isset($config['keyprefix'])) {
			$this->keyPrefix = $config['keyprefix'];
		}

47 48 49
		if (isset($config['dir'])) {
			$this->cacheDir = realpath($config['dir']);
			if (!is_writable($this->cacheDir)) {
50
				$this->error = qa_lang_html_sub('admin/caching_dir_error', $config['dir']);
51 52 53
			}
		} else {
			$this->error = qa_lang_html('admin/caching_dir_missing');
54 55 56 57 58 59 60 61
		}

		$this->enabled = empty($this->error);
	}

	/**
	 * Get the cached data for the supplied key.
	 * @param string $key The unique cache identifier.
62
	 *
63 64 65 66
	 * @return string The cached data, or null otherwise.
	 */
	public function get($key)
	{
Scott committed
67 68 69 70
		if (!$this->enabled) {
			return null;
		}

71 72
		$fullKey = $this->keyPrefix . $key;
		$file = $this->getFilename($fullKey);
73 74 75

		if (is_readable($file)) {
			$lines = file($file, FILE_IGNORE_NEW_LINES);
76
			$skipLine = array_shift($lines);
77 78 79
			$actualKey = array_shift($lines);

			// double check this is the correct data
80
			if ($fullKey === $actualKey) {
81 82 83
				$expiry = array_shift($lines);

				if (is_numeric($expiry) && time() < $expiry) {
Scott committed
84 85 86 87 88 89
					$encData = implode("\n", $lines);
					// decode data, ignoring any notices
					$data = @unserialize($encData);
					if ($data !== false) {
						return $data;
					}
90 91 92 93 94 95 96 97
				}
			}
		}

		return null;
	}

	/**
Scott committed
98
	 * Store something in the cache along with the key and expiry time. Data gets 'serialized' to a string before storing.
99
	 * @param string $key The unique cache identifier.
Scott committed
100
	 * @param mixed $data The data to cache (in core Q2A this is usually an array).
101
	 * @param int $ttl Number of minutes for which to cache the data.
102
	 *
103 104
	 * @return bool Whether the file was successfully cached.
	 */
Scott committed
105
	public function set($key, $data, $ttl)
106 107
	{
		$success = false;
Scott committed
108
		$ttl = (int) $ttl;
109
		$fullKey = $this->keyPrefix . $key;
110

Scott committed
111
		if ($this->enabled && $ttl > 0) {
Scott committed
112
			$encData = serialize($data);
113
			$expiry = time() + ($ttl * 60);
114
			$cache = $this->phpProtect . "\n" . $fullKey . "\n" . $expiry . "\n" . $encData;
115

116
			$file = $this->getFilename($fullKey);
Scott committed
117
			$dir = dirname($file);
118
			if (is_dir($dir) || mkdir($dir, 0777, true)) {
Scott committed
119
				$success = @file_put_contents($file, $cache) !== false;
120 121 122 123 124 125
			}
		}

		return $success;
	}

Scott committed
126 127
	/**
	 * Delete an item from the cache.
128 129
	 * @param string $key The unique cache identifier.
	 *
Scott committed
130 131 132 133
	 * @return bool Whether the operation succeeded.
	 */
	public function delete($key)
	{
134
		$fullKey = $this->keyPrefix . $key;
Scott committed
135

136 137
		if ($this->enabled) {
			$file = $this->getFilename($fullKey);
Scott committed
138 139 140 141 142 143 144 145
			return $this->deleteFile($file);
		}

		return false;
	}

	/**
	 * Delete multiple items from the cache.
146 147 148 149
	 * @param int $limit Maximum number of items to process. 0 = unlimited
	 * @param int $start Offset from which to start (used for 'batching' deletes).
	 * @param bool $expiredOnly Delete cache only if it has expired.
	 *
Scott committed
150 151
	 * @return int Number of files deleted.
	 */
Scott committed
152
	public function clear($limit = 0, $start = 0, $expiredOnly = false)
Scott committed
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
	{
		$seek = $processed = $deleted = 0;

		// fetch directories first to lower memory usage
		$cacheDirs = glob($this->cacheDir . '/*/*', GLOB_ONLYDIR);
		foreach ($cacheDirs as $dir) {
			$cacheFiles = glob($dir . '/*');
			foreach ($cacheFiles as $file) {
				if ($seek < $start) {
					$seek++;
					continue;
				}

				$wasDeleted = false;
				if ($expiredOnly) {
					if (is_readable($file)) {
						$fp = fopen($file, 'r');
						$key = fgets($fp);
Scott committed
171
						$expiry = (int) trim(fgets($fp));
Scott committed
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
						if (is_numeric($expiry) && time() > $expiry) {
							$wasDeleted = $this->deleteFile($file);
						}
					}
				} else {
					$wasDeleted = $this->deleteFile($file);
				}

				if ($wasDeleted) {
					$deleted++;
				}

				$processed++;
				if ($processed >= $limit) {
					break 2;
				}
			}
		}

		// return how many files were deleted - caller can figure out how many to skip next time
		return $deleted;
	}

195 196
	/**
	 * Whether caching is available.
197
	 *
198 199 200 201 202 203 204 205 206
	 * @return bool
	 */
	public function isEnabled()
	{
		return $this->enabled;
	}

	/**
	 * Get the last error.
207
	 *
208 209 210 211 212 213 214
	 * @return string
	 */
	public function getError()
	{
		return $this->error;
	}

215 216 217 218 219 220 221 222 223 224
	/**
	 * Get the prefix used for all cache keys.
	 *
	 * @return string
	 */
	public function getKeyPrefix()
	{
		return $this->keyPrefix;
	}

Scott committed
225 226
	/**
	 * Get current statistics for the cache.
227
	 *
Scott committed
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
	 * @return array Array of stats: 'files' => number of files, 'size' => total file size in bytes.
	 */
	public function getStats()
	{
		if (!$this->enabled) {
			return array('files' => 0, 'size' => 0);
		}

		$totalFiles = 0;
		$totalBytes = 0;
		$dirIter = new RecursiveDirectoryIterator($this->cacheDir);
		foreach (new RecursiveIteratorIterator($dirIter) as $file) {
			if (strpos($file->getFilename(), '.') === 0) {
				// TODO: use FilesystemIterator::SKIP_DOTS once we're on minimum PHP 5.3
				continue;
			}

			$totalFiles++;
			$totalBytes += $file->getSize();
		}

		return array(
			'files' => $totalFiles,
			'size' => $totalBytes,
		);
	}

	/**
	 * Delete a specific file
257 258
	 * @param string $file Filename to delete.
	 *
Scott committed
259 260 261 262 263 264 265 266 267 268 269
	 * @return bool Whether the file was deleted successfully.
	 */
	private function deleteFile($file)
	{
		if (is_writable($file)) {
			return @unlink($file) === true;
		}

		return false;
	}

270 271
	/**
	 * Generates filename for cache key, of the form `1/23/123abc`
272
	 * @param string $key The unique cache key (including prefix).
273
	 *
274 275
	 * @return string
	 */
276
	private function getFilename($fullKey)
277
	{
278
		$filename = sha1($fullKey);
279
		return $this->cacheDir . '/' . substr($filename, 0, 1) . '/' . substr($filename, 1, 2) . '/' . $filename . '.php';
280 281
	}
}