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