Merge pull request #17774 from civicrm/5.28
[civicrm-core.git] / CRM / Dedupe / Finder.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 * $Id$
17 *
18 */
19
20 /**
21 * The CiviCRM duplicate discovery engine is based on an
22 * algorithm designed by David Strauss <david@fourkitchens.com>.
23 */
24 class CRM_Dedupe_Finder {
25
26 /**
27 * Return a contact_id-keyed array of arrays of possible dupes
28 * (of the key contact_id) - limited to dupes of $cids if provided.
29 *
30 * @param int $rgid
31 * Rule group id.
32 * @param array $cids
33 * Contact ids to limit the search to.
34 *
35 * @param bool $checkPermissions
36 * Respect logged in user permissions.
37 *
38 * @return array
39 * Array of (cid1, cid2, weight) dupe triples
40 *
41 * @throws \CRM_Core_Exception
42 */
43 public static function dupes($rgid, $cids = [], $checkPermissions = TRUE) {
44 $rgBao = new CRM_Dedupe_BAO_RuleGroup();
45 $rgBao->id = $rgid;
46 $rgBao->contactIds = $cids;
47 if (!$rgBao->find(TRUE)) {
48 throw new CRM_Core_Exception('Dedupe rule not found for selected contacts');
49 }
50
51 $rgBao->fillTable();
52 $dao = new CRM_Core_DAO();
53 $dao->query($rgBao->thresholdQuery($checkPermissions));
54 $dupes = [];
55 while ($dao->fetch()) {
56 $dupes[] = [$dao->id1, $dao->id2, $dao->weight];
57 }
58 $dao->query($rgBao->tableDropQuery());
59
60 return $dupes;
61 }
62
63 /**
64 * Return an array of possible dupes, based on the provided array of
65 * params, using the default rule group for the given contact type and
66 * usage.
67 *
68 * check_permission is a boolean flag to indicate if permission should be considered.
69 * default is to always check permissioning but public pages for example might not want
70 * permission to be checked for anonymous users. Refer CRM-6211. We might be breaking
71 * Multi-Site dedupe for public pages.
72 *
73 * @param array $params
74 * Array of params of the form $params[$table][$field] == $value.
75 * @param string $ctype
76 * Contact type to match against.
77 * @param string $used
78 * Dedupe rule group usage ('Unsupervised' or 'Supervised' or 'General').
79 * @param array $except
80 * Array of contacts that shouldn't be considered dupes.
81 * @param int $ruleGroupID
82 * The id of the dedupe rule we should be using.
83 *
84 * @return array
85 * matching contact ids
86 * @throws \CRM_Core_Exception
87 */
88 public static function dupesByParams(
89 $params,
90 $ctype,
91 $used = 'Unsupervised',
92 $except = [],
93 $ruleGroupID = NULL
94 ) {
95 // If $params is empty there is zero reason to proceed.
96 if (!$params) {
97 return [];
98 }
99 $checkPermission = CRM_Utils_Array::value('check_permission', $params, TRUE);
100 // This may no longer be required - see https://github.com/civicrm/civicrm-core/pull/13176
101 $params = array_filter($params);
102
103 $foundByID = FALSE;
104 if ($ruleGroupID) {
105 $rgBao = new CRM_Dedupe_BAO_RuleGroup();
106 $rgBao->id = $ruleGroupID;
107 $rgBao->contact_type = $ctype;
108 if ($rgBao->find(TRUE)) {
109 $foundByID = TRUE;
110 }
111 }
112
113 if (!$foundByID) {
114 $rgBao = new CRM_Dedupe_BAO_RuleGroup();
115 $rgBao->contact_type = $ctype;
116 $rgBao->used = $used;
117 if (!$rgBao->find(TRUE)) {
118 throw new CRM_Core_Exception("$used rule for $ctype does not exist");
119 }
120 }
121
122 if (isset($params['civicrm_phone']['phone_numeric'])) {
123 $orig = $params['civicrm_phone']['phone_numeric'];
124 $params['civicrm_phone']['phone_numeric'] = preg_replace('/[^\d]/', '', $orig);
125 }
126 $rgBao->params = $params;
127 $rgBao->fillTable();
128 $dao = new CRM_Core_DAO();
129 $dao->query($rgBao->thresholdQuery($checkPermission));
130 $dupes = [];
131 while ($dao->fetch()) {
132 if (isset($dao->id) && $dao->id) {
133 $dupes[] = $dao->id;
134 }
135 }
136 $dao->query($rgBao->tableDropQuery());
137 return array_diff($dupes, $except);
138 }
139
140 /**
141 * Return a contact_id-keyed array of arrays of possible dupes in the given group.
142 *
143 * @param int $rgid
144 * Rule group id.
145 * @param int $gid
146 * Contact group id.
147 *
148 * @param int $searchLimit
149 * Limit for the number of contacts to be used for comparison.
150 * The search methodology finds all matches for the searchedContacts so this limits
151 * the number of searched contacts, not the matches found.
152 *
153 * @return array
154 * array of (cid1, cid2, weight) dupe triples
155 *
156 * @throws \CRM_Core_Exception
157 */
158 public static function dupesInGroup($rgid, $gid, $searchLimit = 0) {
159 $cids = array_keys(CRM_Contact_BAO_Group::getMember($gid, TRUE, $searchLimit));
160 if (!empty($cids)) {
161 return self::dupes($rgid, $cids);
162 }
163 return [];
164 }
165
166 /**
167 * A hackish function needed to massage CRM_Contact_Form_$ctype::formRule()
168 * object into a valid $params array for dedupe
169 *
170 * @param array $fields
171 * Contact structure from formRule().
172 * @param string $ctype
173 * Contact type of the given contact.
174 *
175 * @return array
176 * valid $params array for dedupe
177 * @throws \CRM_Core_Exception
178 */
179 public static function formatParams($fields, $ctype) {
180 $flat = [];
181 CRM_Utils_Array::flatten($fields, $flat);
182
183 // FIXME: This may no longer be necessary - check inputs
184 $replace_these = [
185 'individual_prefix' => 'prefix_id',
186 'individual_suffix' => 'suffix_id',
187 'gender' => 'gender_id',
188 ];
189 foreach (['individual_suffix', 'individual_prefix', 'gender'] as $name) {
190 if (!empty($fields[$name])) {
191 $flat[$replace_these[$name]] = $flat[$name];
192 unset($flat[$name]);
193 }
194 }
195
196 // handle {birth,deceased}_date
197 foreach ([
198 'birth_date',
199 'deceased_date',
200 ] as $date) {
201 if (!empty($fields[$date])) {
202 $flat[$date] = $fields[$date];
203 if (is_array($flat[$date])) {
204 $flat[$date] = CRM_Utils_Date::format($flat[$date]);
205 }
206 $flat[$date] = CRM_Utils_Date::processDate($flat[$date]);
207 }
208 }
209
210 if (!empty($flat['contact_source'])) {
211 $flat['source'] = $flat['contact_source'];
212 unset($flat['contact_source']);
213 }
214
215 // handle preferred_communication_method
216 if (!empty($fields['preferred_communication_method'])) {
217 $methods = array_intersect($fields['preferred_communication_method'], ['1']);
218 $methods = array_keys($methods);
219 sort($methods);
220 if ($methods) {
221 $flat['preferred_communication_method'] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR, $methods) . CRM_Core_DAO::VALUE_SEPARATOR;
222 }
223 }
224
225 // handle custom data
226 $tree = CRM_Core_BAO_CustomGroup::getTree($ctype, NULL, NULL, -1);
227 CRM_Core_BAO_CustomGroup::postProcess($tree, $fields, TRUE);
228 foreach ($tree as $key => $cg) {
229 if (!is_int($key)) {
230 continue;
231 }
232 foreach ($cg['fields'] as $cf) {
233 $flat[$cf['column_name']] = $cf['customValue']['data'] ?? NULL;
234 }
235 }
236
237 // if the key is dotted, keep just the last part of it
238 foreach ($flat as $key => $value) {
239 if (substr_count($key, '.')) {
240 $last = explode('.', $key);
241 $last = array_pop($last);
242 // make sure the first occurrence is kept, not the last
243 if (!isset($flat[$last])) {
244 $flat[$last] = $value;
245 }
246 unset($flat[$key]);
247 }
248 }
249
250 // drop the -digit (and -Primary, for CRM-3902) postfixes (so event registration's $flat['email-5'] becomes $flat['email'])
251 // FIXME: CRM-5026 should be fixed here; the below clobbers all address info; we should split off address fields and match
252 // the -digit to civicrm_address.location_type_id and -Primary to civicrm_address.is_primary
253 foreach ($flat as $key => $value) {
254 $matches = [];
255 if (preg_match('/(.*)-(Primary-[\d+])$|(.*)-(\d+|Primary)$/', $key, $matches)) {
256 $return = array_values(array_filter($matches));
257 // make sure the first occurrence is kept, not the last
258 $flat[$return[1]] = empty($flat[$return[1]]) ? $value : $flat[$return[1]];
259 unset($flat[$key]);
260 }
261 }
262
263 $params = [];
264 $supportedFields = CRM_Dedupe_BAO_RuleGroup::supportedFields($ctype);
265 if (is_array($supportedFields)) {
266 foreach ($supportedFields as $table => $fields) {
267 if ($table === 'civicrm_address') {
268 // for matching on civicrm_address fields, we also need the location_type_id
269 $fields['location_type_id'] = '';
270 // FIXME: we also need to do some hacking for id and name fields, see CRM-3902’s comments
271 $fixes = [
272 'address_name' => 'name',
273 'country' => 'country_id',
274 'state_province' => 'state_province_id',
275 'county' => 'county_id',
276 ];
277 foreach ($fixes as $orig => $target) {
278 if (!empty($flat[$orig])) {
279 $params[$table][$target] = $flat[$orig];
280 }
281 }
282 }
283 if ($table === 'civicrm_phone') {
284 $fixes = [
285 'phone' => 'phone_numeric',
286 ];
287 foreach ($fixes as $orig => $target) {
288 if (!empty($flat[$orig])) {
289 $params[$table][$target] = $flat[$orig];
290 }
291 }
292 }
293 foreach ($fields as $field => $title) {
294 if (!empty($flat[$field])) {
295 $params[$table][$field] = $flat[$field];
296 }
297 }
298 }
299 }
300 return $params;
301 }
302
303 /**
304 * Parse duplicate pairs into a standardised array and store in the prev_next_cache.
305 *
306 * @param array $foundDupes
307 * @param string $cacheKeyString
308 *
309 * @return array
310 * Dupe pairs with the keys
311 * -srcID
312 * -srcName
313 * -dstID
314 * -dstName
315 * -weight
316 * -canMerge
317 */
318 public static function parseAndStoreDupePairs($foundDupes, $cacheKeyString) {
319 $cids = [];
320 foreach ($foundDupes as $dupe) {
321 $cids[$dupe[0]] = 1;
322 $cids[$dupe[1]] = 1;
323 }
324 $cidString = implode(', ', array_keys($cids));
325
326 $dao = CRM_Core_DAO::executeQuery("SELECT id, display_name FROM civicrm_contact WHERE id IN ($cidString) ORDER BY sort_name");
327 $displayNames = [];
328 while ($dao->fetch()) {
329 $displayNames[$dao->id] = $dao->display_name;
330 }
331
332 $userId = CRM_Core_Session::getLoggedInContactID();
333 foreach ($foundDupes as $dupes) {
334 $srcID = $dupes[1];
335 $dstID = $dupes[0];
336 // The logged in user should never be the src (ie. the contact to be removed).
337 if ($srcID == $userId) {
338 $srcID = $dstID;
339 $dstID = $userId;
340 }
341
342 $mainContacts[] = $row = [
343 'dstID' => (int) $dstID,
344 'dstName' => $displayNames[$dstID],
345 'srcID' => (int) $srcID,
346 'srcName' => $displayNames[$srcID],
347 'weight' => $dupes[2],
348 'canMerge' => TRUE,
349 ];
350
351 CRM_Core_DAO::executeQuery("INSERT INTO civicrm_prevnext_cache (entity_table, entity_id1, entity_id2, cacheKey, data) VALUES
352 ('civicrm_contact', %1, %2, %3, %4)", [
353 1 => [$dstID, 'Integer'],
354 2 => [$srcID, 'Integer'],
355 3 => [$cacheKeyString, 'String'],
356 4 => [serialize($row), 'String'],
357 ]
358 );
359 }
360 return $mainContacts;
361 }
362
363 }