2 /***************************************************************
5 * (c) 2009-2011 Ingo Renner <ingo@typo3.org>
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
17 * This script is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * This copyright notice MUST APPEAR in all copies of the script!
23 ***************************************************************/
26 * A caching backend which stores cache entries in files
28 * This file is a backport from FLOW3
31 * @subpackage t3lib_cache
35 class t3lib_cache_backend_FileBackend
extends t3lib_cache_backend_AbstractBackend
implements t3lib_cache_backend_PhpCapableBackend
{
37 const SEPARATOR
= '^';
39 const EXPIRYTIME_FORMAT
= 'YmdHis';
40 const EXPIRYTIME_LENGTH
= 14;
42 const DATASIZE_DIGITS
= 10;
45 * Directory where the files are stored
49 protected $cacheDirectory = '';
52 * TYPO3 v4 note: This variable is only available in v5
53 * Temporary path to cache directory before setCache() was called. It is
54 * set by setCacheDirectory() and used in setCache() method which calls
55 * the directory creation if needed. The variable is not used afterwards,
56 * the final cache directory path is stored in $this->cacheDirectory then.
58 * @var string Temporary path to cache directory
60 protected $temporaryCacheDirectory = '';
63 * A file extension to use for each cache entry.
67 protected $cacheEntryFileExtension = '';
71 * Sets a reference to the cache frontend which uses this backend and
72 * initializes the default cache directory.
74 * TYPO3 v4 note: This method is different between TYPO3 v4 and FLOW3
75 * because the Environment class to get the path to a temporary directory
76 * does not exist in v4.
78 * @param t3lib_cache_frontend_Frontend $cache The cache frontend
80 * @author Robert Lemke <robert@typo3.org>
82 public function setCache(t3lib_cache_frontend_Frontend
$cache) {
83 parent
::setCache($cache);
85 if (empty($this->temporaryCacheDirectory
)) {
86 // If no cache directory was given with cacheDirectory
87 // configuration option, set it to a path below typo3temp/
88 $temporaryCacheDirectory = PATH_site
. 'typo3temp/';
90 $temporaryCacheDirectory = $this->temporaryCacheDirectory
;
93 $codeOrData = ($cache instanceof t3lib_cache_frontend_PhpFrontend
) ?
'Code' : 'Data';
94 $finalCacheDirectory = $temporaryCacheDirectory . 'Cache/' . $codeOrData . '/' . $this->cacheIdentifier
. '/';
96 if (!is_dir($finalCacheDirectory)) {
97 $this->createFinalCacheDirectory($finalCacheDirectory);
99 unset($this->temporaryCacheDirectory
);
100 $this->cacheDirectory
= $finalCacheDirectory;
102 $this->cacheEntryFileExtension
= ($cache instanceof t3lib_cache_frontend_PhpFrontend
) ?
'.php' : '';
106 * Sets the directory where the cache files are stored. By default it is
107 * assumed that the directory is below the TYPO3_DOCUMENT_ROOT. However, an
108 * absolute path can be selected, too.
110 * This method does not exist in FLOW3 anymore, but it is needed in
111 * TYPO3 v4 to enable a cache path outside of document root. The final
112 * cache path is checked and created in createFinalCachDirectory(),
113 * called by setCache() method, which is done _after_ the cacheDirectory
114 * option was handled.
116 * @param string $cacheDirectory The cache base directory. If a relative path
117 * is given, it is assumed it is in TYPO3_DOCUMENT_ROOT. If an absolute
118 * path is given it is taken as is.
120 * @throws t3lib_cache_Exception if the directory is not within allowed
122 * @author Christian Kuhn <lolli@schwarzbu.ch>
124 public function setCacheDirectory($cacheDirectory) {
125 // Skip handling if directory is a stream ressource
126 // This is used by unit tests with vfs:// directoryies
127 if (strpos($cacheDirectory, '://')) {
128 $this->temporaryCacheDirectory
= $cacheDirectory;
132 $documentRoot = PATH_site
;
134 if (($open_basedir = ini_get('open_basedir'))) {
135 if (TYPO3_OS
=== 'WIN') {
137 $cacheDirectory = str_replace('\\', '/', $cacheDirectory);
138 if (!(preg_match('/[A-Z]:/', substr($cacheDirectory, 0, 2)))) {
139 $cacheDirectory = PATH_site
. $cacheDirectory;
143 if ($cacheDirectory[0] != '/') {
144 // relative path to cache directory.
145 $cacheDirectory = PATH_site
. $cacheDirectory;
149 $basedirs = explode($delimiter, $open_basedir);
150 $cacheDirectoryInBaseDir = FALSE;
151 foreach ($basedirs as $basedir) {
152 if (TYPO3_OS
=== 'WIN') {
153 $basedir = str_replace('\\', '/', $basedir);
155 if ($basedir[strlen($basedir) - 1] !== '/') {
158 if (t3lib_div
::isFirstPartOfStr($cacheDirectory, $basedir)) {
159 $documentRoot = $basedir;
160 $cacheDirectory = str_replace($basedir, '', $cacheDirectory);
161 $cacheDirectoryInBaseDir = TRUE;
165 if (!$cacheDirectoryInBaseDir) {
166 throw new t3lib_cache_Exception(
167 'Open_basedir restriction in effect. The directory "' . $cacheDirectory . '" is not in an allowed path.'
171 if ($cacheDirectory[0] == '/') {
172 // Absolute path to cache directory.
175 if (TYPO3_OS
=== 'WIN') {
176 if (substr($cacheDirectory, 0, strlen($documentRoot)) === $documentRoot) {
182 // After this point all paths have '/' as directory seperator
183 if ($cacheDirectory[strlen($cacheDirectory) - 1] !== '/') {
184 $cacheDirectory .= '/';
187 $this->temporaryCacheDirectory
= $documentRoot . $cacheDirectory . $this->cacheIdentifier
. '/';
191 * Create the final cache directory if it does not exist. This method
192 * exists in TYPO3 v4 only.
194 * @param string $finalCacheDirectory Absolute path to final cache directory
196 * @throws \t3lib_cache_Exception If directory is not writable after creation
198 protected function createFinalCacheDirectory($finalCacheDirectory) {
200 t3lib_div
::mkdir_deep($finalCacheDirectory);
201 } catch (\RuntimeException
$e) {
202 throw new \t3lib_cache_Exception
(
203 'The directory "' . $finalCacheDirectory . '" can not be created.',
208 if (!is_writable($finalCacheDirectory)) {
209 throw new \t3lib_cache_Exception
(
210 'The directory "' . $finalCacheDirectory . '" is not writable.',
217 * Returns the directory where the cache files are stored
219 * @return string Full path of the cache directory
220 * @author Robert Lemke <robert@typo3.org>
223 public function getCacheDirectory() {
224 return $this->cacheDirectory
;
228 * Saves data in a cache file.
230 * @param string $entryIdentifier An identifier for this specific cache entry
231 * @param string $data The data to be stored
232 * @param array $tags Tags to associate with this cache entry
233 * @param integer $lifetime Lifetime of this cache entry in seconds. If NULL is specified, the default lifetime is used. "0" means unlimited lifetime.
235 * @throws t3lib_cache_Exception if the directory does not exist or is not writable or exceeds the maximum allowed path length, or if no cache frontend has been set.
236 * @throws t3lib_cache_exception_InvalidData if the data to bes stored is not a string.
237 * @author Robert Lemke <robert@typo3.org>
240 public function set($entryIdentifier, $data, array $tags = array(), $lifetime = NULL) {
241 if (!is_string($data)) {
242 throw new t3lib_cache_Exception_InvalidData(
243 'The specified data is of type "' . gettype($data) . '" but a string is expected.',
248 if ($entryIdentifier !== basename($entryIdentifier)) {
249 throw new \
InvalidArgumentException(
250 'The specified entry identifier must not contain a path segment.',
255 if ($entryIdentifier === '') {
256 throw new \
InvalidArgumentException(
257 'The specified entry identifier must not be empty.',
262 $this->remove($entryIdentifier);
264 $temporaryCacheEntryPathAndFilename = $this->cacheDirectory
. uniqid() . '.temp';
265 if (strlen($temporaryCacheEntryPathAndFilename) > t3lib_div
::getMaximumPathLength()) {
266 throw new t3lib_cache_Exception(
267 'The length of the temporary cache file path "' . $temporaryCacheEntryPathAndFilename .
268 '" is ' . strlen($temporaryCacheEntryPathAndFilename) . ' characters long and exceeds the maximum path length of ' .
269 t3lib_div
::getMaximumPathLength() . '. Please consider setting the temporaryDirectoryBase option to a shorter path. ',
274 $expiryTime = ($lifetime === NULL) ?
0 : ($GLOBALS['EXEC_TIME'] +
$lifetime);
275 $metaData = str_pad($expiryTime, self
::EXPIRYTIME_LENGTH
) . implode(' ', $tags) . str_pad(strlen($data), self
::DATASIZE_DIGITS
);
276 $result = file_put_contents($temporaryCacheEntryPathAndFilename, $data . $metaData);
277 t3lib_div
::fixPermissions($temporaryCacheEntryPathAndFilename);
279 if ($result === FALSE) {
280 throw new t3lib_cache_exception(
281 'The temporary cache file "' . $temporaryCacheEntryPathAndFilename . '" could not be written.',
287 $cacheEntryPathAndFilename = $this->cacheDirectory
. $entryIdentifier . $this->cacheEntryFileExtension
;
288 // @TODO: Figure out why the heck this is done and maybe find a smarter solution, report to FLOW3
289 while (!rename($temporaryCacheEntryPathAndFilename, $cacheEntryPathAndFilename) && $i < 5) {
293 // @FIXME: At least the result of rename() should be handled here, report to FLOW3
294 if ($result === FALSE) {
295 throw new t3lib_cache_exception(
296 'The cache file "' . $cacheEntryPathAndFilename . '" could not be written.',
303 * Loads data from a cache file.
305 * @param string $entryIdentifier An identifier which describes the cache entry to load
306 * @return mixed The cache entry's content as a string or FALSE if the cache entry could not be loaded
307 * @throws \InvalidArgumentException If identifier is invalid
308 * @author Robert Lemke <robert@typo3.org>
309 * @author Karsten Dambekalns <karsten@typo3.org>
312 public function get($entryIdentifier) {
313 if ($entryIdentifier !== basename($entryIdentifier)) {
314 throw new \
InvalidArgumentException(
315 'The specified entry identifier must not contain a path segment.',
320 $pathAndFilename = $this->cacheDirectory
. $entryIdentifier . $this->cacheEntryFileExtension
;
321 if ($this->isCacheFileExpired($pathAndFilename)) {
324 $dataSize = (integer) file_get_contents($pathAndFilename, NULL, NULL, filesize($pathAndFilename) - self
::DATASIZE_DIGITS
, self
::DATASIZE_DIGITS
);
325 return file_get_contents($pathAndFilename, NULL, NULL, 0, $dataSize);
329 * Checks if a cache entry with the specified identifier exists.
331 * @param string $entryIdentifier
332 * @return boolean TRUE if such an entry exists, FALSE if not
333 * @author Robert Lemke <robert@typo3.org>
336 public function has($entryIdentifier) {
337 if ($entryIdentifier !== basename($entryIdentifier)) {
338 throw new \
InvalidArgumentException(
339 'The specified entry identifier must not contain a path segment.',
344 return !$this->isCacheFileExpired($this->cacheDirectory
. $entryIdentifier . $this->cacheEntryFileExtension
);
348 * Removes all cache entries matching the specified identifier.
349 * Usually this only affects one entry.
351 * @param string $entryIdentifier Specifies the cache entry to remove
352 * @return boolean TRUE if (at least) an entry could be removed or FALSE if no entry was found
353 * @author Robert Lemke <robert@typo3.org>
356 public function remove($entryIdentifier) {
357 if ($entryIdentifier !== basename($entryIdentifier)) {
358 throw new \
InvalidArgumentException(
359 'The specified entry identifier must not contain a path segment.',
363 if ($entryIdentifier === '') {
364 throw new \
InvalidArgumentException(
365 'The specified entry identifier must not be empty.',
370 $pathAndFilename = $this->cacheDirectory
. $entryIdentifier . $this->cacheEntryFileExtension
;
371 if (file_exists($pathAndFilename) === FALSE) {
374 if (unlink($pathAndFilename) === FALSE) {
381 * Finds and returns all cache entry identifiers which are tagged by the
384 * @param string $searchedTag The tag to search for
385 * @return array An array with identifiers of all matching entries. An empty array if no entries matched
386 * @author Robert Lemke <robert@typo3.org>
389 public function findIdentifiersByTag($searchedTag) {
390 $entryIdentifiers = array();
391 $now = $GLOBALS['EXEC_TIME'];
392 $cacheEntryFileExtensionLength = strlen($this->cacheEntryFileExtension
);
393 for ($directoryIterator = t3lib_div
::makeInstance('DirectoryIterator', $this->cacheDirectory
); $directoryIterator->valid(); $directoryIterator->next()) {
394 if ($directoryIterator->isDot()) {
397 $cacheEntryPathAndFilename = $directoryIterator->getPathname();
398 $index = (integer) file_get_contents($cacheEntryPathAndFilename, NULL, NULL, filesize($cacheEntryPathAndFilename) - self
::DATASIZE_DIGITS
, self
::DATASIZE_DIGITS
);
399 $metaData = file_get_contents($cacheEntryPathAndFilename, NULL, NULL, $index);
401 $expiryTime = (integer) substr($metaData, 0, self
::EXPIRYTIME_LENGTH
);
402 if ($expiryTime !== 0 && $expiryTime < $now) {
405 if (in_array($searchedTag, explode(' ', substr($metaData, self
::EXPIRYTIME_LENGTH
, -self
::DATASIZE_DIGITS
)))) {
406 if ($cacheEntryFileExtensionLength > 0) {
407 $entryIdentifiers[] = substr($directoryIterator->getFilename(), 0, - $cacheEntryFileExtensionLength);
409 $entryIdentifiers[] = $directoryIterator->getFilename();
413 return $entryIdentifiers;
417 * Removes all cache entries of this cache.
420 * @author Robert Lemke <robert@typo3.org>
421 * @author Christian Kuhn <lolli@schwarzbu.ch>
424 public function flush() {
425 t3lib_div
::rmdir($this->cacheDirectory
, TRUE);
426 $this->createFinalCacheDirectory($this->cacheDirectory
);
430 * Removes all cache entries of this cache which are tagged by the specified tag.
432 * @param string $tag The tag the entries must have
434 * @author Robert Lemke <robert@typo3.org>
435 * @author Ingo Renner <ingo@typo3.org>
438 public function flushByTag($tag) {
439 $identifiers = $this->findIdentifiersByTag($tag);
440 if (count($identifiers) === 0) {
444 foreach ($identifiers as $entryIdentifier) {
445 $this->remove($entryIdentifier);
450 * Checks if the given cache entry files are still valid or if their
451 * lifetime has exceeded.
453 * @param string $cacheEntryPathAndFilename
455 * @author Robert Lemke <robert@typo3.org>
458 protected function isCacheFileExpired($cacheEntryPathAndFilename) {
459 if (file_exists($cacheEntryPathAndFilename) === FALSE) {
462 $index = (integer) file_get_contents($cacheEntryPathAndFilename, NULL, NULL, filesize($cacheEntryPathAndFilename) - self
::DATASIZE_DIGITS
, self
::DATASIZE_DIGITS
);
463 $expiryTime = file_get_contents($cacheEntryPathAndFilename, NULL, NULL, $index, self
::EXPIRYTIME_LENGTH
);
464 return ($expiryTime != 0 && $expiryTime < $GLOBALS['EXEC_TIME']);
468 * Does garbage collection
471 * @author Karsten Dambekalns <karsten@typo3.org>
474 public function collectGarbage() {
475 for ($directoryIterator = new \
DirectoryIterator($this->cacheDirectory
); $directoryIterator->valid(); $directoryIterator->next()) {
476 if ($directoryIterator->isDot()) {
480 if ($this->isCacheFileExpired($directoryIterator->getPathname())) {
481 $cacheEntryFileExtensionLength = strlen($this->cacheEntryFileExtension
);
482 if ($cacheEntryFileExtensionLength > 0) {
483 $this->remove(substr($directoryIterator->getFilename(), 0, - $cacheEntryFileExtensionLength));
485 $this->remove($directoryIterator->getFilename());
492 * Tries to find the cache entry for the specified identifier.
493 * Usually only one cache entry should be found - if more than one exist, this
494 * is due to some error or crash.
496 * @param string $entryIdentifier The cache entry identifier
497 * @return mixed The file names (including path) as an array if one or more entries could be found, otherwise FALSE
498 * @author Robert Lemke <robert@typo3.org>
501 protected function findCacheFilesByIdentifier($entryIdentifier) {
502 $pattern = $this->cacheDirectory
. $entryIdentifier;
503 $filesFound = glob($pattern);
504 if ($filesFound === FALSE ||
count($filesFound) === 0) {
512 * Loads PHP code from the cache and require_onces it right away.
514 * @param string $entryIdentifier An identifier which describes the cache entry to load
515 * @return mixed Potential return value from the include operation
518 public function requireOnce($entryIdentifier) {
519 if ($entryIdentifier !== basename($entryIdentifier)) {
520 throw new \
InvalidArgumentException(
521 'The specified entry identifier must not contain a path segment.',
526 $pathAndFilename = $this->cacheDirectory
. $entryIdentifier . $this->cacheEntryFileExtension
;
527 return ($this->isCacheFileExpired($pathAndFilename)) ?
FALSE : require_once($pathAndFilename);