3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * BAO object for civicrm_prevnext_cache table.
21 class CRM_Core_BAO_PrevNextCache
extends CRM_Core_DAO_PrevNextCache
{
24 * Get the previous and next keys.
26 * @param string $cacheKey
31 * @param string $where
36 public static function getPositions($cacheKey, $id1, $id2, &$mergeId = NULL, $join = NULL, $where = NULL, $flip = FALSE) {
38 list($id1, $id2) = [$id2, $id1];
41 if ($mergeId == NULL) {
44 FROM civicrm_prevnext_cache
45 WHERE cachekey = %3 AND
48 entity_table = 'civicrm_contact'
52 1 => [$id1, 'Integer'],
53 2 => [$id2, 'Integer'],
54 3 => [$cacheKey, 'String'],
57 $mergeId = CRM_Core_DAO
::singleValueQuery($query, $params);
60 $pos = ['foundEntry' => 0];
62 $pos['foundEntry'] = 1;
66 $where = " AND {$where}";
70 1 => [$mergeId, 'Integer'],
71 2 => [$cacheKey, 'String'],
73 $sql = "SELECT pn.id, pn.entity_id1, pn.entity_id2, pn.data FROM civicrm_prevnext_cache pn {$join} ";
74 $wherePrev = " WHERE pn.id < %1 AND pn.cachekey = %2 {$where} ORDER BY ID DESC LIMIT 1";
75 $sqlPrev = $sql . $wherePrev;
77 $dao = CRM_Core_DAO
::executeQuery($sqlPrev, $p);
79 $pos['prev']['id1'] = $dao->entity_id1
;
80 $pos['prev']['id2'] = $dao->entity_id2
;
81 $pos['prev']['mergeId'] = $dao->id
;
82 $pos['prev']['data'] = $dao->data
;
85 $whereNext = " WHERE pn.id > %1 AND pn.cachekey = %2 {$where} ORDER BY ID ASC LIMIT 1";
86 $sqlNext = $sql . $whereNext;
88 $dao = CRM_Core_DAO
::executeQuery($sqlNext, $p);
90 $pos['next']['id1'] = $dao->entity_id1
;
91 $pos['next']['id2'] = $dao->entity_id2
;
92 $pos['next']['mergeId'] = $dao->id
;
93 $pos['next']['data'] = $dao->data
;
100 * Delete an item from the prevnext cache table based on the entity.
103 * @param string $cacheKey
104 * @param string $entityTable
106 public static function deleteItem($id = NULL, $cacheKey = NULL, $entityTable = 'civicrm_contact') {
109 $sql = "DELETE FROM civicrm_prevnext_cache WHERE entity_table = %1";
110 $params = [1 => [$entityTable, 'String']];
112 if (is_numeric($id)) {
113 $sql .= " AND ( entity_id1 = %2 OR entity_id2 = %2 )";
114 $params[2] = [$id, 'Integer'];
117 if (isset($cacheKey)) {
118 $sql .= " AND cachekey LIKE %3";
119 $params[3] = ["{$cacheKey}%", 'String'];
121 CRM_Core_DAO
::executeQuery($sql, $params);
125 * Delete pair from the previous next cache table to remove it from further merge consideration.
127 * The pair may have been flipped, so make sure we delete using both orders
131 * @param string $cacheKey
133 public static function deletePair($id1, $id2, $cacheKey = NULL) {
134 $sql = "DELETE FROM civicrm_prevnext_cache WHERE entity_table = 'civicrm_contact'";
136 $pair = "(entity_id1 = %2 AND entity_id2 = %3) OR (entity_id1 = %3 AND entity_id2 = %2)";
137 $sql .= " AND ( {$pair} )";
138 $params[2] = [$id1, 'Integer'];
139 $params[3] = [$id2, 'Integer'];
141 if (isset($cacheKey)) {
142 $sql .= " AND cachekey LIKE %4";
143 // used % to address any row with conflict-cacheKey e.g "merge Individual_8_0_conflicts"
144 $params[4] = ["{$cacheKey}%", 'String'];
147 CRM_Core_DAO
::executeQuery($sql, $params);
151 * Mark contacts as being in conflict.
155 * @param string $cacheKey
156 * @param array $conflicts
157 * @param string $mode
160 * @throws CRM_Core_Exception
162 public static function markConflict($id1, $id2, $cacheKey, $conflicts, $mode) {
163 if (empty($cacheKey) ||
empty($conflicts)) {
168 FROM civicrm_prevnext_cache pn
170 ((pn.entity_id1 = %1 AND pn.entity_id2 = %2) OR (pn.entity_id1 = %2 AND pn.entity_id2 = %1)) AND
171 (cachekey = %3 OR cachekey = %4)";
173 1 => [$id1, 'Integer'],
174 2 => [$id2, 'Integer'],
175 3 => ["{$cacheKey}", 'String'],
176 4 => ["{$cacheKey}_conflicts", 'String'],
178 $pncFind = CRM_Core_DAO
::executeQuery($sql, $params);
182 foreach ($conflicts as $entity => $entityConflicts) {
183 if ($entity === 'contact') {
184 foreach ($entityConflicts as $conflict) {
185 $conflictTexts[] = "{$conflict['title']}: '{$conflict[$id1]}' vs. '{$conflict[$id2]}'";
189 foreach ($entityConflicts as $locationConflict) {
190 if (!is_array($locationConflict)) {
193 $displayField = CRM_Dedupe_Merger
::getLocationBlockInfo()[$entity]['displayField'];
194 $conflictTexts[] = "{$locationConflict['title']}: '{$locationConflict[$displayField][$id1]}' vs. '{$locationConflict[$displayField][$id2]}'";
198 $conflictString = implode(', ', $conflictTexts);
200 while ($pncFind->fetch()) {
201 $data = $pncFind->data
;
203 $data = CRM_Core_DAO
::unSerializeField($data, CRM_Core_DAO
::SERIALIZE_PHP
);
204 $data['conflicts'] = $conflictString;
205 $data[$mode]['conflicts'] = $conflicts;
207 $pncUp = new CRM_Core_DAO_PrevNextCache();
208 $pncUp->id
= $pncFind->id
;
209 if ($pncUp->find(TRUE)) {
210 $pncUp->data
= serialize($data);
211 $pncUp->cachekey
= "{$cacheKey}_conflicts";
220 * Retrieve from prev-next cache.
222 * This function is used from a variety of merge related functions, although
223 * it would probably be good to converge on calling CRM_Dedupe_Merger::getDuplicatePairs.
225 * We seem to currently be storing stats in this table too & they might make more sense in
226 * the main cache table.
228 * @param string $cacheKey
229 * @param string $join
230 * @param string $whereClause
232 * @param int $rowCount
233 * @param array $select
234 * @param string $orderByClause
235 * @param bool $includeConflicts
236 * Should we return rows that have already been idenfified as having a conflict.
237 * When this is TRUE you should be careful you do not set up a loop.
238 * @param array $params
242 public static function retrieve($cacheKey, $join = NULL, $whereClause = NULL, $offset = 0, $rowCount = 0, $select = [], $orderByClause = '', $includeConflicts = TRUE, $params = []) {
243 $selectString = 'pn.*';
245 if (!empty($select)) {
247 foreach ($select as $column => $alias) {
248 $aliasArray[] = $column . ' as ' . $alias;
250 $selectString .= " , " . implode(' , ', $aliasArray);
254 1 => [$cacheKey, 'String'],
257 if (!empty($whereClause)) {
258 $whereClause = " AND " . $whereClause;
260 if ($includeConflicts) {
261 $where = ' WHERE (pn.cachekey = %1 OR pn.cachekey = %2)' . $whereClause;
262 $params[2] = ["{$cacheKey}_conflicts", 'String'];
265 $where = ' WHERE (pn.cachekey = %1)' . $whereClause;
269 SELECT SQL_CALC_FOUND_ROWS {$selectString}
270 FROM civicrm_prevnext_cache pn
277 $offset = CRM_Utils_Type
::escape($offset, 'Int');
278 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
280 $query .= " LIMIT {$offset}, {$rowCount}";
283 $dao = CRM_Core_DAO
::executeQuery($query, $params);
287 while ($dao->fetch()) {
288 if (self
::is_serialized($dao->data
)) {
289 $main[$count] = CRM_Utils_String
::unserialize($dao->data
);
292 $main[$count] = $dao->data
;
295 if (!empty($select)) {
297 foreach ($select as $sfield) {
298 $extraData[$sfield] = $dao->$sfield;
301 'prevnext_id' => $dao->id
,
302 'is_selected' => $dao->is_selected
,
303 'entity_id1' => $dao->entity_id1
,
304 'entity_id2' => $dao->entity_id2
,
305 'data' => $main[$count],
307 $main[$count] = array_merge($main[$count], $extraData);
320 public static function is_serialized($string) {
321 return (@CRM_Utils_String
::unserialize($string) !== FALSE);
325 * @param string $sqlValues string of SQLValues to insert
328 public static function convertSetItemValues($sqlValues) {
329 $closingBrace = strpos($sqlValues, ')') - strlen($sqlValues);
330 $valueArray = array_map('trim', explode(', ', substr($sqlValues, strpos($sqlValues, '(') +
1, $closingBrace - 1)));
331 foreach ($valueArray as $key => &$value) {
332 // remove any quotes from values.
333 if (substr($value, 0, 1) == "'") {
334 $valueArray[$key] = substr($value, 1, -1);
341 * @param array|string $entity_table
342 * @param int $entity_id1
343 * @param int $entity_id2
344 * @param string $cacheKey
345 * @param string $data
347 public static function setItem($entity_table = NULL, $entity_id1 = NULL, $entity_id2 = NULL, $cacheKey = NULL, $data = NULL) {
348 // If entity table is an array we are passing in an older format where this function only had 1 param $values. We put a deprecation warning.
349 if (!empty($entity_table) && is_array($entity_table)) {
350 Civi
::log()->warning('Deprecated code path. Values should not be set this is going away in the future in favour of specific function params for each column.', array('civi.tag' => 'deprecated'));
351 foreach ($values as $value) {
352 $valueArray = self
::convertSetItemValues($value);
353 self
::setItem($valueArray[0], $valueArray[1], $valueArray[2], $valueArray[3], $valueArray[4]);
357 CRM_Core_DAO
::executeQuery("INSERT INTO civicrm_prevnext_cache (entity_table, entity_id1, entity_id2, cacheKey, data) VALUES
358 (%1, %2, %3, %4, '{$data}')", [
359 1 => [$entity_table, 'String'],
360 2 => [$entity_id1, 'Integer'],
361 3 => [$entity_id2, 'Integer'],
362 4 => [$cacheKey, 'String'],
368 * Get count of matching rows.
370 * @param string $cacheKey
371 * @param string $join
372 * @param string $where
374 * @param array $params
375 * Extra query params to parse into the query.
379 public static function getCount($cacheKey, $join = NULL, $where = NULL, $op = "=", $params = []) {
381 SELECT COUNT(*) FROM civicrm_prevnext_cache pn
383 WHERE (pn.cachekey $op %1 OR pn.cachekey $op %2)
386 $query .= " AND {$where}";
390 1 => [$cacheKey, 'String'],
391 2 => ["{$cacheKey}_conflicts", 'String'],
393 return (int) CRM_Core_DAO
::singleValueQuery($query, $params, TRUE, FALSE);
397 * Repopulate the cache of merge prospects.
401 * @param array $criteria
402 * Additional criteria to filter by.
404 * @param bool $checkPermissions
405 * Respect logged in user's permissions.
407 * @param int $searchLimit
408 * Limit for the number of contacts to be used for comparison.
409 * The search methodology finds all matches for the searchedContacts so this limits
410 * the number of searched contacts, not the matches found.
412 * @throws \CRM_Core_Exception
413 * @throws \CiviCRM_API3_Exception
415 public static function refillCache($rgid, $gid, $criteria, $checkPermissions, $searchLimit = 0) {
416 $cacheKeyString = CRM_Dedupe_Merger
::getMergeCacheKeyString($rgid, $gid, $criteria, $checkPermissions, $searchLimit);
418 // 1. Clear cache if any
419 $sql = "DELETE FROM civicrm_prevnext_cache WHERE cachekey LIKE %1";
420 CRM_Core_DAO
::executeQuery($sql, [1 => ["{$cacheKeyString}%", 'String']]);
422 // FIXME: we need to start using temp tables / queries here instead of arrays.
423 // And cleanup code in CRM/Contact/Page/DedupeFind.php
428 $foundDupes = CRM_Dedupe_Finder
::dupesInGroup($rgid, $gid, $searchLimit);
432 // The thing we really need to filter out is any chaining that would 'DO SOMETHING' to the DB.
433 // criteria could be passed in via url so we want to ensure nothing could be in that url that
434 // would chain to a delete. Limiting to getfields for 'get' limits us to declared fields,
435 // although we might wish to revisit later to allow joins.
436 $validFieldsForRetrieval = civicrm_api3('Contact', 'getfields', ['action' => 'get'])['values'];
437 $filteredCriteria = isset($criteria['contact']) ?
array_intersect_key($criteria['contact'], $validFieldsForRetrieval) : [];
439 if (!empty($criteria) ||
!empty($searchLimit)) {
440 $contacts = civicrm_api3('Contact', 'get', array_merge([
441 'options' => ['limit' => $searchLimit],
443 'check_permissions' => TRUE,
444 'contact_type' => civicrm_api3('RuleGroup', 'getvalue', ['id' => $rgid, 'return' => 'contact_type']),
445 ], $filteredCriteria));
446 $contactIDs = array_keys($contacts['values']);
448 if (empty($contactIDs)) {
449 // If there is criteria but no contacts were found then we should return now
450 // since we have no contacts to match.
454 $foundDupes = CRM_Dedupe_Finder
::dupes($rgid, $contactIDs, $checkPermissions);
457 if (!empty($foundDupes)) {
458 CRM_Dedupe_Finder
::parseAndStoreDupePairs($foundDupes, $cacheKeyString);
462 public static function cleanupCache() {
463 Civi
::service('prevnext')->cleanup();
467 * Get the selections.
469 * NOTE: This stub has been preserved because one extension in `universe`
470 * was referencing the function.
473 * @see CRM_Core_PrevNextCache_Sql::getSelection()
475 public static function getSelection($cacheKey, $action = 'get') {
476 return Civi
::service('prevnext')->getSelection($cacheKey, $action);
480 * Flip 2 contacts in the prevNext cache.
482 * @param array $prevNextId
483 * @param bool $onlySelected
484 * Only flip those which have been marked as selected.
486 public static function flipPair(array $prevNextId, $onlySelected) {
487 $dao = new CRM_Core_DAO_PrevNextCache();
489 $dao->is_selected
= 1;
491 foreach ($prevNextId as $id) {
493 if ($dao->find(TRUE)) {
494 $originalData = CRM_Utils_String
::unserialize($dao->data
);
495 $srcFields = ['ID', 'Name'];
496 $swapFields = ['srcID', 'srcName', 'dstID', 'dstName'];
497 $data = array_diff_assoc($originalData, array_fill_keys($swapFields, 1));
498 foreach ($srcFields as $key) {
499 $data['src' . $key] = $originalData['dst' . $key];
500 $data['dst' . $key] = $originalData['src' . $key];
502 $dao->data
= serialize($data);
503 $dao->entity_id1
= $data['dstID'];
504 $dao->entity_id2
= $data['srcID'];
511 * Get a list of available backend services.
514 * Array(string $id => string $label).
516 public static function getPrevNextBackends() {
518 'default' => ts('Default (Auto-detect)'),
520 'redis' => ts('Redis'),
525 * Generate and assign an arbitrary value to a field of a test object.
527 * This specifically supports testing the dedupe use case.
529 * @param string $fieldName
530 * @param array $fieldDef
531 * @param int $counter
532 * The globally-unique ID of the test object.
534 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
535 if ($fieldName === 'cachekey') {
536 $this->cachekey
= 'merge_' . rand();
539 if ($fieldName === 'data') {
540 $this->data
= serialize([]);
543 parent
::assignTestValue($fieldName, $fieldDef, $counter);