Merge pull request #14222 from mfb/debug-var
[civicrm-core.git] / CRM / Core / BAO / Cache.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 * BAO object for civicrm_cache table.
30 *
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).
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 */
41 class CRM_Core_BAO_Cache extends CRM_Core_DAO_Cache {
42
43 /**
44 * When store session/form state, how long should the data be retained?
45 *
46 * Default is Two days: 2*24*60*60
47 *
48 * @var int, number of second
49 */
50 const DEFAULT_SESSION_TTL = 172800;
51
52 /**
53 * Cache.
54 *
55 * Format is ($cacheKey => $cacheValue)
56 *
57 * @var array
58 */
59 public static $_cache = NULL;
60
61 /**
62 * Retrieve an item from the DB cache.
63 *
64 * @param string $group
65 * (required) The group name of the item.
66 * @param string $path
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).
70 *
71 * @return object
72 * The data if present in cache, else null
73 * @deprecated
74 */
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'
78 );
79 if (($adapter = CRM_Utils_Constant::value('CIVICRM_BAO_CACHE_ADAPTER')) !== NULL) {
80 $value = $adapter::getItem($group, $path, $componentID);
81 return $value;
82 }
83
84 if (self::$_cache === NULL) {
85 self::$_cache = [];
86 }
87
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;
98
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]);
103 }
104 }
105 }
106 return self::$_cache[$argString];
107 }
108
109 /**
110 * Retrieve all items in a group.
111 *
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).
116 *
117 * @return object
118 * The data if present in cache, else null
119 * @deprecated
120 */
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'
124 );
125 if (($adapter = CRM_Utils_Constant::value('CIVICRM_BAO_CACHE_ADAPTER')) !== NULL) {
126 return $adapter::getItems($group, $componentID);
127 }
128
129 if (self::$_cache === NULL) {
130 self::$_cache = [];
131 }
132
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");
142
143 $result = [];
144 while ($dao->fetch()) {
145 $result[$dao->path] = self::decode($dao->data);
146 }
147
148 self::$_cache[$argString] = $result;
149 $cache->set($cleanKey, self::$_cache[$argString]);
150 }
151 }
152
153 return self::$_cache[$argString];
154 }
155
156 /**
157 * Store an item in the DB cache.
158 *
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).
167 * @deprecated
168 */
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'
172 );
173 if (($adapter = CRM_Utils_Constant::value('CIVICRM_BAO_CACHE_ADAPTER')) !== NULL) {
174 return $adapter::setItem($data, $group, $path, $componentID);
175 }
176
177 if (self::$_cache === NULL) {
178 self::$_cache = [];
179 }
180
181 // get a lock so that multiple ajax requests on the same page
182 // dont trample on each other
183 // CRM-11234
184 $lock = Civi::lockManager()->acquire("cache.{$group}_{$path}._{$componentID}");
185 if (!$lock->isAcquired()) {
186 CRM_Core_Error::fatal();
187 }
188
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);
195
196 // This table has a wonky index, so we cannot use REPLACE or
197 // "INSERT ... ON DUPE". Instead, use SELECT+(INSERT|UPDATE).
198 if ($dataExists) {
199 $sql = "UPDATE $table SET data = %1, created_date = %2 WHERE {$where}";
200 $args = [
201 1 => [$dataSerialized, 'String'],
202 2 => [$now, 'String'],
203 ];
204 $dao = CRM_Core_DAO::executeQuery($sql, $args, TRUE, NULL, FALSE, FALSE);
205 }
206 else {
207 $insert = CRM_Utils_SQL_Insert::into($table)
208 ->row([
209 'group_name' => $group,
210 'path' => $path,
211 'component_id' => $componentID,
212 'data' => $dataSerialized,
213 'created_date' => $now,
214 ]);
215 $dao = CRM_Core_DAO::executeQuery($insert->toSQL(), [], TRUE, NULL, FALSE, FALSE);
216 }
217
218 $lock->release();
219
220 // cache coherency - refresh or remove dependent caches
221
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);
227
228 $argString = "CRM_CT_CI_{$group}_{$componentID}";
229 unset(self::$_cache[$argString]);
230 $cache->delete(self::cleanKey($argString));
231 }
232
233 /**
234 * Delete all the cache elements that belong to a group OR delete the entire cache if group is not specified.
235 *
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
241 * @deprecated
242 */
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'
246 );
247 if (($adapter = CRM_Utils_Constant::value('CIVICRM_BAO_CACHE_ADAPTER')) !== NULL) {
248 return $adapter::deleteGroup($group, $path);
249 }
250 else {
251 $table = self::getTableName();
252 $where = self::whereCache($group, $path, NULL);
253 CRM_Core_DAO::executeQuery("DELETE FROM $table WHERE $where");
254 }
255
256 if ($clearAll) {
257 self::resetCaches();
258 }
259 }
260
261 /**
262 * Cleanup ACL and System Level caches
263 */
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();
268
269 // also reset memory cache if any
270 CRM_Utils_System::flushCache();
271 }
272
273 /**
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
277 */
278
279 /**
280 * This function takes entries from the session array and stores it in the cache.
281 *
282 * It also deletes the entries from the $_SESSION object (for a smaller session size)
283 *
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?.
290 */
291 public static function storeSessionToCache($names, $resetSession = TRUE) {
292 foreach ($names as $key => $sessionName) {
293 if (is_array($sessionName)) {
294 $value = NULL;
295 if (!empty($_SESSION[$sessionName[0]][$sessionName[1]])) {
296 $value = $_SESSION[$sessionName[0]][$sessionName[1]];
297 }
298 $key = "{$sessionName[0]}_{$sessionName[1]}";
299 Civi::cache('session')->set($key, $value, self::pickSessionTtl($key));
300 if ($resetSession) {
301 $_SESSION[$sessionName[0]][$sessionName[1]] = NULL;
302 unset($_SESSION[$sessionName[0]][$sessionName[1]]);
303 }
304 }
305 else {
306 $value = NULL;
307 if (!empty($_SESSION[$sessionName])) {
308 $value = $_SESSION[$sessionName];
309 }
310 Civi::cache('session')->set($sessionName, $value, self::pickSessionTtl($sessionName));
311 if ($resetSession) {
312 $_SESSION[$sessionName] = NULL;
313 unset($_SESSION[$sessionName]);
314 }
315 }
316 }
317
318 self::cleanup();
319 }
320
321 /* Retrieve the session values from the cache and populate the $_SESSION array
322 *
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)
327 */
328
329 /**
330 * Restore session from cache.
331 *
332 * @param string $names
333 */
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]}");
338 if ($value) {
339 $_SESSION[$sessionName[0]][$sessionName[1]] = $value;
340 }
341 }
342 else {
343 $value = Civi::cache('session')->get($sessionName);
344 if ($value) {
345 $_SESSION[$sessionName] = $value;
346 }
347 }
348 }
349 }
350
351 /**
352 * Determine how long session-state should be retained.
353 *
354 * @param string $sessionKey
355 * Ex: '_CRM_Admin_Form_Preferences_Display_f1a5f232e3d850a29a7a4d4079d7c37b_4654_container'
356 * Ex: 'CiviCRM_CRM_Admin_Form_Preferences_Display_f1a5f232e3d850a29a7a4d4079d7c37b_4654'
357 * @return int
358 * Number of seconds.
359 */
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',
366 ];
367 foreach ($transactionPages as $transactionPage) {
368 if (strpos($sessionKey, $transactionPage) !== FALSE) {
369 return $secureSessionTimeoutMinutes * 60;
370 }
371 }
372 }
373
374 return self::DEFAULT_SESSION_TTL;
375 }
376
377 /**
378 * Do periodic cleanup of the CiviCRM session table.
379 *
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.
383 *
384 * @param bool $session
385 * @param bool $table
386 * @param bool $prevNext
387 * @param bool $expired
388 */
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;
392
393 // clean up all sessions older than $cacheTimeIntervalDays days
394 $timeIntervalDays = 2;
395
396 if (mt_rand(1, 100000) % $cleanUpNumber == 0) {
397 $expired = $session = $table = $prevNext = TRUE;
398 }
399
400 if (!$session && !$table && !$prevNext && !$expired) {
401 return;
402 }
403
404 if ($prevNext) {
405 // delete all PrevNext caches
406 CRM_Core_BAO_PrevNextCache::cleanupCache();
407 }
408
409 if ($table) {
410 CRM_Core_Config::clearTempTables($timeIntervalDays . ' day');
411 }
412
413 if ($session) {
414 // Session caches are just regular caches, so they expire naturally per TTL.
415 $expired = TRUE;
416 }
417
418 if ($expired) {
419 $sql = "DELETE FROM civicrm_cache WHERE expired_date < %1";
420 $params = [
421 1 => [date(CRM_Utils_Cache_SqlGroup::TS_FMT, CRM_Utils_Time::getTimeRaw()), 'String'],
422 ];
423 CRM_Core_DAO::executeQuery($sql, $params);
424 }
425 }
426
427 /**
428 * (Quasi-private) Encode an object/array/string/int as a string.
429 *
430 * @param $mixed
431 * @return string
432 */
433 public static function encode($mixed) {
434 return base64_encode(serialize($mixed));
435 }
436
437 /**
438 * (Quasi-private) Decode an object/array/string/int from a string.
439 *
440 * @param $string
441 * @return mixed
442 */
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);
448 }
449 else {
450 return unserialize(base64_decode($string));
451 }
452 }
453
454 /**
455 * Compose a SQL WHERE clause for the cache.
456 *
457 * Note: We need to use the cache during bootstrap, so we don't have
458 * full access to DAO services.
459 *
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.
465 * @return string
466 */
467 protected static function whereCache($group, $path, $componentID) {
468 $clauses = [];
469 $clauses[] = ('group_name = "' . CRM_Core_DAO::escapeString($group) . '"');
470 if ($path) {
471 $clauses[] = ('path = "' . CRM_Core_DAO::escapeString($path) . '"');
472 }
473 if ($componentID && is_numeric($componentID)) {
474 $clauses[] = ('component_id = ' . (int) $componentID);
475 }
476 return $clauses ? implode(' AND ', $clauses) : '(1)';
477 }
478
479 /**
480 * Normalize a cache key.
481 *
482 * This bridges an impedance mismatch between our traditional caching
483 * and PSR-16 -- PSR-16 accepts a narrower range of cache keys.
484 *
485 * @param string $key
486 * Ex: 'ab/cd:ef'
487 * @return string
488 * Ex: '_abcd1234abcd1234' or 'ab_xx/cd_xxef'.
489 * A similar key, but suitable for use with PSR-16-compliant cache providers.
490 * @deprecated
491 * @see CRM_Utils_Cache::cleanKey()
492 */
493 public static function cleanKey($key) {
494 return CRM_Utils_Cache::cleanKey($key);
495 }
496
497 }