3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Core\Cache;
25 use Friendica\Core\BaseCache;
30 class APCuCache extends BaseCache implements IMemoryCache
33 use TraitCompareDelete;
38 public function __construct(string $hostname)
40 if (!self::isAvailable()) {
41 throw new Exception('APCu is not available.');
44 parent::__construct($hostname);
50 public function getAllKeys($prefix = null)
52 $ns = $this->getCacheKey($prefix);
53 $ns = preg_quote($ns, '/');
55 if (class_exists('\APCIterator')) {
56 $iterator = new \APCIterator('user', '/^' . $ns. '/', APC_ITER_KEY);
58 $iterator = new \APCUIterator('/^' . $ns . '/', APC_ITER_KEY);
62 foreach ($iterator as $item) {
63 array_push($keys, $item['key']);
66 return $this->getOriginalKeys($keys);
72 public function get($key)
75 $cachekey = $this->getCacheKey($key);
77 $cached = apcu_fetch($cachekey, $success);
82 $value = unserialize($cached);
84 // Only return a value if the serialized value is valid.
85 // We also check if the db entry is a serialized
86 // boolean 'false' value (which we want to return).
87 if ($cached === serialize(false) || $value !== false) {
97 public function set($key, $value, $ttl = Duration::FIVE_MINUTES)
99 $cachekey = $this->getCacheKey($key);
101 $cached = serialize($value);
120 public function delete($key)
122 $cachekey = $this->getCacheKey($key);
123 return apcu_delete($cachekey);
129 public function clear($outdated = true)
134 $prefix = $this->getPrefix();
135 $prefix = preg_quote($prefix, '/');
137 if (class_exists('\APCIterator')) {
138 $iterator = new \APCIterator('user', '/^' . $prefix . '/', APC_ITER_KEY);
140 $iterator = new \APCUIterator('/^' . $prefix . '/', APC_ITER_KEY);
143 return apcu_delete($iterator);
150 public function add($key, $value, $ttl = Duration::FIVE_MINUTES)
152 $cachekey = $this->getCacheKey($key);
153 $cached = serialize($value);
155 return apcu_add($cachekey, $cached);
158 public static function isAvailable()
160 if (!extension_loaded('apcu')) {
162 } elseif (!ini_get('apc.enabled') && !ini_get('apc.enable_cli')) {
165 version_compare(phpversion('apc') ?: '0.0.0', '4.0.6') === -1 &&
166 version_compare(phpversion('apcu') ?: '0.0.0', '5.1.0') === -1
177 public function getName()