summaryrefslogtreecommitdiff
path: root/poc/poc02-compiling-cake/src/vendor/cakephp-2.2.1-0-gcc44130/lib/Cake/Cache/Engine/FileEngine.php
blob: 9388fafb96bbfdb1b84c2e1b3096bb6595b608ba (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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
<?php
/**
 * File Storage engine for cache.  Filestorage is the slowest cache storage
 * to read and write.  However, it is good for servers that don't have other storage
 * engine available, or have content which is not performance sensitive.
 *
 * You can configure a FileEngine cache, using Cache::config()
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @since         CakePHP(tm) v 1.2.0.4933
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

/**
 * File Storage engine for cache.  Filestorage is the slowest cache storage
 * to read and write.  However, it is good for servers that don't have other storage
 * engine available, or have content which is not performance sensitive.
 *
 * You can configure a FileEngine cache, using Cache::config()
 *
 * @package       Cake.Cache.Engine
 */
class FileEngine extends CacheEngine {

/**
 * Instance of SplFileObject class
 *
 * @var File
 */
	protected $_File = null;

/**
 * Settings
 *
 * - path = absolute path to cache directory, default => CACHE
 * - prefix = string prefix for filename, default => cake_
 * - lock = enable file locking on write, default => false
 * - serialize = serialize the data, default => true
 *
 * @var array
 * @see CacheEngine::__defaults
 */
	public $settings = array();

/**
 * True unless FileEngine::__active(); fails
 *
 * @var boolean
 */
	protected $_init = true;

/**
 * Initialize the Cache Engine
 *
 * Called automatically by the cache frontend
 * To reinitialize the settings call Cache::engine('EngineName', [optional] settings = array());
 *
 * @param array $settings array of setting for the engine
 * @return boolean True if the engine has been successfully initialized, false if not
 */
	public function init($settings = array()) {
		$settings += array(
			'engine' => 'File',
			'path' => CACHE,
			'prefix' => 'cake_',
			'lock' => true,
			'serialize' => true,
			'isWindows' => false,
			'mask' => 0664
		);
		parent::init($settings);

		if (DS === '\\') {
			$this->settings['isWindows'] = true;
		}
		if (substr($this->settings['path'], -1) !== DS) {
			$this->settings['path'] .= DS;
		}
		if (!empty($this->_groupPrefix)) {
			$this->_groupPrefix = str_replace('_', DS, $this->_groupPrefix);
		}
		return $this->_active();
	}

/**
 * Garbage collection. Permanently remove all expired and deleted data
 * 
 * @param integer $expires [optional] An expires timestamp, invalidataing all data before.
 * @return boolean True if garbage collection was successful, false on failure
 */
	public function gc($expires = null) {
		return $this->clear(true);
	}

/**
 * Write data for key into cache
 *
 * @param string $key Identifier for the data
 * @param mixed $data Data to be cached
 * @param integer $duration How long to cache the data, in seconds
 * @return boolean True if the data was successfully cached, false on failure
 */
	public function write($key, $data, $duration) {
		if ($data === '' || !$this->_init) {
			return false;
		}

		if ($this->_setKey($key, true) === false) {
			return false;
		}

		$lineBreak = "\n";

		if ($this->settings['isWindows']) {
			$lineBreak = "\r\n";
		}

		if (!empty($this->settings['serialize'])) {
			if ($this->settings['isWindows']) {
				$data = str_replace('\\', '\\\\\\\\', serialize($data));
			} else {
				$data = serialize($data);
			}
		}

		$expires = time() + $duration;
		$contents = $expires . $lineBreak . $data . $lineBreak;

		if ($this->settings['lock']) {
			$this->_File->flock(LOCK_EX);
		}

		$this->_File->rewind();
		$success = $this->_File->ftruncate(0) && $this->_File->fwrite($contents) && $this->_File->fflush();

		if ($this->settings['lock']) {
			$this->_File->flock(LOCK_UN);
		}

		return $success;
	}

/**
 * Read a key from the cache
 *
 * @param string $key Identifier for the data
 * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
 */
	public function read($key) {
		if (!$this->_init || $this->_setKey($key) === false) {
			return false;
		}

		if ($this->settings['lock']) {
			$this->_File->flock(LOCK_SH);
		}

		$this->_File->rewind();
		$time = time();
		$cachetime = intval($this->_File->current());

		if ($cachetime !== false && ($cachetime < $time || ($time + $this->settings['duration']) < $cachetime)) {
			if ($this->settings['lock']) {
				$this->_File->flock(LOCK_UN);
			}
			return false;
		}

		$data = '';
		$this->_File->next();
		while ($this->_File->valid()) {
			$data .= $this->_File->current();
			$this->_File->next();
		}

		if ($this->settings['lock']) {
			$this->_File->flock(LOCK_UN);
		}

		$data = trim($data);

		if ($data !== '' && !empty($this->settings['serialize'])) {
			if ($this->settings['isWindows']) {
				$data = str_replace('\\\\\\\\', '\\', $data);
			}
			$data = unserialize((string)$data);
		}
		return $data;
	}

/**
 * Delete a key from the cache
 *
 * @param string $key Identifier for the data
 * @return boolean True if the value was successfully deleted, false if it didn't exist or couldn't be removed
 */
	public function delete($key) {
		if ($this->_setKey($key) === false || !$this->_init) {
			return false;
		}
		$path = $this->_File->getRealPath();
		$this->_File = null;
		return unlink($path);
	}

/**
 * Delete all values from the cache
 *
 * @param boolean $check Optional - only delete expired cache items
 * @return boolean True if the cache was successfully cleared, false otherwise
 */
	public function clear($check) {
		if (!$this->_init) {
			return false;
		}
		$dir = dir($this->settings['path']);
		if ($check) {
			$now = time();
			$threshold = $now - $this->settings['duration'];
		}
		$prefixLength = strlen($this->settings['prefix']);
		while (($entry = $dir->read()) !== false) {
			if (substr($entry, 0, $prefixLength) !== $this->settings['prefix']) {
				continue;
			}
			if ($this->_setKey($entry) === false) {
				continue;
			}
			if ($check) {
				$mtime = $this->_File->getMTime();

				if ($mtime > $threshold) {
					continue;
				}

				$expires = (int)$this->_File->current();

				if ($expires > $now) {
					continue;
				}
			}
			$path = $this->_File->getRealPath();
			$this->_File = null;
			if (file_exists($path)) {
				unlink($path);
			}
		}
		$dir->close();
		return true;
	}

/**
 * Not implemented
 *
 * @param string $key
 * @param integer $offset
 * @return void
 * @throws CacheException
 */
	public function decrement($key, $offset = 1) {
		throw new CacheException(__d('cake_dev', 'Files cannot be atomically decremented.'));
	}

/**
 * Not implemented
 *
 * @param string $key
 * @param integer $offset
 * @return void
 * @throws CacheException
 */
	public function increment($key, $offset = 1) {
		throw new CacheException(__d('cake_dev', 'Files cannot be atomically incremented.'));
	}

/**
 * Sets the current cache key this class is managing, and creates a writable SplFileObject
 * for the cache file the key is referring to.
 *
 * @param string $key The key
 * @param boolean $createKey Whether the key should be created if it doesn't exists, or not
 * @return boolean true if the cache key could be set, false otherwise
 */
	protected function _setKey($key, $createKey = false) {
		$groups = null;
		if (!empty($this->_groupPrefix)) {
			$groups = vsprintf($this->_groupPrefix, $this->groups());
		}
		$dir = $this->settings['path'] . $groups;

		if (!is_dir($dir)) {
			mkdir($dir, 0777, true);
		}
		$path = new SplFileInfo($dir . $key);

		if (!$createKey && !$path->isFile()) {
			return false;
		}
		if (empty($this->_File) || $this->_File->getBaseName() !== $key) {
			$exists = file_exists($path->getPathname());
			try {
				$this->_File = $path->openFile('c+');
			} catch (Exception $e) {
				trigger_error($e->getMessage(), E_USER_WARNING);
				return false;
			}
			unset($path);

			if (!$exists && !chmod($this->_File->getPathname(), (int)$this->settings['mask'])) {
				trigger_error(__d(
					'cake_dev', 'Could not apply permission mask "%s" on cache file "%s"',
					array($this->_File->getPathname(), $this->settings['mask'])), E_USER_WARNING);
			}
		}
		return true;
	}

/**
 * Determine is cache directory is writable
 *
 * @return boolean
 */
	protected function _active() {
		$dir = new SplFileInfo($this->settings['path']);
		if ($this->_init && !($dir->isDir() && $dir->isWritable())) {
			$this->_init = false;
			trigger_error(__d('cake_dev', '%s is not writable', $this->settings['path']), E_USER_WARNING);
			return false;
		}
		return true;
	}

/**
 * Generates a safe key for use with cache engine storage engines.
 *
 * @param string $key the key passed over
 * @return mixed string $key or false
 */
	public function key($key) {
		if (empty($key)) {
			return false;
		}

		$key = Inflector::underscore(str_replace(array(DS, '/', '.'), '_', strval($key)));
		return $key;
	}

/**
 * Recursively deletes all files under any directory named as $group
 *
 * @return boolean success
 **/
	public function clearGroup($group) {
		$directoryIterator = new RecursiveDirectoryIterator($this->settings['path']);
		$contents = new RecursiveIteratorIterator($directoryIterator, RecursiveIteratorIterator::CHILD_FIRST);
		foreach ($contents as $object) {
			$containsGroup = strpos($object->getPathName(), DS . $group . DS) !== false;
			if ($object->isFile() && $containsGroup) {
				unlink($object->getPathName());
			}
		}
		return true;
	}
}