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 CRM_Core_Error
::deprecatedFunctionWarning(
77 'CRM_Core_BAO_Cache::getItem is deprecated and will be removed from core soon, use Civi::cache() facade or define cache group using hook_civicrm_container'
79 if (($adapter = CRM_Utils_Constant
::value('CIVICRM_BAO_CACHE_ADAPTER')) !== NULL) {
80 $value = $adapter::getItem($group, $path, $componentID);
84 if (self
::$_cache === NULL) {
88 $argString = "CRM_CT_{$group}_{$path}_{$componentID}";
89 if (!array_key_exists($argString, self
::$_cache)) {
90 $cache = CRM_Utils_Cache
::singleton();
91 $cleanKey = self
::cleanKey($argString);
92 self
::$_cache[$argString] = $cache->get($cleanKey);
93 if (self
::$_cache[$argString] === NULL) {
94 $table = self
::getTableName();
95 $where = self
::whereCache($group, $path, $componentID);
96 $rawData = CRM_Core_DAO
::singleValueQuery("SELECT data FROM $table WHERE $where");
97 $data = $rawData ? self
::decode($rawData) : NULL;
99 self
::$_cache[$argString] = $data;
100 if ($data !== NULL) {
101 // Do not cache 'null' as that is most likely a cache miss & we shouldn't then cache it.
102 $cache->set($cleanKey, self
::$_cache[$argString]);
106 return self
::$_cache[$argString];
110 * Retrieve all items in a group.
112 * @param string $group
113 * (required) The group name of the item.
114 * @param int $componentID
115 * The optional component ID (so componenets can share the same name space).
118 * The data if present in cache, else null
121 public static function &getItems($group, $componentID = NULL) {
122 CRM_Core_Error
::deprecatedFunctionWarning(
123 'CRM_Core_BAO_Cache::getItems is deprecated and will be removed from core soon, use Civi::cache() facade or define cache group using hook_civicrm_container'
125 if (($adapter = CRM_Utils_Constant
::value('CIVICRM_BAO_CACHE_ADAPTER')) !== NULL) {
126 return $adapter::getItems($group, $componentID);
129 if (self
::$_cache === NULL) {
133 $argString = "CRM_CT_CI_{$group}_{$componentID}";
134 if (!array_key_exists($argString, self
::$_cache)) {
135 $cache = CRM_Utils_Cache
::singleton();
136 $cleanKey = self
::cleanKey($argString);
137 self
::$_cache[$argString] = $cache->get($cleanKey);
138 if (!self
::$_cache[$argString]) {
139 $table = self
::getTableName();
140 $where = self
::whereCache($group, NULL, $componentID);
141 $dao = CRM_Core_DAO
::executeQuery("SELECT path, data FROM $table WHERE $where");
144 while ($dao->fetch()) {
145 $result[$dao->path
] = self
::decode($dao->data
);
148 self
::$_cache[$argString] = $result;
149 $cache->set($cleanKey, self
::$_cache[$argString]);
153 return self
::$_cache[$argString];
157 * Store an item in the DB cache.
159 * @param object $data
160 * (required) A reference to the data that will be serialized and stored.
161 * @param string $group
162 * (required) The group name of the item.
163 * @param string $path
164 * (required) The path under which this item is stored.
165 * @param int $componentID
166 * The optional component ID (so componenets can share the same name space).
169 public static function setItem(&$data, $group, $path, $componentID = NULL) {
170 CRM_Core_Error
::deprecatedFunctionWarning(
171 'CRM_Core_BAO_Cache::setItem is deprecated and will be removed from core soon, use Civi::cache() facade or define cache group using hook_civicrm_container'
173 if (($adapter = CRM_Utils_Constant
::value('CIVICRM_BAO_CACHE_ADAPTER')) !== NULL) {
174 return $adapter::setItem($data, $group, $path, $componentID);
177 if (self
::$_cache === NULL) {
181 // get a lock so that multiple ajax requests on the same page
182 // dont trample on each other
184 $lock = Civi
::lockManager()->acquire("cache.{$group}_{$path}._{$componentID}");
185 if (!$lock->isAcquired()) {
186 CRM_Core_Error
::fatal();
189 $table = self
::getTableName();
190 $where = self
::whereCache($group, $path, $componentID);
191 $dataExists = CRM_Core_DAO
::singleValueQuery("SELECT COUNT(*) FROM $table WHERE {$where}");
192 // FIXME - Use SQL NOW() or CRM_Utils_Time?
193 $now = date('Y-m-d H:i:s');
194 $dataSerialized = self
::encode($data);
196 // This table has a wonky index, so we cannot use REPLACE or
197 // "INSERT ... ON DUPE". Instead, use SELECT+(INSERT|UPDATE).
199 $sql = "UPDATE $table SET data = %1, created_date = %2 WHERE {$where}";
201 1 => [$dataSerialized, 'String'],
202 2 => [$now, 'String'],
204 $dao = CRM_Core_DAO
::executeQuery($sql, $args, TRUE, NULL, FALSE, FALSE);
207 $insert = CRM_Utils_SQL_Insert
::into($table)
209 'group_name' => $group,
211 'component_id' => $componentID,
212 'data' => $dataSerialized,
213 'created_date' => $now,
215 $dao = CRM_Core_DAO
::executeQuery($insert->toSQL(), [], TRUE, NULL, FALSE, FALSE);
220 // cache coherency - refresh or remove dependent caches
222 $argString = "CRM_CT_{$group}_{$path}_{$componentID}";
223 $cache = CRM_Utils_Cache
::singleton();
224 $data = self
::decode($dataSerialized);
225 self
::$_cache[$argString] = $data;
226 $cache->set(self
::cleanKey($argString), $data);
228 $argString = "CRM_CT_CI_{$group}_{$componentID}";
229 unset(self
::$_cache[$argString]);
230 $cache->delete(self
::cleanKey($argString));
234 * Delete all the cache elements that belong to a group OR delete the entire cache if group is not specified.
236 * @param string $group
237 * The group name of the entries to be deleted.
238 * @param string $path
239 * Path of the item that needs to be deleted.
240 * @param bool $clearAll clear all caches
243 public static function deleteGroup($group = NULL, $path = NULL, $clearAll = TRUE) {
244 CRM_Core_Error
::deprecatedFunctionWarning(
245 'CRM_Core_BAO_Cache::deleteGroup is deprecated and will be removed from core soon, use Civi::cache() facade or define cache group using hook_civicrm_container'
247 if (($adapter = CRM_Utils_Constant
::value('CIVICRM_BAO_CACHE_ADAPTER')) !== NULL) {
248 return $adapter::deleteGroup($group, $path);
251 $table = self
::getTableName();
252 $where = self
::whereCache($group, $path, NULL);
253 CRM_Core_DAO
::executeQuery("DELETE FROM $table WHERE $where");
262 * Cleanup ACL and System Level caches
264 public static function resetCaches() {
265 // also reset ACL Cache
266 // @todo why is this called when CRM_Utils_System::flushCache() does it as well.
267 CRM_ACL_BAO_Cache
::resetCache();
269 // also reset memory cache if any
270 CRM_Utils_System
::flushCache();
274 * The next two functions are internal functions used to store and retrieve session from
275 * the database cache. This keeps the session to a limited size and allows us to
276 * create separate session scopes for each form in a tab
280 * This function takes entries from the session array and stores it in the cache.
282 * It also deletes the entries from the $_SESSION object (for a smaller session size)
284 * @param array $names
285 * Array of session values that should be persisted.
286 * This is either a form name + qfKey or just a form name
287 * (in the case of profile)
288 * @param bool $resetSession
289 * Should session state be reset on completion of DB store?.
291 public static function storeSessionToCache($names, $resetSession = TRUE) {
292 foreach ($names as $key => $sessionName) {
293 if (is_array($sessionName)) {
295 if (!empty($_SESSION[$sessionName[0]][$sessionName[1]])) {
296 $value = $_SESSION[$sessionName[0]][$sessionName[1]];
298 $key = "{$sessionName[0]}_{$sessionName[1]}";
299 Civi
::cache('session')->set($key, $value, self
::pickSessionTtl($key));
301 $_SESSION[$sessionName[0]][$sessionName[1]] = NULL;
302 unset($_SESSION[$sessionName[0]][$sessionName[1]]);
307 if (!empty($_SESSION[$sessionName])) {
308 $value = $_SESSION[$sessionName];
310 Civi
::cache('session')->set($sessionName, $value, self
::pickSessionTtl($sessionName));
312 $_SESSION[$sessionName] = NULL;
313 unset($_SESSION[$sessionName]);
321 /* Retrieve the session values from the cache and populate the $_SESSION array
323 * @param array $names
324 * Array of session values that should be persisted.
325 * This is either a form name + qfKey or just a form name
326 * (in the case of profile)
330 * Restore session from cache.
332 * @param string $names
334 public static function restoreSessionFromCache($names) {
335 foreach ($names as $key => $sessionName) {
336 if (is_array($sessionName)) {
337 $value = Civi
::cache('session')->get("{$sessionName[0]}_{$sessionName[1]}");
339 $_SESSION[$sessionName[0]][$sessionName[1]] = $value;
343 $value = Civi
::cache('session')->get($sessionName);
345 $_SESSION[$sessionName] = $value;
352 * Determine how long session-state should be retained.
354 * @param string $sessionKey
355 * Ex: '_CRM_Admin_Form_Preferences_Display_f1a5f232e3d850a29a7a4d4079d7c37b_4654_container'
356 * Ex: 'CiviCRM_CRM_Admin_Form_Preferences_Display_f1a5f232e3d850a29a7a4d4079d7c37b_4654'
360 protected static function pickSessionTtl($sessionKey) {
361 $secureSessionTimeoutMinutes = (int) Civi
::settings()->get('secure_cache_timeout_minutes');
362 if ($secureSessionTimeoutMinutes) {
363 $transactionPages = [
364 'CRM_Contribute_Controller_Contribution',
365 'CRM_Event_Controller_Registration',
367 foreach ($transactionPages as $transactionPage) {
368 if (strpos($sessionKey, $transactionPage) !== FALSE) {
369 return $secureSessionTimeoutMinutes * 60;
374 return self
::DEFAULT_SESSION_TTL
;
378 * Do periodic cleanup of the CiviCRM session table.
380 * Also delete all session cache entries which are a couple of days old.
381 * This keeps the session cache to a manageable size
382 * Delete Contribution page session caches more energetically.
384 * @param bool $session
386 * @param bool $prevNext
387 * @param bool $expired
389 public static function cleanup($session = FALSE, $table = FALSE, $prevNext = FALSE, $expired = FALSE) {
390 // clean up the session cache every $cacheCleanUpNumber probabilistically
391 $cleanUpNumber = 757;
393 // clean up all sessions older than $cacheTimeIntervalDays days
394 $timeIntervalDays = 2;
396 if (mt_rand(1, 100000) %
$cleanUpNumber == 0) {
397 $expired = $session = $table = $prevNext = TRUE;
400 if (!$session && !$table && !$prevNext && !$expired) {
405 // delete all PrevNext caches
406 CRM_Core_BAO_PrevNextCache
::cleanupCache();
410 CRM_Core_Config
::clearTempTables($timeIntervalDays . ' day');
414 // Session caches are just regular caches, so they expire naturally per TTL.
419 $sql = "DELETE FROM civicrm_cache WHERE expired_date < %1";
421 1 => [date(CRM_Utils_Cache_SqlGroup
::TS_FMT
, CRM_Utils_Time
::getTimeRaw()), 'String'],
423 CRM_Core_DAO
::executeQuery($sql, $params);
428 * (Quasi-private) Encode an object/array/string/int as a string.
433 public static function encode($mixed) {
434 return base64_encode(serialize($mixed));
438 * (Quasi-private) Decode an object/array/string/int from a string.
443 public static function decode($string) {
444 // Upgrade support -- old records (serialize) always have this punctuation,
445 // and new records (base64) never do.
446 if (strpos($string, ':') !== FALSE ||
strpos($string, ';') !== FALSE) {
447 return unserialize($string);
450 return unserialize(base64_decode($string));
455 * Compose a SQL WHERE clause for the cache.
457 * Note: We need to use the cache during bootstrap, so we don't have
458 * full access to DAO services.
460 * @param string $group
461 * @param string|null $path
462 * Filter by path. If NULL, then return any paths.
463 * @param int|null $componentID
464 * Filter by component. If NULL, then look for explicitly NULL records.
467 protected static function whereCache($group, $path, $componentID) {
469 $clauses[] = ('group_name = "' . CRM_Core_DAO
::escapeString($group) . '"');
471 $clauses[] = ('path = "' . CRM_Core_DAO
::escapeString($path) . '"');
473 if ($componentID && is_numeric($componentID)) {
474 $clauses[] = ('component_id = ' . (int) $componentID);
476 return $clauses ?
implode(' AND ', $clauses) : '(1)';
480 * Normalize a cache key.
482 * This bridges an impedance mismatch between our traditional caching
483 * and PSR-16 -- PSR-16 accepts a narrower range of cache keys.
488 * Ex: '_abcd1234abcd1234' or 'ab_xx/cd_xxef'.
489 * A similar key, but suitable for use with PSR-16-compliant cache providers.
491 * @see CRM_Utils_Cache::cleanKey()
493 public static function cleanKey($key) {
494 return CRM_Utils_Cache
::cleanKey($key);