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_RuleGroup();
44 $rgBao->contactIds
= $cids;
45 if (!$rgBao->find(TRUE)) {
46 throw new CRM_Core_Exception('Dedupe rule not found for selected contacts');
50 $dao = new CRM_Core_DAO();
51 $dao->query($rgBao->thresholdQuery($checkPermissions));
53 while ($dao->fetch()) {
54 $dupes[] = [$dao->id1
, $dao->id2
, $dao->weight
];
56 $dao->query($rgBao->tableDropQuery());
62 * Return an array of possible dupes, based on the provided array of
63 * params, using the default rule group for the given contact type and
66 * check_permission is a boolean flag to indicate if permission should be considered.
67 * default is to always check permissioning but public pages for example might not want
68 * permission to be checked for anonymous users. Refer CRM-6211. We might be breaking
69 * Multi-Site dedupe for public pages.
71 * @param array $params
72 * Array of params of the form $params[$table][$field] == $value.
73 * @param string $ctype
74 * Contact type to match against.
76 * Dedupe rule group usage ('Unsupervised' or 'Supervised' or 'General').
77 * @param array $except
78 * Array of contacts that shouldn't be considered dupes.
79 * @param int $ruleGroupID
80 * The id of the dedupe rule we should be using.
83 * matching contact ids
84 * @throws \CRM_Core_Exception
86 public static function dupesByParams(
89 $used = 'Unsupervised',
93 // If $params is empty there is zero reason to proceed.
97 $checkPermission = CRM_Utils_Array
::value('check_permission', $params, TRUE);
98 // This may no longer be required - see https://github.com/civicrm/civicrm-core/pull/13176
99 $params = array_filter($params);
103 $rgBao = new CRM_Dedupe_BAO_RuleGroup();
104 $rgBao->id
= $ruleGroupID;
105 $rgBao->contact_type
= $ctype;
106 if ($rgBao->find(TRUE)) {
112 $rgBao = new CRM_Dedupe_BAO_RuleGroup();
113 $rgBao->contact_type
= $ctype;
114 $rgBao->used
= $used;
115 if (!$rgBao->find(TRUE)) {
116 throw new CRM_Core_Exception("$used rule for $ctype does not exist");
120 if (isset($params['civicrm_phone']['phone_numeric'])) {
121 $orig = $params['civicrm_phone']['phone_numeric'];
122 $params['civicrm_phone']['phone_numeric'] = preg_replace('/[^\d]/', '', $orig);
124 $rgBao->params
= $params;
126 $dao = new CRM_Core_DAO();
127 $dao->query($rgBao->thresholdQuery($checkPermission));
129 while ($dao->fetch()) {
130 if (isset($dao->id
) && $dao->id
) {
134 $dao->query($rgBao->tableDropQuery());
135 return array_diff($dupes, $except);
139 * Return a contact_id-keyed array of arrays of possible dupes in the given group.
146 * @param int $searchLimit
147 * Limit for the number of contacts to be used for comparison.
148 * The search methodology finds all matches for the searchedContacts so this limits
149 * the number of searched contacts, not the matches found.
152 * array of (cid1, cid2, weight) dupe triples
154 * @throws \CRM_Core_Exception
156 public static function dupesInGroup($rgid, $gid, $searchLimit = 0) {
157 $cids = array_keys(CRM_Contact_BAO_Group
::getMember($gid, TRUE, $searchLimit));
159 return self
::dupes($rgid, $cids);
165 * A hackish function needed to massage CRM_Contact_Form_$ctype::formRule()
166 * object into a valid $params array for dedupe
168 * @param array $fields
169 * Contact structure from formRule().
170 * @param string $ctype
171 * Contact type of the given contact.
174 * valid $params array for dedupe
175 * @throws \CRM_Core_Exception
177 public static function formatParams($fields, $ctype) {
179 CRM_Utils_Array
::flatten($fields, $flat);
181 // FIXME: This may no longer be necessary - check inputs
183 'individual_prefix' => 'prefix_id',
184 'individual_suffix' => 'suffix_id',
185 'gender' => 'gender_id',
187 foreach (['individual_suffix', 'individual_prefix', 'gender'] as $name) {
188 if (!empty($fields[$name])) {
189 $flat[$replace_these[$name]] = $flat[$name];
194 // handle {birth,deceased}_date
199 if (!empty($fields[$date])) {
200 $flat[$date] = $fields[$date];
201 if (is_array($flat[$date])) {
202 $flat[$date] = CRM_Utils_Date
::format($flat[$date]);
204 $flat[$date] = CRM_Utils_Date
::processDate($flat[$date]);
208 if (!empty($flat['contact_source'])) {
209 $flat['source'] = $flat['contact_source'];
210 unset($flat['contact_source']);
213 // handle preferred_communication_method
214 if (!empty($fields['preferred_communication_method'])) {
215 $methods = array_intersect($fields['preferred_communication_method'], ['1']);
216 $methods = array_keys($methods);
219 $flat['preferred_communication_method'] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
, $methods) . CRM_Core_DAO
::VALUE_SEPARATOR
;
223 // handle custom data
224 $tree = CRM_Core_BAO_CustomGroup
::getTree($ctype, NULL, NULL, -1);
225 CRM_Core_BAO_CustomGroup
::postProcess($tree, $fields, TRUE);
226 foreach ($tree as $key => $cg) {
230 foreach ($cg['fields'] as $cf) {
231 $flat[$cf['column_name']] = $cf['customValue']['data'] ??
NULL;
235 // if the key is dotted, keep just the last part of it
236 foreach ($flat as $key => $value) {
237 if (substr_count($key, '.')) {
238 $last = explode('.', $key);
239 $last = array_pop($last);
240 // make sure the first occurrence is kept, not the last
241 if (!isset($flat[$last])) {
242 $flat[$last] = $value;
248 // drop the -digit (and -Primary, for CRM-3902) postfixes (so event registration's $flat['email-5'] becomes $flat['email'])
249 // FIXME: CRM-5026 should be fixed here; the below clobbers all address info; we should split off address fields and match
250 // the -digit to civicrm_address.location_type_id and -Primary to civicrm_address.is_primary
251 foreach ($flat as $key => $value) {
253 if (preg_match('/(.*)-(Primary-[\d+])$|(.*)-(\d+-\d+)$|(.*)-(\d+|Primary)$/', $key, $matches)) {
254 $return = array_values(array_filter($matches));
255 // make sure the first occurrence is kept, not the last
256 $flat[$return[1]] = empty($flat[$return[1]]) ?
$value : $flat[$return[1]];
262 $supportedFields = CRM_Dedupe_BAO_RuleGroup
::supportedFields($ctype);
263 if (is_array($supportedFields)) {
264 foreach ($supportedFields as $table => $fields) {
265 if ($table === 'civicrm_address') {
266 // for matching on civicrm_address fields, we also need the location_type_id
267 $fields['location_type_id'] = '';
268 // FIXME: we also need to do some hacking for id and name fields, see CRM-3902’s comments
270 'address_name' => 'name',
271 'country' => 'country_id',
272 'state_province' => 'state_province_id',
273 'county' => 'county_id',
275 foreach ($fixes as $orig => $target) {
276 if (!empty($flat[$orig])) {
277 $params[$table][$target] = $flat[$orig];
281 if ($table === 'civicrm_phone') {
283 'phone' => 'phone_numeric',
285 foreach ($fixes as $orig => $target) {
286 if (!empty($flat[$orig])) {
287 $params[$table][$target] = $flat[$orig];
291 foreach ($fields as $field => $title) {
292 if (!empty($flat[$field])) {
293 $params[$table][$field] = $flat[$field];
302 * Parse duplicate pairs into a standardised array and store in the prev_next_cache.
304 * @param array $foundDupes
305 * @param string $cacheKeyString
308 * Dupe pairs with the keys
316 public static function parseAndStoreDupePairs($foundDupes, $cacheKeyString) {
318 foreach ($foundDupes as $dupe) {
322 $cidString = implode(', ', array_keys($cids));
324 $dao = CRM_Core_DAO
::executeQuery("SELECT id, display_name FROM civicrm_contact WHERE id IN ($cidString) ORDER BY sort_name");
326 while ($dao->fetch()) {
327 $displayNames[$dao->id
] = $dao->display_name
;
330 $userId = CRM_Core_Session
::getLoggedInContactID();
331 foreach ($foundDupes as $dupes) {
334 // The logged in user should never be the src (ie. the contact to be removed).
335 if ($srcID == $userId) {
340 $mainContacts[] = $row = [
341 'dstID' => (int) $dstID,
342 'dstName' => $displayNames[$dstID],
343 'srcID' => (int) $srcID,
344 'srcName' => $displayNames[$srcID],
345 'weight' => $dupes[2],
349 CRM_Core_DAO
::executeQuery("INSERT INTO civicrm_prevnext_cache (entity_table, entity_id1, entity_id2, cacheKey, data) VALUES
350 ('civicrm_contact', %1, %2, %3, %4)", [
351 1 => [$dstID, 'Integer'],
352 2 => [$srcID, 'Integer'],
353 3 => [$cacheKeyString, 'String'],
354 4 => [serialize($row), 'String'],
358 return $mainContacts;