3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Utils_Cache_Memcached
implements CRM_Utils_Cache_Interface
{
19 // TODO Consider native implementation.
20 use CRM_Utils_Cache_NaiveMultipleTrait
;
22 const DEFAULT_HOST
= 'localhost';
23 const DEFAULT_PORT
= 11211;
24 const DEFAULT_TIMEOUT
= 3600;
25 const DEFAULT_PREFIX
= '';
26 const MAX_KEY_LEN
= 200;
29 * If another process clears namespace, we'll find out in ~5 sec.
31 const NS_LOCAL_TTL
= 5;
34 * The host name of the memcached server
38 protected $_host = self
::DEFAULT_HOST
;
41 * The port on which to connect on
45 protected $_port = self
::DEFAULT_PORT
;
48 * The default timeout to use
52 protected $_timeout = self
::DEFAULT_TIMEOUT
;
55 * The prefix prepended to cache keys.
57 * If we are using the same memcache instance for multiple CiviCRM
58 * installs, we must have a unique prefix for each install to prevent
59 * the keys from clobbering each other.
63 protected $_prefix = self
::DEFAULT_PREFIX
;
66 * The actual memcache object.
75 * This is the effective prefix. It may be bumped up whenever the dataset is flushed.
77 * @see https://github.com/memcached/memcached/wiki/ProgrammingTricks#deleting-by-namespace
79 protected $_truePrefix = NULL;
84 * @param array $config
85 * An array of configuration params.
87 * @return \CRM_Utils_Cache_Memcached
89 public function __construct($config) {
90 if (isset($config['host'])) {
91 $this->_host
= $config['host'];
93 if (isset($config['port'])) {
94 $this->_port
= $config['port'];
96 if (isset($config['timeout'])) {
97 $this->_timeout
= $config['timeout'];
99 if (isset($config['prefix'])) {
100 $this->_prefix
= $config['prefix'];
103 $this->_cache
= new Memcached();
105 if (!$this->_cache
->addServer($this->_host
, $this->_port
)) {
106 // dont use fatal here since we can go in an infinite loop
107 echo 'Could not connect to Memcached server';
108 CRM_Utils_System
::civiExit();
115 * @param null|int|\DateInterval $ttl
120 public function set($key, $value, $ttl = NULL) {
121 CRM_Utils_Cache
::assertValidKey($key);
122 if (is_int($ttl) && $ttl <= 0) {
123 return $this->delete($key);
125 $expires = CRM_Utils_Date
::convertCacheTtlToExpires($ttl, $this->_timeout
);
127 $key = $this->cleanKey($key);
128 if (!$this->_cache
->set($key, serialize($value), $expires)) {
129 if (PHP_SAPI
=== 'cli' ||
(Civi\Core\Container
::isContainerBooted() && CRM_Core_Permission
::check('view debug output'))) {
130 throw new CRM_Utils_Cache_CacheException("Memcached::set($key) failed: " . $this->_cache
->getResultMessage());
133 Civi
::log()->error("Memcached::set($key) failed: " . $this->_cache
->getResultMessage());
134 throw new CRM_Utils_Cache_CacheException("Memcached::set($key) failed");
144 * @param mixed $default
148 public function get($key, $default = NULL) {
149 CRM_Utils_Cache
::assertValidKey($key);
150 $key = $this->cleanKey($key);
151 $result = $this->_cache
->get($key);
152 switch ($this->_cache
->getResultCode()) {
153 case Memcached
::RES_SUCCESS
:
154 return unserialize($result);
156 case Memcached
::RES_NOTFOUND
:
160 Civi
::log()->error("Memcached::get($key) failed: " . $this->_cache
->getResultMessage());
161 throw new CRM_Utils_Cache_CacheException("Memcached set ($key) failed");
169 * @throws \Psr\SimpleCache\CacheException
171 public function has($key) {
172 CRM_Utils_Cache
::assertValidKey($key);
173 $key = $this->cleanKey($key);
174 if ($this->_cache
->get($key) !== FALSE) {
177 switch ($this->_cache
->getResultCode()) {
178 case Memcached
::RES_NOTFOUND
:
181 case Memcached
::RES_SUCCESS
:
185 Civi
::log()->error("Memcached::has($key) failed: " . $this->_cache
->getResultMessage());
186 throw new CRM_Utils_Cache_CacheException("Memcached set ($key) failed");
195 public function delete($key) {
196 CRM_Utils_Cache
::assertValidKey($key);
197 $key = $this->cleanKey($key);
198 if ($this->_cache
->delete($key)) {
201 $code = $this->_cache
->getResultCode();
202 return ($code == Memcached
::RES_DELETED ||
$code == Memcached
::RES_NOTFOUND
);
208 * @return mixed|string
210 public function cleanKey($key) {
211 $truePrefix = $this->getTruePrefix();
212 $maxLen = self
::MAX_KEY_LEN
- strlen($truePrefix);
213 $key = preg_replace('/\s+|\W+/', '_', $key);
214 if (strlen($key) > $maxLen) {
215 // this should be 32 characters in length
217 $subKeyLen = $maxLen - 1 - strlen($md5Key);
218 $key = substr($key, 0, $subKeyLen) . "_" . $md5Key;
220 return $truePrefix . $key;
226 public function flush() {
227 $this->_truePrefix
= NULL;
228 if ($this->_cache
->delete($this->_prefix
)) {
231 $code = $this->_cache
->getResultCode();
232 return ($code == Memcached
::RES_DELETED ||
$code == Memcached
::RES_NOTFOUND
);
235 public function clear() {
236 return $this->flush();
239 protected function getTruePrefix() {
240 if ($this->_truePrefix
=== NULL ||
$this->_truePrefix
['expires'] < time()) {
241 $key = $this->_prefix
;
242 $value = $this->_cache
->get($key);
243 if ($this->_cache
->getResultCode() === Memcached
::RES_NOTFOUND
) {
246 $this->_cache
->add($key, $value, 0);
248 $this->_truePrefix
= [
250 'expires' => time() + self
::NS_LOCAL_TTL
,
253 return $this->_prefix
. $this->_truePrefix
['value'] . '/';