2 namespace TYPO3\CMS\Core\Cache\Backend
;
5 * This file is part of the TYPO3 CMS project.
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
14 * The TYPO3 project - inspiring people to share!
17 use TYPO3\CMS\Core\Cache
;
18 use TYPO3\CMS\Core\Core\Environment
;
19 use TYPO3\CMS\Core\Utility\GeneralUtility
;
22 * A caching backend which stores cache entries by using APCu.
24 * This backend uses the following types of keys:
26 * xxx is tag name, value is array of associated identifiers identifier. This
27 * is "forward" tag index. It is mainly used for obtaining content by tag
28 * (get identifier by tag -> get content by identifier)
30 * xxx is identifier, value is array of associated tags. This is "reverse" tag
31 * index. It provides quick access for all tags associated with this identifier
32 * and used when removing the identifier
34 * Each key is prepended with a prefix. By default prefix consists from two parts
35 * separated by underscore character and ends in yet another underscore character:
37 * - MD5 of path to TYPO3 and user running TYPO3
38 * This prefix makes sure that keys from the different installations do not
43 class ApcuBackend
extends AbstractBackend
implements TaggableBackendInterface
46 * A prefix to separate stored data from other data possible stored in the APC
50 protected $identifierPrefix;
53 * Set the cache identifier prefix.
55 * @param string $identifierPrefix
57 protected function setIdentifierPrefix($identifierPrefix)
59 $this->identifierPrefix
= $identifierPrefix;
63 * Retrieves the cache identifier prefix.
67 protected function getIdentifierPrefix()
69 return $this->identifierPrefix
;
73 * Constructs this backend
75 * @param string $context Unused, for backward compatibility only
76 * @param array $options Configuration options - unused here
77 * @throws Cache\Exception
79 public function __construct($context, array $options = [])
81 if (!extension_loaded('apcu')) {
82 throw new Cache\
Exception('The PHP extension "apcu" must be installed and loaded in order to use the APCu backend.', 1232985914);
84 if (PHP_SAPI
=== 'cli' && ini_get('apc.enable_cli') == 0) {
85 throw new Cache\
Exception('The APCu backend cannot be used because apcu is disabled on CLI.', 1232985915);
87 parent
::__construct($context, $options);
91 * Initializes the identifier prefix when setting the cache.
93 * @param \TYPO3\CMS\Core\Cache\Frontend\FrontendInterface $cache
95 public function setCache(\TYPO3\CMS\Core\Cache\Frontend\FrontendInterface
$cache)
97 parent
::setCache($cache);
98 $processUser = $this->getCurrentUserData();
99 $pathHash = GeneralUtility
::shortMD5(Environment
::getProjectPath() . $processUser['name'] . $this->context
. $cache->getIdentifier(), 12);
100 $this->setIdentifierPrefix('TYPO3_' . $pathHash);
104 * Returns the current user data with posix_getpwuid or a default structure when
105 * posix_getpwuid is not available.
109 protected function getCurrentUserData()
111 return extension_loaded('posix') ?
posix_getpwuid(posix_geteuid()) : ['name' => 'default'];
115 * Saves data in the cache.
117 * @param string $entryIdentifier An identifier for this specific cache entry
118 * @param string $data The data to be stored
119 * @param array $tags Tags to associate with this cache entry
120 * @param int $lifetime Lifetime of this cache entry in seconds. If NULL is specified, the default lifetime is used. "0" means unlimited lifetime.
121 * @throws Cache\Exception if no cache frontend has been set.
122 * @throws Cache\Exception\InvalidDataException if $data is not a string
125 public function set($entryIdentifier, $data, array $tags = [], $lifetime = null
)
127 if (!$this->cache
instanceof Cache\Frontend\FrontendInterface
) {
128 throw new Cache\
Exception('No cache frontend has been set yet via setCache().', 1232986118);
130 if (!is_string($data)) {
131 throw new Cache\Exception\
InvalidDataException('The specified data is of type "' . gettype($data) . '" but a string is expected.', 1232986125);
133 $tags[] = '%APCBE%' . $this->cacheIdentifier
;
134 $expiration = $lifetime ??
$this->defaultLifetime
;
135 $success = apcu_store($this->getIdentifierPrefix() . $entryIdentifier, $data, $expiration);
136 if ($success === true
) {
137 $this->removeIdentifierFromAllTags($entryIdentifier);
138 $this->addIdentifierToTags($entryIdentifier, $tags);
140 $this->logger
->alert('Error using APCu: Could not save data in the cache.');
145 * Loads data from the cache.
147 * @param string $entryIdentifier An identifier which describes the cache entry to load
148 * @return mixed The cache entry's content as a string or FALSE if the cache entry could not be loaded
151 public function get($entryIdentifier)
154 $value = apcu_fetch($this->getIdentifierPrefix() . $entryIdentifier, $success);
155 return $success ?
$value : $success;
159 * Checks if a cache entry with the specified identifier exists.
161 * @param string $entryIdentifier An identifier specifying the cache entry
162 * @return bool TRUE if such an entry exists, FALSE if not
165 public function has($entryIdentifier)
168 apcu_fetch($this->getIdentifierPrefix() . $entryIdentifier, $success);
173 * Removes all cache entries matching the specified identifier.
174 * Usually this only affects one entry but if - for what reason ever -
175 * old entries for the identifier still exist, they are removed as well.
177 * @param string $entryIdentifier Specifies the cache entry to remove
178 * @return bool TRUE if (at least) an entry could be removed or FALSE if no entry was found
181 public function remove($entryIdentifier)
183 $this->removeIdentifierFromAllTags($entryIdentifier);
184 return apcu_delete($this->getIdentifierPrefix() . $entryIdentifier);
188 * Finds and returns all cache entry identifiers which are tagged by the
191 * @param string $tag The tag to search for
192 * @return array An array with identifiers of all matching entries. An empty array if no entries matched
195 public function findIdentifiersByTag($tag)
198 $identifiers = apcu_fetch($this->getIdentifierPrefix() . 'tag_' . $tag, $success);
199 if ($success === false
) {
202 return (array)$identifiers;
206 * Finds all tags for the given identifier. This function uses reverse tag
207 * index to search for tags.
209 * @param string $identifier Identifier to find tags by
210 * @return array Array with tags
212 protected function findTagsByIdentifier($identifier)
215 $tags = apcu_fetch($this->getIdentifierPrefix() . 'ident_' . $identifier, $success);
216 return $success ?
(array)$tags : [];
220 * Removes all cache entries of this cache.
222 * @throws Cache\Exception
225 public function flush()
227 if (!$this->cache
instanceof Cache\Frontend\FrontendInterface
) {
228 throw new Cache\
Exception('Yet no cache frontend has been set via setCache().', 1232986571);
230 $this->flushByTag('%APCBE%' . $this->cacheIdentifier
);
234 * Removes all cache entries of this cache which are tagged by the specified tag.
236 * @param string $tag The tag the entries must have
239 public function flushByTag($tag)
241 $identifiers = $this->findIdentifiersByTag($tag);
242 foreach ($identifiers as $identifier) {
243 $this->remove($identifier);
248 * Associates the identifier with the given tags
250 * @param string $entryIdentifier
253 protected function addIdentifierToTags($entryIdentifier, array $tags)
255 // Get identifier-to-tag index to look for updates
256 $existingTags = $this->findTagsByIdentifier($entryIdentifier);
257 $existingTagsUpdated = false
;
259 foreach ($tags as $tag) {
260 // Update tag-to-identifier index
261 $identifiers = $this->findIdentifiersByTag($tag);
262 if (!in_array($entryIdentifier, $identifiers, true
)) {
263 $identifiers[] = $entryIdentifier;
264 apcu_store($this->getIdentifierPrefix() . 'tag_' . $tag, $identifiers);
266 // Test if identifier-to-tag index needs update
267 if (!in_array($tag, $existingTags, true
)) {
268 $existingTags[] = $tag;
269 $existingTagsUpdated = true
;
273 // Update identifier-to-tag index if needed
274 if ($existingTagsUpdated) {
275 apcu_store($this->getIdentifierPrefix() . 'ident_' . $entryIdentifier, $existingTags);
280 * Removes association of the identifier with the given tags
282 * @param string $entryIdentifier
284 protected function removeIdentifierFromAllTags($entryIdentifier)
286 // Get tags for this identifier
287 $tags = $this->findTagsByIdentifier($entryIdentifier);
288 // De-associate tags with this identifier
289 foreach ($tags as $tag) {
290 $identifiers = $this->findIdentifiersByTag($tag);
291 // Formally array_search() below should never return FALSE due to
292 // the behavior of findTagsByIdentifier(). But if reverse index is
293 // corrupted, we still can get 'FALSE' from array_search(). This is
294 // not a problem because we are removing this identifier from
296 if (($key = array_search($entryIdentifier, $identifiers)) !== false
) {
297 unset($identifiers[$key]);
298 if (!empty($identifiers)) {
299 apcu_store($this->getIdentifierPrefix() . 'tag_' . $tag, $identifiers);
301 apcu_delete($this->getIdentifierPrefix() . 'tag_' . $tag);
305 // Clear reverse tag index for this identifier
306 apcu_delete($this->getIdentifierPrefix() . 'ident_' . $entryIdentifier);
310 * Does nothing, as APCu does GC itself
312 public function collectGarbage()