Merge pull request #13993 from eileenmcnaughton/recur_fixes
[civicrm-core.git] / CRM / Core / BAO / PrevNextCache.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 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2019
32 */
33
34 /**
35 * BAO object for civicrm_prevnext_cache table.
36 */
37 class CRM_Core_BAO_PrevNextCache extends CRM_Core_DAO_PrevNextCache {
38
39 /**
40 * Get the previous and next keys.
41 *
42 * @param string $cacheKey
43 * @param int $id1
44 * @param int $id2
45 * @param int $mergeId
46 * @param string $join
47 * @param string $where
48 * @param bool $flip
49 *
50 * @return array
51 */
52 public static function getPositions($cacheKey, $id1, $id2, &$mergeId = NULL, $join = NULL, $where = NULL, $flip = FALSE) {
53 if ($flip) {
54 list($id1, $id2) = [$id2, $id1];
55 }
56
57 if ($mergeId == NULL) {
58 $query = "
59 SELECT id
60 FROM civicrm_prevnext_cache
61 WHERE cacheKey = %3 AND
62 entity_id1 = %1 AND
63 entity_id2 = %2 AND
64 entity_table = 'civicrm_contact'
65 ";
66
67 $params = [
68 1 => [$id1, 'Integer'],
69 2 => [$id2, 'Integer'],
70 3 => [$cacheKey, 'String'],
71 ];
72
73 $mergeId = CRM_Core_DAO::singleValueQuery($query, $params);
74 }
75
76 $pos = ['foundEntry' => 0];
77 if ($mergeId) {
78 $pos['foundEntry'] = 1;
79
80 if ($where) {
81
82 $where = " AND {$where}";
83
84 }
85 $p = [
86 1 => [$mergeId, 'Integer'],
87 2 => [$cacheKey, 'String'],
88 ];
89 $sql = "SELECT pn.id, pn.entity_id1, pn.entity_id2, pn.data FROM civicrm_prevnext_cache pn {$join} ";
90 $wherePrev = " WHERE pn.id < %1 AND pn.cacheKey = %2 {$where} ORDER BY ID DESC LIMIT 1";
91 $sqlPrev = $sql . $wherePrev;
92
93 $dao = CRM_Core_DAO::executeQuery($sqlPrev, $p);
94 if ($dao->fetch()) {
95 $pos['prev']['id1'] = $dao->entity_id1;
96 $pos['prev']['id2'] = $dao->entity_id2;
97 $pos['prev']['mergeId'] = $dao->id;
98 $pos['prev']['data'] = $dao->data;
99 }
100
101 $whereNext = " WHERE pn.id > %1 AND pn.cacheKey = %2 {$where} ORDER BY ID ASC LIMIT 1";
102 $sqlNext = $sql . $whereNext;
103
104 $dao = CRM_Core_DAO::executeQuery($sqlNext, $p);
105 if ($dao->fetch()) {
106 $pos['next']['id1'] = $dao->entity_id1;
107 $pos['next']['id2'] = $dao->entity_id2;
108 $pos['next']['mergeId'] = $dao->id;
109 $pos['next']['data'] = $dao->data;
110 }
111 }
112 return $pos;
113 }
114
115 /**
116 * Delete an item from the prevnext cache table based on the entity.
117 *
118 * @param int $id
119 * @param string $cacheKey
120 * @param string $entityTable
121 */
122 public static function deleteItem($id = NULL, $cacheKey = NULL, $entityTable = 'civicrm_contact') {
123
124 //clear cache
125 $sql = "DELETE FROM civicrm_prevnext_cache WHERE entity_table = %1";
126 $params = [1 => [$entityTable, 'String']];
127
128 if (is_numeric($id)) {
129 $sql .= " AND ( entity_id1 = %2 OR entity_id2 = %2 )";
130 $params[2] = [$id, 'Integer'];
131 }
132
133 if (isset($cacheKey)) {
134 $sql .= " AND cacheKey LIKE %3";
135 $params[3] = ["{$cacheKey}%", 'String'];
136 }
137 CRM_Core_DAO::executeQuery($sql, $params);
138 }
139
140 /**
141 * Delete from the previous next cache table for a pair of ids.
142 *
143 * @param int $id1
144 * @param int $id2
145 * @param string $cacheKey
146 * @param bool $isViceVersa
147 * @param string $entityTable
148 */
149 public static function deletePair($id1, $id2, $cacheKey = NULL, $isViceVersa = FALSE, $entityTable = 'civicrm_contact') {
150 $sql = "DELETE FROM civicrm_prevnext_cache WHERE entity_table = %1";
151 $params = [1 => [$entityTable, 'String']];
152
153 $pair = !$isViceVersa ? "entity_id1 = %2 AND entity_id2 = %3" : "(entity_id1 = %2 AND entity_id2 = %3) OR (entity_id1 = %3 AND entity_id2 = %2)";
154 $sql .= " AND ( {$pair} )";
155 $params[2] = [$id1, 'Integer'];
156 $params[3] = [$id2, 'Integer'];
157
158 if (isset($cacheKey)) {
159 $sql .= " AND cacheKey LIKE %4";
160 // used % to address any row with conflict-cacheKey e.g "merge Individual_8_0_conflicts"
161 $params[4] = ["{$cacheKey}%", 'String'];
162 }
163
164 CRM_Core_DAO::executeQuery($sql, $params);
165 }
166
167 /**
168 * Mark contacts as being in conflict.
169 *
170 * @param int $id1
171 * @param int $id2
172 * @param string $cacheKey
173 * @param array $conflicts
174 *
175 * @return bool
176 */
177 public static function markConflict($id1, $id2, $cacheKey, $conflicts) {
178 if (empty($cacheKey) || empty($conflicts)) {
179 return FALSE;
180 }
181
182 $sql = "SELECT pn.*
183 FROM civicrm_prevnext_cache pn
184 WHERE
185 ((pn.entity_id1 = %1 AND pn.entity_id2 = %2) OR (pn.entity_id1 = %2 AND pn.entity_id2 = %1)) AND
186 (cacheKey = %3 OR cacheKey = %4)";
187 $params = [
188 1 => [$id1, 'Integer'],
189 2 => [$id2, 'Integer'],
190 3 => ["{$cacheKey}", 'String'],
191 4 => ["{$cacheKey}_conflicts", 'String'],
192 ];
193 $pncFind = CRM_Core_DAO::executeQuery($sql, $params);
194
195 while ($pncFind->fetch()) {
196 $data = $pncFind->data;
197 if (!empty($data)) {
198 $data = unserialize($data);
199 $data['conflicts'] = implode(",", array_values($conflicts));
200
201 $pncUp = new CRM_Core_DAO_PrevNextCache();
202 $pncUp->id = $pncFind->id;
203 if ($pncUp->find(TRUE)) {
204 $pncUp->data = serialize($data);
205 $pncUp->cacheKey = "{$cacheKey}_conflicts";
206 $pncUp->save();
207 }
208 }
209 }
210 return TRUE;
211 }
212
213 /**
214 * Retrieve from prev-next cache.
215 *
216 * This function is used from a variety of merge related functions, although
217 * it would probably be good to converge on calling CRM_Dedupe_Merger::getDuplicatePairs.
218 *
219 * We seem to currently be storing stats in this table too & they might make more sense in
220 * the main cache table.
221 *
222 * @param string $cacheKey
223 * @param string $join
224 * @param string $whereClause
225 * @param int $offset
226 * @param int $rowCount
227 * @param array $select
228 * @param string $orderByClause
229 * @param bool $includeConflicts
230 * Should we return rows that have already been idenfified as having a conflict.
231 * When this is TRUE you should be careful you do not set up a loop.
232 * @param array $params
233 *
234 * @return array
235 */
236 public static function retrieve($cacheKey, $join = NULL, $whereClause = NULL, $offset = 0, $rowCount = 0, $select = [], $orderByClause = '', $includeConflicts = TRUE, $params = []) {
237 $selectString = 'pn.*';
238
239 if (!empty($select)) {
240 $aliasArray = [];
241 foreach ($select as $column => $alias) {
242 $aliasArray[] = $column . ' as ' . $alias;
243 }
244 $selectString .= " , " . implode(' , ', $aliasArray);
245 }
246
247 $params = [
248 1 => [$cacheKey, 'String'],
249 ] + $params;
250
251 if (!empty($whereClause)) {
252 $whereClause = " AND " . $whereClause;
253 }
254 if ($includeConflicts) {
255 $where = ' WHERE (pn.cacheKey = %1 OR pn.cacheKey = %2)' . $whereClause;
256 $params[2] = ["{$cacheKey}_conflicts", 'String'];
257 }
258 else {
259 $where = ' WHERE (pn.cacheKey = %1)' . $whereClause;
260 }
261
262 $query = "
263 SELECT SQL_CALC_FOUND_ROWS {$selectString}
264 FROM civicrm_prevnext_cache pn
265 {$join}
266 $where
267 $orderByClause
268 ";
269
270 if ($rowCount) {
271 $offset = CRM_Utils_Type::escape($offset, 'Int');
272 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
273
274 $query .= " LIMIT {$offset}, {$rowCount}";
275 }
276
277 $dao = CRM_Core_DAO::executeQuery($query, $params);
278
279 $main = [];
280 $count = 0;
281 while ($dao->fetch()) {
282 if (self::is_serialized($dao->data)) {
283 $main[$count] = unserialize($dao->data);
284 }
285 else {
286 $main[$count] = $dao->data;
287 }
288
289 if (!empty($select)) {
290 $extraData = [];
291 foreach ($select as $sfield) {
292 $extraData[$sfield] = $dao->$sfield;
293 }
294 $main[$count] = [
295 'prevnext_id' => $dao->id,
296 'is_selected' => $dao->is_selected,
297 'entity_id1' => $dao->entity_id1,
298 'entity_id2' => $dao->entity_id2,
299 'data' => $main[$count],
300 ];
301 $main[$count] = array_merge($main[$count], $extraData);
302 }
303 $count++;
304 }
305
306 return $main;
307 }
308
309 /**
310 * @param $string
311 *
312 * @return bool
313 */
314 public static function is_serialized($string) {
315 return (@unserialize($string) !== FALSE);
316 }
317
318 /**
319 * @param $values
320 */
321 public static function setItem($values) {
322 $insert = "INSERT INTO civicrm_prevnext_cache ( entity_table, entity_id1, entity_id2, cacheKey, data ) VALUES \n";
323 $query = $insert . implode(",\n ", $values);
324
325 //dump the dedupe matches in the prevnext_cache table
326 CRM_Core_DAO::executeQuery($query);
327 }
328
329 /**
330 * Get count of matching rows.
331 *
332 * @param string $cacheKey
333 * @param string $join
334 * @param string $where
335 * @param string $op
336 * @param array $params
337 * Extra query params to parse into the query.
338 *
339 * @return int
340 */
341 public static function getCount($cacheKey, $join = NULL, $where = NULL, $op = "=", $params = []) {
342 $query = "
343 SELECT COUNT(*) FROM civicrm_prevnext_cache pn
344 {$join}
345 WHERE (pn.cacheKey $op %1 OR pn.cacheKey $op %2)
346 ";
347 if ($where) {
348 $query .= " AND {$where}";
349 }
350
351 $params = [
352 1 => [$cacheKey, 'String'],
353 2 => ["{$cacheKey}_conflicts", 'String'],
354 ] + $params;
355 return (int) CRM_Core_DAO::singleValueQuery($query, $params, TRUE, FALSE);
356 }
357
358 /**
359 * Repopulate the cache of merge prospects.
360 *
361 * @param int $rgid
362 * @param int $gid
363 * @param NULL $cacheKeyString
364 * @param array $criteria
365 * Additional criteria to filter by.
366 *
367 * @param bool $checkPermissions
368 * Respect logged in user's permissions.
369 *
370 * @param int $searchLimit
371 * Limit for the number of contacts to be used for comparison.
372 * The search methodology finds all matches for the searchedContacts so this limits
373 * the number of searched contacts, not the matches found.
374 *
375 * @return bool
376 * @throws \CRM_Core_Exception
377 * @throws \CiviCRM_API3_Exception
378 */
379 public static function refillCache($rgid, $gid, $cacheKeyString, $criteria, $checkPermissions, $searchLimit = 0) {
380 if (!$cacheKeyString && $rgid) {
381 $cacheKeyString = CRM_Dedupe_Merger::getMergeCacheKeyString($rgid, $gid, $criteria, $checkPermissions);
382 }
383
384 if (!$cacheKeyString) {
385 return FALSE;
386 }
387
388 // 1. Clear cache if any
389 $sql = "DELETE FROM civicrm_prevnext_cache WHERE cacheKey LIKE %1";
390 CRM_Core_DAO::executeQuery($sql, [1 => ["{$cacheKeyString}%", 'String']]);
391
392 // FIXME: we need to start using temp tables / queries here instead of arrays.
393 // And cleanup code in CRM/Contact/Page/DedupeFind.php
394
395 // 2. FILL cache
396 $foundDupes = [];
397 if ($rgid && $gid) {
398 $foundDupes = CRM_Dedupe_Finder::dupesInGroup($rgid, $gid, $searchLimit);
399 }
400 elseif ($rgid) {
401 $contactIDs = [];
402 // The thing we really need to filter out is any chaining that would 'DO SOMETHING' to the DB.
403 // criteria could be passed in via url so we want to ensure nothing could be in that url that
404 // would chain to a delete. Limiting to getfields for 'get' limits us to declared fields,
405 // although we might wish to revisit later to allow joins.
406 $validFieldsForRetrieval = civicrm_api3('Contact', 'getfields', ['action' => 'get'])['values'];
407 if (!empty($criteria)) {
408 $contacts = civicrm_api3('Contact', 'get', array_merge([
409 'options' => ['limit' => 0],
410 'return' => 'id',
411 'check_permissions' => TRUE,
412 ], array_intersect_key($criteria['contact'], $validFieldsForRetrieval)));
413 $contactIDs = array_keys($contacts['values']);
414 }
415 $foundDupes = CRM_Dedupe_Finder::dupes($rgid, $contactIDs, $checkPermissions, $searchLimit);
416 }
417
418 if (!empty($foundDupes)) {
419 CRM_Dedupe_Finder::parseAndStoreDupePairs($foundDupes, $cacheKeyString);
420 }
421 }
422
423 public static function cleanupCache() {
424 // clean up all prev next caches older than $cacheTimeIntervalDays days
425 $cacheTimeIntervalDays = 2;
426
427 // first find all the cacheKeys that match this
428 $sql = "
429 DELETE pn, c
430 FROM civicrm_cache c
431 INNER JOIN civicrm_prevnext_cache pn ON c.path = pn.cacheKey
432 WHERE c.group_name = %1
433 AND c.created_date < date_sub( NOW( ), INTERVAL %2 day )
434 ";
435 $params = [
436 1 => ['CiviCRM Search PrevNextCache', 'String'],
437 2 => [$cacheTimeIntervalDays, 'Integer'],
438 ];
439 CRM_Core_DAO::executeQuery($sql, $params);
440 }
441
442 /**
443 * Get the selections.
444 *
445 * NOTE: This stub has been preserved because one extension in `universe`
446 * was referencing the function.
447 *
448 * @deprecated
449 * @see CRM_Core_PrevNextCache_Sql::getSelection()
450 */
451 public static function getSelection($cacheKey, $action = 'get') {
452 return Civi::service('prevnext')->getSelection($cacheKey, $action);
453 }
454
455 /**
456 * Flip 2 contacts in the prevNext cache.
457 *
458 * @param array $prevNextId
459 * @param bool $onlySelected
460 * Only flip those which have been marked as selected.
461 */
462 public static function flipPair(array $prevNextId, $onlySelected) {
463 $dao = new CRM_Core_DAO_PrevNextCache();
464 if ($onlySelected) {
465 $dao->is_selected = 1;
466 }
467 foreach ($prevNextId as $id) {
468 $dao->id = $id;
469 if ($dao->find(TRUE)) {
470 $originalData = unserialize($dao->data);
471 $srcFields = ['ID', 'Name'];
472 $swapFields = ['srcID', 'srcName', 'dstID', 'dstName'];
473 $data = array_diff_assoc($originalData, array_fill_keys($swapFields, 1));
474 foreach ($srcFields as $key) {
475 $data['src' . $key] = $originalData['dst' . $key];
476 $data['dst' . $key] = $originalData['src' . $key];
477 }
478 $dao->data = serialize($data);
479 $dao->entity_id1 = $data['dstID'];
480 $dao->entity_id2 = $data['srcID'];
481 $dao->save();
482 }
483 }
484 }
485
486 /**
487 * Get a list of available backend services.
488 *
489 * @return array
490 * Array(string $id => string $label).
491 */
492 public static function getPrevNextBackends() {
493 return [
494 'default' => ts('Default (Auto-detect)'),
495 'sql' => ts('SQL'),
496 'redis' => ts('Redis'),
497 ];
498 }
499
500 }