[TASK] Use Environment API instead of PATH_site for Cache Backends
[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\Core\Environment;
19 use TYPO3\CMS\Core\Utility\GeneralUtility;
20
21 /**
22 * A caching backend which stores cache entries by using APCu.
23 *
24 * This backend uses the following types of keys:
25 * - tag_xxx
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)
29 * - ident_xxx
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
33 *
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:
36 * - "TYPO3"
37 * - MD5 of path to TYPO3 and user running TYPO3
38 * This prefix makes sure that keys from the different installations do not
39 * conflict.
40 *
41 * @api
42 */
43 class ApcuBackend extends AbstractBackend implements TaggableBackendInterface
44 {
45 /**
46 * A prefix to separate stored data from other data possible stored in the APC
47 *
48 * @var string
49 */
50 protected $identifierPrefix;
51
52 /**
53 * Set the cache identifier prefix.
54 *
55 * @param string $identifierPrefix
56 */
57 protected function setIdentifierPrefix($identifierPrefix)
58 {
59 $this->identifierPrefix = $identifierPrefix;
60 }
61
62 /**
63 * Retrieves the cache identifier prefix.
64 *
65 * @return string
66 */
67 protected function getIdentifierPrefix()
68 {
69 return $this->identifierPrefix;
70 }
71
72 /**
73 * Constructs this backend
74 *
75 * @param string $context Unused, for backward compatibility only
76 * @param array $options Configuration options - unused here
77 * @throws Cache\Exception
78 */
79 public function __construct($context, array $options = [])
80 {
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);
83 }
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);
86 }
87 parent::__construct($context, $options);
88 }
89
90 /**
91 * Initializes the identifier prefix when setting the cache.
92 *
93 * @param \TYPO3\CMS\Core\Cache\Frontend\FrontendInterface $cache
94 */
95 public function setCache(\TYPO3\CMS\Core\Cache\Frontend\FrontendInterface $cache)
96 {
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);
101 }
102
103 /**
104 * Returns the current user data with posix_getpwuid or a default structure when
105 * posix_getpwuid is not available.
106 *
107 * @return array
108 */
109 protected function getCurrentUserData()
110 {
111 return extension_loaded('posix') ? posix_getpwuid(posix_geteuid()) : ['name' => 'default'];
112 }
113
114 /**
115 * Saves data in the cache.
116 *
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
123 * @api
124 */
125 public function set($entryIdentifier, $data, array $tags = [], $lifetime = null)
126 {
127 if (!$this->cache instanceof Cache\Frontend\FrontendInterface) {
128 throw new Cache\Exception('No cache frontend has been set yet via setCache().', 1232986118);
129 }
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);
132 }
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);
139 } else {
140 $this->logger->alert('Error using APCu: Could not save data in the cache.');
141 }
142 }
143
144 /**
145 * Loads data from the cache.
146 *
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
149 * @api
150 */
151 public function get($entryIdentifier)
152 {
153 $success = false;
154 $value = apcu_fetch($this->getIdentifierPrefix() . $entryIdentifier, $success);
155 return $success ? $value : $success;
156 }
157
158 /**
159 * Checks if a cache entry with the specified identifier exists.
160 *
161 * @param string $entryIdentifier An identifier specifying the cache entry
162 * @return bool TRUE if such an entry exists, FALSE if not
163 * @api
164 */
165 public function has($entryIdentifier)
166 {
167 $success = false;
168 apcu_fetch($this->getIdentifierPrefix() . $entryIdentifier, $success);
169 return $success;
170 }
171
172 /**
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.
176 *
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
179 * @api
180 */
181 public function remove($entryIdentifier)
182 {
183 $this->removeIdentifierFromAllTags($entryIdentifier);
184 return apcu_delete($this->getIdentifierPrefix() . $entryIdentifier);
185 }
186
187 /**
188 * Finds and returns all cache entry identifiers which are tagged by the
189 * specified tag.
190 *
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
193 * @api
194 */
195 public function findIdentifiersByTag($tag)
196 {
197 $success = false;
198 $identifiers = apcu_fetch($this->getIdentifierPrefix() . 'tag_' . $tag, $success);
199 if ($success === false) {
200 return [];
201 }
202 return (array)$identifiers;
203 }
204
205 /**
206 * Finds all tags for the given identifier. This function uses reverse tag
207 * index to search for tags.
208 *
209 * @param string $identifier Identifier to find tags by
210 * @return array Array with tags
211 */
212 protected function findTagsByIdentifier($identifier)
213 {
214 $success = false;
215 $tags = apcu_fetch($this->getIdentifierPrefix() . 'ident_' . $identifier, $success);
216 return $success ? (array)$tags : [];
217 }
218
219 /**
220 * Removes all cache entries of this cache.
221 *
222 * @throws Cache\Exception
223 * @api
224 */
225 public function flush()
226 {
227 if (!$this->cache instanceof Cache\Frontend\FrontendInterface) {
228 throw new Cache\Exception('Yet no cache frontend has been set via setCache().', 1232986571);
229 }
230 $this->flushByTag('%APCBE%' . $this->cacheIdentifier);
231 }
232
233 /**
234 * Removes all cache entries of this cache which are tagged by the specified tag.
235 *
236 * @param string $tag The tag the entries must have
237 * @api
238 */
239 public function flushByTag($tag)
240 {
241 $identifiers = $this->findIdentifiersByTag($tag);
242 foreach ($identifiers as $identifier) {
243 $this->remove($identifier);
244 }
245 }
246
247 /**
248 * Associates the identifier with the given tags
249 *
250 * @param string $entryIdentifier
251 * @param array $tags
252 */
253 protected function addIdentifierToTags($entryIdentifier, array $tags)
254 {
255 // Get identifier-to-tag index to look for updates
256 $existingTags = $this->findTagsByIdentifier($entryIdentifier);
257 $existingTagsUpdated = false;
258
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);
265 }
266 // Test if identifier-to-tag index needs update
267 if (!in_array($tag, $existingTags, true)) {
268 $existingTags[] = $tag;
269 $existingTagsUpdated = true;
270 }
271 }
272
273 // Update identifier-to-tag index if needed
274 if ($existingTagsUpdated) {
275 apcu_store($this->getIdentifierPrefix() . 'ident_' . $entryIdentifier, $existingTags);
276 }
277 }
278
279 /**
280 * Removes association of the identifier with the given tags
281 *
282 * @param string $entryIdentifier
283 */
284 protected function removeIdentifierFromAllTags($entryIdentifier)
285 {
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
295 // anywhere.
296 if (($key = array_search($entryIdentifier, $identifiers)) !== false) {
297 unset($identifiers[$key]);
298 if (!empty($identifiers)) {
299 apcu_store($this->getIdentifierPrefix() . 'tag_' . $tag, $identifiers);
300 } else {
301 apcu_delete($this->getIdentifierPrefix() . 'tag_' . $tag);
302 }
303 }
304 }
305 // Clear reverse tag index for this identifier
306 apcu_delete($this->getIdentifierPrefix() . 'ident_' . $entryIdentifier);
307 }
308
309 /**
310 * Does nothing, as APCu does GC itself
311 */
312 public function collectGarbage()
313 {
314 }
315 }