Merge pull request #13967 from eileenmcnaughton/activity_token
[civicrm-core.git] / CRM / Utils / Cache.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
34 /**
35 * Cache is an empty base object, we'll modify the scheme when we have different caching schemes
36 */
37 class CRM_Utils_Cache {
38
39 const DELIMITER = '/';
40
41 /**
42 * (Quasi-Private) Treat this as private. It is marked public to facilitate testing.
43 *
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
48 */
49 public static $_singleton = NULL;
50
51 /**
52 * Constructor.
53 *
54 * @param array $config
55 * An array of configuration params.
56 *
57 * @return \CRM_Utils_Cache
58 */
59 public function __construct(&$config) {
60 CRM_Core_Error::fatal(ts('this is just an interface and should not be called directly'));
61 }
62
63 /**
64 * Singleton function used to manage this object.
65 *
66 * @return CRM_Utils_Cache_Interface
67 */
68 public static function &singleton() {
69 if (self::$_singleton === NULL) {
70 $className = self::getCacheDriver();
71 // a generic method for utilizing any of the available db caches.
72 $dbCacheClass = 'CRM_Utils_Cache_' . $className;
73 $settings = self::getCacheSettings($className);
74 $settings['prefix'] = CRM_Utils_Array::value('prefix', $settings, '') . self::DELIMITER . 'default' . self::DELIMITER;
75 self::$_singleton = new $dbCacheClass($settings);
76 }
77 return self::$_singleton;
78 }
79
80 /**
81 * Get cache relevant settings.
82 *
83 * @param $cachePlugin
84 *
85 * @return array
86 * associative array of settings for the cache
87 */
88 public static function getCacheSettings($cachePlugin) {
89 switch ($cachePlugin) {
90 case 'ArrayCache':
91 case 'NoCache':
92 $defaults = array();
93 break;
94
95 case 'Redis':
96 case 'Memcache':
97 case 'Memcached':
98 $defaults = array(
99 'host' => 'localhost',
100 'port' => 11211,
101 'timeout' => 3600,
102 'prefix' => '',
103 );
104
105 // Use old constants if needed to ensure backward compatibility
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':
142 $defaults = array();
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 }
153
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.
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.
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).
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.
178 * @return CRM_Utils_Cache_Interface
179 * @throws CRM_Core_Exception
180 * @see Civi::cache()
181 */
182 public static function create($params = array()) {
183 $types = (array) $params['type'];
184
185 if (!empty($params['name'])) {
186 $params['name'] = CRM_Core_BAO_Cache::cleanKey($params['name']);
187 }
188
189 foreach ($types as $type) {
190 switch ($type) {
191 case '*memory*':
192 if (defined('CIVICRM_DB_CACHE_CLASS') && in_array(CIVICRM_DB_CACHE_CLASS, array('Memcache', 'Memcached', 'Redis'))) {
193 $dbCacheClass = 'CRM_Utils_Cache_' . CIVICRM_DB_CACHE_CLASS;
194 $settings = self::getCacheSettings(CIVICRM_DB_CACHE_CLASS);
195 $settings['prefix'] = CRM_Utils_Array::value('prefix', $settings, '') . self::DELIMITER . $params['name'] . self::DELIMITER;
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;
201 }
202 break;
203
204 case 'SqlGroup':
205 if (defined('CIVICRM_DSN') && CIVICRM_DSN) {
206 return new CRM_Utils_Cache_SqlGroup(array(
207 'group' => $params['name'],
208 'prefetch' => CRM_Utils_Array::value('prefetch', $params, FALSE),
209 ));
210 }
211 break;
212
213 case 'Arraycache':
214 case 'ArrayCache':
215 return new CRM_Utils_Cache_ArrayCache(array());
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
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
249 /**
250 * @return string
251 * Ex: 'ArrayCache', 'Memcache', 'Redis'.
252 */
253 public static function getCacheDriver() {
254 $className = 'ArrayCache'; // default to ArrayCache for now
255
256 // Maintain backward compatibility for now.
257 // Setting CIVICRM_USE_MEMCACHE or CIVICRM_USE_ARRAYCACHE will
258 // override the CIVICRM_DB_CACHE_CLASS setting.
259 // Going forward, CIVICRM_USE_xxxCACHE should be deprecated.
260 if (defined('CIVICRM_USE_MEMCACHE') && CIVICRM_USE_MEMCACHE) {
261 $className = 'Memcache';
262 return $className;
263 }
264 elseif (defined('CIVICRM_USE_ARRAYCACHE') && CIVICRM_USE_ARRAYCACHE) {
265 $className = 'ArrayCache';
266 return $className;
267 }
268 elseif (defined('CIVICRM_DB_CACHE_CLASS') && CIVICRM_DB_CACHE_CLASS) {
269 $className = CIVICRM_DB_CACHE_CLASS;
270 return $className;
271 }
272 return $className;
273 }
274
275 /**
276 * Generate a unique negative-acknowledgement token (NACK).
277 *
278 * When using PSR-16 to read a value, the `$cahce->get()` will a return a default
279 * value on cache-miss, so it's hard to know if you've gotten a geniune value
280 * from the cache or just a default. If you're in an edge-case where it matters
281 * (and you want to do has()+get() in a single roundtrip), use the nack() as
282 * the default:
283 *
284 * $nack = CRM_Utils_Cache::nack();
285 * $value = $cache->get('foo', $nack);
286 * echo ($value === $nack) ? "Cache has a value, and we got it" : "Cache has no value".
287 *
288 * The value should be unique to avoid accidental matches.
289 *
290 * @return string
291 * Unique nonce value indicating a "negative acknowledgement" (failed read).
292 * If we need to accurately perform has($key)+get($key), we can
293 * use `get($key,$nack)`.
294 */
295 public static function nack() {
296 $st =& Civi::$statics[__CLASS__];
297 if (!isset($st['nack-c'])) {
298 $st['nack-c'] = md5(CRM_Utils_Request::id() . CIVICRM_SITE_KEY . CIVICRM_DSN . mt_rand(0, 10000));
299 $st['nack-i'] = 0;
300 }
301 return 'NACK:' . $st['nack-c'] . $st['nack-i']++;
302 }
303
304 }