Merge pull request #12801 from civicrm/5.5
[civicrm-core.git] / CRM / Core / BAO / Cache.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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 * @var int, number of second
47 */
48 const DEFAULT_SESSION_TTL = 172800; // Two days: 2*24*60*60
49
50 /**
51 * @var array ($cacheKey => $cacheValue)
52 */
53 static $_cache = NULL;
54
55 /**
56 * Retrieve an item from the DB cache.
57 *
58 * @param string $group
59 * (required) The group name of the item.
60 * @param string $path
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).
64 *
65 * @return object
66 * The data if present in cache, else null
67 */
68 public static function &getItem($group, $path, $componentID = NULL) {
69 if (self::$_cache === NULL) {
70 self::$_cache = array();
71 }
72
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]) {
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;
83
84 self::$_cache[$argString] = $data;
85 $cache->set($cleanKey, self::$_cache[$argString]);
86 }
87 }
88 return self::$_cache[$argString];
89 }
90
91 /**
92 * Retrieve all items in a group.
93 *
94 * @param string $group
95 * (required) The group name of the item.
96 * @param int $componentID
97 * The optional component ID (so componenets can share the same name space).
98 *
99 * @return object
100 * The data if present in cache, else null
101 */
102 public static function &getItems($group, $componentID = NULL) {
103 if (self::$_cache === NULL) {
104 self::$_cache = array();
105 }
106
107 $argString = "CRM_CT_CI_{$group}_{$componentID}";
108 if (!array_key_exists($argString, self::$_cache)) {
109 $cache = CRM_Utils_Cache::singleton();
110 $cleanKey = self::cleanKey($argString);
111 self::$_cache[$argString] = $cache->get($cleanKey);
112 if (!self::$_cache[$argString]) {
113 $table = self::getTableName();
114 $where = self::whereCache($group, NULL, $componentID);
115 $dao = CRM_Core_DAO::executeQuery("SELECT path, data FROM $table WHERE $where");
116
117 $result = array();
118 while ($dao->fetch()) {
119 $result[$dao->path] = self::decode($dao->data);
120 }
121 $dao->free();
122
123 self::$_cache[$argString] = $result;
124 $cache->set($cleanKey, self::$_cache[$argString]);
125 }
126 }
127
128 return self::$_cache[$argString];
129 }
130
131 /**
132 * Store an item in the DB cache.
133 *
134 * @param object $data
135 * (required) A reference to the data that will be serialized and stored.
136 * @param string $group
137 * (required) The group name of the item.
138 * @param string $path
139 * (required) The path under which this item is stored.
140 * @param int $componentID
141 * The optional component ID (so componenets can share the same name space).
142 */
143 public static function setItem(&$data, $group, $path, $componentID = NULL) {
144 if (self::$_cache === NULL) {
145 self::$_cache = array();
146 }
147
148 // get a lock so that multiple ajax requests on the same page
149 // dont trample on each other
150 // CRM-11234
151 $lock = Civi::lockManager()->acquire("cache.{$group}_{$path}._{$componentID}");
152 if (!$lock->isAcquired()) {
153 CRM_Core_Error::fatal();
154 }
155
156 $table = self::getTableName();
157 $where = self::whereCache($group, $path, $componentID);
158 $dataExists = CRM_Core_DAO::singleValueQuery("SELECT COUNT(*) FROM $table WHERE {$where}");
159 $now = date('Y-m-d H:i:s'); // FIXME - Use SQL NOW() or CRM_Utils_Time?
160 $dataSerialized = self::encode($data);
161
162 // This table has a wonky index, so we cannot use REPLACE or
163 // "INSERT ... ON DUPE". Instead, use SELECT+(INSERT|UPDATE).
164 if ($dataExists) {
165 $sql = "UPDATE $table SET data = %1, created_date = %2 WHERE {$where}";
166 $args = array(
167 1 => array($dataSerialized, 'String'),
168 2 => array($now, 'String'),
169 );
170 $dao = CRM_Core_DAO::executeQuery($sql, $args, TRUE, NULL, FALSE, FALSE);
171 }
172 else {
173 $insert = CRM_Utils_SQL_Insert::into($table)
174 ->row(array(
175 'group_name' => $group,
176 'path' => $path,
177 'component_id' => $componentID,
178 'data' => $dataSerialized,
179 'created_date' => $now,
180 ));
181 $dao = CRM_Core_DAO::executeQuery($insert->toSQL(), array(), TRUE, NULL, FALSE, FALSE);
182 }
183
184 $lock->release();
185
186 $dao->free();
187
188 // cache coherency - refresh or remove dependent caches
189
190 $argString = "CRM_CT_{$group}_{$path}_{$componentID}";
191 $cache = CRM_Utils_Cache::singleton();
192 $data = self::decode($dataSerialized);
193 self::$_cache[$argString] = $data;
194 $cache->set(self::cleanKey($argString), $data);
195
196 $argString = "CRM_CT_CI_{$group}_{$componentID}";
197 unset(self::$_cache[$argString]);
198 $cache->delete(self::cleanKey($argString));
199 }
200
201 /**
202 * Delete all the cache elements that belong to a group OR delete the entire cache if group is not specified.
203 *
204 * @param string $group
205 * The group name of the entries to be deleted.
206 * @param string $path
207 * Path of the item that needs to be deleted.
208 * @param bool $clearAll clear all caches
209 */
210 public static function deleteGroup($group = NULL, $path = NULL, $clearAll = TRUE) {
211 $table = self::getTableName();
212 $where = self::whereCache($group, $path, NULL);
213 CRM_Core_DAO::executeQuery("DELETE FROM $table WHERE $where");
214
215 if ($clearAll) {
216 // also reset ACL Cache
217 CRM_ACL_BAO_Cache::resetCache();
218
219 // also reset memory cache if any
220 CRM_Utils_System::flushCache();
221 }
222 }
223
224 /**
225 * The next two functions are internal functions used to store and retrieve session from
226 * the database cache. This keeps the session to a limited size and allows us to
227 * create separate session scopes for each form in a tab
228 */
229
230 /**
231 * This function takes entries from the session array and stores it in the cache.
232 *
233 * It also deletes the entries from the $_SESSION object (for a smaller session size)
234 *
235 * @param array $names
236 * Array of session values that should be persisted.
237 * This is either a form name + qfKey or just a form name
238 * (in the case of profile)
239 * @param bool $resetSession
240 * Should session state be reset on completion of DB store?.
241 */
242 public static function storeSessionToCache($names, $resetSession = TRUE) {
243 foreach ($names as $key => $sessionName) {
244 if (is_array($sessionName)) {
245 $value = NULL;
246 if (!empty($_SESSION[$sessionName[0]][$sessionName[1]])) {
247 $value = $_SESSION[$sessionName[0]][$sessionName[1]];
248 }
249 $key = "{$sessionName[0]}_{$sessionName[1]}";
250 Civi::cache('session')->set($key, $value, self::pickSessionTtl($key));
251 if ($resetSession) {
252 $_SESSION[$sessionName[0]][$sessionName[1]] = NULL;
253 unset($_SESSION[$sessionName[0]][$sessionName[1]]);
254 }
255 }
256 else {
257 $value = NULL;
258 if (!empty($_SESSION[$sessionName])) {
259 $value = $_SESSION[$sessionName];
260 }
261 Civi::cache('session')->set($sessionName, $value, self::pickSessionTtl($sessionName));
262 if ($resetSession) {
263 $_SESSION[$sessionName] = NULL;
264 unset($_SESSION[$sessionName]);
265 }
266 }
267 }
268
269 self::cleanup();
270 }
271
272 /* Retrieve the session values from the cache and populate the $_SESSION array
273 *
274 * @param array $names
275 * Array of session values that should be persisted.
276 * This is either a form name + qfKey or just a form name
277 * (in the case of profile)
278 */
279
280 /**
281 * Restore session from cache.
282 *
283 * @param string $names
284 */
285 public static function restoreSessionFromCache($names) {
286 foreach ($names as $key => $sessionName) {
287 if (is_array($sessionName)) {
288 $value = Civi::cache('session')->get("{$sessionName[0]}_{$sessionName[1]}");
289 if ($value) {
290 $_SESSION[$sessionName[0]][$sessionName[1]] = $value;
291 }
292 }
293 else {
294 $value = Civi::cache('session')->get($sessionName);
295 if ($value) {
296 $_SESSION[$sessionName] = $value;
297 }
298 }
299 }
300 }
301
302 /**
303 * Determine how long session-state should be retained.
304 *
305 * @param string $sessionKey
306 * Ex: '_CRM_Admin_Form_Preferences_Display_f1a5f232e3d850a29a7a4d4079d7c37b_4654_container'
307 * Ex: 'CiviCRM_CRM_Admin_Form_Preferences_Display_f1a5f232e3d850a29a7a4d4079d7c37b_4654'
308 * @return int
309 * Number of seconds.
310 */
311 protected static function pickSessionTtl($sessionKey) {
312 $secureSessionTimeoutMinutes = (int) Civi::settings()->get('secure_cache_timeout_minutes');
313 if ($secureSessionTimeoutMinutes) {
314 $transactionPages = array(
315 'CRM_Contribute_Controller_Contribution',
316 'CRM_Event_Controller_Registration',
317 );
318 foreach ($transactionPages as $transactionPage) {
319 if (strpos($sessionKey, $transactionPage) !== FALSE) {
320 return $secureSessionTimeoutMinutes * 60;
321 }
322 }
323 }
324
325 return self::DEFAULT_SESSION_TTL;
326 }
327
328 /**
329 * Do periodic cleanup of the CiviCRM session table.
330 *
331 * Also delete all session cache entries which are a couple of days old.
332 * This keeps the session cache to a manageable size
333 * Delete Contribution page session caches more energetically.
334 *
335 * @param bool $session
336 * @param bool $table
337 * @param bool $prevNext
338 */
339 public static function cleanup($session = FALSE, $table = FALSE, $prevNext = FALSE, $expired = FALSE) {
340 // clean up the session cache every $cacheCleanUpNumber probabilistically
341 $cleanUpNumber = 757;
342
343 // clean up all sessions older than $cacheTimeIntervalDays days
344 $timeIntervalDays = 2;
345
346 if (mt_rand(1, 100000) % $cleanUpNumber == 0) {
347 $expired = $session = $table = $prevNext = TRUE;
348 }
349
350 if (!$session && !$table && !$prevNext && !$expired) {
351 return;
352 }
353
354 if ($prevNext) {
355 // delete all PrevNext caches
356 CRM_Core_BAO_PrevNextCache::cleanupCache();
357 }
358
359 if ($table) {
360 CRM_Core_Config::clearTempTables($timeIntervalDays . ' day');
361 }
362
363 if ($session) {
364 // Session caches are just regular caches, so they expire naturally per TTL.
365 $expired = TRUE;
366 }
367
368 if ($expired) {
369 $sql = "DELETE FROM civicrm_cache WHERE expired_date < %1";
370 $params = [
371 1 => [date(CRM_Utils_Cache_SqlGroup::TS_FMT, CRM_Utils_Time::getTimeRaw()), 'String'],
372 ];
373 CRM_Core_DAO::executeQuery($sql, $params);
374 }
375 }
376
377 /**
378 * (Quasi-private) Encode an object/array/string/int as a string.
379 *
380 * @param $mixed
381 * @return string
382 */
383 public static function encode($mixed) {
384 return base64_encode(serialize($mixed));
385 }
386
387 /**
388 * (Quasi-private) Decode an object/array/string/int from a string.
389 *
390 * @param $string
391 * @return mixed
392 */
393 public static function decode($string) {
394 // Upgrade support -- old records (serialize) always have this punctuation,
395 // and new records (base64) never do.
396 if (strpos($string, ':') !== FALSE || strpos($string, ';') !== FALSE) {
397 return unserialize($string);
398 }
399 else {
400 return unserialize(base64_decode($string));
401 }
402 }
403
404 /**
405 * Compose a SQL WHERE clause for the cache.
406 *
407 * Note: We need to use the cache during bootstrap, so we don't have
408 * full access to DAO services.
409 *
410 * @param string $group
411 * @param string|NULL $path
412 * Filter by path. If NULL, then return any paths.
413 * @param int|NULL $componentID
414 * Filter by component. If NULL, then look for explicitly NULL records.
415 * @return string
416 */
417 protected static function whereCache($group, $path, $componentID) {
418 $clauses = array();
419 $clauses[] = ('group_name = "' . CRM_Core_DAO::escapeString($group) . '"');
420 if ($path) {
421 $clauses[] = ('path = "' . CRM_Core_DAO::escapeString($path) . '"');
422 }
423 if ($componentID && is_numeric($componentID)) {
424 $clauses[] = ('component_id = ' . (int) $componentID);
425 }
426 return $clauses ? implode(' AND ', $clauses) : '(1)';
427 }
428
429 /**
430 * Normalize a cache key.
431 *
432 * This bridges an impedance mismatch between our traditional caching
433 * and PSR-16 -- PSR-16 accepts a narrower range of cache keys.
434 *
435 * @param string $key
436 * Ex: 'ab/cd:ef'
437 * @return string
438 * Ex: '_abcd1234abcd1234' or 'ab_xx/cd_xxef'.
439 * A similar key, but suitable for use with PSR-16-compliant cache providers.
440 */
441 public static function cleanKey($key) {
442 if (!is_string($key) && !is_int($key)) {
443 throw new \RuntimeException("Malformed cache key");
444 }
445
446 $maxLen = 64;
447 $escape = '-';
448
449 if (strlen($key) >= $maxLen) {
450 return $escape . md5($key);
451 }
452
453 $r = preg_replace_callback(';[^A-Za-z0-9_\.];', function($m) use ($escape) {
454 return $escape . dechex(ord($m[0]));
455 }, $key);
456
457 return strlen($r) >= $maxLen ? $escape . md5($key) : $r;
458 }
459
460 }