Merge pull request #12337 from lcdservices/dev-core-190
[civicrm-core.git] / CRM / Utils / Cache / Memcached.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2019
32 */
33 class CRM_Utils_Cache_Memcached implements CRM_Utils_Cache_Interface {
34
35 use CRM_Utils_Cache_NaiveMultipleTrait; // TODO Consider native implementation.
36
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;
42
43 /**
44 * If another process clears namespace, we'll find out in ~5 sec.
45 */
46 const NS_LOCAL_TTL = 5;
47
48 /**
49 * The host name of the memcached server
50 *
51 * @var string
52 */
53 protected $_host = self::DEFAULT_HOST;
54
55 /**
56 * The port on which to connect on
57 *
58 * @var int
59 */
60 protected $_port = self::DEFAULT_PORT;
61
62 /**
63 * The default timeout to use
64 *
65 * @var int
66 */
67 protected $_timeout = self::DEFAULT_TIMEOUT;
68
69 /**
70 * The prefix prepended to cache keys.
71 *
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.
75 *
76 * @var string
77 */
78 protected $_prefix = self::DEFAULT_PREFIX;
79
80 /**
81 * The actual memcache object.
82 *
83 * @var Memcached
84 */
85 protected $_cache;
86
87 /**
88 * @var NULL|array
89 *
90 * This is the effective prefix. It may be bumped up whenever the dataset is flushed.
91 *
92 * @see https://github.com/memcached/memcached/wiki/ProgrammingTricks#deleting-by-namespace
93 */
94 protected $_truePrefix = NULL;
95
96 /**
97 * Constructor.
98 *
99 * @param array $config
100 * An array of configuration params.
101 *
102 * @return \CRM_Utils_Cache_Memcached
103 */
104 public function __construct($config) {
105 if (isset($config['host'])) {
106 $this->_host = $config['host'];
107 }
108 if (isset($config['port'])) {
109 $this->_port = $config['port'];
110 }
111 if (isset($config['timeout'])) {
112 $this->_timeout = $config['timeout'];
113 }
114 if (isset($config['prefix'])) {
115 $this->_prefix = $config['prefix'];
116 }
117
118 $this->_cache = new Memcached();
119
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();
124 }
125 }
126
127 /**
128 * @param $key
129 * @param $value
130 * @param null|int|\DateInterval $ttl
131 *
132 * @return bool
133 * @throws Exception
134 */
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);
139 }
140 $expires = CRM_Utils_Date::convertCacheTtlToExpires($ttl, $this->_timeout);
141
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());
146 }
147 else {
148 Civi::log()->error("Memcached::set($key) failed: " . $this->_cache->getResultMessage());
149 throw new CRM_Utils_Cache_CacheException("Memcached::set($key) failed");
150 }
151 return FALSE;
152
153 }
154 return TRUE;
155 }
156
157 /**
158 * @param $key
159 * @param mixed $default
160 *
161 * @return mixed
162 */
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);
170
171 case Memcached::RES_NOTFOUND:
172 return $default;
173
174 default:
175 Civi::log()->error("Memcached::get($key) failed: " . $this->_cache->getResultMessage());
176 throw new CRM_Utils_Cache_CacheException("Memcached set ($key) failed");
177 }
178 }
179
180 /**
181 * @param string $key
182 *
183 * @return bool
184 * @throws \Psr\SimpleCache\CacheException
185 */
186 public function has($key) {
187 CRM_Utils_Cache::assertValidKey($key);
188 $key = $this->cleanKey($key);
189 if ($this->_cache->get($key) !== FALSE) {
190 return TRUE;
191 }
192 switch ($this->_cache->getResultCode()) {
193 case Memcached::RES_NOTFOUND:
194 return FALSE;
195
196 case Memcached::RES_SUCCESS:
197 return TRUE;
198
199 default:
200 Civi::log()->error("Memcached::has($key) failed: " . $this->_cache->getResultMessage());
201 throw new CRM_Utils_Cache_CacheException("Memcached set ($key) failed");
202 }
203 }
204
205 /**
206 * @param $key
207 *
208 * @return mixed
209 */
210 public function delete($key) {
211 CRM_Utils_Cache::assertValidKey($key);
212 $key = $this->cleanKey($key);
213 if ($this->_cache->delete($key)) {
214 return TRUE;
215 }
216 $code = $this->_cache->getResultCode();
217 return ($code == Memcached::RES_DELETED || $code == Memcached::RES_NOTFOUND);
218 }
219
220 /**
221 * @param $key
222 *
223 * @return mixed|string
224 */
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;
233 }
234 return $truePrefix . $key;
235 }
236
237 /**
238 * @return bool
239 */
240 public function flush() {
241 $this->_truePrefix = NULL;
242 if ($this->_cache->delete($this->_prefix)) {
243 return TRUE;
244 }
245 $code = $this->_cache->getResultCode();
246 return ($code == Memcached::RES_DELETED || $code == Memcached::RES_NOTFOUND);
247 }
248
249 public function clear() {
250 return $this->flush();
251 }
252
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) {
258 $value = uniqid();
259 $this->_cache->add($key, $value, 0); // Indefinite.
260 }
261 $this->_truePrefix = [
262 'value' => $value,
263 'expires' => time() + self::NS_LOCAL_TTL,
264 ];
265 }
266 return $this->_prefix . $this->_truePrefix['value'] . '/';
267 }
268
269 }