3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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 * @var int, number of second
48 const DEFAULT_SESSION_TTL
= 172800; // Two days: 2*24*60*60
51 * @var array ($cacheKey => $cacheValue)
53 static $_cache = NULL;
56 * Retrieve an item from the DB cache.
58 * @param string $group
59 * (required) The group name of the item.
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).
66 * The data if present in cache, else null
68 public static function &getItem($group, $path, $componentID = NULL) {
69 if (self
::$_cache === NULL) {
70 self
::$_cache = array();
73 $argString = "CRM_CT_{$group}_{$path}_{$componentID}";
74 if (!array_key_exists($argString, self
::$_cache)) {
75 $cache = CRM_Utils_Cache
::singleton();
76 $cleanKey = self
::cleanKey($argString);
77 self
::$_cache[$argString] = $cache->get($cleanKey);
78 if (self
::$_cache[$argString] === NULL) {
79 $table = self
::getTableName();
80 $where = self
::whereCache($group, $path, $componentID);
81 $rawData = CRM_Core_DAO
::singleValueQuery("SELECT data FROM $table WHERE $where");
82 $data = $rawData ? self
::decode($rawData) : NULL;
84 self
::$_cache[$argString] = $data;
86 // Do not cache 'null' as that is most likely a cache miss & we shouldn't then cache it.
87 $cache->set($cleanKey, self
::$_cache[$argString]);
91 return self
::$_cache[$argString];
95 * Retrieve all items in a group.
97 * @param string $group
98 * (required) The group name of the item.
99 * @param int $componentID
100 * The optional component ID (so componenets can share the same name space).
103 * The data if present in cache, else null
105 public static function &getItems($group, $componentID = NULL) {
106 if (self
::$_cache === NULL) {
107 self
::$_cache = array();
110 $argString = "CRM_CT_CI_{$group}_{$componentID}";
111 if (!array_key_exists($argString, self
::$_cache)) {
112 $cache = CRM_Utils_Cache
::singleton();
113 $cleanKey = self
::cleanKey($argString);
114 self
::$_cache[$argString] = $cache->get($cleanKey);
115 if (!self
::$_cache[$argString]) {
116 $table = self
::getTableName();
117 $where = self
::whereCache($group, NULL, $componentID);
118 $dao = CRM_Core_DAO
::executeQuery("SELECT path, data FROM $table WHERE $where");
121 while ($dao->fetch()) {
122 $result[$dao->path
] = self
::decode($dao->data
);
126 self
::$_cache[$argString] = $result;
127 $cache->set($cleanKey, self
::$_cache[$argString]);
131 return self
::$_cache[$argString];
135 * Store an item in the DB cache.
137 * @param object $data
138 * (required) A reference to the data that will be serialized and stored.
139 * @param string $group
140 * (required) The group name of the item.
141 * @param string $path
142 * (required) The path under which this item is stored.
143 * @param int $componentID
144 * The optional component ID (so componenets can share the same name space).
146 public static function setItem(&$data, $group, $path, $componentID = NULL) {
147 if (self
::$_cache === NULL) {
148 self
::$_cache = array();
151 // get a lock so that multiple ajax requests on the same page
152 // dont trample on each other
154 $lock = Civi
::lockManager()->acquire("cache.{$group}_{$path}._{$componentID}");
155 if (!$lock->isAcquired()) {
156 CRM_Core_Error
::fatal();
159 $table = self
::getTableName();
160 $where = self
::whereCache($group, $path, $componentID);
161 $dataExists = CRM_Core_DAO
::singleValueQuery("SELECT COUNT(*) FROM $table WHERE {$where}");
162 $now = date('Y-m-d H:i:s'); // FIXME - Use SQL NOW() or CRM_Utils_Time?
163 $dataSerialized = self
::encode($data);
165 // This table has a wonky index, so we cannot use REPLACE or
166 // "INSERT ... ON DUPE". Instead, use SELECT+(INSERT|UPDATE).
168 $sql = "UPDATE $table SET data = %1, created_date = %2 WHERE {$where}";
170 1 => array($dataSerialized, 'String'),
171 2 => array($now, 'String'),
173 $dao = CRM_Core_DAO
::executeQuery($sql, $args, TRUE, NULL, FALSE, FALSE);
176 $insert = CRM_Utils_SQL_Insert
::into($table)
178 'group_name' => $group,
180 'component_id' => $componentID,
181 'data' => $dataSerialized,
182 'created_date' => $now,
184 $dao = CRM_Core_DAO
::executeQuery($insert->toSQL(), array(), TRUE, NULL, FALSE, FALSE);
191 // cache coherency - refresh or remove dependent caches
193 $argString = "CRM_CT_{$group}_{$path}_{$componentID}";
194 $cache = CRM_Utils_Cache
::singleton();
195 $data = self
::decode($dataSerialized);
196 self
::$_cache[$argString] = $data;
197 $cache->set(self
::cleanKey($argString), $data);
199 $argString = "CRM_CT_CI_{$group}_{$componentID}";
200 unset(self
::$_cache[$argString]);
201 $cache->delete(self
::cleanKey($argString));
205 * Delete all the cache elements that belong to a group OR delete the entire cache if group is not specified.
207 * @param string $group
208 * The group name of the entries to be deleted.
209 * @param string $path
210 * Path of the item that needs to be deleted.
211 * @param bool $clearAll clear all caches
213 public static function deleteGroup($group = NULL, $path = NULL, $clearAll = TRUE) {
214 $table = self
::getTableName();
215 $where = self
::whereCache($group, $path, NULL);
216 CRM_Core_DAO
::executeQuery("DELETE FROM $table WHERE $where");
219 // also reset ACL Cache
220 CRM_ACL_BAO_Cache
::resetCache();
222 // also reset memory cache if any
223 CRM_Utils_System
::flushCache();
228 * The next two functions are internal functions used to store and retrieve session from
229 * the database cache. This keeps the session to a limited size and allows us to
230 * create separate session scopes for each form in a tab
234 * This function takes entries from the session array and stores it in the cache.
236 * It also deletes the entries from the $_SESSION object (for a smaller session size)
238 * @param array $names
239 * Array of session values that should be persisted.
240 * This is either a form name + qfKey or just a form name
241 * (in the case of profile)
242 * @param bool $resetSession
243 * Should session state be reset on completion of DB store?.
245 public static function storeSessionToCache($names, $resetSession = TRUE) {
246 foreach ($names as $key => $sessionName) {
247 if (is_array($sessionName)) {
249 if (!empty($_SESSION[$sessionName[0]][$sessionName[1]])) {
250 $value = $_SESSION[$sessionName[0]][$sessionName[1]];
252 $key = "{$sessionName[0]}_{$sessionName[1]}";
253 Civi
::cache('session')->set($key, $value, self
::pickSessionTtl($key));
255 $_SESSION[$sessionName[0]][$sessionName[1]] = NULL;
256 unset($_SESSION[$sessionName[0]][$sessionName[1]]);
261 if (!empty($_SESSION[$sessionName])) {
262 $value = $_SESSION[$sessionName];
264 Civi
::cache('session')->set($sessionName, $value, self
::pickSessionTtl($sessionName));
266 $_SESSION[$sessionName] = NULL;
267 unset($_SESSION[$sessionName]);
275 /* Retrieve the session values from the cache and populate the $_SESSION array
277 * @param array $names
278 * Array of session values that should be persisted.
279 * This is either a form name + qfKey or just a form name
280 * (in the case of profile)
284 * Restore session from cache.
286 * @param string $names
288 public static function restoreSessionFromCache($names) {
289 foreach ($names as $key => $sessionName) {
290 if (is_array($sessionName)) {
291 $value = Civi
::cache('session')->get("{$sessionName[0]}_{$sessionName[1]}");
293 $_SESSION[$sessionName[0]][$sessionName[1]] = $value;
297 $value = Civi
::cache('session')->get($sessionName);
299 $_SESSION[$sessionName] = $value;
306 * Determine how long session-state should be retained.
308 * @param string $sessionKey
309 * Ex: '_CRM_Admin_Form_Preferences_Display_f1a5f232e3d850a29a7a4d4079d7c37b_4654_container'
310 * Ex: 'CiviCRM_CRM_Admin_Form_Preferences_Display_f1a5f232e3d850a29a7a4d4079d7c37b_4654'
314 protected static function pickSessionTtl($sessionKey) {
315 $secureSessionTimeoutMinutes = (int) Civi
::settings()->get('secure_cache_timeout_minutes');
316 if ($secureSessionTimeoutMinutes) {
317 $transactionPages = array(
318 'CRM_Contribute_Controller_Contribution',
319 'CRM_Event_Controller_Registration',
321 foreach ($transactionPages as $transactionPage) {
322 if (strpos($sessionKey, $transactionPage) !== FALSE) {
323 return $secureSessionTimeoutMinutes * 60;
328 return self
::DEFAULT_SESSION_TTL
;
332 * Do periodic cleanup of the CiviCRM session table.
334 * Also delete all session cache entries which are a couple of days old.
335 * This keeps the session cache to a manageable size
336 * Delete Contribution page session caches more energetically.
338 * @param bool $session
340 * @param bool $prevNext
342 public static function cleanup($session = FALSE, $table = FALSE, $prevNext = FALSE, $expired = FALSE) {
343 // clean up the session cache every $cacheCleanUpNumber probabilistically
344 $cleanUpNumber = 757;
346 // clean up all sessions older than $cacheTimeIntervalDays days
347 $timeIntervalDays = 2;
349 if (mt_rand(1, 100000) %
$cleanUpNumber == 0) {
350 $expired = $session = $table = $prevNext = TRUE;
353 if (!$session && !$table && !$prevNext && !$expired) {
358 // delete all PrevNext caches
359 CRM_Core_BAO_PrevNextCache
::cleanupCache();
363 CRM_Core_Config
::clearTempTables($timeIntervalDays . ' day');
367 // Session caches are just regular caches, so they expire naturally per TTL.
372 $sql = "DELETE FROM civicrm_cache WHERE expired_date < %1";
374 1 => [date(CRM_Utils_Cache_SqlGroup
::TS_FMT
, CRM_Utils_Time
::getTimeRaw()), 'String'],
376 CRM_Core_DAO
::executeQuery($sql, $params);
381 * (Quasi-private) Encode an object/array/string/int as a string.
386 public static function encode($mixed) {
387 return base64_encode(serialize($mixed));
391 * (Quasi-private) Decode an object/array/string/int from a string.
396 public static function decode($string) {
397 // Upgrade support -- old records (serialize) always have this punctuation,
398 // and new records (base64) never do.
399 if (strpos($string, ':') !== FALSE ||
strpos($string, ';') !== FALSE) {
400 return unserialize($string);
403 return unserialize(base64_decode($string));
408 * Compose a SQL WHERE clause for the cache.
410 * Note: We need to use the cache during bootstrap, so we don't have
411 * full access to DAO services.
413 * @param string $group
414 * @param string|NULL $path
415 * Filter by path. If NULL, then return any paths.
416 * @param int|NULL $componentID
417 * Filter by component. If NULL, then look for explicitly NULL records.
420 protected static function whereCache($group, $path, $componentID) {
422 $clauses[] = ('group_name = "' . CRM_Core_DAO
::escapeString($group) . '"');
424 $clauses[] = ('path = "' . CRM_Core_DAO
::escapeString($path) . '"');
426 if ($componentID && is_numeric($componentID)) {
427 $clauses[] = ('component_id = ' . (int) $componentID);
429 return $clauses ?
implode(' AND ', $clauses) : '(1)';
433 * Normalize a cache key.
435 * This bridges an impedance mismatch between our traditional caching
436 * and PSR-16 -- PSR-16 accepts a narrower range of cache keys.
441 * Ex: '_abcd1234abcd1234' or 'ab_xx/cd_xxef'.
442 * A similar key, but suitable for use with PSR-16-compliant cache providers.
444 public static function cleanKey($key) {
445 if (!is_string($key) && !is_int($key)) {
446 throw new \
RuntimeException("Malformed cache key");
452 if (strlen($key) >= $maxLen) {
453 return $escape . md5($key);
456 $r = preg_replace_callback(';[^A-Za-z0-9_\.];', function($m) use ($escape) {
457 return $escape . dechex(ord($m[0]));
460 return strlen($r) >= $maxLen ?
$escape . md5($key) : $r;