Merge pull request #13390 from MegaphoneJon/core-609
[civicrm-core.git] / CRM / Core / BAO / 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 27
6a488035 28/**
192d36c5 29 * BAO object for civicrm_cache table.
30 *
31 * This is a database cache and is persisted across sessions. Typically we use
6a488035
TO
32 * this to store meta data (like profile fields, custom fields etc).
33 *
34 * The group_name column is used for grouping together all cache elements that logically belong to the same set.
35 * Thus all session cache entries are grouped under 'CiviCRM Session'. This allows us to delete all entries of
36 * a specific group if needed.
37 *
38 * The path column allows us to differentiate between items in that group. Thus for the session cache, the path is
39 * the unique form name for each form (per user)
40 */
41class CRM_Core_BAO_Cache extends CRM_Core_DAO_Cache {
42
19707a63
TO
43 /**
44 * When store session/form state, how long should the data be retained?
45 *
46 * @var int, number of second
47 */
48 const DEFAULT_SESSION_TTL = 172800; // Two days: 2*24*60*60
49
e79e9c87
TO
50 /**
51 * @var array ($cacheKey => $cacheValue)
52 */
53 static $_cache = NULL;
54
6a488035 55 /**
fe482240 56 * Retrieve an item from the DB cache.
6a488035 57 *
6a0b768e
TO
58 * @param string $group
59 * (required) The group name of the item.
60 * @param string $path
61 * (required) The path under which this item is stored.
62 * @param int $componentID
63 * The optional component ID (so componenets can share the same name space).
6a488035 64 *
a6c01b45
CW
65 * @return object
66 * The data if present in cache, else null
920fa38f 67 * @deprecated
6a488035 68 */
00be9182 69 public static function &getItem($group, $path, $componentID = NULL) {
88dfeb5c 70 if (($adapter = CRM_Utils_Constant::value('CIVICRM_BAO_CACHE_ADAPTER')) !== NULL) {
b5e7d576
TO
71 $value = $adapter::getItem($group, $path, $componentID);
72 return $value;
5a302bbc
TO
73 }
74
e79e9c87
TO
75 if (self::$_cache === NULL) {
76 self::$_cache = array();
def0681b 77 }
6a488035 78
def0681b 79 $argString = "CRM_CT_{$group}_{$path}_{$componentID}";
e79e9c87 80 if (!array_key_exists($argString, self::$_cache)) {
def0681b 81 $cache = CRM_Utils_Cache::singleton();
972b0e25
CB
82 $cleanKey = self::cleanKey($argString);
83 self::$_cache[$argString] = $cache->get($cleanKey);
22263d41 84 if (self::$_cache[$argString] === NULL) {
61d29839
TO
85 $table = self::getTableName();
86 $where = self::whereCache($group, $path, $componentID);
5d1e8768 87 $rawData = CRM_Core_DAO::singleValueQuery("SELECT data FROM $table WHERE $where");
3c643fe7 88 $data = $rawData ? self::decode($rawData) : NULL;
61d29839 89
e79e9c87 90 self::$_cache[$argString] = $data;
ce18ad0f 91 if ($data !== NULL) {
92 // Do not cache 'null' as that is most likely a cache miss & we shouldn't then cache it.
93 $cache->set($cleanKey, self::$_cache[$argString]);
94 }
def0681b 95 }
6a488035 96 }
e79e9c87 97 return self::$_cache[$argString];
6a488035
TO
98 }
99
100 /**
fe482240 101 * Retrieve all items in a group.
6a488035 102 *
6a0b768e
TO
103 * @param string $group
104 * (required) The group name of the item.
105 * @param int $componentID
106 * The optional component ID (so componenets can share the same name space).
6a488035 107 *
a6c01b45
CW
108 * @return object
109 * The data if present in cache, else null
920fa38f 110 * @deprecated
6a488035 111 */
00be9182 112 public static function &getItems($group, $componentID = NULL) {
88dfeb5c 113 if (($adapter = CRM_Utils_Constant::value('CIVICRM_BAO_CACHE_ADAPTER')) !== NULL) {
5a302bbc
TO
114 return $adapter::getItems($group, $componentID);
115 }
116
e79e9c87
TO
117 if (self::$_cache === NULL) {
118 self::$_cache = array();
def0681b 119 }
6a488035 120
def0681b 121 $argString = "CRM_CT_CI_{$group}_{$componentID}";
e79e9c87 122 if (!array_key_exists($argString, self::$_cache)) {
def0681b 123 $cache = CRM_Utils_Cache::singleton();
972b0e25
CB
124 $cleanKey = self::cleanKey($argString);
125 self::$_cache[$argString] = $cache->get($cleanKey);
e79e9c87 126 if (!self::$_cache[$argString]) {
61d29839
TO
127 $table = self::getTableName();
128 $where = self::whereCache($group, NULL, $componentID);
129 $dao = CRM_Core_DAO::executeQuery("SELECT path, data FROM $table WHERE $where");
6a488035 130
1a4e6781 131 $result = array();
def0681b 132 while ($dao->fetch()) {
3c643fe7 133 $result[$dao->path] = self::decode($dao->data);
def0681b
KJ
134 }
135 $dao->free();
136
e79e9c87 137 self::$_cache[$argString] = $result;
972b0e25 138 $cache->set($cleanKey, self::$_cache[$argString]);
def0681b 139 }
6a488035 140 }
def0681b 141
e79e9c87 142 return self::$_cache[$argString];
6a488035
TO
143 }
144
145 /**
fe482240 146 * Store an item in the DB cache.
6a488035 147 *
6a0b768e
TO
148 * @param object $data
149 * (required) A reference to the data that will be serialized and stored.
150 * @param string $group
151 * (required) The group name of the item.
152 * @param string $path
153 * (required) The path under which this item is stored.
154 * @param int $componentID
155 * The optional component ID (so componenets can share the same name space).
920fa38f 156 * @deprecated
6a488035 157 */
00be9182 158 public static function setItem(&$data, $group, $path, $componentID = NULL) {
88dfeb5c 159 if (($adapter = CRM_Utils_Constant::value('CIVICRM_BAO_CACHE_ADAPTER')) !== NULL) {
5a302bbc
TO
160 return $adapter::setItem($data, $group, $path, $componentID);
161 }
162
e79e9c87
TO
163 if (self::$_cache === NULL) {
164 self::$_cache = array();
def0681b
KJ
165 }
166
6a488035
TO
167 // get a lock so that multiple ajax requests on the same page
168 // dont trample on each other
169 // CRM-11234
83617886 170 $lock = Civi::lockManager()->acquire("cache.{$group}_{$path}._{$componentID}");
6a488035
TO
171 if (!$lock->isAcquired()) {
172 CRM_Core_Error::fatal();
173 }
174
61d29839
TO
175 $table = self::getTableName();
176 $where = self::whereCache($group, $path, $componentID);
21ca2cb6 177 $dataExists = CRM_Core_DAO::singleValueQuery("SELECT COUNT(*) FROM $table WHERE {$where}");
61d29839 178 $now = date('Y-m-d H:i:s'); // FIXME - Use SQL NOW() or CRM_Utils_Time?
3c643fe7 179 $dataSerialized = self::encode($data);
61d29839
TO
180
181 // This table has a wonky index, so we cannot use REPLACE or
182 // "INSERT ... ON DUPE". Instead, use SELECT+(INSERT|UPDATE).
21ca2cb6 183 if ($dataExists) {
184 $sql = "UPDATE $table SET data = %1, created_date = %2 WHERE {$where}";
3d6878c6 185 $args = array(
61d29839
TO
186 1 => array($dataSerialized, 'String'),
187 2 => array($now, 'String'),
3d6878c6 188 );
189 $dao = CRM_Core_DAO::executeQuery($sql, $args, TRUE, NULL, FALSE, FALSE);
61d29839
TO
190 }
191 else {
192 $insert = CRM_Utils_SQL_Insert::into($table)
193 ->row(array(
194 'group_name' => $group,
195 'path' => $path,
196 'component_id' => $componentID,
197 'data' => $dataSerialized,
198 'created_date' => $now,
199 ));
3d6878c6 200 $dao = CRM_Core_DAO::executeQuery($insert->toSQL(), array(), TRUE, NULL, FALSE, FALSE);
61d29839 201 }
6a488035
TO
202
203 $lock->release();
204
205 $dao->free();
def0681b 206
80259ba2
TO
207 // cache coherency - refresh or remove dependent caches
208
def0681b
KJ
209 $argString = "CRM_CT_{$group}_{$path}_{$componentID}";
210 $cache = CRM_Utils_Cache::singleton();
3c643fe7 211 $data = self::decode($dataSerialized);
e79e9c87 212 self::$_cache[$argString] = $data;
bd76ee83 213 $cache->set(self::cleanKey($argString), $data);
80259ba2
TO
214
215 $argString = "CRM_CT_CI_{$group}_{$componentID}";
e79e9c87 216 unset(self::$_cache[$argString]);
bd76ee83 217 $cache->delete(self::cleanKey($argString));
6a488035
TO
218 }
219
220 /**
1a4e6781 221 * Delete all the cache elements that belong to a group OR delete the entire cache if group is not specified.
6a488035 222 *
6a0b768e
TO
223 * @param string $group
224 * The group name of the entries to be deleted.
225 * @param string $path
226 * Path of the item that needs to be deleted.
1a4e6781 227 * @param bool $clearAll clear all caches
920fa38f 228 * @deprecated
6a488035 229 */
00be9182 230 public static function deleteGroup($group = NULL, $path = NULL, $clearAll = TRUE) {
88dfeb5c 231 if (($adapter = CRM_Utils_Constant::value('CIVICRM_BAO_CACHE_ADAPTER')) !== NULL) {
5a302bbc
TO
232 return $adapter::deleteGroup($group, $path);
233 }
234 else {
235 $table = self::getTableName();
236 $where = self::whereCache($group, $path, NULL);
237 CRM_Core_DAO::executeQuery("DELETE FROM $table WHERE $where");
238 }
6a488035
TO
239
240 if ($clearAll) {
241 // also reset ACL Cache
242 CRM_ACL_BAO_Cache::resetCache();
243
244 // also reset memory cache if any
245 CRM_Utils_System::flushCache();
246 }
247 }
248
249 /**
250 * The next two functions are internal functions used to store and retrieve session from
251 * the database cache. This keeps the session to a limited size and allows us to
252 * create separate session scopes for each form in a tab
6a488035
TO
253 */
254
255 /**
256 * This function takes entries from the session array and stores it in the cache.
1a4e6781 257 *
6a488035
TO
258 * It also deletes the entries from the $_SESSION object (for a smaller session size)
259 *
6a0b768e
TO
260 * @param array $names
261 * Array of session values that should be persisted.
6a488035
TO
262 * This is either a form name + qfKey or just a form name
263 * (in the case of profile)
6a0b768e
TO
264 * @param bool $resetSession
265 * Should session state be reset on completion of DB store?.
6a488035 266 */
00be9182 267 public static function storeSessionToCache($names, $resetSession = TRUE) {
6a488035
TO
268 foreach ($names as $key => $sessionName) {
269 if (is_array($sessionName)) {
2aa397bc 270 $value = NULL;
6a488035
TO
271 if (!empty($_SESSION[$sessionName[0]][$sessionName[1]])) {
272 $value = $_SESSION[$sessionName[0]][$sessionName[1]];
273 }
19707a63
TO
274 $key = "{$sessionName[0]}_{$sessionName[1]}";
275 Civi::cache('session')->set($key, $value, self::pickSessionTtl($key));
2aa397bc
TO
276 if ($resetSession) {
277 $_SESSION[$sessionName[0]][$sessionName[1]] = NULL;
278 unset($_SESSION[$sessionName[0]][$sessionName[1]]);
6a488035 279 }
2aa397bc 280 }
6a488035 281 else {
2aa397bc 282 $value = NULL;
6a488035
TO
283 if (!empty($_SESSION[$sessionName])) {
284 $value = $_SESSION[$sessionName];
285 }
19707a63 286 Civi::cache('session')->set($sessionName, $value, self::pickSessionTtl($sessionName));
2aa397bc
TO
287 if ($resetSession) {
288 $_SESSION[$sessionName] = NULL;
289 unset($_SESSION[$sessionName]);
6a488035
TO
290 }
291 }
2aa397bc 292 }
6a488035
TO
293
294 self::cleanup();
295 }
296
297 /* Retrieve the session values from the cache and populate the $_SESSION array
006389de
TO
298 *
299 * @param array $names
300 * Array of session values that should be persisted.
301 * This is either a form name + qfKey or just a form name
302 * (in the case of profile)
006389de 303 */
6a488035 304
b5c2afd0 305 /**
1a4e6781
EM
306 * Restore session from cache.
307 *
100fef9d 308 * @param string $names
b5c2afd0 309 */
00be9182 310 public static function restoreSessionFromCache($names) {
6a488035
TO
311 foreach ($names as $key => $sessionName) {
312 if (is_array($sessionName)) {
19707a63 313 $value = Civi::cache('session')->get("{$sessionName[0]}_{$sessionName[1]}");
6a488035
TO
314 if ($value) {
315 $_SESSION[$sessionName[0]][$sessionName[1]] = $value;
316 }
317 }
318 else {
19707a63 319 $value = Civi::cache('session')->get($sessionName);
6a488035
TO
320 if ($value) {
321 $_SESSION[$sessionName] = $value;
322 }
323 }
324 }
325 }
326
19707a63
TO
327 /**
328 * Determine how long session-state should be retained.
329 *
330 * @param string $sessionKey
331 * Ex: '_CRM_Admin_Form_Preferences_Display_f1a5f232e3d850a29a7a4d4079d7c37b_4654_container'
332 * Ex: 'CiviCRM_CRM_Admin_Form_Preferences_Display_f1a5f232e3d850a29a7a4d4079d7c37b_4654'
333 * @return int
334 * Number of seconds.
335 */
336 protected static function pickSessionTtl($sessionKey) {
337 $secureSessionTimeoutMinutes = (int) Civi::settings()->get('secure_cache_timeout_minutes');
338 if ($secureSessionTimeoutMinutes) {
339 $transactionPages = array(
340 'CRM_Contribute_Controller_Contribution',
341 'CRM_Event_Controller_Registration',
342 );
343 foreach ($transactionPages as $transactionPage) {
344 if (strpos($sessionKey, $transactionPage) !== FALSE) {
345 return $secureSessionTimeoutMinutes * 60;
346 }
347 }
348 }
349
350 return self::DEFAULT_SESSION_TTL;
351 }
352
6a488035 353 /**
1a4e6781
EM
354 * Do periodic cleanup of the CiviCRM session table.
355 *
356 * Also delete all session cache entries which are a couple of days old.
357 * This keeps the session cache to a manageable size
f26d31eb 358 * Delete Contribution page session caches more energetically.
6a488035 359 *
554259a7
EM
360 * @param bool $session
361 * @param bool $table
362 * @param bool $prevNext
6a488035 363 */
fd33fead 364 public static function cleanup($session = FALSE, $table = FALSE, $prevNext = FALSE, $expired = FALSE) {
6a488035
TO
365 // clean up the session cache every $cacheCleanUpNumber probabilistically
366 $cleanUpNumber = 757;
367
368 // clean up all sessions older than $cacheTimeIntervalDays days
369 $timeIntervalDays = 2;
6a488035
TO
370
371 if (mt_rand(1, 100000) % $cleanUpNumber == 0) {
fd33fead 372 $expired = $session = $table = $prevNext = TRUE;
6a488035
TO
373 }
374
fd33fead 375 if (!$session && !$table && !$prevNext && !$expired) {
6a488035
TO
376 return;
377 }
378
f9f40af3 379 if ($prevNext) {
6a488035
TO
380 // delete all PrevNext caches
381 CRM_Core_BAO_PrevNextCache::cleanupCache();
382 }
383
f9f40af3 384 if ($table) {
40c712ed 385 CRM_Core_Config::clearTempTables($timeIntervalDays . ' day');
6a488035
TO
386 }
387
f9f40af3 388 if ($session) {
19707a63
TO
389 // Session caches are just regular caches, so they expire naturally per TTL.
390 $expired = TRUE;
8c52547a 391 }
fd33fead
TO
392
393 if ($expired) {
394 $sql = "DELETE FROM civicrm_cache WHERE expired_date < %1";
395 $params = [
396 1 => [date(CRM_Utils_Cache_SqlGroup::TS_FMT, CRM_Utils_Time::getTimeRaw()), 'String'],
397 ];
398 CRM_Core_DAO::executeQuery($sql, $params);
399 }
6a488035 400 }
96025800 401
3c643fe7
TO
402 /**
403 * (Quasi-private) Encode an object/array/string/int as a string.
404 *
405 * @param $mixed
406 * @return string
407 */
408 public static function encode($mixed) {
409 return base64_encode(serialize($mixed));
410 }
411
412 /**
413 * (Quasi-private) Decode an object/array/string/int from a string.
414 *
415 * @param $string
416 * @return mixed
417 */
418 public static function decode($string) {
419 // Upgrade support -- old records (serialize) always have this punctuation,
420 // and new records (base64) never do.
421 if (strpos($string, ':') !== FALSE || strpos($string, ';') !== FALSE) {
422 return unserialize($string);
423 }
424 else {
425 return unserialize(base64_decode($string));
426 }
427 }
428
61d29839
TO
429 /**
430 * Compose a SQL WHERE clause for the cache.
431 *
432 * Note: We need to use the cache during bootstrap, so we don't have
433 * full access to DAO services.
434 *
435 * @param string $group
436 * @param string|NULL $path
437 * Filter by path. If NULL, then return any paths.
438 * @param int|NULL $componentID
439 * Filter by component. If NULL, then look for explicitly NULL records.
440 * @return string
441 */
442 protected static function whereCache($group, $path, $componentID) {
443 $clauses = array();
444 $clauses[] = ('group_name = "' . CRM_Core_DAO::escapeString($group) . '"');
445 if ($path) {
446 $clauses[] = ('path = "' . CRM_Core_DAO::escapeString($path) . '"');
447 }
448 if ($componentID && is_numeric($componentID)) {
449 $clauses[] = ('component_id = ' . (int) $componentID);
450 }
451 return $clauses ? implode(' AND ', $clauses) : '(1)';
452 }
453
bd76ee83
TO
454 /**
455 * Normalize a cache key.
456 *
457 * This bridges an impedance mismatch between our traditional caching
458 * and PSR-16 -- PSR-16 accepts a narrower range of cache keys.
459 *
460 * @param string $key
461 * Ex: 'ab/cd:ef'
462 * @return string
463 * Ex: '_abcd1234abcd1234' or 'ab_xx/cd_xxef'.
464 * A similar key, but suitable for use with PSR-16-compliant cache providers.
465 */
466 public static function cleanKey($key) {
467 if (!is_string($key) && !is_int($key)) {
468 throw new \RuntimeException("Malformed cache key");
469 }
470
471 $maxLen = 64;
472 $escape = '-';
473
474 if (strlen($key) >= $maxLen) {
475 return $escape . md5($key);
476 }
477
816e59c4 478 $r = preg_replace_callback(';[^A-Za-z0-9_\.];', function($m) use ($escape) {
bd76ee83
TO
479 return $escape . dechex(ord($m[0]));
480 }, $key);
481
482 return strlen($r) >= $maxLen ? $escape . md5($key) : $r;
483 }
484
6a488035 485}