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 +--------------------------------------------------------------------+
29 * BAO object for civicrm_cache table.
31 * This is a database cache and is persisted across sessions. Typically we use
32 * this to store meta data (like profile fields, custom fields etc).
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.
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)
41 class CRM_Core_BAO_Cache
extends CRM_Core_DAO_Cache
{
44 * When store session/form state, how long should the data be retained?
46 * Default is Two days: 2*24*60*60
48 * @var int, number of second
50 const DEFAULT_SESSION_TTL
= 172800;
55 * Format is ($cacheKey => $cacheValue)
59 public static $_cache = NULL;
62 * Retrieve an item from the DB cache.
64 * @param string $group
65 * (required) The group name of the item.
67 * (required) The path under which this item is stored.
68 * @param int $componentID
69 * The optional component ID (so componenets can share the same name space).
72 * The data if present in cache, else null
75 public static function &getItem($group, $path, $componentID = NULL) {
76 if (($adapter = CRM_Utils_Constant
::value('CIVICRM_BAO_CACHE_ADAPTER')) !== NULL) {
77 $value = $adapter::getItem($group, $path, $componentID);
81 if (self
::$_cache === NULL) {
85 $argString = "CRM_CT_{$group}_{$path}_{$componentID}";
86 if (!array_key_exists($argString, self
::$_cache)) {
87 $cache = CRM_Utils_Cache
::singleton();
88 $cleanKey = self
::cleanKey($argString);
89 self
::$_cache[$argString] = $cache->get($cleanKey);
90 if (self
::$_cache[$argString] === NULL) {
91 $table = self
::getTableName();
92 $where = self
::whereCache($group, $path, $componentID);
93 $rawData = CRM_Core_DAO
::singleValueQuery("SELECT data FROM $table WHERE $where");
94 $data = $rawData ? self
::decode($rawData) : NULL;
96 self
::$_cache[$argString] = $data;
98 // Do not cache 'null' as that is most likely a cache miss & we shouldn't then cache it.
99 $cache->set($cleanKey, self
::$_cache[$argString]);
103 return self
::$_cache[$argString];
107 * Retrieve all items in a group.
109 * @param string $group
110 * (required) The group name of the item.
111 * @param int $componentID
112 * The optional component ID (so componenets can share the same name space).
115 * The data if present in cache, else null
118 public static function &getItems($group, $componentID = NULL) {
119 if (($adapter = CRM_Utils_Constant
::value('CIVICRM_BAO_CACHE_ADAPTER')) !== NULL) {
120 return $adapter::getItems($group, $componentID);
123 if (self
::$_cache === NULL) {
127 $argString = "CRM_CT_CI_{$group}_{$componentID}";
128 if (!array_key_exists($argString, self
::$_cache)) {
129 $cache = CRM_Utils_Cache
::singleton();
130 $cleanKey = self
::cleanKey($argString);
131 self
::$_cache[$argString] = $cache->get($cleanKey);
132 if (!self
::$_cache[$argString]) {
133 $table = self
::getTableName();
134 $where = self
::whereCache($group, NULL, $componentID);
135 $dao = CRM_Core_DAO
::executeQuery("SELECT path, data FROM $table WHERE $where");
138 while ($dao->fetch()) {
139 $result[$dao->path
] = self
::decode($dao->data
);
142 self
::$_cache[$argString] = $result;
143 $cache->set($cleanKey, self
::$_cache[$argString]);
147 return self
::$_cache[$argString];
151 * Store an item in the DB cache.
153 * @param object $data
154 * (required) A reference to the data that will be serialized and stored.
155 * @param string $group
156 * (required) The group name of the item.
157 * @param string $path
158 * (required) The path under which this item is stored.
159 * @param int $componentID
160 * The optional component ID (so componenets can share the same name space).
163 public static function setItem(&$data, $group, $path, $componentID = NULL) {
164 if (($adapter = CRM_Utils_Constant
::value('CIVICRM_BAO_CACHE_ADAPTER')) !== NULL) {
165 return $adapter::setItem($data, $group, $path, $componentID);
168 if (self
::$_cache === NULL) {
172 // get a lock so that multiple ajax requests on the same page
173 // dont trample on each other
175 $lock = Civi
::lockManager()->acquire("cache.{$group}_{$path}._{$componentID}");
176 if (!$lock->isAcquired()) {
177 CRM_Core_Error
::fatal();
180 $table = self
::getTableName();
181 $where = self
::whereCache($group, $path, $componentID);
182 $dataExists = CRM_Core_DAO
::singleValueQuery("SELECT COUNT(*) FROM $table WHERE {$where}");
183 // FIXME - Use SQL NOW() or CRM_Utils_Time?
184 $now = date('Y-m-d H:i:s');
185 $dataSerialized = self
::encode($data);
187 // This table has a wonky index, so we cannot use REPLACE or
188 // "INSERT ... ON DUPE". Instead, use SELECT+(INSERT|UPDATE).
190 $sql = "UPDATE $table SET data = %1, created_date = %2 WHERE {$where}";
192 1 => [$dataSerialized, 'String'],
193 2 => [$now, 'String'],
195 $dao = CRM_Core_DAO
::executeQuery($sql, $args, TRUE, NULL, FALSE, FALSE);
198 $insert = CRM_Utils_SQL_Insert
::into($table)
200 'group_name' => $group,
202 'component_id' => $componentID,
203 'data' => $dataSerialized,
204 'created_date' => $now,
206 $dao = CRM_Core_DAO
::executeQuery($insert->toSQL(), [], TRUE, NULL, FALSE, FALSE);
211 // cache coherency - refresh or remove dependent caches
213 $argString = "CRM_CT_{$group}_{$path}_{$componentID}";
214 $cache = CRM_Utils_Cache
::singleton();
215 $data = self
::decode($dataSerialized);
216 self
::$_cache[$argString] = $data;
217 $cache->set(self
::cleanKey($argString), $data);
219 $argString = "CRM_CT_CI_{$group}_{$componentID}";
220 unset(self
::$_cache[$argString]);
221 $cache->delete(self
::cleanKey($argString));
225 * Delete all the cache elements that belong to a group OR delete the entire cache if group is not specified.
227 * @param string $group
228 * The group name of the entries to be deleted.
229 * @param string $path
230 * Path of the item that needs to be deleted.
231 * @param bool $clearAll clear all caches
234 public static function deleteGroup($group = NULL, $path = NULL, $clearAll = TRUE) {
235 if (($adapter = CRM_Utils_Constant
::value('CIVICRM_BAO_CACHE_ADAPTER')) !== NULL) {
236 return $adapter::deleteGroup($group, $path);
239 $table = self
::getTableName();
240 $where = self
::whereCache($group, $path, NULL);
241 CRM_Core_DAO
::executeQuery("DELETE FROM $table WHERE $where");
250 * Cleanup ACL and System Level caches
252 public static function resetCaches() {
253 // also reset ACL Cache
254 // @todo why is this called when CRM_Utils_System::flushCache() does it as well.
255 CRM_ACL_BAO_Cache
::resetCache();
257 // also reset memory cache if any
258 CRM_Utils_System
::flushCache();
262 * The next two functions are internal functions used to store and retrieve session from
263 * the database cache. This keeps the session to a limited size and allows us to
264 * create separate session scopes for each form in a tab
268 * This function takes entries from the session array and stores it in the cache.
270 * It also deletes the entries from the $_SESSION object (for a smaller session size)
272 * @param array $names
273 * Array of session values that should be persisted.
274 * This is either a form name + qfKey or just a form name
275 * (in the case of profile)
276 * @param bool $resetSession
277 * Should session state be reset on completion of DB store?.
279 public static function storeSessionToCache($names, $resetSession = TRUE) {
280 foreach ($names as $key => $sessionName) {
281 if (is_array($sessionName)) {
283 if (!empty($_SESSION[$sessionName[0]][$sessionName[1]])) {
284 $value = $_SESSION[$sessionName[0]][$sessionName[1]];
286 $key = "{$sessionName[0]}_{$sessionName[1]}";
287 Civi
::cache('session')->set($key, $value, self
::pickSessionTtl($key));
289 $_SESSION[$sessionName[0]][$sessionName[1]] = NULL;
290 unset($_SESSION[$sessionName[0]][$sessionName[1]]);
295 if (!empty($_SESSION[$sessionName])) {
296 $value = $_SESSION[$sessionName];
298 Civi
::cache('session')->set($sessionName, $value, self
::pickSessionTtl($sessionName));
300 $_SESSION[$sessionName] = NULL;
301 unset($_SESSION[$sessionName]);
309 /* Retrieve the session values from the cache and populate the $_SESSION array
311 * @param array $names
312 * Array of session values that should be persisted.
313 * This is either a form name + qfKey or just a form name
314 * (in the case of profile)
318 * Restore session from cache.
320 * @param string $names
322 public static function restoreSessionFromCache($names) {
323 foreach ($names as $key => $sessionName) {
324 if (is_array($sessionName)) {
325 $value = Civi
::cache('session')->get("{$sessionName[0]}_{$sessionName[1]}");
327 $_SESSION[$sessionName[0]][$sessionName[1]] = $value;
331 $value = Civi
::cache('session')->get($sessionName);
333 $_SESSION[$sessionName] = $value;
340 * Determine how long session-state should be retained.
342 * @param string $sessionKey
343 * Ex: '_CRM_Admin_Form_Preferences_Display_f1a5f232e3d850a29a7a4d4079d7c37b_4654_container'
344 * Ex: 'CiviCRM_CRM_Admin_Form_Preferences_Display_f1a5f232e3d850a29a7a4d4079d7c37b_4654'
348 protected static function pickSessionTtl($sessionKey) {
349 $secureSessionTimeoutMinutes = (int) Civi
::settings()->get('secure_cache_timeout_minutes');
350 if ($secureSessionTimeoutMinutes) {
351 $transactionPages = [
352 'CRM_Contribute_Controller_Contribution',
353 'CRM_Event_Controller_Registration',
355 foreach ($transactionPages as $transactionPage) {
356 if (strpos($sessionKey, $transactionPage) !== FALSE) {
357 return $secureSessionTimeoutMinutes * 60;
362 return self
::DEFAULT_SESSION_TTL
;
366 * Do periodic cleanup of the CiviCRM session table.
368 * Also delete all session cache entries which are a couple of days old.
369 * This keeps the session cache to a manageable size
370 * Delete Contribution page session caches more energetically.
372 * @param bool $session
374 * @param bool $prevNext
375 * @param bool $expired
377 public static function cleanup($session = FALSE, $table = FALSE, $prevNext = FALSE, $expired = FALSE) {
378 // clean up the session cache every $cacheCleanUpNumber probabilistically
379 $cleanUpNumber = 757;
381 // clean up all sessions older than $cacheTimeIntervalDays days
382 $timeIntervalDays = 2;
384 if (mt_rand(1, 100000) %
$cleanUpNumber == 0) {
385 $expired = $session = $table = $prevNext = TRUE;
388 if (!$session && !$table && !$prevNext && !$expired) {
393 // delete all PrevNext caches
394 CRM_Core_BAO_PrevNextCache
::cleanupCache();
398 CRM_Core_Config
::clearTempTables($timeIntervalDays . ' day');
402 // Session caches are just regular caches, so they expire naturally per TTL.
407 $sql = "DELETE FROM civicrm_cache WHERE expired_date < %1";
409 1 => [date(CRM_Utils_Cache_SqlGroup
::TS_FMT
, CRM_Utils_Time
::getTimeRaw()), 'String'],
411 CRM_Core_DAO
::executeQuery($sql, $params);
416 * (Quasi-private) Encode an object/array/string/int as a string.
421 public static function encode($mixed) {
422 return base64_encode(serialize($mixed));
426 * (Quasi-private) Decode an object/array/string/int from a string.
431 public static function decode($string) {
432 // Upgrade support -- old records (serialize) always have this punctuation,
433 // and new records (base64) never do.
434 if (strpos($string, ':') !== FALSE ||
strpos($string, ';') !== FALSE) {
435 return unserialize($string);
438 return unserialize(base64_decode($string));
443 * Compose a SQL WHERE clause for the cache.
445 * Note: We need to use the cache during bootstrap, so we don't have
446 * full access to DAO services.
448 * @param string $group
449 * @param string|null $path
450 * Filter by path. If NULL, then return any paths.
451 * @param int|null $componentID
452 * Filter by component. If NULL, then look for explicitly NULL records.
455 protected static function whereCache($group, $path, $componentID) {
457 $clauses[] = ('group_name = "' . CRM_Core_DAO
::escapeString($group) . '"');
459 $clauses[] = ('path = "' . CRM_Core_DAO
::escapeString($path) . '"');
461 if ($componentID && is_numeric($componentID)) {
462 $clauses[] = ('component_id = ' . (int) $componentID);
464 return $clauses ?
implode(' AND ', $clauses) : '(1)';
468 * Normalize a cache key.
470 * This bridges an impedance mismatch between our traditional caching
471 * and PSR-16 -- PSR-16 accepts a narrower range of cache keys.
476 * Ex: '_abcd1234abcd1234' or 'ab_xx/cd_xxef'.
477 * A similar key, but suitable for use with PSR-16-compliant cache providers.
479 * @see CRM_Utils_Cache::cleanKey()
481 public static function cleanKey($key) {
482 return CRM_Utils_Cache
::cleanKey($key);