Merge pull request #14067 from colemanw/menuZindex
[civicrm-core.git] / CRM / Utils / Cache.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
6b83d5bd 31 * @copyright CiviCRM LLC (c) 2004-2019
6a488035
TO
32 */
33
34/**
35 * Cache is an empty base object, we'll modify the scheme when we have different caching schemes
6a488035
TO
36 */
37class CRM_Utils_Cache {
118eb830
TO
38
39 const DELIMITER = '/';
40
6a488035 41 /**
64c2ecd4
TO
42 * (Quasi-Private) Treat this as private. It is marked public to facilitate testing.
43 *
6a488035
TO
44 * We only need one instance of this object. So we use the singleton
45 * pattern and cache the instance in this variable
46 *
47 * @var object
6a488035 48 */
64c2ecd4 49 public static $_singleton = NULL;
6a488035
TO
50
51 /**
fe482240 52 * Constructor.
6a488035 53 *
77855840
TO
54 * @param array $config
55 * An array of configuration params.
6a488035 56 *
f4aaa82a 57 * @return \CRM_Utils_Cache
6a488035 58 */
00be9182 59 public function __construct(&$config) {
6a488035
TO
60 CRM_Core_Error::fatal(ts('this is just an interface and should not be called directly'));
61 }
62
63 /**
fe482240 64 * Singleton function used to manage this object.
6a488035 65 *
c039f658 66 * @return CRM_Utils_Cache_Interface
6a488035 67 */
00be9182 68 public static function &singleton() {
6a488035 69 if (self::$_singleton === NULL) {
81487911 70 $className = self::getCacheDriver();
6a488035
TO
71 // a generic method for utilizing any of the available db caches.
72 $dbCacheClass = 'CRM_Utils_Cache_' . $className;
6a488035 73 $settings = self::getCacheSettings($className);
118eb830 74 $settings['prefix'] = CRM_Utils_Array::value('prefix', $settings, '') . self::DELIMITER . 'default' . self::DELIMITER;
6a488035 75 self::$_singleton = new $dbCacheClass($settings);
ee1d325f 76 }
6a488035
TO
77 return self::$_singleton;
78 }
79
80 /**
fe482240 81 * Get cache relevant settings.
6a488035 82 *
77b97be7
EM
83 * @param $cachePlugin
84 *
6a488035
TO
85 * @return array
86 * associative array of settings for the cache
6a488035 87 */
00be9182 88 public static function getCacheSettings($cachePlugin) {
6a488035
TO
89 switch ($cachePlugin) {
90 case 'ArrayCache':
91 case 'NoCache':
be2fb01f 92 $defaults = [];
6a488035 93 break;
838fc623 94
59e56021 95 case 'Redis':
6a488035
TO
96 case 'Memcache':
97 case 'Memcached':
be2fb01f 98 $defaults = [
6a488035
TO
99 'host' => 'localhost',
100 'port' => 11211,
101 'timeout' => 3600,
102 'prefix' => '',
be2fb01f 103 ];
6a488035 104
b44e3f84 105 // Use old constants if needed to ensure backward compatibility
6a488035
TO
106 if (defined('CIVICRM_MEMCACHE_HOST')) {
107 $defaults['host'] = CIVICRM_MEMCACHE_HOST;
108 }
109
110 if (defined('CIVICRM_MEMCACHE_PORT')) {
111 $defaults['port'] = CIVICRM_MEMCACHE_PORT;
112 }
113
114 if (defined('CIVICRM_MEMCACHE_TIMEOUT')) {
115 $defaults['timeout'] = CIVICRM_MEMCACHE_TIMEOUT;
116 }
117
118 if (defined('CIVICRM_MEMCACHE_PREFIX')) {
119 $defaults['prefix'] = CIVICRM_MEMCACHE_PREFIX;
120 }
121
122 // Use new constants if possible
123 if (defined('CIVICRM_DB_CACHE_HOST')) {
124 $defaults['host'] = CIVICRM_DB_CACHE_HOST;
125 }
126
127 if (defined('CIVICRM_DB_CACHE_PORT')) {
128 $defaults['port'] = CIVICRM_DB_CACHE_PORT;
129 }
130
131 if (defined('CIVICRM_DB_CACHE_TIMEOUT')) {
132 $defaults['timeout'] = CIVICRM_DB_CACHE_TIMEOUT;
133 }
134
135 if (defined('CIVICRM_DB_CACHE_PREFIX')) {
136 $defaults['prefix'] = CIVICRM_DB_CACHE_PREFIX;
137 }
138
139 break;
140
141 case 'APCcache':
be2fb01f 142 $defaults = [];
6a488035
TO
143 if (defined('CIVICRM_DB_CACHE_TIMEOUT')) {
144 $defaults['timeout'] = CIVICRM_DB_CACHE_TIMEOUT;
145 }
146 if (defined('CIVICRM_DB_CACHE_PREFIX')) {
147 $defaults['prefix'] = CIVICRM_DB_CACHE_PREFIX;
148 }
149 break;
150 }
151 return $defaults;
152 }
96025800 153
a4704404
TO
154 /**
155 * Create a new, named, limited-use cache.
156 *
157 * This is a factory function. Generally, you should use Civi::cache($name)
158 * to locate managed cached instance.
159 *
160 * @param array $params
161 * Array with keys:
162 * - name: string, unique symbolic name.
7c34772b
TO
163 * For a naming convention, use `snake_case` or `CamelCase` to maximize
164 * portability/cleanliness. Any other punctuation or whitespace
165 * should function correctly, but it can be harder to inspect/debug.
a4704404
TO
166 * - type: array|string, list of acceptable cache types, in order of preference.
167 * - prefetch: bool, whether to prefetch all data in cache (if possible).
84413eca
TO
168 * - withArray: bool|null|'fast', whether to setup a thread-local array-cache in front of the cache driver.
169 * Note that cache-values may be passed to the underlying driver with extra metadata,
170 * so this will slightly change/enlarge the on-disk format.
171 * Support varies by driver:
172 * - For most memory backed caches, this option is meaningful.
173 * - For SqlGroup, this option is ignored. SqlGroup has equivalent behavior built-in.
174 * - For Arraycache, this option is ignored. It's redundant.
175 * If this is a short-lived process in which TTL's don't matter, you might
176 * use 'fast' mode. It sacrifices some PSR-16 compliance and cache-coherency
177 * protections to improve performance.
a4704404
TO
178 * @return CRM_Utils_Cache_Interface
179 * @throws CRM_Core_Exception
180 * @see Civi::cache()
181 */
be2fb01f 182 public static function create($params = []) {
a4704404
TO
183 $types = (array) $params['type'];
184
76e697a9
CB
185 if (!empty($params['name'])) {
186 $params['name'] = CRM_Core_BAO_Cache::cleanKey($params['name']);
187 }
188
a4704404
TO
189 foreach ($types as $type) {
190 switch ($type) {
a944a143 191 case '*memory*':
be2fb01f 192 if (defined('CIVICRM_DB_CACHE_CLASS') && in_array(CIVICRM_DB_CACHE_CLASS, ['Memcache', 'Memcached', 'Redis'])) {
a944a143
TO
193 $dbCacheClass = 'CRM_Utils_Cache_' . CIVICRM_DB_CACHE_CLASS;
194 $settings = self::getCacheSettings(CIVICRM_DB_CACHE_CLASS);
118eb830 195 $settings['prefix'] = CRM_Utils_Array::value('prefix', $settings, '') . self::DELIMITER . $params['name'] . self::DELIMITER;
84413eca
TO
196 $cache = new $dbCacheClass($settings);
197 if (!empty($params['withArray'])) {
198 $cache = $params['withArray'] === 'fast' ? new CRM_Utils_Cache_FastArrayDecorator($cache) : new CRM_Utils_Cache_ArrayDecorator($cache);
199 }
200 return $cache;
a944a143
TO
201 }
202 break;
203
a4704404
TO
204 case 'SqlGroup':
205 if (defined('CIVICRM_DSN') && CIVICRM_DSN) {
be2fb01f 206 return new CRM_Utils_Cache_SqlGroup([
a4704404
TO
207 'group' => $params['name'],
208 'prefetch' => CRM_Utils_Array::value('prefetch', $params, FALSE),
be2fb01f 209 ]);
a4704404
TO
210 }
211 break;
212
213 case 'Arraycache':
214 case 'ArrayCache':
be2fb01f 215 return new CRM_Utils_Cache_ArrayCache([]);
a4704404
TO
216
217 }
218 }
219
220 throw new CRM_Core_Exception("Failed to instantiate cache. No supported cache type found. " . print_r($params, 1));
221 }
222
cdee59f7
TO
223 /**
224 * Assert that a key is well-formed.
225 *
226 * @param string $key
227 * @return string
228 * Same $key, if it's valid.
229 * @throws \CRM_Utils_Cache_InvalidArgumentException
230 */
231 public static function assertValidKey($key) {
232 $strict = CRM_Utils_Constant::value('CIVICRM_PSR16_STRICT', FALSE) || defined('CIVICRM_TEST');
233
234 if (!is_string($key)) {
235 throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache key: Not a string");
236 }
237
238 if ($strict && !preg_match(';^[A-Za-z0-9_\-\. ]+$;', $key)) {
239 throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache key: Illegal characters");
240 }
241
242 if ($strict && strlen($key) > 255) {
243 throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache key: Too long");
244 }
245
246 return $key;
247 }
248
81487911
TO
249 /**
250 * @return string
251 * Ex: 'ArrayCache', 'Memcache', 'Redis'.
252 */
253 public static function getCacheDriver() {
6714d8d2
SL
254 // default to ArrayCache for now
255 $className = 'ArrayCache';
81487911
TO
256
257 // Maintain backward compatibility for now.
258 // Setting CIVICRM_USE_MEMCACHE or CIVICRM_USE_ARRAYCACHE will
259 // override the CIVICRM_DB_CACHE_CLASS setting.
260 // Going forward, CIVICRM_USE_xxxCACHE should be deprecated.
261 if (defined('CIVICRM_USE_MEMCACHE') && CIVICRM_USE_MEMCACHE) {
262 $className = 'Memcache';
263 return $className;
264 }
265 elseif (defined('CIVICRM_USE_ARRAYCACHE') && CIVICRM_USE_ARRAYCACHE) {
266 $className = 'ArrayCache';
267 return $className;
268 }
269 elseif (defined('CIVICRM_DB_CACHE_CLASS') && CIVICRM_DB_CACHE_CLASS) {
270 $className = CIVICRM_DB_CACHE_CLASS;
271 return $className;
272 }
273 return $className;
274 }
275
e0ba77f3
TO
276 /**
277 * Generate a unique negative-acknowledgement token (NACK).
278 *
279 * When using PSR-16 to read a value, the `$cahce->get()` will a return a default
280 * value on cache-miss, so it's hard to know if you've gotten a geniune value
281 * from the cache or just a default. If you're in an edge-case where it matters
282 * (and you want to do has()+get() in a single roundtrip), use the nack() as
283 * the default:
284 *
285 * $nack = CRM_Utils_Cache::nack();
286 * $value = $cache->get('foo', $nack);
287 * echo ($value === $nack) ? "Cache has a value, and we got it" : "Cache has no value".
288 *
89861474 289 * The value should be unique to avoid accidental matches.
e0ba77f3
TO
290 *
291 * @return string
292 * Unique nonce value indicating a "negative acknowledgement" (failed read).
293 * If we need to accurately perform has($key)+get($key), we can
294 * use `get($key,$nack)`.
295 */
296 public static function nack() {
89861474
TO
297 $st =& Civi::$statics[__CLASS__];
298 if (!isset($st['nack-c'])) {
299 $st['nack-c'] = md5(CRM_Utils_Request::id() . CIVICRM_SITE_KEY . CIVICRM_DSN . mt_rand(0, 10000));
300 $st['nack-i'] = 0;
e0ba77f3 301 }
89861474 302 return 'NACK:' . $st['nack-c'] . $st['nack-i']++;
e0ba77f3
TO
303 }
304
6a488035 305}