Merge branch 4.6 into master
[civicrm-core.git] / CRM / Core / BAO / Cache.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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. This is a database cache and is persisted across sessions. Typically we use
30 * this to store meta data (like profile fields, custom fields etc).
31 *
32 * The group_name column is used for grouping together all cache elements that logically belong to the same set.
33 * Thus all session cache entries are grouped under 'CiviCRM Session'. This allows us to delete all entries of
34 * a specific group if needed.
35 *
36 * The path column allows us to differentiate between items in that group. Thus for the session cache, the path is
37 * the unique form name for each form (per user)
38 */
39 class CRM_Core_BAO_Cache extends CRM_Core_DAO_Cache {
40
41 /**
42 * @var array ($cacheKey => $cacheValue)
43 */
44 static $_cache = NULL;
45
46 /**
47 * Retrieve an item from the DB cache.
48 *
49 * @param string $group
50 * (required) The group name of the item.
51 * @param string $path
52 * (required) The path under which this item is stored.
53 * @param int $componentID
54 * The optional component ID (so componenets can share the same name space).
55 *
56 * @return object
57 * The data if present in cache, else null
58 */
59 public static function &getItem($group, $path, $componentID = NULL) {
60 if (self::$_cache === NULL) {
61 self::$_cache = array();
62 }
63
64 $argString = "CRM_CT_{$group}_{$path}_{$componentID}";
65 if (!array_key_exists($argString, self::$_cache)) {
66 $cache = CRM_Utils_Cache::singleton();
67 self::$_cache[$argString] = $cache->get($argString);
68 if (!self::$_cache[$argString]) {
69 $dao = new CRM_Core_DAO_Cache();
70
71 $dao->group_name = $group;
72 $dao->path = $path;
73 $dao->component_id = $componentID;
74
75 $data = NULL;
76 if ($dao->find(TRUE)) {
77 $data = unserialize($dao->data);
78 }
79 $dao->free();
80 self::$_cache[$argString] = $data;
81 $cache->set($argString, self::$_cache[$argString]);
82 }
83 }
84 return self::$_cache[$argString];
85 }
86
87 /**
88 * Retrieve all items in a group.
89 *
90 * @param string $group
91 * (required) The group name of the item.
92 * @param int $componentID
93 * The optional component ID (so componenets can share the same name space).
94 *
95 * @return object
96 * The data if present in cache, else null
97 */
98 public static function &getItems($group, $componentID = NULL) {
99 if (self::$_cache === NULL) {
100 self::$_cache = array();
101 }
102
103 $argString = "CRM_CT_CI_{$group}_{$componentID}";
104 if (!array_key_exists($argString, self::$_cache)) {
105 $cache = CRM_Utils_Cache::singleton();
106 self::$_cache[$argString] = $cache->get($argString);
107 if (!self::$_cache[$argString]) {
108 $dao = new CRM_Core_DAO_Cache();
109
110 $dao->group_name = $group;
111 $dao->component_id = $componentID;
112 $dao->find();
113
114 $result = array();
115 while ($dao->fetch()) {
116 $result[$dao->path] = unserialize($dao->data);
117 }
118 $dao->free();
119
120 self::$_cache[$argString] = $result;
121 $cache->set($argString, self::$_cache[$argString]);
122 }
123 }
124
125 return self::$_cache[$argString];
126 }
127
128 /**
129 * Store an item in the DB cache.
130 *
131 * @param object $data
132 * (required) A reference to the data that will be serialized and stored.
133 * @param string $group
134 * (required) The group name of the item.
135 * @param string $path
136 * (required) The path under which this item is stored.
137 * @param int $componentID
138 * The optional component ID (so componenets can share the same name space).
139 */
140 public static function setItem(&$data, $group, $path, $componentID = NULL) {
141 if (self::$_cache === NULL) {
142 self::$_cache = array();
143 }
144
145 $dao = new CRM_Core_DAO_Cache();
146
147 $dao->group_name = $group;
148 $dao->path = $path;
149 $dao->component_id = $componentID;
150
151 // get a lock so that multiple ajax requests on the same page
152 // dont trample on each other
153 // CRM-11234
154 $lockName = "civicrm.cache.{$group}_{$path}._{$componentID}";
155 $lock = new CRM_Core_Lock($lockName);
156 if (!$lock->isAcquired()) {
157 CRM_Core_Error::fatal();
158 }
159
160 $dao->find(TRUE);
161 $dao->data = serialize($data);
162 $dao->created_date = date('YmdHis');
163 $dao->save();
164
165 $lock->release();
166
167 $dao->free();
168
169 // cache coherency - refresh or remove dependent caches
170
171 $argString = "CRM_CT_{$group}_{$path}_{$componentID}";
172 $cache = CRM_Utils_Cache::singleton();
173 $data = unserialize($dao->data);
174 self::$_cache[$argString] = $data;
175 $cache->set($argString, $data);
176
177 $argString = "CRM_CT_CI_{$group}_{$componentID}";
178 unset(self::$_cache[$argString]);
179 $cache->delete($argString);
180 }
181
182 /**
183 * Delete all the cache elements that belong to a group OR delete the entire cache if group is not specified.
184 *
185 * @param string $group
186 * The group name of the entries to be deleted.
187 * @param string $path
188 * Path of the item that needs to be deleted.
189 * @param bool $clearAll clear all caches
190 */
191 public static function deleteGroup($group = NULL, $path = NULL, $clearAll = TRUE) {
192 $dao = new CRM_Core_DAO_Cache();
193
194 if (!empty($group)) {
195 $dao->group_name = $group;
196 }
197
198 if (!empty($path)) {
199 $dao->path = $path;
200 }
201
202 $dao->delete();
203
204 if ($clearAll) {
205 // also reset ACL Cache
206 CRM_ACL_BAO_Cache::resetCache();
207
208 // also reset memory cache if any
209 CRM_Utils_System::flushCache();
210 }
211 }
212
213 /**
214 * The next two functions are internal functions used to store and retrieve session from
215 * the database cache. This keeps the session to a limited size and allows us to
216 * create separate session scopes for each form in a tab
217 */
218
219 /**
220 * This function takes entries from the session array and stores it in the cache.
221 *
222 * It also deletes the entries from the $_SESSION object (for a smaller session size)
223 *
224 * @param array $names
225 * Array of session values that should be persisted.
226 * This is either a form name + qfKey or just a form name
227 * (in the case of profile)
228 * @param bool $resetSession
229 * Should session state be reset on completion of DB store?.
230 */
231 public static function storeSessionToCache($names, $resetSession = TRUE) {
232 foreach ($names as $key => $sessionName) {
233 if (is_array($sessionName)) {
234 $value = NULL;
235 if (!empty($_SESSION[$sessionName[0]][$sessionName[1]])) {
236 $value = $_SESSION[$sessionName[0]][$sessionName[1]];
237 }
238 self::setItem($value, 'CiviCRM Session', "{$sessionName[0]}_{$sessionName[1]}");
239 if ($resetSession) {
240 $_SESSION[$sessionName[0]][$sessionName[1]] = NULL;
241 unset($_SESSION[$sessionName[0]][$sessionName[1]]);
242 }
243 }
244 else {
245 $value = NULL;
246 if (!empty($_SESSION[$sessionName])) {
247 $value = $_SESSION[$sessionName];
248 }
249 self::setItem($value, 'CiviCRM Session', $sessionName);
250 if ($resetSession) {
251 $_SESSION[$sessionName] = NULL;
252 unset($_SESSION[$sessionName]);
253 }
254 }
255 }
256
257 self::cleanup();
258 }
259
260 /* Retrieve the session values from the cache and populate the $_SESSION array
261 *
262 * @param array $names
263 * Array of session values that should be persisted.
264 * This is either a form name + qfKey or just a form name
265 * (in the case of profile)
266 *
267 * @return void
268 */
269
270 /**
271 * Restore session from cache.
272 *
273 * @param string $names
274 */
275 public static function restoreSessionFromCache($names) {
276 foreach ($names as $key => $sessionName) {
277 if (is_array($sessionName)) {
278 $value = self::getItem('CiviCRM Session',
279 "{$sessionName[0]}_{$sessionName[1]}"
280 );
281 if ($value) {
282 $_SESSION[$sessionName[0]][$sessionName[1]] = $value;
283 }
284 }
285 else {
286 $value = self::getItem('CiviCRM Session',
287 $sessionName
288 );
289 if ($value) {
290 $_SESSION[$sessionName] = $value;
291 }
292 }
293 }
294 }
295
296 /**
297 * Do periodic cleanup of the CiviCRM session table.
298 *
299 * Also delete all session cache entries which are a couple of days old.
300 * This keeps the session cache to a manageable size
301 *
302 * @param bool $session
303 * @param bool $table
304 * @param bool $prevNext
305 */
306 public static function cleanup($session = FALSE, $table = FALSE, $prevNext = FALSE) {
307 // clean up the session cache every $cacheCleanUpNumber probabilistically
308 $cleanUpNumber = 757;
309
310 // clean up all sessions older than $cacheTimeIntervalDays days
311 $timeIntervalDays = 2;
312 $timeIntervalMins = 30;
313
314 if (mt_rand(1, 100000) % $cleanUpNumber == 0) {
315 $session = $table = $prevNext = TRUE;
316 }
317
318 if (!$session && !$table && !$prevNext) {
319 return;
320 }
321
322 if ($prevNext) {
323 // delete all PrevNext caches
324 CRM_Core_BAO_PrevNextCache::cleanupCache();
325 }
326
327 if ($table) {
328 CRM_Core_Config::clearTempTables($timeIntervalDays . ' day');
329 }
330
331 if ($session) {
332 // first delete all sessions which are related to any potential transaction
333 // page
334 $transactionPages = array(
335 'CRM_Contribute_Controller_Contribution',
336 'CRM_Event_Controller_Registration',
337 );
338
339 $params = array(
340 1 => array(
341 date('Y-m-d H:i:s', time() - $timeIntervalMins * 60),
342 'String',
343 ),
344 );
345 foreach ($transactionPages as $trPage) {
346 $params[] = array("%${trPage}%", 'String');
347 $where[] = 'path LIKE %' . count($params);
348 }
349
350 $sql = "
351 DELETE FROM civicrm_cache
352 WHERE group_name = 'CiviCRM Session'
353 AND created_date <= %1
354 AND (" . implode(' OR ', $where) . ")";
355 CRM_Core_DAO::executeQuery($sql, $params);
356
357 $sql = "
358 DELETE FROM civicrm_cache
359 WHERE group_name = 'CiviCRM Session'
360 AND created_date < date_sub( NOW( ), INTERVAL $timeIntervalDays DAY )
361 ";
362 CRM_Core_DAO::executeQuery($sql);
363 }
364 }
365
366 }