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 * The CiviCRM duplicate discovery engine is based on an
20 * algorithm designed by David Strauss <david@fourkitchens.com>.
22 class CRM_Dedupe_Finder
{
25 * Return a contact_id-keyed array of arrays of possible dupes
26 * (of the key contact_id) - limited to dupes of $cids if provided.
31 * Contact ids to limit the search to.
33 * @param bool $checkPermissions
34 * Respect logged in user permissions.
37 * Array of (cid1, cid2, weight) dupe triples
39 * @throws \CRM_Core_Exception
41 public static function dupes($rgid, $cids = [], $checkPermissions = TRUE) {
42 $rgBao = new CRM_Dedupe_BAO_DedupeRuleGroup();
44 $rgBao->contactIds
= $cids;
45 if (!$rgBao->find(TRUE)) {
46 throw new CRM_Core_Exception('Dedupe rule not found for selected contacts');
50 $dao = CRM_Core_DAO
::executeQuery($rgBao->thresholdQuery($checkPermissions));
52 while ($dao->fetch()) {
53 $dupes[] = [$dao->id1
, $dao->id2
, $dao->weight
];
55 CRM_Core_DAO
::executeQuery(($rgBao->tableDropQuery()));
61 * Return an array of possible dupes, based on the provided array of
62 * params, using the default rule group for the given contact type and
65 * check_permission is a boolean flag to indicate if permission should be considered.
66 * default is to always check permissioning but public pages for example might not want
67 * permission to be checked for anonymous users. Refer CRM-6211. We might be breaking
68 * Multi-Site dedupe for public pages.
70 * @param array $params
71 * Array of params of the form $params[$table][$field] == $value.
72 * @param string $ctype
73 * Contact type to match against.
75 * Dedupe rule group usage ('Unsupervised' or 'Supervised' or 'General').
76 * @param array $except
77 * Array of contacts that shouldn't be considered dupes.
78 * @param int $ruleGroupID
79 * The id of the dedupe rule we should be using.
82 * matching contact ids
83 * @throws \CRM_Core_Exception
85 public static function dupesByParams(
88 $used = 'Unsupervised',
92 // If $params is empty there is zero reason to proceed.
96 $checkPermission = CRM_Utils_Array
::value('check_permission', $params, TRUE);
97 // This may no longer be required - see https://github.com/civicrm/civicrm-core/pull/13176
98 $params = array_filter($params);
102 $rgBao = new CRM_Dedupe_BAO_DedupeRuleGroup();
103 $rgBao->id
= $ruleGroupID;
104 $rgBao->contact_type
= $ctype;
105 if ($rgBao->find(TRUE)) {
111 $rgBao = new CRM_Dedupe_BAO_DedupeRuleGroup();
112 $rgBao->contact_type
= $ctype;
113 $rgBao->used
= $used;
114 if (!$rgBao->find(TRUE)) {
115 throw new CRM_Core_Exception("$used rule for $ctype does not exist");
119 if (isset($params['civicrm_phone']['phone_numeric'])) {
120 $orig = $params['civicrm_phone']['phone_numeric'];
121 $params['civicrm_phone']['phone_numeric'] = preg_replace('/[^\d]/', '', $orig);
123 $rgBao->params
= $params;
125 $dao = new CRM_Core_DAO();
126 $dao->query($rgBao->thresholdQuery($checkPermission));
128 while ($dao->fetch()) {
129 if (isset($dao->id
) && $dao->id
) {
133 $dao->query($rgBao->tableDropQuery());
134 return array_diff($dupes, $except);
138 * Return a contact_id-keyed array of arrays of possible dupes in the given group.
145 * @param int $searchLimit
146 * Limit for the number of contacts to be used for comparison.
147 * The search methodology finds all matches for the searchedContacts so this limits
148 * the number of searched contacts, not the matches found.
151 * array of (cid1, cid2, weight) dupe triples
153 * @throws \CRM_Core_Exception
155 public static function dupesInGroup($rgid, $gid, $searchLimit = 0) {
156 $cids = array_keys(CRM_Contact_BAO_Group
::getMember($gid, TRUE, $searchLimit));
158 return self
::dupes($rgid, $cids);
164 * A hackish function needed to massage CRM_Contact_Form_$ctype::formRule()
165 * object into a valid $params array for dedupe
167 * @param array $fields
168 * Contact structure from formRule().
169 * @param string $ctype
170 * Contact type of the given contact.
173 * valid $params array for dedupe
174 * @throws \CRM_Core_Exception
176 public static function formatParams($fields, $ctype) {
178 CRM_Utils_Array
::flatten($fields, $flat);
180 // FIXME: This may no longer be necessary - check inputs
182 'individual_prefix' => 'prefix_id',
183 'individual_suffix' => 'suffix_id',
184 'gender' => 'gender_id',
186 foreach (['individual_suffix', 'individual_prefix', 'gender'] as $name) {
187 if (!empty($fields[$name])) {
188 $flat[$replace_these[$name]] = $flat[$name];
193 // handle {birth,deceased}_date
198 if (!empty($fields[$date])) {
199 $flat[$date] = $fields[$date];
200 if (is_array($flat[$date])) {
201 $flat[$date] = CRM_Utils_Date
::format($flat[$date]);
203 $flat[$date] = CRM_Utils_Date
::processDate($flat[$date]);
207 if (!empty($flat['contact_source'])) {
208 $flat['source'] = $flat['contact_source'];
209 unset($flat['contact_source']);
212 // handle preferred_communication_method
213 if (!empty($fields['preferred_communication_method'])) {
214 $methods = array_intersect($fields['preferred_communication_method'], ['1']);
215 $methods = array_keys($methods);
218 $flat['preferred_communication_method'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $methods) . CRM_Core_DAO
::VALUE_SEPARATOR
;
222 // handle custom data
223 $tree = CRM_Core_BAO_CustomGroup
::getTree($ctype, NULL, NULL, -1);
224 CRM_Core_BAO_CustomGroup
::postProcess($tree, $fields, TRUE);
225 foreach ($tree as $key => $cg) {
229 foreach ($cg['fields'] as $cf) {
230 $flat[$cf['column_name']] = $cf['customValue']['data'] ??
NULL;
234 // if the key is dotted, keep just the last part of it
235 foreach ($flat as $key => $value) {
236 if (substr_count($key, '.')) {
237 $last = explode('.', $key);
238 $last = array_pop($last);
239 // make sure the first occurrence is kept, not the last
240 if (!isset($flat[$last])) {
241 $flat[$last] = $value;
247 // drop the -digit (and -Primary, for CRM-3902) postfixes (so event registration's $flat['email-5'] becomes $flat['email'])
248 // FIXME: CRM-5026 should be fixed here; the below clobbers all address info; we should split off address fields and match
249 // the -digit to civicrm_address.location_type_id and -Primary to civicrm_address.is_primary
250 foreach ($flat as $key => $value) {
252 if (preg_match('/(.*)-(Primary-[\d+])$|(.*)-(\d+-\d+)$|(.*)-(\d+|Primary)$/', $key, $matches)) {
253 $return = array_values(array_filter($matches));
254 // make sure the first occurrence is kept, not the last
255 $flat[$return[1]] = empty($flat[$return[1]]) ?
$value : $flat[$return[1]];
261 $supportedFields = CRM_Dedupe_BAO_DedupeRuleGroup
::supportedFields($ctype);
262 if (is_array($supportedFields)) {
263 foreach ($supportedFields as $table => $fields) {
264 if ($table === 'civicrm_address') {
265 // for matching on civicrm_address fields, we also need the location_type_id
266 $fields['location_type_id'] = '';
267 // FIXME: we also need to do some hacking for id and name fields, see CRM-3902’s comments
269 'address_name' => 'name',
270 'country' => 'country_id',
271 'state_province' => 'state_province_id',
272 'county' => 'county_id',
274 foreach ($fixes as $orig => $target) {
275 if (!empty($flat[$orig])) {
276 $params[$table][$target] = $flat[$orig];
280 if ($table === 'civicrm_phone') {
282 'phone' => 'phone_numeric',
284 foreach ($fixes as $orig => $target) {
285 if (!empty($flat[$orig])) {
286 $params[$table][$target] = $flat[$orig];
290 foreach ($fields as $field => $title) {
291 if (!empty($flat[$field])) {
292 $params[$table][$field] = $flat[$field];
301 * Parse duplicate pairs into a standardised array and store in the prev_next_cache.
303 * @param array $foundDupes
304 * @param string $cacheKeyString
307 * Dupe pairs with the keys
315 public static function parseAndStoreDupePairs($foundDupes, $cacheKeyString) {
317 foreach ($foundDupes as $dupe) {
321 $cidString = implode(', ', array_keys($cids));
323 $dao = CRM_Core_DAO
::executeQuery("SELECT id, display_name FROM civicrm_contact WHERE id IN ($cidString) ORDER BY sort_name");
325 while ($dao->fetch()) {
326 $displayNames[$dao->id
] = $dao->display_name
;
329 $userId = CRM_Core_Session
::getLoggedInContactID();
330 foreach ($foundDupes as $dupes) {
333 // The logged in user should never be the src (ie. the contact to be removed).
334 if ($srcID == $userId) {
339 $mainContacts[] = $row = [
340 'dstID' => (int) $dstID,
341 'dstName' => $displayNames[$dstID],
342 'srcID' => (int) $srcID,
343 'srcName' => $displayNames[$srcID],
344 'weight' => $dupes[2],
348 CRM_Core_DAO
::executeQuery("INSERT INTO civicrm_prevnext_cache (entity_table, entity_id1, entity_id2, cacheKey, data) VALUES
349 ('civicrm_contact', %1, %2, %3, %4)", [
350 1 => [$dstID, 'Integer'],
351 2 => [$srcID, 'Integer'],
352 3 => [$cacheKeyString, 'String'],
353 4 => [serialize($row), 'String'],
357 return $mainContacts;