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