ff647373285510395b46e83ad1cab7920f7e91bd
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Cache / Backend / ApcuBackend.php
1 <?php
2 namespace TYPO3\CMS\Core\Cache\Backend;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
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.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Core\Cache;
18 use TYPO3\CMS\Core\Utility\GeneralUtility;
19
20 /**
21 * A caching backend which stores cache entries by using APCu.
22 *
23 * This backend uses the following types of keys:
24 * - tag_xxx
25 * xxx is tag name, value is array of associated identifiers identifier. This
26 * is "forward" tag index. It is mainly used for obtaining content by tag
27 * (get identifier by tag -> get content by identifier)
28 * - ident_xxx
29 * xxx is identifier, value is array of associated tags. This is "reverse" tag
30 * index. It provides quick access for all tags associated with this identifier
31 * and used when removing the identifier
32 *
33 * Each key is prepended with a prefix. By default prefix consists from two parts
34 * separated by underscore character and ends in yet another underscore character:
35 * - "TYPO3"
36 * - MD5 of path to TYPO3 and user running TYPO3
37 * This prefix makes sure that keys from the different installations do not
38 * conflict.
39 *
40 * @api
41 */
42 class ApcuBackend extends AbstractBackend implements TaggableBackendInterface
43 {
44 /**
45 * A prefix to separate stored data from other data possible stored in the APC
46 *
47 * @var string
48 */
49 protected $identifierPrefix;
50
51 /**
52 * Set the cache identifier prefix.
53 *
54 * @param string $identifierPrefix
55 */
56 protected function setIdentifierPrefix($identifierPrefix)
57 {
58 $this->identifierPrefix = $identifierPrefix;
59 }
60
61 /**
62 * Retrieves the cache identifier prefix.
63 *
64 * @return string
65 */
66 protected function getIdentifierPrefix()
67 {
68 return $this->identifierPrefix;
69 }
70
71 /**
72 * Constructs this backend
73 *
74 * @param string $context Unused, for backward compatibility only
75 * @param array $options Configuration options - unused here
76 * @throws Cache\Exception
77 */
78 public function __construct($context, array $options = [])
79 {
80 if (!extension_loaded('apcu')) {
81 throw new Cache\Exception('The PHP extension "apcu" must be installed and loaded in order to use the APCu backend.', 1232985914);
82 }
83 if (PHP_SAPI === 'cli' && ini_get('apc.enable_cli') == 0) {
84 throw new Cache\Exception('The APCu backend cannot be used because apcu is disabled on CLI.', 1232985915);
85 }
86 parent::__construct($context, $options);
87 }
88
89 /**
90 * Initializes the identifier prefix when setting the cache.
91 *
92 * @param \TYPO3\CMS\Core\Cache\Frontend\FrontendInterface $cache
93 */
94 public function setCache(\TYPO3\CMS\Core\Cache\Frontend\FrontendInterface $cache)
95 {
96 parent::setCache($cache);
97 $processUser = $this->getCurrentUserData();
98 $pathHash = GeneralUtility::shortMD5($this->getPathSite() . $processUser['name'] . $this->context . $cache->getIdentifier(), 12);
99 $this->setIdentifierPrefix('TYPO3_' . $pathHash);
100 }
101
102 /**
103 * Returns the current user data with posix_getpwuid or a default structure when
104 * posix_getpwuid is not available.
105 *
106 * @return array
107 */
108 protected function getCurrentUserData()
109 {
110 return extension_loaded('posix') ? posix_getpwuid(posix_geteuid()) : ['name' => 'default'];
111 }
112
113 /**
114 * Returns the PATH_site constant.
115 *
116 * @return string
117 */
118 protected function getPathSite()
119 {
120 return PATH_site;
121 }
122
123 /**
124 * Saves data in the cache.
125 *
126 * @param string $entryIdentifier An identifier for this specific cache entry
127 * @param string $data The data to be stored
128 * @param array $tags Tags to associate with this cache entry
129 * @param int $lifetime Lifetime of this cache entry in seconds. If NULL is specified, the default lifetime is used. "0" means unlimited lifetime.
130 * @throws Cache\Exception if no cache frontend has been set.
131 * @throws Cache\Exception\InvalidDataException if $data is not a string
132 * @api
133 */
134 public function set($entryIdentifier, $data, array $tags = [], $lifetime = null)
135 {
136 if (!$this->cache instanceof Cache\Frontend\FrontendInterface) {
137 throw new Cache\Exception('No cache frontend has been set yet via setCache().', 1232986118);
138 }
139 if (!is_string($data)) {
140 throw new Cache\Exception\InvalidDataException('The specified data is of type "' . gettype($data) . '" but a string is expected.', 1232986125);
141 }
142 $tags[] = '%APCBE%' . $this->cacheIdentifier;
143 $expiration = $lifetime ?? $this->defaultLifetime;
144 $success = apcu_store($this->getIdentifierPrefix() . $entryIdentifier, $data, $expiration);
145 if ($success === true) {
146 $this->removeIdentifierFromAllTags($entryIdentifier);
147 $this->addIdentifierToTags($entryIdentifier, $tags);
148 } else {
149 $this->logger->alert('Error using APCu: Could not save data in the cache.');
150 }
151 }
152
153 /**
154 * Loads data from the cache.
155 *
156 * @param string $entryIdentifier An identifier which describes the cache entry to load
157 * @return mixed The cache entry's content as a string or FALSE if the cache entry could not be loaded
158 * @api
159 */
160 public function get($entryIdentifier)
161 {
162 $success = false;
163 $value = apcu_fetch($this->getIdentifierPrefix() . $entryIdentifier, $success);
164 return $success ? $value : $success;
165 }
166
167 /**
168 * Checks if a cache entry with the specified identifier exists.
169 *
170 * @param string $entryIdentifier An identifier specifying the cache entry
171 * @return bool TRUE if such an entry exists, FALSE if not
172 * @api
173 */
174 public function has($entryIdentifier)
175 {
176 $success = false;
177 apcu_fetch($this->getIdentifierPrefix() . $entryIdentifier, $success);
178 return $success;
179 }
180
181 /**
182 * Removes all cache entries matching the specified identifier.
183 * Usually this only affects one entry but if - for what reason ever -
184 * old entries for the identifier still exist, they are removed as well.
185 *
186 * @param string $entryIdentifier Specifies the cache entry to remove
187 * @return bool TRUE if (at least) an entry could be removed or FALSE if no entry was found
188 * @api
189 */
190 public function remove($entryIdentifier)
191 {
192 $this->removeIdentifierFromAllTags($entryIdentifier);
193 return apcu_delete($this->getIdentifierPrefix() . $entryIdentifier);
194 }
195
196 /**
197 * Finds and returns all cache entry identifiers which are tagged by the
198 * specified tag.
199 *
200 * @param string $tag The tag to search for
201 * @return array An array with identifiers of all matching entries. An empty array if no entries matched
202 * @api
203 */
204 public function findIdentifiersByTag($tag)
205 {
206 $success = false;
207 $identifiers = apcu_fetch($this->getIdentifierPrefix() . 'tag_' . $tag, $success);
208 if ($success === false) {
209 return [];
210 }
211 return (array)$identifiers;
212 }
213
214 /**
215 * Finds all tags for the given identifier. This function uses reverse tag
216 * index to search for tags.
217 *
218 * @param string $identifier Identifier to find tags by
219 * @return array Array with tags
220 */
221 protected function findTagsByIdentifier($identifier)
222 {
223 $success = false;
224 $tags = apcu_fetch($this->getIdentifierPrefix() . 'ident_' . $identifier, $success);
225 return $success ? (array)$tags : [];
226 }
227
228 /**
229 * Removes all cache entries of this cache.
230 *
231 * @throws Cache\Exception
232 * @api
233 */
234 public function flush()
235 {
236 if (!$this->cache instanceof Cache\Frontend\FrontendInterface) {
237 throw new Cache\Exception('Yet no cache frontend has been set via setCache().', 1232986571);
238 }
239 $this->flushByTag('%APCBE%' . $this->cacheIdentifier);
240 }
241
242 /**
243 * Removes all cache entries of this cache which are tagged by the specified tag.
244 *
245 * @param string $tag The tag the entries must have
246 * @api
247 */
248 public function flushByTag($tag)
249 {
250 $identifiers = $this->findIdentifiersByTag($tag);
251 foreach ($identifiers as $identifier) {
252 $this->remove($identifier);
253 }
254 }
255
256 /**
257 * Associates the identifier with the given tags
258 *
259 * @param string $entryIdentifier
260 * @param array $tags
261 */
262 protected function addIdentifierToTags($entryIdentifier, array $tags)
263 {
264 // Get identifier-to-tag index to look for updates
265 $existingTags = $this->findTagsByIdentifier($entryIdentifier);
266 $existingTagsUpdated = false;
267
268 foreach ($tags as $tag) {
269 // Update tag-to-identifier index
270 $identifiers = $this->findIdentifiersByTag($tag);
271 if (!in_array($entryIdentifier, $identifiers, true)) {
272 $identifiers[] = $entryIdentifier;
273 apcu_store($this->getIdentifierPrefix() . 'tag_' . $tag, $identifiers);
274 }
275 // Test if identifier-to-tag index needs update
276 if (!in_array($tag, $existingTags, true)) {
277 $existingTags[] = $tag;
278 $existingTagsUpdated = true;
279 }
280 }
281
282 // Update identifier-to-tag index if needed
283 if ($existingTagsUpdated) {
284 apcu_store($this->getIdentifierPrefix() . 'ident_' . $entryIdentifier, $existingTags);
285 }
286 }
287
288 /**
289 * Removes association of the identifier with the given tags
290 *
291 * @param string $entryIdentifier
292 */
293 protected function removeIdentifierFromAllTags($entryIdentifier)
294 {
295 // Get tags for this identifier
296 $tags = $this->findTagsByIdentifier($entryIdentifier);
297 // De-associate tags with this identifier
298 foreach ($tags as $tag) {
299 $identifiers = $this->findIdentifiersByTag($tag);
300 // Formally array_search() below should never return FALSE due to
301 // the behavior of findTagsByIdentifier(). But if reverse index is
302 // corrupted, we still can get 'FALSE' from array_search(). This is
303 // not a problem because we are removing this identifier from
304 // anywhere.
305 if (($key = array_search($entryIdentifier, $identifiers)) !== false) {
306 unset($identifiers[$key]);
307 if (!empty($identifiers)) {
308 apcu_store($this->getIdentifierPrefix() . 'tag_' . $tag, $identifiers);
309 } else {
310 apcu_delete($this->getIdentifierPrefix() . 'tag_' . $tag);
311 }
312 }
313 }
314 // Clear reverse tag index for this identifier
315 apcu_delete($this->getIdentifierPrefix() . 'ident_' . $entryIdentifier);
316 }
317
318 /**
319 * Does nothing, as APCu does GC itself
320 */
321 public function collectGarbage()
322 {
323 }
324 }