3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
33 class CRM_Utils_Cache_Memcached
implements CRM_Utils_Cache_Interface
{
35 use CRM_Utils_Cache_NaiveMultipleTrait
; // TODO Consider native implementation.
37 const DEFAULT_HOST
= 'localhost';
38 const DEFAULT_PORT
= 11211;
39 const DEFAULT_TIMEOUT
= 3600;
40 const DEFAULT_PREFIX
= '';
41 const MAX_KEY_LEN
= 200;
44 * If another process clears namespace, we'll find out in ~5 sec.
46 const NS_LOCAL_TTL
= 5;
49 * The host name of the memcached server
53 protected $_host = self
::DEFAULT_HOST
;
56 * The port on which to connect on
60 protected $_port = self
::DEFAULT_PORT
;
63 * The default timeout to use
67 protected $_timeout = self
::DEFAULT_TIMEOUT
;
70 * The prefix prepended to cache keys.
72 * If we are using the same memcache instance for multiple CiviCRM
73 * installs, we must have a unique prefix for each install to prevent
74 * the keys from clobbering each other.
78 protected $_prefix = self
::DEFAULT_PREFIX
;
81 * The actual memcache object.
90 * This is the effective prefix. It may be bumped up whenever the dataset is flushed.
92 * @see https://github.com/memcached/memcached/wiki/ProgrammingTricks#deleting-by-namespace
94 protected $_truePrefix = NULL;
99 * @param array $config
100 * An array of configuration params.
102 * @return \CRM_Utils_Cache_Memcached
104 public function __construct($config) {
105 if (isset($config['host'])) {
106 $this->_host
= $config['host'];
108 if (isset($config['port'])) {
109 $this->_port
= $config['port'];
111 if (isset($config['timeout'])) {
112 $this->_timeout
= $config['timeout'];
114 if (isset($config['prefix'])) {
115 $this->_prefix
= $config['prefix'];
118 $this->_cache
= new Memcached();
120 if (!$this->_cache
->addServer($this->_host
, $this->_port
)) {
121 // dont use fatal here since we can go in an infinite loop
122 echo 'Could not connect to Memcached server';
123 CRM_Utils_System
::civiExit();
130 * @param null|int|\DateInterval $ttl
135 public function set($key, $value, $ttl = NULL) {
136 CRM_Utils_Cache
::assertValidKey($key);
137 if (is_int($ttl) && $ttl <= 0) {
138 return $this->delete($key);
140 $expires = CRM_Utils_Date
::convertCacheTtlToExpires($ttl, $this->_timeout
);
142 $key = $this->cleanKey($key);
143 if (!$this->_cache
->set($key, serialize($value), $expires)) {
144 if (PHP_SAPI
=== 'cli' ||
(Civi\Core\Container
::isContainerBooted() && CRM_Core_Permission
::check('view debug output'))) {
145 throw new CRM_Utils_Cache_CacheException("Memcached::set($key) failed: " . $this->_cache
->getResultMessage());
148 Civi
::log()->error("Memcached::set($key) failed: " . $this->_cache
->getResultMessage());
149 throw new CRM_Utils_Cache_CacheException("Memcached::set($key) failed");
159 * @param mixed $default
163 public function get($key, $default = NULL) {
164 CRM_Utils_Cache
::assertValidKey($key);
165 $key = $this->cleanKey($key);
166 $result = $this->_cache
->get($key);
167 switch ($this->_cache
->getResultCode()) {
168 case Memcached
::RES_SUCCESS
:
169 return unserialize($result);
171 case Memcached
::RES_NOTFOUND
:
175 Civi
::log()->error("Memcached::get($key) failed: " . $this->_cache
->getResultMessage());
176 throw new CRM_Utils_Cache_CacheException("Memcached set ($key) failed");
184 * @throws \Psr\SimpleCache\CacheException
186 public function has($key) {
187 CRM_Utils_Cache
::assertValidKey($key);
188 $key = $this->cleanKey($key);
189 if ($this->_cache
->get($key) !== FALSE) {
192 switch ($this->_cache
->getResultCode()) {
193 case Memcached
::RES_NOTFOUND
:
196 case Memcached
::RES_SUCCESS
:
200 Civi
::log()->error("Memcached::has($key) failed: " . $this->_cache
->getResultMessage());
201 throw new CRM_Utils_Cache_CacheException("Memcached set ($key) failed");
210 public function delete($key) {
211 CRM_Utils_Cache
::assertValidKey($key);
212 $key = $this->cleanKey($key);
213 if ($this->_cache
->delete($key)) {
216 $code = $this->_cache
->getResultCode();
217 return ($code == Memcached
::RES_DELETED ||
$code == Memcached
::RES_NOTFOUND
);
223 * @return mixed|string
225 public function cleanKey($key) {
226 $truePrefix = $this->getTruePrefix();
227 $maxLen = self
::MAX_KEY_LEN
- strlen($truePrefix);
228 $key = preg_replace('/\s+|\W+/', '_', $key);
229 if (strlen($key) > $maxLen) {
230 $md5Key = md5($key); // this should be 32 characters in length
231 $subKeyLen = $maxLen - 1 - strlen($md5Key);
232 $key = substr($key, 0, $subKeyLen) . "_" . $md5Key;
234 return $truePrefix . $key;
240 public function flush() {
241 $this->_truePrefix
= NULL;
242 if ($this->_cache
->delete($this->_prefix
)) {
245 $code = $this->_cache
->getResultCode();
246 return ($code == Memcached
::RES_DELETED ||
$code == Memcached
::RES_NOTFOUND
);
249 public function clear() {
250 return $this->flush();
253 protected function getTruePrefix() {
254 if ($this->_truePrefix
=== NULL ||
$this->_truePrefix
['expires'] < time()) {
255 $key = $this->_prefix
;
256 $value = $this->_cache
->get($key);
257 if ($this->_cache
->getResultCode() === Memcached
::RES_NOTFOUND
) {
259 $this->_cache
->add($key, $value, 0); // Indefinite.
261 $this->_truePrefix
= [
263 'expires' => time() + self
::NS_LOCAL_TTL
,
266 return $this->_prefix
. $this->_truePrefix
['value'] . '/';