Merge pull request #23742 from eileenmcnaughton/import_remove
[civicrm-core.git] / CRM / Core / BAO / Cache.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 * BAO object for civicrm_cache table.
14 *
15 * This is a database cache and is persisted across sessions. Typically we use
16 * this to store meta data (like profile fields, custom fields etc).
17 *
18 * The group_name column is used for grouping together all cache elements that logically belong to the same set.
19 * Thus all session cache entries are grouped under 'CiviCRM Session'. This allows us to delete all entries of
20 * a specific group if needed.
21 *
22 * The path column allows us to differentiate between items in that group. Thus for the session cache, the path is
23 * the unique form name for each form (per user)
24 */
25 class CRM_Core_BAO_Cache extends CRM_Core_DAO_Cache {
26
27 /**
28 * When store session/form state, how long should the data be retained?
29 *
30 * Default is Two days: 2*24*60*60
31 *
32 * @var int, number of second
33 */
34 const DEFAULT_SESSION_TTL = 172800;
35
36 /**
37 * Cleanup ACL and System Level caches
38 */
39 public static function resetCaches() {
40 CRM_Utils_System::flushCache();
41 }
42
43 /**
44 * The next two functions are internal functions used to store and retrieve session from
45 * the database cache. This keeps the session to a limited size and allows us to
46 * create separate session scopes for each form in a tab
47 */
48
49 /**
50 * This function takes entries from the session array and stores it in the cache.
51 *
52 * It also deletes the entries from the $_SESSION object (for a smaller session size)
53 *
54 * @param array $names
55 * Array of session values that should be persisted.
56 * This is either a form name + qfKey or just a form name
57 * (in the case of profile)
58 * @param bool $resetSession
59 * Should session state be reset on completion of DB store?.
60 */
61 public static function storeSessionToCache($names, $resetSession = TRUE) {
62 foreach ($names as $key => $sessionName) {
63 if (is_array($sessionName)) {
64 $value = NULL;
65 if (!empty($_SESSION[$sessionName[0]][$sessionName[1]])) {
66 $value = $_SESSION[$sessionName[0]][$sessionName[1]];
67 }
68 $key = "{$sessionName[0]}_{$sessionName[1]}";
69 Civi::cache('session')->set($key, $value, self::pickSessionTtl($key));
70 if ($resetSession) {
71 $_SESSION[$sessionName[0]][$sessionName[1]] = NULL;
72 unset($_SESSION[$sessionName[0]][$sessionName[1]]);
73 }
74 }
75 else {
76 $value = NULL;
77 if (!empty($_SESSION[$sessionName])) {
78 $value = $_SESSION[$sessionName];
79 }
80 Civi::cache('session')->set($sessionName, $value, self::pickSessionTtl($sessionName));
81 if ($resetSession) {
82 $_SESSION[$sessionName] = NULL;
83 unset($_SESSION[$sessionName]);
84 }
85 }
86 }
87
88 self::cleanup();
89 }
90
91 /* Retrieve the session values from the cache and populate the $_SESSION array
92 *
93 * @param array $names
94 * Array of session values that should be persisted.
95 * This is either a form name + qfKey or just a form name
96 * (in the case of profile)
97 */
98
99 /**
100 * Restore session from cache.
101 *
102 * @param string $names
103 */
104 public static function restoreSessionFromCache($names) {
105 foreach ($names as $key => $sessionName) {
106 if (is_array($sessionName)) {
107 $value = Civi::cache('session')->get("{$sessionName[0]}_{$sessionName[1]}");
108 if ($value) {
109 $_SESSION[$sessionName[0]][$sessionName[1]] = $value;
110 }
111 }
112 else {
113 $value = Civi::cache('session')->get($sessionName);
114 if ($value) {
115 $_SESSION[$sessionName] = $value;
116 }
117 }
118 }
119 }
120
121 /**
122 * Determine how long session-state should be retained.
123 *
124 * @param string $sessionKey
125 * Ex: '_CRM_Admin_Form_Preferences_Display_f1a5f232e3d850a29a7a4d4079d7c37b_4654_container'
126 * Ex: 'CiviCRM_CRM_Admin_Form_Preferences_Display_f1a5f232e3d850a29a7a4d4079d7c37b_4654'
127 * @return int
128 * Number of seconds.
129 */
130 protected static function pickSessionTtl($sessionKey) {
131 $secureSessionTimeoutMinutes = (int) Civi::settings()->get('secure_cache_timeout_minutes');
132 if ($secureSessionTimeoutMinutes) {
133 $transactionPages = [
134 'CRM_Contribute_Controller_Contribution',
135 'CRM_Event_Controller_Registration',
136 ];
137 foreach ($transactionPages as $transactionPage) {
138 if (strpos($sessionKey, $transactionPage) !== FALSE) {
139 return $secureSessionTimeoutMinutes * 60;
140 }
141 }
142 }
143
144 return self::DEFAULT_SESSION_TTL;
145 }
146
147 /**
148 * Do periodic cleanup of the CiviCRM session table.
149 *
150 * Also delete all session cache entries which are a couple of days old.
151 * This keeps the session cache to a manageable size
152 * Delete Contribution page session caches more energetically.
153 *
154 * @param bool $session
155 * @param bool $table
156 * @param bool $prevNext
157 * @param bool $expired
158 */
159 public static function cleanup($session = FALSE, $table = FALSE, $prevNext = FALSE, $expired = FALSE) {
160 // clean up the session cache every $cacheCleanUpNumber probabilistically
161 $cleanUpNumber = 757;
162
163 // clean up all sessions older than $cacheTimeIntervalDays days
164 $timeIntervalDays = 2;
165
166 if (mt_rand(1, 100000) % $cleanUpNumber == 0) {
167 $expired = $session = $table = $prevNext = TRUE;
168 }
169
170 if (!$session && !$table && !$prevNext && !$expired) {
171 return;
172 }
173
174 if ($prevNext) {
175 // delete all PrevNext caches
176 Civi::service('prevnext')->cleanup();
177 }
178
179 if ($table) {
180 CRM_Core_Config::clearTempTables($timeIntervalDays . ' day');
181 }
182
183 if ($session) {
184 // Session caches are just regular caches, so they expire naturally per TTL.
185 $expired = TRUE;
186 }
187
188 if ($expired) {
189 $sql = "DELETE FROM civicrm_cache WHERE expired_date < %1";
190 $params = [
191 1 => [date(CRM_Utils_Cache_SqlGroup::TS_FMT, CRM_Utils_Time::getTimeRaw()), 'String'],
192 ];
193 CRM_Core_DAO::executeQuery($sql, $params);
194 }
195 }
196
197 /**
198 * (Quasi-private) Encode an object/array/string/int as a string.
199 *
200 * @param $mixed
201 * @return string
202 */
203 public static function encode($mixed) {
204 return base64_encode(serialize($mixed));
205 }
206
207 /**
208 * (Quasi-private) Decode an object/array/string/int from a string.
209 *
210 * @param $string
211 * @return mixed
212 */
213 public static function decode($string) {
214 // Upgrade support -- old records (serialize) always have this punctuation,
215 // and new records (base64) never do.
216 if (strpos($string, ':') !== FALSE || strpos($string, ';') !== FALSE) {
217 return unserialize($string);
218 }
219 else {
220 return unserialize(base64_decode($string));
221 }
222 }
223
224 /**
225 * Compose a SQL WHERE clause for the cache.
226 *
227 * Note: We need to use the cache during bootstrap, so we don't have
228 * full access to DAO services.
229 *
230 * @param string $group
231 * @param string|null $path
232 * Filter by path. If NULL, then return any paths.
233 * @param int|null $componentID
234 * Filter by component. If NULL, then look for explicitly NULL records.
235 * @return string
236 */
237 protected static function whereCache($group, $path, $componentID) {
238 $clauses = [];
239 $clauses[] = ('group_name = "' . CRM_Core_DAO::escapeString($group) . '"');
240 if ($path) {
241 $clauses[] = ('path = "' . CRM_Core_DAO::escapeString($path) . '"');
242 }
243 if ($componentID && is_numeric($componentID)) {
244 $clauses[] = ('component_id = ' . (int) $componentID);
245 }
246 return $clauses ? implode(' AND ', $clauses) : '(1)';
247 }
248
249 /**
250 * Normalize a cache key.
251 *
252 * This bridges an impedance mismatch between our traditional caching
253 * and PSR-16 -- PSR-16 accepts a narrower range of cache keys.
254 *
255 * @param string $key
256 * Ex: 'ab/cd:ef'
257 * @return string
258 * Ex: '_abcd1234abcd1234' or 'ab_xx/cd_xxef'.
259 * A similar key, but suitable for use with PSR-16-compliant cache providers.
260 * @deprecated
261 * @see CRM_Utils_Cache::cleanKey()
262 */
263 public static function cleanKey($key) {
264 CRM_Core_Error::deprecatedFunctionWarning('CRM_Utils_Cache::cleanKey');
265 return CRM_Utils_Cache::cleanKey($key);
266 }
267
268 }