Dedupe permissions - allow safe mode merging based on 'merge duplicate contacts'
[civicrm-core.git] / CRM / Dedupe / Merger.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 class CRM_Dedupe_Merger {
34
35 /**
36 * FIXME: consider creating a common structure with cidRefs() and eidRefs()
37 * FIXME: the sub-pages references by the URLs should
38 * be loaded dynamically on the merge form instead
39 * @return array
40 */
41 public static function relTables() {
42
43 if (!isset(Civi::$statics[__CLASS__]['relTables'])) {
44
45 // Setting these merely prevents enotices - but it may be more appropriate not to add the user table below
46 // if the url can't be retrieved. A more standardised way to retrieve them is.
47 // CRM_Core_Config::singleton()->userSystem->getUserRecordUrl() - however that function takes a contact_id &
48 // we may need a different function when it is not known.
49 $title = $userRecordUrl = '';
50
51 $config = CRM_Core_Config::singleton();
52 if ($config->userSystem->is_drupal) {
53 $userRecordUrl = CRM_Utils_System::url('user/%ufid');
54 $title = ts('%1 User: %2; user id: %3', [
55 1 => $config->userFramework,
56 2 => '$ufname',
57 3 => '$ufid',
58 ]);
59 }
60 elseif ($config->userFramework == 'Joomla') {
61 $userRecordUrl = $config->userSystem->getVersion() > 1.5 ? $config->userFrameworkBaseURL . "index.php?option=com_users&view=user&task=user.edit&id=" . '%ufid' : $config->userFrameworkBaseURL . "index2.php?option=com_users&view=user&task=edit&id[]=" . '%ufid';
62 $title = ts('%1 User: %2; user id: %3', [
63 1 => $config->userFramework,
64 2 => '$ufname',
65 3 => '$ufid',
66 ]);
67 }
68
69 $relTables = [
70 'rel_table_contributions' => [
71 'title' => ts('Contributions'),
72 'tables' => [
73 'civicrm_contribution',
74 'civicrm_contribution_recur',
75 'civicrm_contribution_soft',
76 ],
77 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=contribute'),
78 ],
79 'rel_table_contribution_page' => [
80 'title' => ts('Contribution Pages'),
81 'tables' => ['civicrm_contribution_page'],
82 'url' => CRM_Utils_System::url('civicrm/admin/contribute', 'reset=1&cid=$cid'),
83 ],
84 'rel_table_memberships' => [
85 'title' => ts('Memberships'),
86 'tables' => [
87 'civicrm_membership',
88 'civicrm_membership_log',
89 'civicrm_membership_type',
90 ],
91 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=member'),
92 ],
93 'rel_table_participants' => [
94 'title' => ts('Participants'),
95 'tables' => ['civicrm_participant'],
96 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=participant'),
97 ],
98 'rel_table_events' => [
99 'title' => ts('Events'),
100 'tables' => ['civicrm_event'],
101 'url' => CRM_Utils_System::url('civicrm/event/manage', 'reset=1&cid=$cid'),
102 ],
103 'rel_table_activities' => [
104 'title' => ts('Activities'),
105 'tables' => ['civicrm_activity', 'civicrm_activity_contact'],
106 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=activity'),
107 ],
108 'rel_table_relationships' => [
109 'title' => ts('Relationships'),
110 'tables' => ['civicrm_relationship'],
111 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=rel'),
112 ],
113 'rel_table_custom_groups' => [
114 'title' => ts('Custom Groups'),
115 'tables' => ['civicrm_custom_group'],
116 'url' => CRM_Utils_System::url('civicrm/admin/custom/group', 'reset=1'),
117 ],
118 'rel_table_uf_groups' => [
119 'title' => ts('Profiles'),
120 'tables' => ['civicrm_uf_group'],
121 'url' => CRM_Utils_System::url('civicrm/admin/uf/group', 'reset=1'),
122 ],
123 'rel_table_groups' => [
124 'title' => ts('Groups'),
125 'tables' => ['civicrm_group_contact'],
126 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=group'),
127 ],
128 'rel_table_notes' => [
129 'title' => ts('Notes'),
130 'tables' => ['civicrm_note'],
131 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=note'),
132 ],
133 'rel_table_tags' => [
134 'title' => ts('Tags'),
135 'tables' => ['civicrm_entity_tag'],
136 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=tag'),
137 ],
138 'rel_table_mailings' => [
139 'title' => ts('Mailings'),
140 'tables' => [
141 'civicrm_mailing',
142 'civicrm_mailing_event_queue',
143 'civicrm_mailing_event_subscribe',
144 ],
145 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=mailing'),
146 ],
147 'rel_table_cases' => [
148 'title' => ts('Cases'),
149 'tables' => ['civicrm_case_contact'],
150 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=case'),
151 ],
152 'rel_table_grants' => [
153 'title' => ts('Grants'),
154 'tables' => ['civicrm_grant'],
155 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=grant'),
156 ],
157 'rel_table_pcp' => [
158 'title' => ts('PCPs'),
159 'tables' => ['civicrm_pcp'],
160 'url' => CRM_Utils_System::url('civicrm/contribute/pcp/manage', 'reset=1'),
161 ],
162 'rel_table_pledges' => [
163 'title' => ts('Pledges'),
164 'tables' => ['civicrm_pledge', 'civicrm_pledge_payment'],
165 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=pledge'),
166 ],
167 'rel_table_users' => [
168 'title' => $title,
169 'tables' => ['civicrm_uf_match'],
170 'url' => $userRecordUrl,
171 ],
172 ];
173
174 $relTables += self::getMultiValueCustomSets('relTables');
175
176 // Allow hook_civicrm_merge() to adjust $relTables
177 CRM_Utils_Hook::merge('relTables', $relTables);
178
179 // Cache the results in a static variable
180 Civi::$statics[__CLASS__]['relTables'] = $relTables;
181 }
182
183 return Civi::$statics[__CLASS__]['relTables'];
184 }
185
186 /**
187 * Returns the related tables groups for which a contact has any info entered.
188 *
189 * @param int $cid
190 *
191 * @return array
192 */
193 public static function getActiveRelTables($cid) {
194 $cid = (int) $cid;
195 $groups = [];
196
197 $relTables = self::relTables();
198 $cidRefs = self::cidRefs();
199 $eidRefs = self::eidRefs();
200 foreach ($relTables as $group => $params) {
201 $sqls = [];
202 foreach ($params['tables'] as $table) {
203 if (isset($cidRefs[$table])) {
204 foreach ($cidRefs[$table] as $field) {
205 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $field = $cid";
206 }
207 }
208 if (isset($eidRefs[$table])) {
209 foreach ($eidRefs[$table] as $entityTable => $entityId) {
210 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $entityId = $cid AND $entityTable = 'civicrm_contact'";
211 }
212 }
213 foreach ($sqls as $sql) {
214 if (CRM_Core_DAO::singleValueQuery($sql) > 0) {
215 $groups[] = $group;
216 }
217 }
218 }
219 }
220 return array_unique($groups);
221 }
222
223 /**
224 * Get array tables and fields that reference civicrm_contact.id.
225 *
226 * This function calls the merge hook and only exists to wrap the DAO function to support that deprecated call.
227 * The entityTypes hook is the recommended way to add tables to this result.
228 *
229 * I thought about adding another hook to alter tableReferences but decided it was unclear if there
230 * are use cases not covered by entityTables and instead we should wait & see.
231 */
232 public static function cidRefs() {
233 if (isset(\Civi::$statics[__CLASS__]) && isset(\Civi::$statics[__CLASS__]['contact_references'])) {
234 return \Civi::$statics[__CLASS__]['contact_references'];
235 }
236
237 $contactReferences = $coreReferences = CRM_Core_DAO::getReferencesToContactTable();
238
239 CRM_Utils_Hook::merge('cidRefs', $contactReferences);
240 if ($contactReferences !== $coreReferences) {
241 Civi::log()
242 ->warning("Deprecated hook ::merge in context of 'cidRefs. Use entityTypes instead.", ['civi.tag' => 'deprecated']);
243 }
244 \Civi::$statics[__CLASS__]['contact_references'] = $contactReferences;
245 return \Civi::$statics[__CLASS__]['contact_references'];
246 }
247
248 /**
249 * Return tables and their fields referencing civicrm_contact.contact_id with entity_id
250 */
251 public static function eidRefs() {
252 static $eidRefs;
253 if (!$eidRefs) {
254 // FIXME: this should be generated dynamically from the schema
255 // tables that reference contacts with entity_{id,table}
256 $eidRefs = [
257 'civicrm_acl' => ['entity_table' => 'entity_id'],
258 'civicrm_acl_entity_role' => ['entity_table' => 'entity_id'],
259 'civicrm_entity_file' => ['entity_table' => 'entity_id'],
260 'civicrm_log' => ['entity_table' => 'entity_id'],
261 'civicrm_mailing_group' => ['entity_table' => 'entity_id'],
262 'civicrm_note' => ['entity_table' => 'entity_id'],
263 ];
264
265 // Allow hook_civicrm_merge() to adjust $eidRefs
266 CRM_Utils_Hook::merge('eidRefs', $eidRefs);
267 }
268 return $eidRefs;
269 }
270
271 /**
272 * Return tables using locations.
273 */
274 public static function locTables() {
275 static $locTables;
276 if (!$locTables) {
277 $locTables = ['civicrm_email', 'civicrm_address', 'civicrm_phone'];
278
279 // Allow hook_civicrm_merge() to adjust $locTables
280 CRM_Utils_Hook::merge('locTables', $locTables);
281 }
282 return $locTables;
283 }
284
285 /**
286 * We treat multi-valued custom sets as "related tables" similar to activities, contributions, etc.
287 * @param string $request
288 * 'relTables' or 'cidRefs'.
289 * @return array
290 * @see CRM-13836
291 */
292 public static function getMultiValueCustomSets($request) {
293
294 if (!isset(Civi::$statics[__CLASS__]['multiValueCustomSets'])) {
295 $data = [
296 'relTables' => [],
297 'cidRefs' => [],
298 ];
299 $result = civicrm_api3('custom_group', 'get', [
300 'is_multiple' => 1,
301 'extends' => [
302 'IN' => [
303 'Individual',
304 'Organization',
305 'Household',
306 'Contact',
307 ],
308 ],
309 'return' => ['id', 'title', 'table_name', 'style'],
310 ]);
311 foreach ($result['values'] as $custom) {
312 $data['cidRefs'][$custom['table_name']] = ['entity_id'];
313 $urlSuffix = $custom['style'] == 'Tab' ? '&selectedChild=custom_' . $custom['id'] : '';
314 $data['relTables']['rel_table_custom_' . $custom['id']] = [
315 'title' => $custom['title'],
316 'tables' => [$custom['table_name']],
317 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid' . $urlSuffix),
318 ];
319 }
320
321 // Store the result in a static variable cache
322 Civi::$statics[__CLASS__]['multiValueCustomSets'] = $data;
323 }
324
325 return Civi::$statics[__CLASS__]['multiValueCustomSets'][$request];
326 }
327
328 /**
329 * Tables which require custom processing should declare functions to call here.
330 * Doing so will override normal processing.
331 */
332 public static function cpTables() {
333 static $tables;
334 if (!$tables) {
335 $tables = [
336 'civicrm_case_contact' => ['CRM_Case_BAO_Case' => 'mergeContacts'],
337 'civicrm_group_contact' => ['CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'],
338 // Empty array == do nothing - this table is handled by mergeGroupContact
339 'civicrm_subscription_history' => [],
340 'civicrm_relationship' => ['CRM_Contact_BAO_Relationship' => 'mergeRelationships'],
341 'civicrm_membership' => ['CRM_Member_BAO_Membership' => 'mergeMemberships'],
342 ];
343 }
344 return $tables;
345 }
346
347 /**
348 * Return payment related table.
349 */
350 public static function paymentTables() {
351 static $tables;
352 if (!$tables) {
353 $tables = ['civicrm_pledge', 'civicrm_membership', 'civicrm_participant'];
354 }
355 return $tables;
356 }
357
358 /**
359 * Return payment update Query.
360 *
361 * @param string $tableName
362 * @param int $mainContactId
363 * @param int $otherContactId
364 *
365 * @return array
366 */
367 public static function paymentSql($tableName, $mainContactId, $otherContactId) {
368 $sqls = [];
369 if (!$tableName || !$mainContactId || !$otherContactId) {
370 return $sqls;
371 }
372
373 $paymentTables = self::paymentTables();
374 if (!in_array($tableName, $paymentTables)) {
375 return $sqls;
376 }
377
378 switch ($tableName) {
379 case 'civicrm_pledge':
380 $sqls[] = "
381 UPDATE IGNORE civicrm_contribution contribution
382 INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id )
383 INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id )
384 SET contribution.contact_id = $mainContactId
385 WHERE pledge.contact_id = $otherContactId";
386 break;
387
388 case 'civicrm_membership':
389 $sqls[] = "
390 UPDATE IGNORE civicrm_contribution contribution
391 INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id )
392 INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id )
393 SET contribution.contact_id = $mainContactId
394 WHERE membership.contact_id = $otherContactId";
395 break;
396
397 case 'civicrm_participant':
398 $sqls[] = "
399 UPDATE IGNORE civicrm_contribution contribution
400 INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id )
401 INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id )
402 SET contribution.contact_id = $mainContactId
403 WHERE participant.contact_id = $otherContactId";
404 break;
405 }
406
407 return $sqls;
408 }
409
410 /**
411 * @param int $mainId
412 * @param int $otherId
413 * @param string $tableName
414 * @param array $tableOperations
415 * @param string $mode
416 *
417 * @return array
418 */
419 public static function operationSql($mainId, $otherId, $tableName, $tableOperations = [], $mode = 'add') {
420 $sqls = [];
421 if (!$tableName || !$mainId || !$otherId) {
422 return $sqls;
423 }
424
425 switch ($tableName) {
426 case 'civicrm_membership':
427 if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add']) {
428 break;
429 }
430 if ($mode == 'add') {
431 $sqls[] = "
432 DELETE membership1.* FROM civicrm_membership membership1
433 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
434 AND membership1.contact_id = {$mainId}
435 AND membership2.contact_id = {$otherId} ";
436 }
437 if ($mode == 'payment') {
438 $sqls[] = "
439 DELETE contribution.* FROM civicrm_contribution contribution
440 INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id
441 INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id
442 AND membership1.contact_id = {$mainId}
443 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
444 AND membership2.contact_id = {$otherId}";
445 }
446 break;
447
448 case 'civicrm_uf_match':
449 // normal queries won't work for uf_match since that will lead to violation of unique constraint,
450 // failing to meet intended result. Therefore we introduce this additional query:
451 $sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}";
452 break;
453 }
454
455 return $sqls;
456 }
457
458 /**
459 * Based on the provided two contact_ids and a set of tables, remove the
460 * belongings of the other contact and of their relations.
461 *
462 * @param int $otherID
463 * @param bool $tables
464 */
465 public static function removeContactBelongings($otherID, $tables) {
466 // CRM-20421: Removing Inherited memberships when memberships of parent are not migrated to new contact.
467 if (in_array("civicrm_membership", $tables)) {
468 $membershipIDs = CRM_Utils_Array::collect('id',
469 CRM_Utils_Array::value('values',
470 civicrm_api3("Membership", "get", [
471 "contact_id" => $otherID,
472 "return" => "id",
473 ])
474 )
475 );
476
477 if (!empty($membershipIDs)) {
478 civicrm_api3("Membership", "get", [
479 'owner_membership_id' => ['IN' => $membershipIDs],
480 'api.Membership.delete' => ['id' => '$value.id'],
481 ]);
482 }
483 }
484 }
485
486 /**
487 * Based on the provided two contact_ids and a set of tables, move the
488 * belongings of the other contact to the main one.
489 *
490 * @param int $mainId
491 * @param int $otherId
492 * @param bool $tables
493 * @param array $tableOperations
494 * @param array $customTableToCopyFrom
495 */
496 public static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = [], $customTableToCopyFrom = NULL) {
497 $cidRefs = self::cidRefs();
498 $eidRefs = self::eidRefs();
499 $cpTables = self::cpTables();
500 $paymentTables = self::paymentTables();
501
502 // getting all custom tables
503 $customTables = [];
504 if ($customTableToCopyFrom !== NULL) {
505 // @todo this duplicates cidRefs?
506 CRM_Core_DAO::appendCustomTablesExtendingContacts($customTables);
507 CRM_Core_DAO::appendCustomContactReferenceFields($customTables);
508 $customTables = array_keys($customTables);
509 }
510
511 $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
512
513 // if there aren't any specific tables, don't affect the ones handled by relTables()
514 // also don't affect tables in locTables() CRM-15658
515 $relTables = self::relTables();
516 $handled = self::locTables();
517
518 foreach ($relTables as $params) {
519 $handled = array_merge($handled, $params['tables']);
520 }
521 $affected = array_diff($affected, $handled);
522 $affected = array_unique(array_merge($affected, $tables));
523
524 $mainId = (int) $mainId;
525 $otherId = (int) $otherId;
526 $multi_value_tables = array_keys(CRM_Dedupe_Merger::getMultiValueCustomSets('cidRefs'));
527
528 $sqls = [];
529 foreach ($affected as $table) {
530 // skipping non selected single-value custom table's value migration
531 if (!in_array($table, $multi_value_tables)) {
532 if ($customTableToCopyFrom !== NULL && in_array($table, $customTables) && !in_array($table, $customTableToCopyFrom)) {
533 if (isset($cidRefs[$table]) && ($delCol = array_search('entity_id', $cidRefs[$table])) !== FALSE) {
534 // remove entity_id from the field list
535 unset($cidRefs[$table][$delCol]);
536 }
537 }
538 }
539
540 // Call custom processing function for objects that require it
541 if (isset($cpTables[$table])) {
542 foreach ($cpTables[$table] as $className => $fnName) {
543 $className::$fnName($mainId, $otherId, $sqls, $tables, $tableOperations);
544 }
545 // Skip normal processing
546 continue;
547 }
548
549 // use UPDATE IGNORE + DELETE query pair to skip on situations when
550 // there's a UNIQUE restriction on ($field, some_other_field) pair
551 if (isset($cidRefs[$table])) {
552 foreach ($cidRefs[$table] as $field) {
553 // carry related contributions CRM-5359
554 if (in_array($table, $paymentTables)) {
555 $paymentSqls = self::paymentSql($table, $mainId, $otherId);
556 $sqls = array_merge($sqls, $paymentSqls);
557
558 if (!empty($tables) && !in_array('civicrm_contribution', $tables)) {
559 $payOprSqls = self::operationSql($mainId, $otherId, $table, $tableOperations, 'payment');
560 $sqls = array_merge($sqls, $payOprSqls);
561 }
562 }
563
564 $preOperationSqls = self::operationSql($mainId, $otherId, $table, $tableOperations);
565 $sqls = array_merge($sqls, $preOperationSqls);
566
567 if ($customTableToCopyFrom !== NULL && in_array($table, $customTableToCopyFrom) && !self::customRecordExists($mainId, $table, $field) && $field == 'entity_id') {
568 // this is the entity_id column of a custom field group where:
569 // - the custom table should be copied as indicated by $customTableToCopyFrom
570 // e.g. because a field in the group was selected in a form
571 // - AND no record exists yet for the $mainId contact
572 // we only do this for column "entity_id" as we wouldn't want to
573 // run this INSERT for ContactReference fields
574 $sqls[] = "INSERT INTO $table ($field) VALUES ($mainId)";
575 }
576 $sqls[] = "UPDATE IGNORE $table SET $field = $mainId WHERE $field = $otherId";
577 $sqls[] = "DELETE FROM $table WHERE $field = $otherId";
578 }
579 }
580
581 if (isset($eidRefs[$table])) {
582 foreach ($eidRefs[$table] as $entityTable => $entityId) {
583 $sqls[] = "UPDATE IGNORE $table SET $entityId = $mainId WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
584 $sqls[] = "DELETE FROM $table WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
585 }
586 }
587 }
588
589 // Allow hook_civicrm_merge() to add SQL statements for the merge operation.
590 CRM_Utils_Hook::merge('sqls', $sqls, $mainId, $otherId, $tables);
591
592 foreach ($sqls as $sql) {
593 CRM_Core_DAO::executeQuery($sql, [], TRUE, NULL, TRUE);
594 }
595 CRM_Dedupe_Merger::addMembershipToRealtedContacts($mainId);
596 }
597
598 /**
599 * Given a contact ID, will check if a record exists in given table.
600 *
601 * @param $contactID
602 * @param $table
603 * @param $idField
604 * Field where the contact's ID is stored in the table
605 *
606 * @return bool
607 * True if a record is found for the given contact ID, false otherwise
608 */
609 private static function customRecordExists($contactID, $table, $idField) {
610 $sql = "
611 SELECT COUNT(*) AS count
612 FROM $table
613 WHERE $idField = $contactID
614 ";
615 $dbResult = CRM_Core_DAO::executeQuery($sql);
616 $dbResult->fetch();
617
618 if ($dbResult->count > 0) {
619 return TRUE;
620 }
621
622 return FALSE;
623 }
624
625 /**
626 * Load all non-empty fields for the contacts
627 *
628 * @param array $main
629 * Contact details.
630 * @param array $other
631 * Contact details.
632 *
633 * @return array
634 */
635 public static function retrieveFields($main, $other) {
636 $result = [
637 'contact' => [],
638 'custom' => [],
639 ];
640 foreach (self::getContactFields() as $validField) {
641 // CRM-17556 Get all non-empty fields, to make comparison easier
642 if (!empty($main[$validField]) || !empty($other[$validField])) {
643 $result['contact'][] = $validField;
644 }
645 }
646
647 $mainEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($main['id']);
648 $otherEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($other['id']);
649 $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
650 foreach ($keys as $key) {
651 // Exclude multi-value fields CRM-13836
652 if (strpos($key, '_')) {
653 continue;
654 }
655 $key1 = CRM_Utils_Array::value($key, $mainEvs);
656 $key2 = CRM_Utils_Array::value($key, $otherEvs);
657 // We wish to retain '0' as it has a different meaning than NULL on a checkbox.
658 // However I can't think of a case where an empty string is more meaningful than null
659 // or where it would be FALSE or something else nullish.
660 $valuesToIgnore = [NULL, '', []];
661 if (!in_array($key1, $valuesToIgnore, TRUE) || !in_array($key2, $valuesToIgnore, TRUE)) {
662 $result['custom'][] = $key;
663 }
664 }
665 return $result;
666 }
667
668 /**
669 * Batch merge a set of contacts based on rule-group and group.
670 *
671 * @param int $rgid
672 * Rule group id.
673 * @param int $gid
674 * Group id.
675 * @param string $mode
676 * Helps decide how to behave when there are conflicts.
677 * A 'safe' value skips the merge if there are any un-resolved conflicts, wheras 'aggressive'
678 * mode does a force merge.
679 * @param int $batchLimit number of merges to carry out in one batch.
680 * @param int $isSelected if records with is_selected column needs to be processed.
681 * Note the option of '2' is only used in conjunction with $redirectForPerformance
682 * to determine when to reload the cache (!). The use of anything other than a boolean is being grandfathered
683 * out in favour of explicitly passing in $reloadCacheIfEmpty
684 *
685 * @param array $criteria
686 * Criteria to use in the filter.
687 *
688 * @param bool $checkPermissions
689 * Respect logged in user permissions.
690 * @param bool|NULL $reloadCacheIfEmpty
691 * If not set explicitly this is calculated but it is preferred that it be set
692 * per comments on isSelected above.
693 *
694 * @return array|bool
695 *
696 * @throws \CRM_Core_Exception
697 * @throws \CiviCRM_API3_Exception
698 */
699 public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $batchLimit = 1, $isSelected = 2, $criteria = [], $checkPermissions = TRUE, $reloadCacheIfEmpty = NULL) {
700 $redirectForPerformance = ($batchLimit > 1) ? TRUE : FALSE;
701 if ($mode === 'aggressive' && $checkPermissions && !CRM_Core_Permission::check('force merge duplicate contacts')) {
702 throw new CRM_Core_Exception(ts('Insufficient permissions for aggressive mode batch merge'));
703 }
704 if (!isset($reloadCacheIfEmpty)) {
705 $reloadCacheIfEmpty = (!$redirectForPerformance && $isSelected == 2);
706 }
707 if ($isSelected !== 0 && $isSelected !== 1) {
708 // explicitly set to NULL if not 1 or 0 as part of grandfathering out the mystical '2' value.
709 $isSelected = NULL;
710 }
711 $dupePairs = self::getDuplicatePairs($rgid, $gid, $reloadCacheIfEmpty, $batchLimit, $isSelected, ($mode == 'aggressive'), $criteria, $checkPermissions);
712
713 $cacheParams = [
714 'cache_key_string' => self::getMergeCacheKeyString($rgid, $gid, $criteria, $checkPermissions),
715 // @todo stop passing these parameters in & instead calculate them in the merge function based
716 // on the 'real' params like $isRespectExclusions $batchLimit and $isSelected.
717 'join' => self::getJoinOnDedupeTable(),
718 'where' => self::getWhereString($isSelected),
719 'limit' => (int) $batchLimit,
720 ];
721 return CRM_Dedupe_Merger::merge($dupePairs, $cacheParams, $mode, $redirectForPerformance, $checkPermissions);
722 }
723
724 /**
725 * Get the string to join the prevnext cache to the dedupe table.
726 *
727 * @return string
728 * The join string to join prevnext cache on the dedupe table.
729 */
730 public static function getJoinOnDedupeTable() {
731 return "
732 LEFT JOIN civicrm_dedupe_exception de
733 ON (
734 pn.entity_id1 = de.contact_id1
735 AND pn.entity_id2 = de.contact_id2 )
736 ";
737 }
738
739 /**
740 * Get where string for dedupe join.
741 *
742 * @param bool $isSelected
743 *
744 * @return string
745 */
746 protected static function getWhereString($isSelected) {
747 $where = "de.id IS NULL";
748 if ($isSelected === 0 || $isSelected === 1) {
749 $where .= " AND pn.is_selected = {$isSelected}";
750 }
751 return $where;
752 }
753
754 /**
755 * Update the statistics for the merge set.
756 *
757 * @param string $cacheKeyString
758 * @param array $result
759 */
760 public static function updateMergeStats($cacheKeyString, $result = []) {
761 // gather latest stats
762 $merged = count($result['merged']);
763 $skipped = count($result['skipped']);
764
765 if ($merged <= 0 && $skipped <= 0) {
766 return;
767 }
768
769 // get previous stats
770 $previousStats = CRM_Dedupe_Merger::getMergeStats($cacheKeyString);
771 if (!empty($previousStats)) {
772 if ($previousStats['merged']) {
773 $merged = $merged + $previousStats['merged'];
774 }
775 if ($previousStats['skipped']) {
776 $skipped = $skipped + $previousStats['skipped'];
777 }
778 }
779
780 // delete old stats
781 CRM_Dedupe_Merger::resetMergeStats($cacheKeyString);
782
783 // store the updated stats
784 $data = [
785 'merged' => $merged,
786 'skipped' => $skipped,
787 ];
788 $data = CRM_Core_DAO::escapeString(serialize($data));
789
790 CRM_Core_BAO_PrevNextCache::setItem('civicrm_contact', 0, 0, $cacheKeyString . '_stats', $data);
791 }
792
793 /**
794 * Delete information about merges for the given string.
795 *
796 * @param $cacheKeyString
797 */
798 public static function resetMergeStats($cacheKeyString) {
799 CRM_Core_BAO_PrevNextCache::deleteItem(NULL, "{$cacheKeyString}_stats");
800 }
801
802 /**
803 * Get merge outcome statistics.
804 *
805 * @param string $cacheKeyString
806 *
807 * @return array
808 * Array of how many were merged and how many were skipped.
809 *
810 * @throws \CiviCRM_API3_Exception
811 */
812 public static function getMergeStats($cacheKeyString) {
813 $stats = civicrm_api3('Dedupe', 'get', ['cachekey' => "{$cacheKeyString}_stats", 'sequential' => 1])['values'];
814 if (!empty($stats)) {
815 return $stats[0]['data'];
816 }
817 return [];
818 }
819
820 /**
821 * Get merge statistics message.
822 *
823 * @param array $stats
824 *
825 * @return string
826 */
827 public static function getMergeStatsMsg($stats) {
828 $msg = '';
829 if (!empty($stats['merged'])) {
830 $msg = '<p>' . ts('One contact merged.', [
831 'count' => $stats['merged'],
832 'plural' => '%count contacts merged.',
833 ]) . '</p>';
834 }
835 if (!empty($stats['skipped'])) {
836 $msg .= '<p>' . ts('One contact was skipped.', [
837 'count' => $stats['skipped'],
838 'plural' => '%count contacts were skipped.',
839 ]) . '</p>';
840 }
841 return $msg;
842 }
843
844 /**
845 * Merge given set of contacts. Performs core operation.
846 *
847 * @param array $dupePairs
848 * Set of pair of contacts for whom merge is to be done.
849 * @param array $cacheParams
850 * Prev-next-cache params based on which next pair of contacts are computed.
851 * Generally used with batch-merge.
852 * @param string $mode
853 * Helps decide how to behave when there are conflicts.
854 * A 'safe' value skips the merge if there are any un-resolved conflicts.
855 * Does a force merge otherwise (aggressive mode).
856 *
857 * @param bool $redirectForPerformance
858 * Redirect to a url for batch processing.
859 *
860 * @param bool $checkPermissions
861 * Respect logged in user permissions.
862 *
863 * @return array|bool
864 */
865 public static function merge($dupePairs = [], $cacheParams = [], $mode = 'safe',
866 $redirectForPerformance = FALSE, $checkPermissions = TRUE
867 ) {
868 $cacheKeyString = CRM_Utils_Array::value('cache_key_string', $cacheParams);
869 $resultStats = ['merged' => [], 'skipped' => []];
870
871 // we don't want dupe caching to get reset after every-merge, and therefore set the
872 CRM_Core_Config::setPermitCacheFlushMode(FALSE);
873 $deletedContacts = [];
874
875 while (!empty($dupePairs)) {
876 foreach ($dupePairs as $index => $dupes) {
877 if (in_array($dupes['dstID'], $deletedContacts) || in_array($dupes['srcID'], $deletedContacts)) {
878 unset($dupePairs[$index]);
879 continue;
880 }
881 CRM_Utils_Hook::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']);
882 $mainId = $dupes['dstID'];
883 $otherId = $dupes['srcID'];
884
885 if (!$mainId || !$otherId) {
886 // return error
887 return FALSE;
888 }
889
890 self::dedupePair($resultStats, $deletedContacts, $mode, $checkPermissions, $mainId, $otherId, $cacheKeyString);
891 }
892
893 if ($cacheKeyString && !$redirectForPerformance) {
894 // retrieve next pair of dupes
895 // @todo call getDuplicatePairs.
896 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString,
897 $cacheParams['join'],
898 $cacheParams['where'],
899 0,
900 $cacheParams['limit'],
901 [],
902 '',
903 FALSE
904 );
905 }
906 else {
907 // do not proceed. Terminate the loop
908 unset($dupePairs);
909 }
910 }
911
912 CRM_Dedupe_Merger::updateMergeStats($cacheKeyString, $resultStats);
913 return $resultStats;
914 }
915
916 /**
917 * A function which uses various rules / algorithms for choosing which contact to bias to
918 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
919 *
920 * @param int $mainId
921 * Main contact with whom merge has to happen.
922 * @param int $otherId
923 * Duplicate contact which would be deleted after merge operation.
924 * @param array $migrationInfo
925 * Array of information about which elements to merge.
926 * @param string $mode
927 * Helps decide how to behave when there are conflicts.
928 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
929 * - Does a force merge otherwise (aggressive mode).
930 *
931 * @param array $conflicts
932 * An empty array to be filed with conflict information.
933 *
934 * @return bool
935 *
936 * @throws \CRM_Core_Exception
937 * @throws \CiviCRM_API3_Exception
938 * @throws \API_Exception
939 */
940 public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe', &$conflicts = []) {
941
942 $conflicts = self::getConflicts($migrationInfo, $mainId, $otherId, $mode);
943
944 if (!empty($conflicts)) {
945 // if there are conflicts and mode is aggressive, allow hooks to decide if to skip merges
946 return (bool) $migrationInfo['skip_merge'];
947 }
948 return FALSE;
949 }
950
951 /**
952 * Compare 2 addresses to see if they are the same.
953 *
954 * @param array $mainAddress
955 * @param array $comparisonAddress
956 *
957 * @return bool
958 */
959 public static function locationIsSame($mainAddress, $comparisonAddress) {
960 $keysToIgnore = self::ignoredFields();
961 foreach ($comparisonAddress as $field => $value) {
962 if (in_array($field, $keysToIgnore)) {
963 continue;
964 }
965 if ((!empty($value) || $value === '0') && isset($mainAddress[$field]) && $mainAddress[$field] != $value) {
966 return FALSE;
967 }
968 }
969 return TRUE;
970 }
971
972 /**
973 * A function to build an array of information about location blocks that is
974 * required when merging location fields
975 *
976 * @return array
977 */
978 public static function getLocationBlockInfo() {
979 $locationBlocks = [
980 'address' => [
981 'label' => 'Address',
982 'displayField' => 'display',
983 'sortString' => 'location_type_id',
984 'hasLocation' => TRUE,
985 'hasType' => FALSE,
986 ],
987 'email' => [
988 'label' => 'Email',
989 'displayField' => 'display',
990 'sortString' => 'location_type_id',
991 'hasLocation' => TRUE,
992 'hasType' => FALSE,
993 ],
994 'im' => [
995 'label' => 'IM',
996 'displayField' => 'name',
997 'sortString' => 'location_type_id,provider_id',
998 'hasLocation' => TRUE,
999 'hasType' => 'provider_id',
1000 ],
1001 'phone' => [
1002 'label' => 'Phone',
1003 'displayField' => 'phone',
1004 'sortString' => 'location_type_id,phone_type_id',
1005 'hasLocation' => TRUE,
1006 'hasType' => 'phone_type_id',
1007 ],
1008 'website' => [
1009 'label' => 'Website',
1010 'displayField' => 'url',
1011 'sortString' => 'website_type_id',
1012 'hasLocation' => FALSE,
1013 'hasType' => 'website_type_id',
1014 ],
1015 ];
1016 return $locationBlocks;
1017 }
1018
1019 /**
1020 * A function to build an array of information required by merge function and the merge UI.
1021 *
1022 * @param int $mainId
1023 * Main contact with whom merge has to happen.
1024 * @param int $otherId
1025 * Duplicate contact which would be deleted after merge operation.
1026 * @param bool $checkPermissions
1027 * Should the logged in user's permissions be ignore. Setting this to false is
1028 * highly risky as it could cause data to be lost due to conflicts not showing up.
1029 * OTOH there is a risk a merger might view custom data they do not have permission to.
1030 * Hence for now only making this really explicit and making it reflect perms in
1031 * an api call.
1032 *
1033 * @todo review permissions issue!
1034 *
1035 * @return array|bool|int
1036 *
1037 * rows => An array of arrays, each is row of merge information for the table
1038 * Format: move_fieldname, eg: move_contact_type
1039 * main => Value associated with the main contact
1040 * other => Value associated with the other contact
1041 * title => The title of the field to display in the merge table
1042 *
1043 * elements => An array of form elements for the merge UI
1044 *
1045 * rel_table_elements => An array of form elements for the merge UI for
1046 * entities related to the contact (eg: checkbox to move 'mailings')
1047 *
1048 * rel_tables => Stores the tables that have related entities for the contact
1049 * for example mailings, groups
1050 *
1051 * main_details => An array of core contact field values, eg: first_name, etc.
1052 * location_blocks => An array of location block data for the main contact
1053 * stored as the 'result' of an API call.
1054 * eg: main_details['location_blocks']['address'][0]['id']
1055 * eg: main_details['location_blocks']['email'][1]['id']
1056 *
1057 * other_details => As above, but for the 'other' contact
1058 *
1059 * migration_info => Stores the 'default' merge actions for each field which
1060 * is used when programatically merging contacts. It contains instructions
1061 * to move all fields from the 'other' contact to the 'main' contact, as
1062 * though the form had been submitted with those options.
1063 *
1064 * @throws \CRM_Core_Exception
1065 * @throws \CiviCRM_API3_Exception
1066 * @throws \Exception
1067 */
1068 public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissions = TRUE) {
1069 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1070 $fields = self::getMergeFieldsMetadata();
1071
1072 $main = self::getMergeContactDetails($mainId);
1073 $other = self::getMergeContactDetails($otherId);
1074
1075 $compareFields = self::retrieveFields($main, $other);
1076
1077 $rows = $elements = $relTableElements = $migrationInfo = [];
1078
1079 foreach ($compareFields['contact'] as $field) {
1080 if ($field == 'contact_sub_type') {
1081 // CRM-15681 don't display sub-types in UI
1082 continue;
1083 }
1084 foreach (['main' => $main, 'other' => $other] as $moniker => $contact) {
1085 $value = $label = CRM_Utils_Array::value($field, $contact);
1086 $fieldSpec = $fields[$field];
1087 if (!empty($fieldSpec['serialize']) && is_array($value)) {
1088 // In practice this only applies to preferred_communication_method as the sub types are skipped above
1089 // and no others are serialized.
1090 $labels = [];
1091 foreach ($value as $individualValue) {
1092 $labels[] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_BAO_Contact', $field, $individualValue);
1093 }
1094 $label = implode(', ', $labels);
1095 // We serialize this due to historic handling but it's likely that if we just left it as an
1096 // array all would be well & we would have less code.
1097 $value = CRM_Core_DAO::serializeField($value, $fieldSpec['serialize']);
1098 }
1099 elseif (!empty($fieldSpec['type']) && $fieldSpec['type'] == CRM_Utils_Type::T_DATE) {
1100 if ($value) {
1101 $value = str_replace('-', '', $value);
1102 $label = CRM_Utils_Date::customFormat($label);
1103 }
1104 else {
1105 $value = "null";
1106 }
1107 }
1108 elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) {
1109 if ($label === '0') {
1110 $label = ts('[ ]');
1111 }
1112 if ($label === '1') {
1113 $label = ts('[x]');
1114 }
1115 }
1116 elseif (!empty($fieldSpec['pseudoconstant'])) {
1117 $label = CRM_Core_PseudoConstant::getLabel('CRM_Contact_BAO_Contact', $field, $value);
1118 }
1119 elseif ($field == 'current_employer_id' && !empty($value)) {
1120 $label = "$value (" . CRM_Contact_BAO_Contact::displayName($value) . ")";
1121 }
1122 $rows["move_$field"][$moniker] = $label;
1123 if ($moniker == 'other') {
1124 //CRM-14334
1125 if ($value === NULL || $value == '') {
1126 $value = 'null';
1127 }
1128 if ($value === 0 or $value === '0') {
1129 $value = $qfZeroBug;
1130 }
1131 if (is_array($value) && empty($value[1])) {
1132 $value[1] = NULL;
1133 }
1134
1135 // Display a checkbox to migrate, only if the values are different
1136 if ($value != $main[$field]) {
1137 $elements[] = [
1138 'advcheckbox',
1139 "move_$field",
1140 NULL,
1141 NULL,
1142 NULL,
1143 $value,
1144 ];
1145 }
1146
1147 $migrationInfo["move_$field"] = $value;
1148 }
1149 }
1150 $rows["move_$field"]['title'] = $fields[$field]['title'];
1151 }
1152
1153 // Handle location blocks.
1154 // @todo OpenID not in API yet, so is not supported here.
1155
1156 // Set up useful information about the location blocks
1157 $locationBlocks = self::getLocationBlockInfo();
1158
1159 $locations = [
1160 'main' => [],
1161 'other' => [],
1162 ];
1163
1164 // @todo This could probably be defined and used earlier
1165 $mergeTargets = [
1166 'main' => $mainId,
1167 'other' => $otherId,
1168 ];
1169
1170 foreach ($locationBlocks as $blockName => $blockInfo) {
1171
1172 // Collect existing fields from both 'main' and 'other' contacts first
1173 // This allows us to match up location/types when building the table rows
1174 foreach ($mergeTargets as $moniker => $cid) {
1175 $searchParams = [
1176 'contact_id' => $cid,
1177 // CRM-17556 Order by field-specific criteria
1178 'options' => [
1179 'sort' => $blockInfo['sortString'],
1180 ],
1181 ];
1182 $values = civicrm_api3($blockName, 'get', $searchParams);
1183 if ($values['count']) {
1184 $cnt = 0;
1185 foreach ($values['values'] as $value) {
1186 $locations[$moniker][$blockName][$cnt] = $value;
1187 // Fix address display
1188 if ($blockName == 'address') {
1189 CRM_Core_BAO_Address::fixAddress($value);
1190 $locations[$moniker][$blockName][$cnt]['display'] = CRM_Utils_Address::format($value);
1191 }
1192 // Fix email display
1193 elseif ($blockName == 'email') {
1194 $locations[$moniker][$blockName][$cnt]['display'] = CRM_Utils_Mail::format($value);
1195 }
1196
1197 $cnt++;
1198 }
1199 }
1200 }
1201
1202 // Now, build the table rows appropriately, based off the information on
1203 // the 'other' contact
1204 if (!empty($locations['other']) && !empty($locations['other'][$blockName])) {
1205 foreach ($locations['other'][$blockName] as $count => $value) {
1206
1207 $displayValue = $value[$blockInfo['displayField']];
1208
1209 // Add this value to the table rows
1210 $rows["move_location_{$blockName}_{$count}"]['other'] = $displayValue;
1211
1212 // CRM-17556 Only display 'main' contact value if it's the same location + type
1213 // Look it up from main values...
1214
1215 $lookupLocation = FALSE;
1216 if ($blockInfo['hasLocation']) {
1217 $lookupLocation = $value['location_type_id'];
1218 }
1219
1220 $lookupType = FALSE;
1221 if ($blockInfo['hasType']) {
1222 $lookupType = CRM_Utils_Array::value($blockInfo['hasType'], $value);
1223 }
1224
1225 // Hold ID of main contact's matching block
1226 $mainContactBlockId = 0;
1227
1228 if (!empty($locations['main'][$blockName])) {
1229 foreach ($locations['main'][$blockName] as $mainValueCheck) {
1230 // No location/type, or matching location and type
1231 if (
1232 (empty($lookupLocation) || $lookupLocation == $mainValueCheck['location_type_id'])
1233 && (empty($lookupType) || $lookupType == $mainValueCheck[$blockInfo['hasType']])
1234 ) {
1235 // Set this value as the default against the 'other' contact value
1236 $rows["move_location_{$blockName}_{$count}"]['main'] = $mainValueCheck[$blockInfo['displayField']];
1237 $rows["move_location_{$blockName}_{$count}"]['main_is_primary'] = $mainValueCheck['is_primary'];
1238 $rows["move_location_{$blockName}_{$count}"]['location_entity'] = $blockName;
1239 $mainContactBlockId = $mainValueCheck['id'];
1240 break;
1241 }
1242 }
1243 }
1244
1245 // Add checkbox to migrate data from 'other' to 'main'
1246 $elements[] = ['advcheckbox', "move_location_{$blockName}_{$count}"];
1247
1248 // Add checkbox to set the 'other' location as primary
1249 $elements[] = [
1250 'advcheckbox',
1251 "location_blocks[$blockName][$count][set_other_primary]",
1252 NULL,
1253 ts('Set as primary'),
1254 ];
1255
1256 // Flag up this field to skipMerge function (@todo: do we need to?)
1257 $migrationInfo["move_location_{$blockName}_{$count}"] = 1;
1258
1259 // Add a hidden field to store the ID of the target main contact block
1260 $elements[] = [
1261 'hidden',
1262 "location_blocks[$blockName][$count][mainContactBlockId]",
1263 $mainContactBlockId,
1264 ];
1265
1266 // Setup variables
1267 $thisTypeId = FALSE;
1268 $thisLocId = FALSE;
1269
1270 // Provide a select drop-down for the location's location type
1271 // eg: Home, Work...
1272
1273 if ($blockInfo['hasLocation']) {
1274
1275 // Load the location options for this entity
1276 $locationOptions = civicrm_api3($blockName, 'getoptions', ['field' => 'location_type_id']);
1277
1278 $thisLocId = $value['location_type_id'];
1279
1280 // Put this field's location type at the top of the list
1281 $tmpIdList = $locationOptions['values'];
1282 $defaultLocId = [$thisLocId => $tmpIdList[$thisLocId]];
1283 unset($tmpIdList[$thisLocId]);
1284
1285 // Add the element
1286 $elements[] = [
1287 'select',
1288 "location_blocks[$blockName][$count][locTypeId]",
1289 NULL,
1290 $defaultLocId + $tmpIdList,
1291 ];
1292
1293 // Add the relevant information to the $migrationInfo
1294 // Keep location-type-id same as that of other-contact
1295 // @todo Check this logic out
1296 $migrationInfo['location_blocks'][$blockName][$count]['locTypeId'] = $thisLocId;
1297 if ($blockName != 'address') {
1298 $elements[] = [
1299 'advcheckbox',
1300 "location_blocks[{$blockName}][$count][operation]",
1301 NULL,
1302 ts('Add new'),
1303 ];
1304 // always use add operation
1305 $migrationInfo['location_blocks'][$blockName][$count]['operation'] = 1;
1306 }
1307
1308 }
1309
1310 // Provide a select drop-down for the location's type/provider
1311 // eg websites: Google+, Facebook...
1312
1313 if ($blockInfo['hasType']) {
1314
1315 // Load the type options for this entity
1316 $typeOptions = civicrm_api3($blockName, 'getoptions', ['field' => $blockInfo['hasType']]);
1317
1318 $thisTypeId = CRM_Utils_Array::value($blockInfo['hasType'], $value);
1319
1320 // Put this field's location type at the top of the list
1321 $tmpIdList = $typeOptions['values'];
1322 $defaultTypeId = [$thisTypeId => CRM_Utils_Array::value($thisTypeId, $tmpIdList)];
1323 unset($tmpIdList[$thisTypeId]);
1324
1325 // Add the element
1326 $elements[] = [
1327 'select',
1328 "location_blocks[$blockName][$count][typeTypeId]",
1329 NULL,
1330 $defaultTypeId + $tmpIdList,
1331 ];
1332
1333 // Add the information to the migrationInfo
1334 $migrationInfo['location_blocks'][$blockName][$count]['typeTypeId'] = $thisTypeId;
1335
1336 }
1337
1338 // Set the label for this row
1339 $rowTitle = $blockInfo['label'] . ' ' . ($count + 1);
1340 if (!empty($thisLocId)) {
1341 $rowTitle .= ' (' . $locationOptions['values'][$thisLocId] . ')';
1342 }
1343 if (!empty($thisTypeId)) {
1344 $rowTitle .= ' (' . $typeOptions['values'][$thisTypeId] . ')';
1345 }
1346 $rows["move_location_{$blockName}_$count"]['title'] = $rowTitle;
1347
1348 } // End loop through 'other' locations of this type
1349
1350 } // End if 'other' location for this type exists
1351
1352 } // End loop through each location block entity
1353
1354 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1355 $config = CRM_Core_Config::singleton();
1356 $mainUfId = CRM_Core_BAO_UFMatch::getUFId($mainId);
1357 $mainUser = NULL;
1358 if ($mainUfId) {
1359 // d6 compatible
1360 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1361 $mainUser = user_load($mainUfId);
1362 }
1363 elseif ($config->userFramework == 'Joomla') {
1364 $mainUser = JFactory::getUser($mainUfId);
1365 }
1366 }
1367 $otherUfId = CRM_Core_BAO_UFMatch::getUFId($otherId);
1368 $otherUser = NULL;
1369 if ($otherUfId) {
1370 // d6 compatible
1371 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1372 $otherUser = user_load($otherUfId);
1373 }
1374 elseif ($config->userFramework == 'Joomla') {
1375 $otherUser = JFactory::getUser($otherUfId);
1376 }
1377 }
1378
1379 $relTables = CRM_Dedupe_Merger::relTables();
1380 $activeRelTables = CRM_Dedupe_Merger::getActiveRelTables($otherId);
1381 $activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId);
1382 foreach ($relTables as $name => $null) {
1383 if (!in_array($name, $activeRelTables) &&
1384 !(($name == 'rel_table_users') && in_array($name, $activeMainRelTables))
1385 ) {
1386 unset($relTables[$name]);
1387 continue;
1388 }
1389
1390 $relTableElements[] = ['checkbox', "move_$name"];
1391 $migrationInfo["move_$name"] = 1;
1392
1393 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1394 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1395 if ($name == 'rel_table_users') {
1396 $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
1397 $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
1398 $find = ['$ufid', '$ufname'];
1399 if ($mainUser) {
1400 $replace = [$mainUfId, $mainUser->name];
1401 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1402 }
1403 if ($otherUser) {
1404 $replace = [$otherUfId, $otherUser->name];
1405 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1406 }
1407 }
1408 if ($name == 'rel_table_memberships') {
1409 //Enable 'add new' checkbox if main contact does not contain any membership similar to duplicate contact.
1410 $attributes = ['checked' => 'checked'];
1411 $otherContactMemberships = CRM_Member_BAO_Membership::getAllContactMembership($otherId);
1412 foreach ($otherContactMemberships as $membership) {
1413 $mainMembership = CRM_Member_BAO_Membership::getContactMembership($mainId, $membership['membership_type_id'], FALSE);
1414 if ($mainMembership) {
1415 $attributes = [];
1416 }
1417 }
1418 $elements[] = [
1419 'checkbox',
1420 "operation[move_{$name}][add]",
1421 NULL,
1422 ts('add new'),
1423 $attributes,
1424 ];
1425 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1426 }
1427 }
1428 foreach ($relTables as $name => $null) {
1429 $relTables["move_$name"] = $relTables[$name];
1430 unset($relTables[$name]);
1431 }
1432
1433 // handle custom fields
1434 $mainTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], NULL, $mainId, -1,
1435 CRM_Utils_Array::value('contact_sub_type', $main), NULL, TRUE, NULL, TRUE, $checkPermissions
1436 );
1437 $otherTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], NULL, $otherId, -1,
1438 CRM_Utils_Array::value('contact_sub_type', $other), NULL, TRUE, NULL, TRUE, $checkPermissions
1439 );
1440
1441 foreach ($otherTree as $gid => $group) {
1442 $foundField = FALSE;
1443 if (!isset($group['fields'])) {
1444 continue;
1445 }
1446
1447 foreach ($group['fields'] as $fid => $field) {
1448 if (in_array($fid, $compareFields['custom'])) {
1449 if (!$foundField) {
1450 $rows["custom_group_$gid"]['title'] = $group['title'];
1451 $foundField = TRUE;
1452 }
1453 if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) {
1454 foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1455 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid);
1456 }
1457 }
1458 $value = "null";
1459 if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) {
1460 foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1461 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid);
1462 if ($values['data'] === 0 || $values['data'] === '0') {
1463 $values['data'] = $qfZeroBug;
1464 }
1465 $value = ($values['data']) ? $values['data'] : $value;
1466 }
1467 }
1468 $rows["move_custom_$fid"]['title'] = $field['label'];
1469
1470 $elements[] = [
1471 'advcheckbox',
1472 "move_custom_$fid",
1473 NULL,
1474 NULL,
1475 NULL,
1476 $value,
1477 ];
1478 $migrationInfo["move_custom_$fid"] = $value;
1479 }
1480 }
1481 }
1482
1483 $result = [
1484 'rows' => $rows,
1485 'elements' => $elements,
1486 'rel_table_elements' => $relTableElements,
1487 'rel_tables' => $relTables,
1488 'main_details' => $main,
1489 'other_details' => $other,
1490 'migration_info' => $migrationInfo,
1491 ];
1492
1493 $result['main_details']['location_blocks'] = $locations['main'];
1494 $result['other_details']['location_blocks'] = $locations['other'];
1495
1496 return $result;
1497 }
1498
1499 /**
1500 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1501 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1502 * A superset of moveContactBelongings() function.
1503 *
1504 * @param int $mainId
1505 * Main contact with whom merge has to happen.
1506 * @param int $otherId
1507 * Duplicate contact which would be deleted after merge operation.
1508 *
1509 * @param array $migrationInfo
1510 *
1511 * @param bool $checkPermissions
1512 * Respect logged in user permissions.
1513 *
1514 * @return bool
1515 * @throws \CiviCRM_API3_Exception
1516 */
1517 public static function moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions = TRUE) {
1518 if (empty($migrationInfo)) {
1519 return FALSE;
1520 }
1521 // Encapsulate in a transaction to avoid half-merges.
1522 $transaction = new CRM_Core_Transaction();
1523
1524 $contactType = $migrationInfo['main_details']['contact_type'];
1525 $relTables = CRM_Dedupe_Merger::relTables();
1526 $submittedCustomFields = $moveTables = $tableOperations = $removeTables = [];
1527
1528 self::swapOutFieldsAffectedByQFZeroBug($migrationInfo);
1529 foreach ($migrationInfo as $key => $value) {
1530
1531 if (substr($key, 0, 12) == 'move_custom_' && $value != NULL) {
1532 $submitted[substr($key, 5)] = $value;
1533 $submittedCustomFields[] = substr($key, 12);
1534 }
1535 elseif (in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) && $value != NULL) {
1536 $submitted[substr($key, 5)] = $value;
1537 }
1538 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1539 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1540 if (array_key_exists('operation', $migrationInfo)) {
1541 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1542 if (array_key_exists($key, $migrationInfo['operation'])) {
1543 $tableOperations[$table] = $migrationInfo['operation'][$key];
1544 }
1545 }
1546 }
1547 }
1548 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '0') {
1549 $removeTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1550 }
1551 }
1552 self::mergeLocations($mainId, $otherId, $migrationInfo);
1553
1554 // **** Do contact related migrations
1555 $customTablesToCopyValues = self::getAffectedCustomTables($submittedCustomFields);
1556 // @todo - move all custom field processing to the move class & eventually have an
1557 // overridable DAO class for it.
1558 $customFieldBAO = new CRM_Core_BAO_CustomField();
1559 $customFieldBAO->move($otherId, $mainId, $submittedCustomFields);
1560 CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations, $customTablesToCopyValues);
1561 unset($moveTables, $tableOperations);
1562
1563 // **** Do table related removals
1564 if (!empty($removeTables)) {
1565 // **** CRM-20421
1566 CRM_Dedupe_Merger::removeContactBelongings($otherId, $removeTables);
1567 $removeTables = [];
1568 }
1569
1570 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
1571 $names['gender'] = ['newName' => 'gender_id', 'groupName' => 'gender'];
1572 $names['individual_prefix'] = [
1573 'newName' => 'prefix_id',
1574 'groupName' => 'individual_prefix',
1575 ];
1576 $names['individual_suffix'] = [
1577 'newName' => 'suffix_id',
1578 'groupName' => 'individual_suffix',
1579 ];
1580 $names['communication_style'] = [
1581 'newName' => 'communication_style_id',
1582 'groupName' => 'communication_style',
1583 ];
1584 $names['addressee'] = [
1585 'newName' => 'addressee_id',
1586 'groupName' => 'addressee',
1587 ];
1588 $names['email_greeting'] = [
1589 'newName' => 'email_greeting_id',
1590 'groupName' => 'email_greeting',
1591 ];
1592 $names['postal_greeting'] = [
1593 'newName' => 'postal_greeting_id',
1594 'groupName' => 'postal_greeting',
1595 ];
1596 CRM_Core_OptionGroup::lookupValues($submitted, $names, TRUE);
1597 // fix custom fields so they're edible by createProfileContact()
1598 $cFields = self::getCustomFieldMetadata($contactType);
1599
1600 if (!isset($submitted)) {
1601 $submitted = [];
1602 }
1603 foreach ($submitted as $key => $value) {
1604 list($cFields, $submitted) = self::processCustomFields($mainId, $key, $cFields, $submitted, $value);
1605 }
1606
1607 // move view only custom fields CRM-5362
1608 $viewOnlyCustomFields = [];
1609 foreach ($submitted as $key => $value) {
1610 $fid = CRM_Core_BAO_CustomField::getKeyID($key);
1611 if ($fid && array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])
1612 ) {
1613 $viewOnlyCustomFields[$key] = $value;
1614 }
1615 }
1616 // special case to set values for view only, CRM-5362
1617 if (!empty($viewOnlyCustomFields)) {
1618 $viewOnlyCustomFields['entityID'] = $mainId;
1619 CRM_Core_BAO_CustomValueTable::setValues($viewOnlyCustomFields);
1620 }
1621
1622 // dev/core#996 Ensure that the earliest created date is stored against the kept contact id
1623 $mainCreatedDate = civicrm_api3('Contact', 'getsingle', [
1624 'id' => $mainId,
1625 'return' => ['created_date'],
1626 ])['created_date'];
1627 $otherCreatedDate = civicrm_api3('Contact', 'getsingle', [
1628 'id' => $otherId,
1629 'return' => ['created_date'],
1630 ])['created_date'];
1631 if ($otherCreatedDate < $mainCreatedDate) {
1632 CRM_Core_DAO::executeQuery("UPDATE civicrm_contact SET created_date = %1 WHERE id = %2", [
1633 1 => [$otherCreatedDate, 'String'],
1634 2 => [$mainId, 'Positive'],
1635 ]);
1636 }
1637
1638 if (!$checkPermissions || (CRM_Core_Permission::check('merge duplicate contacts') &&
1639 CRM_Core_Permission::check('delete contacts'))
1640 ) {
1641 // if ext id is submitted then set it null for contact to be deleted
1642 if (!empty($submitted['external_identifier'])) {
1643 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1644 CRM_Core_DAO::executeQuery($query);
1645 }
1646 civicrm_api3('contact', 'delete', ['id' => $otherId]);
1647 }
1648
1649 // CRM-15681 merge sub_types
1650 if ($other_sub_types = CRM_Utils_Array::value('contact_sub_type', $migrationInfo['other_details'])) {
1651 if ($main_sub_types = CRM_Utils_Array::value('contact_sub_type', $migrationInfo['main_details'])) {
1652 $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types));
1653 }
1654 else {
1655 $submitted['contact_sub_type'] = $other_sub_types;
1656 }
1657 }
1658
1659 // **** Update contact related info for the main contact
1660 if (!empty($submitted)) {
1661 $submitted['contact_id'] = $mainId;
1662
1663 //update current employer field
1664 if ($currentEmloyerId = CRM_Utils_Array::value('current_employer_id', $submitted)) {
1665 if (!CRM_Utils_System::isNull($currentEmloyerId)) {
1666 $submitted['current_employer'] = $submitted['current_employer_id'];
1667 }
1668 else {
1669 $submitted['current_employer'] = '';
1670 }
1671 unset($submitted['current_employer_id']);
1672 }
1673
1674 //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
1675 if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) {
1676 $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
1677 }
1678 if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) {
1679 $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
1680 }
1681 $null = [];
1682 CRM_Contact_BAO_Contact::createProfileContact($submitted, $null, $mainId);
1683 }
1684 $transaction->commit();
1685 CRM_Utils_Hook::post('merge', 'Contact', $mainId);
1686 self::createMergeActivities($mainId, $otherId);
1687
1688 return TRUE;
1689 }
1690
1691 /**
1692 * Builds an Array of Custom tables for given custom field ID's.
1693 *
1694 * @param $customFieldIDs
1695 *
1696 * @return array
1697 * Array of custom table names
1698 */
1699 private static function getAffectedCustomTables($customFieldIDs) {
1700 $customTableToCopyValues = [];
1701
1702 foreach ($customFieldIDs as $fieldID) {
1703 if (!empty($fieldID)) {
1704 $customField = civicrm_api3('custom_field', 'getsingle', [
1705 'id' => $fieldID,
1706 'is_active' => TRUE,
1707 ]);
1708 if (!civicrm_error($customField) && !empty($customField['custom_group_id'])) {
1709 $customGroup = civicrm_api3('custom_group', 'getsingle', [
1710 'id' => $customField['custom_group_id'],
1711 'is_active' => TRUE,
1712 ]);
1713
1714 if (!civicrm_error($customGroup) && !empty($customGroup['table_name'])) {
1715 $customTableToCopyValues[] = $customGroup['table_name'];
1716 }
1717 }
1718 }
1719 }
1720
1721 return $customTableToCopyValues;
1722 }
1723
1724 /**
1725 * Get fields in the contact table suitable for merging.
1726 *
1727 * @return array
1728 * Array of field names to be potentially merged.
1729 */
1730 public static function getContactFields() {
1731 $contactFields = CRM_Contact_DAO_Contact::fields();
1732 $invalidFields = [
1733 'api_key',
1734 'created_date',
1735 'display_name',
1736 'hash',
1737 'id',
1738 'modified_date',
1739 'primary_contact_id',
1740 'sort_name',
1741 'user_unique_id',
1742 ];
1743 foreach ($contactFields as $field => $value) {
1744 if (in_array($field, $invalidFields)) {
1745 unset($contactFields[$field]);
1746 }
1747 }
1748 return array_keys($contactFields);
1749 }
1750
1751 /**
1752 * Added for CRM-12695
1753 * Based on the contactID provided
1754 * add/update membership(s) to related contacts
1755 *
1756 * @param int $contactID
1757 */
1758 public static function addMembershipToRealtedContacts($contactID) {
1759 $dao = new CRM_Member_DAO_Membership();
1760 $dao->contact_id = $contactID;
1761 $dao->is_test = 0;
1762 $dao->find();
1763
1764 //checks membership of contact itself
1765 while ($dao->fetch()) {
1766 $relationshipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id, 'relationship_type_id', 'id');
1767 if ($relationshipTypeId) {
1768 $membershipParams = [
1769 'id' => $dao->id,
1770 'contact_id' => $dao->contact_id,
1771 'membership_type_id' => $dao->membership_type_id,
1772 'join_date' => CRM_Utils_Date::isoToMysql($dao->join_date),
1773 'start_date' => CRM_Utils_Date::isoToMysql($dao->start_date),
1774 'end_date' => CRM_Utils_Date::isoToMysql($dao->end_date),
1775 'source' => $dao->source,
1776 'status_id' => $dao->status_id,
1777 ];
1778 // create/update membership(s) for related contact(s)
1779 CRM_Member_BAO_Membership::createRelatedMemberships($membershipParams, $dao);
1780 } // end of if relationshipTypeId
1781 }
1782 }
1783
1784 /**
1785 * Create activities tracking the merge on affected contacts.
1786 *
1787 * @param int $mainId
1788 * @param int $otherId
1789 *
1790 * @throws \CiviCRM_API3_Exception
1791 */
1792 public static function createMergeActivities($mainId, $otherId) {
1793 $params = [
1794 1 => $otherId,
1795 2 => $mainId,
1796 ];
1797 $activity = civicrm_api3('activity', 'create', [
1798 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() :
1799 $mainId,
1800 'subject' => ts('Contact ID %1 has been merged and deleted.', $params),
1801 'target_contact_id' => $mainId,
1802 'activity_type_id' => 'Contact Merged',
1803 'status_id' => 'Completed',
1804 ]);
1805 if (civicrm_api3('Setting', 'getvalue', [
1806 'name' => 'contact_undelete',
1807 'group' => 'CiviCRM Preferences',
1808 ])) {
1809 civicrm_api3('activity', 'create', [
1810 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() :
1811 $otherId,
1812 'subject' => ts('Contact ID %1 has been merged into Contact ID %2 and deleted.', $params),
1813 'target_contact_id' => $otherId,
1814 'activity_type_id' => 'Contact Deleted by Merge',
1815 'parent_id' => $activity['id'],
1816 'status_id' => 'Completed',
1817 ]);
1818 }
1819 }
1820
1821 /**
1822 * Get Duplicate Pairs based on a rule for a group.
1823 *
1824 * @param int $rule_group_id
1825 * @param int $group_id
1826 * @param bool $reloadCacheIfEmpty
1827 * Should the cache be reloaded if empty - this must be false when in a dedupe action!
1828 * @param int $batchLimit
1829 * @param bool $isSelected
1830 * Limit to selected pairs.
1831 * @param bool $includeConflicts
1832 * @param array $criteria
1833 * Additional criteria to narrow down the merge group.
1834 *
1835 * @param bool $checkPermissions
1836 * Respect logged in user permissions.
1837 *
1838 * @param int $searchLimit
1839 * Limit to searching for matches against this many contacts.
1840 *
1841 * @return array
1842 * Array of matches meeting the criteria.
1843 *
1844 * @throws \CRM_Core_Exception
1845 * @throws \CiviCRM_API3_Exception
1846 */
1847 public static function getDuplicatePairs($rule_group_id, $group_id, $reloadCacheIfEmpty, $batchLimit, $isSelected, $includeConflicts = TRUE, $criteria = [], $checkPermissions = TRUE, $searchLimit = 0) {
1848 $dupePairs = self::getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, $includeConflicts, $criteria, $checkPermissions);
1849 if (empty($dupePairs) && $reloadCacheIfEmpty) {
1850 // If we haven't found any dupes, probably cache is empty.
1851 // Try filling cache and give another try. We don't need to specify include conflicts here are there will not be any
1852 // until we have done some processing.
1853 CRM_Core_BAO_PrevNextCache::refillCache($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit);
1854 return self::getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, FALSE, $criteria, $checkPermissions);
1855 }
1856 return $dupePairs;
1857 }
1858
1859 /**
1860 * Get the cache key string for the merge action.
1861 *
1862 * @param int $rule_group_id
1863 * @param int $group_id
1864 * @param array $criteria
1865 * Additional criteria to narrow down the merge group.
1866 * Currently we are only supporting the key 'contact' within it.
1867 *
1868 * @param bool $checkPermissions
1869 * Respect the users permissions.
1870 *
1871 * @return string
1872 */
1873 public static function getMergeCacheKeyString($rule_group_id, $group_id, $criteria = [], $checkPermissions = TRUE) {
1874 $contactType = CRM_Dedupe_BAO_RuleGroup::getContactTypeForRuleGroup($rule_group_id);
1875 $cacheKeyString = "merge_{$contactType}";
1876 $cacheKeyString .= $rule_group_id ? "_{$rule_group_id}" : '_0';
1877 $cacheKeyString .= $group_id ? "_{$group_id}" : '_0';
1878 $cacheKeyString .= !empty($criteria) ? md5(serialize($criteria)) : '_0';
1879 if ($checkPermissions) {
1880 $contactID = CRM_Core_Session::getLoggedInContactID();
1881 if (!$contactID) {
1882 // Distinguish between no permission check & no logged in user.
1883 $contactID = 'null';
1884 }
1885 $cacheKeyString .= '_' . $contactID;
1886 }
1887 else {
1888 $cacheKeyString .= '_0';
1889 }
1890 return $cacheKeyString;
1891 }
1892
1893 /**
1894 * Get the metadata for the merge fields.
1895 *
1896 * This is basically the contact metadata, augmented with fields to
1897 * represent email greeting, postal greeting & addressee.
1898 *
1899 * @return array
1900 */
1901 public static function getMergeFieldsMetadata() {
1902 if (isset(\Civi::$statics[__CLASS__]) && isset(\Civi::$statics[__CLASS__]['merge_fields_metadata'])) {
1903 return \Civi::$statics[__CLASS__]['merge_fields_metadata'];
1904 }
1905 $fields = CRM_Contact_DAO_Contact::fields();
1906 static $optionValueFields = [];
1907 if (empty($optionValueFields)) {
1908 $optionValueFields = CRM_Core_OptionValue::getFields();
1909 }
1910 foreach ($optionValueFields as $field => $params) {
1911 $fields[$field]['title'] = $params['title'];
1912 }
1913 \Civi::$statics[__CLASS__]['merge_fields_metadata'] = $fields;
1914 return \Civi::$statics[__CLASS__]['merge_fields_metadata'];
1915 }
1916
1917 /**
1918 * Get the details of the contact to be merged.
1919 *
1920 * @param int $contact_id
1921 *
1922 * @return array
1923 *
1924 * @throws CRM_Core_Exception
1925 */
1926 public static function getMergeContactDetails($contact_id) {
1927 $params = [
1928 'contact_id' => $contact_id,
1929 'version' => 3,
1930 'return' => array_merge(['display_name'], self::getContactFields()),
1931 ];
1932 $result = civicrm_api('contact', 'get', $params);
1933
1934 // CRM-18480: Cancel the process if the contact is already deleted
1935 if (isset($result['values'][$contact_id]['contact_is_deleted']) && !empty($result['values'][$contact_id]['contact_is_deleted'])) {
1936 throw new CRM_Core_Exception(ts('Cannot merge because one contact (ID %1) has been deleted.', [
1937 1 => $contact_id,
1938 ]));
1939 }
1940
1941 return $result['values'][$contact_id];
1942 }
1943
1944 /**
1945 * Merge location.
1946 *
1947 * Based on the data in the $locationMigrationInfo merge the locations for 2 contacts.
1948 *
1949 * The data is in the format received from the merge form (which is a fairly confusing format).
1950 *
1951 * It is converted into an array of DAOs which is passed to the alterLocationMergeData hook
1952 * before saving or deleting the DAOs. A new hook is added to allow these to be altered after they have
1953 * been calculated and before saving because
1954 * - the existing format & hook combo is so confusing it is hard for developers to change & inherently fragile
1955 * - passing to a hook right before save means calculations only have to be done once
1956 * - the existing pattern of passing dissimilar data to the same (merge) hook with a different 'type' is just
1957 * ugly.
1958 *
1959 * The use of the new hook is tested, including the fact it is called before contributions are merged, as this
1960 * is likely to be significant data in merge hooks.
1961 *
1962 * @param int $mainId
1963 * @param int $otherId
1964 *
1965 * @param array $migrationInfo
1966 * Migration info for the merge. This is passed to the hook as informational only.
1967 */
1968 public static function mergeLocations($mainId, $otherId, $migrationInfo) {
1969 foreach ($migrationInfo as $key => $value) {
1970 $isLocationField = (substr($key, 0, 14) == 'move_location_' and $value != NULL);
1971 if (!$isLocationField) {
1972 continue;
1973 }
1974 $locField = explode('_', $key);
1975 $fieldName = $locField[2];
1976 $fieldCount = $locField[3];
1977
1978 // Set up the operation type (add/overwrite)
1979 // Ignore operation for websites
1980 // @todo Tidy this up
1981 $operation = 0;
1982 if ($fieldName != 'website') {
1983 $operation = CRM_Utils_Array::value('operation', $migrationInfo['location_blocks'][$fieldName][$fieldCount]);
1984 }
1985 // default operation is overwrite.
1986 if (!$operation) {
1987 $operation = 2;
1988 }
1989 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
1990 }
1991 $blocksDAO = [];
1992
1993 // @todo Handle OpenID (not currently in API).
1994 if (!empty($locBlocks)) {
1995 $locationBlocks = self::getLocationBlockInfo();
1996
1997 $primaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, ['is_primary' => 1]);
1998 $billingBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, ['is_billing' => 1]);
1999
2000 foreach ($locBlocks as $name => $block) {
2001 $blocksDAO[$name] = ['delete' => [], 'update' => []];
2002 if (!is_array($block) || CRM_Utils_System::isNull($block)) {
2003 continue;
2004 }
2005 $daoName = 'CRM_Core_DAO_' . $locationBlocks[$name]['label'];
2006 $changePrimary = FALSE;
2007 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ? array_pop($primaryBlockIds[$name]) : NULL;
2008 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ? array_pop($billingBlockIds[$name]) : NULL;
2009
2010 foreach ($block as $blkCount => $values) {
2011 $otherBlockId = CRM_Utils_Array::value('id', $migrationInfo['other_details']['location_blocks'][$name][$blkCount]);
2012 $mainBlockId = CRM_Utils_Array::value('mainContactBlockId', $migrationInfo['location_blocks'][$name][$blkCount], 0);
2013 if (!$otherBlockId) {
2014 continue;
2015 }
2016
2017 // For the block which belongs to other-contact, link the location block to main-contact
2018 $otherBlockDAO = new $daoName();
2019 $otherBlockDAO->contact_id = $mainId;
2020
2021 // Get the ID of this block on the 'other' contact, otherwise skip
2022 $otherBlockDAO->id = $otherBlockId;
2023
2024 // Add/update location and type information from the form, if applicable
2025 if ($locationBlocks[$name]['hasLocation']) {
2026 $locTypeId = CRM_Utils_Array::value('locTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
2027 $otherBlockDAO->location_type_id = $locTypeId;
2028 }
2029 if ($locationBlocks[$name]['hasType']) {
2030 $typeTypeId = CRM_Utils_Array::value('typeTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
2031 $otherBlockDAO->{$locationBlocks[$name]['hasType']} = $typeTypeId;
2032 }
2033
2034 // If we're deliberately setting this as primary then add the flag
2035 // and remove it from the current primary location (if there is one).
2036 // But only once for each entity.
2037 $set_primary = CRM_Utils_Array::value('set_other_primary', $migrationInfo['location_blocks'][$name][$blkCount]);
2038 if (!$changePrimary && $set_primary == "1") {
2039 $otherBlockDAO->is_primary = 1;
2040 if ($primaryDAOId) {
2041 $removePrimaryDAO = new $daoName();
2042 $removePrimaryDAO->id = $primaryDAOId;
2043 $removePrimaryDAO->is_primary = 0;
2044 $blocksDAO[$name]['update'][$primaryDAOId] = $removePrimaryDAO;
2045 }
2046 $changePrimary = TRUE;
2047 }
2048 // Otherwise, if main contact already has primary, set it to 0.
2049 elseif ($primaryDAOId) {
2050 $otherBlockDAO->is_primary = 0;
2051 }
2052
2053 // If the main contact already has a billing location, set this to 0.
2054 if ($billingDAOId) {
2055 $otherBlockDAO->is_billing = 0;
2056 }
2057
2058 $operation = CRM_Utils_Array::value('operation', $values, 2);
2059 // overwrite - need to delete block which belongs to main-contact.
2060 if (!empty($mainBlockId) && ($operation == 2)) {
2061 $deleteDAO = new $daoName();
2062 $deleteDAO->id = $mainBlockId;
2063 $deleteDAO->find(TRUE);
2064
2065 // if we about to delete a primary / billing block, set the flags for new block
2066 // that we going to assign to main-contact
2067 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id)) {
2068 $otherBlockDAO->is_primary = 1;
2069 }
2070 if ($billingDAOId && ($billingDAOId == $deleteDAO->id)) {
2071 $otherBlockDAO->is_billing = 1;
2072 }
2073 $blocksDAO[$name]['delete'][$deleteDAO->id] = $deleteDAO;
2074 }
2075 $blocksDAO[$name]['update'][$otherBlockDAO->id] = $otherBlockDAO;
2076 }
2077 }
2078 }
2079
2080 CRM_Utils_Hook::alterLocationMergeData($blocksDAO, $mainId, $otherId, $migrationInfo);
2081 foreach ($blocksDAO as $blockDAOs) {
2082 if (!empty($blockDAOs['update'])) {
2083 foreach ($blockDAOs['update'] as $blockDAO) {
2084 $blockDAO->save();
2085 }
2086 }
2087 if (!empty($blockDAOs['delete'])) {
2088 foreach ($blockDAOs['delete'] as $blockDAO) {
2089 $blockDAO->delete();
2090 }
2091 }
2092 }
2093 }
2094
2095 /**
2096 * Dedupe a pair of contacts.
2097 *
2098 * @param array $resultStats
2099 * @param array $deletedContacts
2100 * @param string $mode
2101 * @param bool $checkPermissions
2102 * @param int $mainId
2103 * @param int $otherId
2104 * @param string $cacheKeyString
2105 *
2106 * @throws \CRM_Core_Exception
2107 * @throws \CiviCRM_API3_Exception
2108 * @throws \API_Exception
2109 */
2110 protected static function dedupePair(&$resultStats, &$deletedContacts, $mode, $checkPermissions, $mainId, $otherId, $cacheKeyString) {
2111
2112 $migrationInfo = [];
2113 $conflicts = [];
2114 if (!CRM_Dedupe_Merger::skipMerge($mainId, $otherId, $migrationInfo, $mode, $conflicts)) {
2115 CRM_Dedupe_Merger::moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions);
2116 $resultStats['merged'][] = [
2117 'main_id' => $mainId,
2118 'other_id' => $otherId,
2119 ];
2120 $deletedContacts[] = $otherId;
2121 }
2122 else {
2123 $resultStats['skipped'][] = [
2124 'main_id' => $mainId,
2125 'other_id' => $otherId,
2126 ];
2127 }
2128
2129 // store any conflicts
2130 if (!empty($conflicts)) {
2131 CRM_Core_BAO_PrevNextCache::markConflict($mainId, $otherId, $cacheKeyString, $conflicts, $mode);
2132 }
2133 else {
2134 CRM_Core_BAO_PrevNextCache::deletePair($mainId, $otherId, $cacheKeyString);
2135 }
2136 }
2137
2138 /**
2139 * Replace the pseudo QFKey with zero if it is present.
2140 *
2141 * @todo - on the slim chance this is still relevant it should be moved to the form layer.
2142 *
2143 * Details about this bug are somewhat obscured by the move from svn but perhaps JIRA
2144 * can still help.
2145 *
2146 * @param array $migrationInfo
2147 */
2148 protected static function swapOutFieldsAffectedByQFZeroBug(&$migrationInfo) {
2149 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
2150 foreach ($migrationInfo as $key => &$value) {
2151 if ($value == $qfZeroBug) {
2152 $value = '0';
2153 }
2154 }
2155 }
2156
2157 /**
2158 * Honestly - what DOES this do - hopefully some refactoring will reveal it's purpose.
2159 *
2160 * Update this function formats fields in preparation for them to be submitted to the
2161 * 'ProfileContactCreate action. This is a lot of code to do this & for
2162 * - for some fields it fails - e.g Country - per testMergeCustomFields.
2163 *
2164 * Goal is to move all custom field handling into 'move' functions on the various BAO
2165 * with an underlying DAO function. For custom fields it has been started on the BAO.
2166 *
2167 * @param $mainId
2168 * @param $key
2169 * @param $cFields
2170 * @param $submitted
2171 * @param $value
2172 *
2173 * @return array
2174 * @throws \Exception
2175 */
2176 protected static function processCustomFields($mainId, $key, $cFields, $submitted, $value) {
2177 if (substr($key, 0, 7) == 'custom_') {
2178 $fid = (int) substr($key, 7);
2179 if (empty($cFields[$fid])) {
2180 return [$cFields, $submitted];
2181 }
2182 $htmlType = $cFields[$fid]['attributes']['html_type'];
2183 switch ($htmlType) {
2184 case 'File':
2185 // Handled in CustomField->move(). Tested in testMergeCustomFields.
2186 unset($submitted["custom_$fid"]);
2187 break;
2188
2189 case 'Select Country':
2190 // @todo Test in testMergeCustomFields disabled as this does not work, Handle in CustomField->move().
2191 case 'Select State/Province':
2192 $submitted[$key] = CRM_Core_BAO_CustomField::displayValue($value, $fid);
2193 break;
2194
2195 case 'Select Date':
2196 if ($cFields[$fid]['attributes']['is_view']) {
2197 $submitted[$key] = date('YmdHis', strtotime($submitted[$key]));
2198 }
2199 break;
2200
2201 case 'CheckBox':
2202 case 'Multi-Select':
2203 case 'Multi-Select Country':
2204 case 'Multi-Select State/Province':
2205 // Merge values from both contacts for multivalue fields, CRM-4385
2206 // get the existing custom values from db.
2207 $customParams = ['entityID' => $mainId, $key => TRUE];
2208 $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams);
2209 if (!empty($customfieldValues[$key])) {
2210 $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]);
2211 if (is_array($existingValue) && !empty($existingValue)) {
2212 $mergeValue = $submittedCustomFields = [];
2213 if ($value == 'null') {
2214 // CRM-19074 if someone has deliberately chosen to overwrite with 'null', respect it.
2215 $submitted[$key] = $value;
2216 }
2217 else {
2218 if ($value) {
2219 $submittedCustomFields = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
2220 }
2221
2222 // CRM-19653: overwrite or add the existing custom field value with dupicate contact's
2223 // custom field value stored at $submittedCustomValue.
2224 foreach ($submittedCustomFields as $k => $v) {
2225 if ($v != '' && !in_array($v, $mergeValue)) {
2226 $mergeValue[] = $v;
2227 }
2228 }
2229
2230 //keep state and country as array format.
2231 //for checkbox and m-select format w/ VALUE_SEPARATOR
2232 if (in_array($htmlType, [
2233 'CheckBox',
2234 'Multi-Select',
2235 ])) {
2236 $submitted[$key] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
2237 $mergeValue
2238 ) . CRM_Core_DAO::VALUE_SEPARATOR;
2239 }
2240 else {
2241 $submitted[$key] = $mergeValue;
2242 }
2243 }
2244 }
2245 }
2246 elseif (in_array($htmlType, [
2247 'Multi-Select Country',
2248 'Multi-Select State/Province',
2249 ])) {
2250 //we require submitted values should be in array format
2251 if ($value) {
2252 $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
2253 //hack to remove null values from array.
2254 $mergeValue = [];
2255 foreach ($mergeValueArray as $k => $v) {
2256 if ($v != '') {
2257 $mergeValue[] = $v;
2258 }
2259 }
2260 $submitted[$key] = $mergeValue;
2261 }
2262 }
2263 break;
2264
2265 default:
2266 break;
2267 }
2268 }
2269 return [$cFields, $submitted];
2270 }
2271
2272 /**
2273 * Get metadata for the custom fields for the merge.
2274 *
2275 * @param string $contactType
2276 *
2277 * @return array
2278 */
2279 protected static function getCustomFieldMetadata($contactType) {
2280 $treeCache = [];
2281 if (!array_key_exists($contactType, $treeCache)) {
2282 $treeCache[$contactType] = CRM_Core_BAO_CustomGroup::getTree(
2283 $contactType,
2284 NULL,
2285 NULL,
2286 -1,
2287 [],
2288 NULL,
2289 TRUE,
2290 NULL,
2291 FALSE,
2292 FALSE
2293 );
2294 }
2295
2296 $cFields = [];
2297 foreach ($treeCache[$contactType] as $key => $group) {
2298 if (!isset($group['fields'])) {
2299 continue;
2300 }
2301 foreach ($group['fields'] as $fid => $field) {
2302 $cFields[$fid]['attributes'] = $field;
2303 }
2304 }
2305 return $cFields;
2306 }
2307
2308 /**
2309 * Get conflicts for proposed merge pair.
2310 *
2311 * @param array $migrationInfo
2312 * This is primarily to inform hooks. The can also modify it which feels
2313 * pretty fragile to do it here - but it is historical.
2314 * @param int $mainId
2315 * Main contact with whom merge has to happen.
2316 * @param int $otherId
2317 * Duplicate contact which would be deleted after merge operation.
2318 * @param string $mode
2319 * Helps decide how to behave when there are conflicts.
2320 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
2321 * - Does a force merge otherwise (aggressive mode).
2322 *
2323 * @return array
2324 *
2325 * @throws \CRM_Core_Exception
2326 * @throws \CiviCRM_API3_Exception
2327 */
2328 public static function getConflicts(&$migrationInfo, $mainId, $otherId, $mode) {
2329 $conflicts = [];
2330 // Generate var $migrationInfo. The variable structure is exactly same as
2331 // $formValues submitted during a UI merge for a pair of contacts.
2332 $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($mainId, $otherId, FALSE);
2333 // add additional details that we might need to resolve conflicts
2334 $migrationInfo = $rowsElementsAndInfo['migration_info'];
2335 $migrationInfo['main_details'] = &$rowsElementsAndInfo['main_details'];
2336 $migrationInfo['other_details'] = &$rowsElementsAndInfo['other_details'];
2337 $migrationInfo['rows'] = &$rowsElementsAndInfo['rows'];
2338 // go ahead with merge if there is no conflict
2339 $originalMigrationInfo = $migrationInfo;
2340 foreach ($migrationInfo as $key => $val) {
2341 if ($val === "null") {
2342 // Rule: Never overwrite with an empty value (in any mode)
2343 unset($migrationInfo[$key]);
2344 continue;
2345 }
2346 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) or
2347 substr($key, 0, 12) == 'move_custom_'
2348 ) and $val != NULL
2349 ) {
2350 // Rule: If both main-contact, and other-contact have a field with a
2351 // different value, then let $mode decide if to merge it or not
2352 if (
2353 (!empty($migrationInfo['rows'][$key]['main'])
2354 // For custom fields a 0 (e.g in an int field) could be a true conflict. This
2355 // is probably true for other fields too - e.g. 'do_not_email' but
2356 // leaving that investigation as a @todo - until tests can be written.
2357 // Note the handling of this has test coverage - although the data-typing
2358 // of '0' feels flakey we have insurance.
2359 || ($migrationInfo['rows'][$key]['main'] === '0' && substr($key, 0, 12) == 'move_custom_')
2360 )
2361 && $migrationInfo['rows'][$key]['main'] != $migrationInfo['rows'][$key]['other']
2362 ) {
2363
2364 // note it down & lets wait for response from the hook.
2365 // For no response $mode will decide if to skip this merge
2366 $conflicts[$key] = NULL;
2367 }
2368 }
2369 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
2370 $locField = explode('_', $key);
2371 $fieldName = $locField[2];
2372 $fieldCount = $locField[3];
2373
2374 // Rule: Catch address conflicts (same address type on both contacts)
2375 if (
2376 isset($migrationInfo['main_details']['location_blocks'][$fieldName]) &&
2377 !empty($migrationInfo['main_details']['location_blocks'][$fieldName])
2378 ) {
2379
2380 // Load the address we're inspecting from the 'other' contact
2381 $addressRecord = $migrationInfo['other_details']['location_blocks'][$fieldName][$fieldCount];
2382 $addressRecordLocTypeId = CRM_Utils_Array::value('location_type_id', $addressRecord);
2383
2384 // If it exists on the 'main' contact already, skip it. Otherwise
2385 // if the location type exists already, log a conflict.
2386 foreach ($migrationInfo['main_details']['location_blocks'][$fieldName] as $mainAddressKey => $mainAddressRecord) {
2387 if (self::locationIsSame($addressRecord, $mainAddressRecord)) {
2388 unset($migrationInfo[$key]);
2389 break;
2390 }
2391 elseif ($addressRecordLocTypeId == $mainAddressRecord['location_type_id']) {
2392 $conflicts[$key] = NULL;
2393 break;
2394 }
2395 }
2396 }
2397
2398 // For other locations, don't merge/add if the values are the same
2399 elseif (CRM_Utils_Array::value('main', $migrationInfo['rows'][$key]) == $migrationInfo['rows'][$key]['other']) {
2400 unset($migrationInfo[$key]);
2401 }
2402 }
2403 }
2404
2405 // A hook to implement other algorithms for choosing which contact to bias to when
2406 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
2407 // merge happens with new values filled in here. For a particular field / row not to be merged
2408 // field should be unset from fields_in_conflict.
2409 $migrationData = [
2410 'old_migration_info' => $originalMigrationInfo,
2411 'mode' => $mode,
2412 'fields_in_conflict' => $conflicts,
2413 'merge_mode' => $mode,
2414 'migration_info' => $migrationInfo,
2415 ];
2416 CRM_Utils_Hook::merge('batch', $migrationData, $mainId, $otherId);
2417 $conflicts = $migrationData['fields_in_conflict'];
2418 // allow hook to override / manipulate migrationInfo as well
2419 $migrationInfo = $migrationData['migration_info'];
2420 foreach ($conflicts as $key => $val) {
2421 if ($val !== NULL || $mode !== 'safe') {
2422 // copy over the resolved values
2423 $migrationInfo[$key] = $val;
2424 unset($conflicts[$key]);
2425 }
2426 }
2427 $migrationInfo['skip_merge'] = $migrationData['skip_merge'] ?? !empty($conflicts);
2428 return self::formatConflictArray($conflicts, $migrationInfo['rows'], $migrationInfo['main_details']['location_blocks'], $migrationInfo['other_details']['location_blocks'], $mainId, $otherId);
2429 }
2430
2431 /**
2432 * @param array $conflicts
2433 * @param array $migrationInfo
2434 * @param $toKeepContactLocationBlocks
2435 * @param $toRemoveContactLocationBlocks
2436 * @param $toKeepID
2437 * @param $toRemoveID
2438 *
2439 * @return mixed
2440 * @throws \CRM_Core_Exception
2441 */
2442 protected static function formatConflictArray($conflicts, $migrationInfo, $toKeepContactLocationBlocks, $toRemoveContactLocationBlocks, $toKeepID, $toRemoveID) {
2443 $return = [];
2444 foreach (array_keys($conflicts) as $index) {
2445 if (substr($index, 0, 14) === 'move_location_') {
2446 $parts = explode('_', $index);
2447 $entity = $parts[2];
2448 $blockIndex = $parts[3];
2449 $locationTypeID = $toKeepContactLocationBlocks[$entity][$blockIndex]['location_type_id'];
2450 $entityConflicts = [
2451 'location_type_id' => $locationTypeID,
2452 'title' => $migrationInfo[$index]['title'],
2453 ];
2454 foreach ($toKeepContactLocationBlocks[$entity][$blockIndex] as $fieldName => $fieldValue) {
2455 if (in_array($fieldName, self::ignoredFields())) {
2456 continue;
2457 }
2458 $toRemoveValue = CRM_Utils_Array::value($fieldName, $toRemoveContactLocationBlocks[$entity][$blockIndex]);
2459 if ($fieldValue !== $toRemoveValue) {
2460 $entityConflicts[$fieldName] = [
2461 $toKeepID => $fieldValue,
2462 $toRemoveID => $toRemoveValue,
2463 ];
2464 }
2465 }
2466 $return[$entity][] = $entityConflicts;
2467 }
2468 elseif (substr($index, 0, 5) === 'move_') {
2469 $contactFieldsToCompare[] = str_replace('move_', '', $index);
2470 $return['contact'][str_replace('move_', '', $index)] = [
2471 'title' => $migrationInfo[$index]['title'],
2472 $toKeepID => $migrationInfo[$index]['main'],
2473 $toRemoveID => $migrationInfo[$index]['other'],
2474 ];
2475 }
2476 else {
2477 // Can't think of why this would be the case but perhaps it's ensuring it isn't as we
2478 // refactor this.
2479 throw new CRM_Core_Exception(ts('Unknown parameter') . $index);
2480 }
2481 }
2482 return $return;
2483 }
2484
2485 /**
2486 * Get any duplicate merge pairs that have been previously cached.
2487 *
2488 * @param int $rule_group_id
2489 * @param int $group_id
2490 * @param int $batchLimit
2491 * @param bool $isSelected
2492 * @param bool $includeConflicts
2493 * @param array $criteria
2494 * @param int $checkPermissions
2495 *
2496 * @return array
2497 */
2498 protected static function getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, $includeConflicts, $criteria, $checkPermissions) {
2499 return CRM_Core_BAO_PrevNextCache::retrieve(
2500 self::getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions),
2501 self::getJoinOnDedupeTable(),
2502 self::getWhereString($isSelected),
2503 0, $batchLimit,
2504 [], '',
2505 $includeConflicts
2506 );
2507 }
2508
2509 /**
2510 * @return array
2511 */
2512 protected static function ignoredFields(): array {
2513 $keysToIgnore = [
2514 'id',
2515 'is_primary',
2516 'is_billing',
2517 'manual_geo_code',
2518 'contact_id',
2519 'reset_date',
2520 'hold_date',
2521 ];
2522 return $keysToIgnore;
2523 }
2524
2525 }