summaryrefslogtreecommitdiff
path: root/kohana/libraries/drivers/Cache/File.php
blob: 01d6c383b90391805a9c1ab4cada078a3681eb59 (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
<?php defined('SYSPATH') or die('No direct script access.');
/**
 * File-based Cache driver.
 *
 * $Id$
 *
 * @package    Cache
 * @author     Kohana Team
 * @copyright  (c) 2007-2008 Kohana Team
 * @license    http://kohanaphp.com/license.html
 */
class Cache_File_Driver implements Cache_Driver {

	protected $directory = '';

	/**
	 * Tests that the storage location is a directory and is writable.
	 */
	public function __construct($directory)
	{
		// Find the real path to the directory
		$directory = str_replace('\\', '/', realpath($directory)).'/';

		// Make sure the cache directory is writable
		if ( ! is_dir($directory) OR ! is_writable($directory))
			throw new Kohana_Exception('cache.unwritable', $directory);

		// Directory is valid
		$this->directory = $directory;
	}

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

			// Find all tags matching the given tag
			foreach ($files as $i => $file)
			{
				// Split the files
				$tags = explode('~', $file);

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

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

				if ( ! in_array($tag, $tags))
				{
					// This entry does not match the tag
					unset($files[$i]);
				}
			}
		}
		else
		{
			// Find all the files matching the given id
			$files = glob($this->directory.$id.'~*');
		}

		return empty($files) ? NULL : $files;
	}

	/**
	 * Sets a cache item to the given data, tags, and lifetime.
	 *
	 * @param   string   cache id to set
	 * @param   string   data in the cache
	 * @param   array    cache tags
	 * @param   integer  lifetime
	 * @return  bool
	 */
	public function set($id, $data, $tags, $lifetime)
	{
		// Remove old cache files
		$this->delete($id);

		// Cache File driver expects unix timestamp
		if ($lifetime !== 0)
		{
			$lifetime += time();
		}

		// Construct the filename
		$filename = $id.'~'.implode('+', $tags).'~'.$lifetime;

		// Write the file, appending the sha1 signature to the beginning of the data
		return (bool) file_put_contents($this->directory.$filename, sha1($data).$data);
	}

	/**
	 * Finds an array of ids for a given tag.
	 *
	 * @param  string  tag name
	 * @return array   of ids that match the tag
	 */
	public function find($tag)
	{
		if ($files = $this->exists($tag, TRUE))
		{
			// Length of directory name
			$offset = strlen($this->directory);

			// Find all the files with the given tag
			$array = array();
			foreach ($files as $file)
			{
				// Get the id from the filename
				$array[] = substr(current(explode('~', $file)), $offset);
			}

			return $array;
		}

		return FALSE;
	}

	/**
	 * Fetches a cache item. This will delete the item if it is expired or if
	 * the hash does not match the stored hash.
	 *
	 * @param   string  cache id
	 * @return  mixed|NULL
	 */
	public function get($id)
	{
		if ($file = $this->exists($id))
		{
			// Always process the first result
			$file = current($file);

			// Validate that the cache has not expired
			if ($this->expired($file))
			{
				// Remove this cache, it has expired
				$this->delete($id);
			}
			else
			{
				$data = file_get_contents($file);

				// Find the hash of the data
				$hash = substr($data, 0, 40);

				// Remove the hash from the data
				$data = substr($data, 40);

				if ($hash !== sha1($data))
				{
					// Remove this cache, it doesn't validate
					$this->delete($id);

					// Unset data to prevent it from being returned
					unset($data);
				}
			}
		}

		// Return NULL if there is no data
		return isset($data) ? $data : NULL;
	}

	/**
	 * Deletes a cache item by id or tag
	 *
	 * @param   string   cache id or tag, or TRUE for "all items"
	 * @param   boolean  use tags
	 * @return  boolean
	 */
	public function delete($id, $tag = FALSE)
	{
		$files = $this->exists($id, $tag);

		if (empty($files))
			return FALSE;

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

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

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

		return TRUE;
	}

	/**
	 * Deletes all cache files that are older than the current time.
	 *
	 * @return void
	 */
	public function delete_expired()
	{
		if ($files = $this->exists(TRUE))
		{
			foreach ($files as $file)
			{
				if ($this->expired($file))
				{
					// The cache file has already expired, delete it
					@unlink($file) or Kohana::log('error', 'Cache: Unable to delete cache file: '.$file);
				}
			}
		}
	}

	/**
	 * Check if a cache file has expired by filename.
	 *
	 * @param  string  filename
	 * @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 File Driver