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