summaryrefslogtreecommitdiff
path: root/system/libraries/drivers/Cache/File.php
blob: fc20c22d9eacd0265ae9235f89f4671d029eeb23 (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
<?php defined('SYSPATH') OR die('No direct access allowed.');
/**
 * Memcache-based Cache driver.
 *
 * $Id: File.php 4605 2009-09-14 17:22:21Z kiall $
 *
 * @package    Cache
 * @author     Kohana Team
 * @copyright  (c) 2007-2009 Kohana Team
 * @license    http://kohanaphp.com/license
 */
class Cache_File_Driver extends Cache_Driver {
	protected $config;
	protected $backend;

	public function __construct($config)
	{
		$this->config = $config;
		$this->config['directory'] = str_replace('\\', '/', realpath($this->config['directory'])).'/';

		if ( ! is_dir($this->config['directory']) OR ! is_writable($this->config['directory']))
			throw new Cache_Exception('The configured cache directory, :directory:, is not writable.', array(':directory:' => $this->config['directory']));
	}

	/**
	 * Finds an array of files matching the given id or tag.
	 *
	 * @param  string  cache key or tag
	 * @param  bool    search for tags
	 * @return array   of filenames matching the id or tag
	 */
	public function exists($keys, $tag = FALSE)
	{
		if ($keys === TRUE)
		{
			// Find all the files
			return glob($this->config['directory'].'*~*~*');
		}
		elseif ($tag === TRUE)
		{
			// Find all the files that have the tag name
			$paths = array();

			foreach ( (array) $keys as $tag)
			{
				$paths = array_merge($paths, glob($this->config['directory'].'*~*'.$tag.'*~*'));
			}

			// Find all tags matching the given tag
			$files = array();

			foreach ($paths as $path)
			{
				// Split the files
				$tags = explode('~', basename($path));

				// Find valid tags
				if (count($tags) !== 3 OR empty($tags[1]))
					continue;

				// Split the tags by plus signs, used to separate tags
				$item_tags = explode('+', $tags[1]);

				// Check each supplied tag, and match aginst the tags on each item.
				foreach ($keys as $tag)
				{
					if (in_array($tag, $item_tags))
					{
						// Add the file to the array, it has the requested tag
						$files[] = $path;
					}
				}
			}

			return $files;
		}
		else
		{
			$paths = array();

			foreach ( (array) $keys as $key)
			{
				// Find the file matching the given key
				$paths = array_merge($paths, glob($this->config['directory'].str_replace(array('/', '\\', ' '), '_', $key).'~*'));
			}

			return $paths;
		}
	}

	public function set($items, $tags = NULL, $lifetime = NULL)
	{
		if ($lifetime !== 0)
		{
			// File driver expects unix timestamp
			$lifetime += time();
		}


		if ( ! is_null($tags) AND ! empty($tags))
		{
			// Convert the tags into a string list
			$tags = implode('+', (array) $tags);
		}

		$success = TRUE;

		foreach ($items as $key => $value)
		{
			if (is_resource($value))
				throw new Cache_Exception('Caching of resources is impossible, because resources cannot be serialised.');

			// Remove old cache file
			$this->delete($key);

			if ( ! (bool) file_put_contents($this->config['directory'].str_replace(array('/', '\\', ' '), '_', $key).'~'.$tags.'~'.$lifetime, serialize($value)))
			{
				$success = FALSE;
			}
		}

		return $success;
	}

	public function get($keys, $single = FALSE)
	{
		$items = array();

		if ($files = $this->exists($keys))
		{
			// Turn off errors while reading the files
			$ER = error_reporting(0);

			foreach ($files as $file)
			{
				// Validate that the item has not expired
				if ($this->expired($file))
					continue;

				list($key, $junk) = explode('~', basename($file), 2);

				if (($data = file_get_contents($file)) !== FALSE)
				{
					// Unserialize the data
					$data = unserialize($data);
				}
				else
				{
					$data = NULL;
				}

				$items[$key] = $data;
			}

			// Turn errors back on
			error_reporting($ER);
		}

		// Reutrn a single item if only one key was requested
		if ($single)
		{
			return (count($items) > 0) ? current($items) : NULL;
		}
		else
		{
			return $items;
		}
	}

	/**
	 * Get cache items by tag
	 */
	public function get_tag($tags)
	{
		// An array will always be returned
		$result = array();

		if ($paths = $this->exists($tags, TRUE))
		{
			// Find all the files with the given tag
			foreach ($paths as $path)
			{
				// Get the id from the filename
				list($key, $junk) = explode('~', basename($path), 2);

				if (($data = $this->get($key)) !== FALSE)
				{
					// Add the result to the array
					$result[$key] = $data;
				}
			}
		}

		return $result;
	}

	/**
	 * Delete cache items by keys or tags
	 */
	public function delete($keys, $tag = FALSE)
	{
		$success = TRUE;

		$paths = $this->exists($keys, $tag);

		// Disable all error reporting while deleting
		$ER = error_reporting(0);

		foreach ($paths as $path)
		{
			// Remove the cache file
			if ( ! unlink($path))
			{
				Kohana::log('error', 'Cache: Unable to delete cache file: '.$path);
				$success = FALSE;
			}
		}

		// Turn on error reporting again
		error_reporting($ER);

		return $success;
	}

	/**
	 * Delete cache items by tag
	 */
	public function delete_tag($tags)
	{
		return $this->delete($tags, TRUE);
	}

	/**
	 * Empty the cache
	 */
	public function delete_all()
	{
		return $this->delete(TRUE);
	}

	/**
	 * Check if a cache file has expired by filename.
	 *
	 * @param  string|array   array of filenames
	 * @return bool
	 */
	protected function expired($file)
	{
		// Get the expiration time
		$expires = (int) substr($file, strrpos($file, '~') + 1);

		// Expirations of 0 are "never expire"
		return ($expires !== 0 AND $expires <= time());
	}
} // End Cache Memcache Driver