3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
12 use Civi\Api4\CustomGroup
;
17 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 class CRM_Dedupe_Merger
{
22 * FIXME: consider creating a common structure with cidRefs() and eidRefs()
23 * FIXME: the sub-pages references by the URLs should
24 * be loaded dynamically on the merge form instead
27 public static function relTables() {
29 if (!isset(Civi
::$statics[__CLASS__
]['relTables'])) {
31 // Setting these merely prevents enotices - but it may be more appropriate not to add the user table below
32 // if the url can't be retrieved. A more standardised way to retrieve them is.
33 // CRM_Core_Config::singleton()->userSystem->getUserRecordUrl() - however that function takes a contact_id &
34 // we may need a different function when it is not known.
35 $title = $userRecordUrl = '';
37 $config = CRM_Core_Config
::singleton();
38 // @todo - this user url stuff is only needed for the form layer - move to CRM_Contact_Form_Merge
39 if ($config->userSystem
->is_drupal
) {
40 $userRecordUrl = CRM_Utils_System
::url('user/%ufid');
41 $title = ts('%1 User: %2; user id: %3', [
42 1 => $config->userFramework
,
47 elseif ($config->userFramework
== 'Joomla') {
48 $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';
49 $title = ts('%1 User: %2; user id: %3', [
50 1 => $config->userFramework
,
57 'rel_table_contributions' => [
58 'title' => ts('Contributions'),
60 'civicrm_contribution',
61 'civicrm_contribution_recur',
62 'civicrm_contribution_soft',
64 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=contribute'),
66 'rel_table_contribution_page' => [
67 'title' => ts('Contribution Pages'),
68 'tables' => ['civicrm_contribution_page'],
69 'url' => CRM_Utils_System
::url('civicrm/admin/contribute', 'reset=1&cid=$cid'),
71 'rel_table_memberships' => [
72 'title' => ts('Memberships'),
75 'civicrm_membership_log',
76 'civicrm_membership_type',
78 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=member'),
80 'rel_table_participants' => [
81 'title' => ts('Participants'),
82 'tables' => ['civicrm_participant'],
83 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=participant'),
85 'rel_table_events' => [
86 'title' => ts('Events'),
87 'tables' => ['civicrm_event'],
88 'url' => CRM_Utils_System
::url('civicrm/event/manage', 'reset=1&cid=$cid'),
90 'rel_table_activities' => [
91 'title' => ts('Activities'),
92 'tables' => ['civicrm_activity', 'civicrm_activity_contact'],
93 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=activity'),
95 'rel_table_relationships' => [
96 'title' => ts('Relationships'),
97 'tables' => ['civicrm_relationship'],
98 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=rel'),
100 'rel_table_custom_groups' => [
101 'title' => ts('Custom Groups'),
102 'tables' => ['civicrm_custom_group'],
103 'url' => CRM_Utils_System
::url('civicrm/admin/custom/group', 'reset=1'),
105 'rel_table_uf_groups' => [
106 'title' => ts('Profiles'),
107 'tables' => ['civicrm_uf_group'],
108 'url' => CRM_Utils_System
::url('civicrm/admin/uf/group', 'reset=1'),
110 'rel_table_groups' => [
111 'title' => ts('Groups'),
112 'tables' => ['civicrm_group_contact'],
113 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=group'),
115 'rel_table_notes' => [
116 'title' => ts('Notes'),
117 'tables' => ['civicrm_note'],
118 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=note'),
120 'rel_table_tags' => [
121 'title' => ts('Tags'),
122 'tables' => ['civicrm_entity_tag'],
123 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=tag'),
125 'rel_table_mailings' => [
126 'title' => ts('Mailings'),
129 'civicrm_mailing_event_queue',
130 'civicrm_mailing_event_subscribe',
132 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=mailing'),
134 'rel_table_cases' => [
135 'title' => ts('Cases'),
136 'tables' => ['civicrm_case_contact'],
137 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=case'),
139 'rel_table_grants' => [
140 'title' => ts('Grants'),
141 'tables' => ['civicrm_grant'],
142 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=grant'),
145 'title' => ts('PCPs'),
146 'tables' => ['civicrm_pcp'],
147 'url' => CRM_Utils_System
::url('civicrm/contribute/pcp/manage', 'reset=1'),
149 'rel_table_pledges' => [
150 'title' => ts('Pledges'),
151 'tables' => ['civicrm_pledge', 'civicrm_pledge_payment'],
152 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=pledge'),
154 'rel_table_users' => [
156 'tables' => ['civicrm_uf_match'],
157 'url' => $userRecordUrl,
161 $relTables +
= self
::getMultiValueCustomSets('relTables');
163 // Allow hook_civicrm_merge() to adjust $relTables
164 CRM_Utils_Hook
::merge('relTables', $relTables);
166 // Cache the results in a static variable
167 Civi
::$statics[__CLASS__
]['relTables'] = $relTables;
170 return Civi
::$statics[__CLASS__
]['relTables'];
174 * Returns the related tables groups for which a contact has any info entered.
180 public static function getActiveRelTables($cid) {
184 $relTables = self
::relTables();
185 $cidRefs = self
::cidRefs();
186 $eidRefs = self
::eidRefs();
187 foreach ($relTables as $group => $params) {
189 foreach ($params['tables'] as $table) {
190 if (isset($cidRefs[$table])) {
191 foreach ($cidRefs[$table] as $field) {
192 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $field = $cid";
195 if (isset($eidRefs[$table])) {
196 foreach ($eidRefs[$table] as $entityTable => $entityId) {
197 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $entityId = $cid AND $entityTable = 'civicrm_contact'";
200 foreach ($sqls as $sql) {
201 if (CRM_Core_DAO
::singleValueQuery($sql) > 0) {
207 return array_unique($groups);
211 * Get array tables and fields that reference civicrm_contact.id.
213 * This function calls the merge hook and only exists to wrap the DAO function to support that deprecated call.
214 * The entityTypes hook is the recommended way to add tables to this result.
216 * I thought about adding another hook to alter tableReferences but decided it was unclear if there
217 * are use cases not covered by entityTables and instead we should wait & see.
219 public static function cidRefs() {
220 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['contact_references'])) {
221 return \Civi
::$statics[__CLASS__
]['contact_references'];
224 $contactReferences = $coreReferences = CRM_Core_DAO
::getReferencesToContactTable();
226 CRM_Utils_Hook
::merge('cidRefs', $contactReferences);
227 if ($contactReferences !== $coreReferences) {
229 ->warning("Deprecated hook ::merge in context of 'cidRefs. Use entityTypes instead.", ['civi.tag' => 'deprecated']);
231 \Civi
::$statics[__CLASS__
]['contact_references'] = $contactReferences;
232 return \Civi
::$statics[__CLASS__
]['contact_references'];
236 * Return tables and their fields referencing civicrm_contact.contact_id with entity_id
238 public static function eidRefs() {
241 // FIXME: this should be generated dynamically from the schema
242 // tables that reference contacts with entity_{id,table}
244 'civicrm_acl' => ['entity_table' => 'entity_id'],
245 'civicrm_acl_entity_role' => ['entity_table' => 'entity_id'],
246 'civicrm_entity_file' => ['entity_table' => 'entity_id'],
247 'civicrm_log' => ['entity_table' => 'entity_id'],
248 'civicrm_mailing_group' => ['entity_table' => 'entity_id'],
249 'civicrm_note' => ['entity_table' => 'entity_id'],
252 // Allow hook_civicrm_merge() to adjust $eidRefs
253 CRM_Utils_Hook
::merge('eidRefs', $eidRefs);
259 * Return tables using locations.
261 public static function locTables() {
264 $locTables = ['civicrm_email', 'civicrm_address', 'civicrm_phone'];
266 // Allow hook_civicrm_merge() to adjust $locTables
267 CRM_Utils_Hook
::merge('locTables', $locTables);
273 * We treat multi-valued custom sets as "related tables" similar to activities, contributions, etc.
275 * @param string $request
276 * 'relTables' or 'cidRefs'.
279 * @throws \CiviCRM_API3_Exception
282 public static function getMultiValueCustomSets($request) {
284 if (!isset(Civi
::$statics[__CLASS__
]['multiValueCustomSets'])) {
289 $result = civicrm_api3('custom_group', 'get', [
299 'return' => ['id', 'title', 'table_name', 'style'],
301 foreach ($result['values'] as $custom) {
302 $data['cidRefs'][$custom['table_name']] = ['entity_id'];
303 $urlSuffix = $custom['style'] == 'Tab' ?
'&selectedChild=custom_' . $custom['id'] : '';
304 $data['relTables']['rel_table_custom_' . $custom['id']] = [
305 'title' => $custom['title'],
306 'tables' => [$custom['table_name']],
307 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid' . $urlSuffix),
311 // Store the result in a static variable cache
312 Civi
::$statics[__CLASS__
]['multiValueCustomSets'] = $data;
315 return Civi
::$statics[__CLASS__
]['multiValueCustomSets'][$request];
319 * Tables which require custom processing should declare functions to call here.
320 * Doing so will override normal processing.
322 public static function cpTables() {
326 'civicrm_case_contact' => ['CRM_Case_BAO_Case' => 'mergeContacts'],
327 'civicrm_group_contact' => ['CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'],
328 // Empty array == do nothing - this table is handled by mergeGroupContact
329 'civicrm_subscription_history' => [],
330 'civicrm_relationship' => ['CRM_Contact_BAO_Relationship' => 'mergeRelationships'],
331 'civicrm_membership' => ['CRM_Member_BAO_Membership' => 'mergeMemberships'],
338 * Return payment related table.
340 public static function paymentTables() {
343 $tables = ['civicrm_pledge', 'civicrm_membership', 'civicrm_participant'];
349 * Return payment update Query.
351 * @param string $tableName
352 * @param int $mainContactId
353 * @param int $otherContactId
357 public static function paymentSql($tableName, $mainContactId, $otherContactId) {
359 if (!$tableName ||
!$mainContactId ||
!$otherContactId) {
363 $paymentTables = self
::paymentTables();
364 if (!in_array($tableName, $paymentTables)) {
368 switch ($tableName) {
369 case 'civicrm_pledge':
371 UPDATE IGNORE civicrm_contribution contribution
372 INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id )
373 INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id )
374 SET contribution.contact_id = $mainContactId
375 WHERE pledge.contact_id = $otherContactId";
378 case 'civicrm_membership':
380 UPDATE IGNORE civicrm_contribution contribution
381 INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id )
382 INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id )
383 SET contribution.contact_id = $mainContactId
384 WHERE membership.contact_id = $otherContactId";
387 case 'civicrm_participant':
389 UPDATE IGNORE civicrm_contribution contribution
390 INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id )
391 INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id )
392 SET contribution.contact_id = $mainContactId
393 WHERE participant.contact_id = $otherContactId";
402 * @param int $otherId
403 * @param string $tableName
404 * @param array $tableOperations
405 * @param string $mode
409 public static function operationSql($mainId, $otherId, $tableName, $tableOperations = [], $mode = 'add') {
411 if (!$tableName ||
!$mainId ||
!$otherId) {
415 switch ($tableName) {
416 case 'civicrm_membership':
417 if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add']) {
420 if ($mode == 'add') {
422 DELETE membership1.* FROM civicrm_membership membership1
423 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
424 AND membership1.contact_id = {$mainId}
425 AND membership2.contact_id = {$otherId} ";
427 if ($mode == 'payment') {
429 DELETE contribution.* FROM civicrm_contribution contribution
430 INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id
431 INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id
432 AND membership1.contact_id = {$mainId}
433 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
434 AND membership2.contact_id = {$otherId}";
438 case 'civicrm_uf_match':
439 // normal queries won't work for uf_match since that will lead to violation of unique constraint,
440 // failing to meet intended result. Therefore we introduce this additional query:
441 $sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}";
449 * Based on the provided two contact_ids and a set of tables, remove the
450 * belongings of the other contact and of their relations.
452 * @param int $otherID
453 * @param array $tables
455 * @throws \CiviCRM_API3_Exception
457 public static function removeContactBelongings($otherID, $tables) {
458 // CRM-20421: Removing Inherited memberships when memberships of parent are not migrated to new contact.
459 if (in_array('civicrm_membership', $tables, TRUE)) {
460 $membershipIDs = CRM_Utils_Array
::collect('id',
461 CRM_Utils_Array
::value('values',
462 civicrm_api3('Membership', "get", [
463 'contact_id' => $otherID,
469 if (!empty($membershipIDs)) {
470 civicrm_api3('Membership', 'get', [
471 'owner_membership_id' => ['IN' => $membershipIDs],
472 'api.Membership.delete' => ['id' => '$value.id'],
479 * Based on the provided two contact_ids and a set of tables, move the
480 * belongings of the other contact to the main one.
482 * @param CRM_Dedupe_MergeHandler $mergeHandler
483 * @param array $tables
484 * @param array $tableOperations
486 * @throws \API_Exception
487 * @throws \CiviCRM_API3_Exception
488 * @throws \Civi\API\Exception\UnauthorizedException
490 public static function moveContactBelongings($mergeHandler, $tables, $tableOperations) {
491 $mainId = $mergeHandler->getToKeepID();
492 $otherId = $mergeHandler->getToRemoveID();
493 $cidRefs = self
::cidRefs();
494 $eidRefs = $mergeHandler->getTablesDynamicallyRelatedToContactTable();
495 $cpTables = self
::cpTables();
496 $paymentTables = self
::paymentTables();
497 self
::filterRowBasedCustomDataFromCustomTables($cidRefs);
499 $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
501 // if there aren't any specific tables, don't affect the ones handled by relTables()
502 // also don't affect tables in locTables() CRM-15658
503 $relTables = self
::relTables();
504 // These arrays don't make a lot of sense. For now ensure the tested handling of tags works...
505 // it is moved over further down....
506 unset($relTables['rel_table_tags']);
507 $handled = self
::locTables();
509 foreach ($relTables as $params) {
510 $handled = array_merge($handled, $params['tables']);
512 $affected = array_diff($affected, $handled);
513 $affected = array_unique(array_merge($affected, $tables));
515 $mainId = (int) $mainId;
516 $otherId = (int) $otherId;
519 foreach ($affected as $table) {
520 // Call custom processing function for objects that require it
521 if (isset($cpTables[$table])) {
522 foreach ($cpTables[$table] as $className => $fnName) {
523 $className::$fnName($mainId, $otherId, $sqls, $tables, $tableOperations);
525 // Skip normal processing
529 // use UPDATE IGNORE + DELETE query pair to skip on situations when
530 // there's a UNIQUE restriction on ($field, some_other_field) pair
531 if (isset($cidRefs[$table])) {
532 foreach ($cidRefs[$table] as $field) {
533 // carry related contributions CRM-5359
534 if (in_array($table, $paymentTables)) {
535 $paymentSqls = self
::paymentSql($table, $mainId, $otherId);
536 $sqls = array_merge($sqls, $paymentSqls);
538 if (!empty($tables) && !in_array('civicrm_contribution', $tables)) {
539 $payOprSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations, 'payment');
540 $sqls = array_merge($sqls, $payOprSqls);
544 $preOperationSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations);
545 $sqls = array_merge($sqls, $preOperationSqls);
546 $sqls[] = "UPDATE $table SET $field = $mainId WHERE $field = $otherId";
550 if (isset($eidRefs[$table])) {
551 $sqls[] = "UPDATE IGNORE $table SET {$eidRefs[$table]}= $mainId WHERE {$eidRefs[$table]} = $otherId AND entity_table = 'civicrm_contact'";
552 $sqls[] = "DELETE FROM $table WHERE {$eidRefs[$table]} = $otherId AND entity_table = 'civicrm_contact'";
556 // Allow hook_civicrm_merge() to add SQL statements for the merge operation.
557 CRM_Utils_Hook
::merge('sqls', $sqls, $mainId, $otherId, $tables);
559 foreach ($sqls as $sql) {
560 CRM_Core_DAO
::executeQuery($sql, [], TRUE, NULL, TRUE);
562 CRM_Dedupe_Merger
::addMembershipToRealtedContacts($mainId);
566 * Filter out custom tables from cidRefs unless they are there due to a contact reference or are a multiple set.
568 * The only fields where we want to move the data by sql is where entity reference fields
569 * on another contact refer to the contact being merged, or it is a multiple record set.
570 * The transference of custom data from one contact to another is done in 2 other places in the dedupe process but should
571 * not be done in moveAllContactData.
573 * Note it's a bit silly the way we build & then cull cidRefs - however, poor hook placement means that
574 * until we fully deprecate calling the hook from cidRefs we are stuck.
576 * It was deprecated in code (via deprecation notices if people altered it) in Mar 2019 but in docs only in Apri 2020.
578 * @param array $cidRefs
580 * @throws \API_Exception
581 * @throws \Civi\API\Exception\UnauthorizedException
583 protected static function filterRowBasedCustomDataFromCustomTables(array &$cidRefs) {
584 $customTables = (array) CustomGroup
::get()
585 ->setCheckPermissions(FALSE)
586 ->setSelect(['table_name'])
587 ->addWhere('is_multiple', '=', 0)
588 ->addWhere('extends', 'IN', array_merge(['Contact'], CRM_Contact_BAO_ContactType
::contactTypes()))
590 ->indexBy('table_name');
591 foreach (array_intersect_key($cidRefs, $customTables) as $tableName => $cidSpec) {
592 if (in_array('entity_id', $cidSpec, TRUE)) {
593 unset($cidRefs[$tableName][array_search('entity_id', $cidSpec, TRUE)]);
595 if (empty($cidRefs[$tableName])) {
596 unset($cidRefs[$tableName]);
602 * Given a contact ID, will check if a record exists in given table.
607 * Field where the contact's ID is stored in the table
610 * True if a record is found for the given contact ID, false otherwise
612 private static function customRecordExists($contactID, $table, $idField) {
614 SELECT COUNT(*) AS count
616 WHERE $idField = $contactID
618 $dbResult = CRM_Core_DAO
::executeQuery($sql);
621 if ($dbResult->count
> 0) {
629 * Load all non-empty fields for the contacts
633 * @param array $other
638 public static function retrieveFields($main, $other) {
643 foreach (self
::getContactFields() as $validField) {
644 // CRM-17556 Get all non-empty fields, to make comparison easier
645 if (!empty($main[$validField]) ||
!empty($other[$validField])) {
646 $result['contact'][] = $validField;
650 $mainEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($main['id']);
651 $otherEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($other['id']);
652 $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
653 foreach ($keys as $key) {
654 // Exclude multi-value fields CRM-13836
655 if (strpos($key, '_')) {
658 $key1 = $mainEvs[$key] ??
NULL;
659 $key2 = $otherEvs[$key] ??
NULL;
660 // We wish to retain '0' as it has a different meaning than NULL on a checkbox.
661 // However I can't think of a case where an empty string is more meaningful than null
662 // or where it would be FALSE or something else nullish.
663 $valuesToIgnore = [NULL, '', []];
664 if (!in_array($key1, $valuesToIgnore, TRUE) ||
!in_array($key2, $valuesToIgnore, TRUE)) {
665 $result['custom'][] = $key;
672 * Batch merge a set of contacts based on rule-group and group.
678 * @param string $mode
679 * Helps decide how to behave when there are conflicts.
680 * A 'safe' value skips the merge if there are any un-resolved conflicts, wheras 'aggressive'
681 * mode does a force merge.
682 * @param int $batchLimit number of merges to carry out in one batch.
683 * @param int $isSelected if records with is_selected column needs to be processed.
684 * Note the option of '2' is only used in conjunction with $redirectForPerformance
685 * to determine when to reload the cache (!). The use of anything other than a boolean is being grandfathered
686 * out in favour of explicitly passing in $reloadCacheIfEmpty
688 * @param array $criteria
689 * Criteria to use in the filter.
691 * @param bool $checkPermissions
692 * Respect logged in user permissions.
693 * @param bool|NULL $reloadCacheIfEmpty
694 * If not set explicitly this is calculated but it is preferred that it be set
695 * per comments on isSelected above.
697 * @param int $searchLimit
698 * Limit on number of contacts to search for duplicates for.
699 * This means that if the limit is 1000 then only duplicates for the first 1000 contacts
700 * matching criteria will be found and batchMerged (the number of merges could be less than or greater than 100)
704 * @throws \CRM_Core_Exception
705 * @throws \CiviCRM_API3_Exception
706 * @throws \API_Exception
708 public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $batchLimit = 1, $isSelected = 2, $criteria = [], $checkPermissions = TRUE, $reloadCacheIfEmpty = NULL, $searchLimit = 0) {
709 $redirectForPerformance = $batchLimit > 1;
710 if ($mode === 'aggressive' && $checkPermissions && !CRM_Core_Permission
::check('force merge duplicate contacts')) {
711 throw new CRM_Core_Exception(ts('Insufficient permissions for aggressive mode batch merge'));
713 if (!isset($reloadCacheIfEmpty)) {
714 $reloadCacheIfEmpty = (!$redirectForPerformance && $isSelected == 2);
716 if ($isSelected !== 0 && $isSelected !== 1) {
717 // explicitly set to NULL if not 1 or 0 as part of grandfathering out the mystical '2' value.
720 $dupePairs = self
::getDuplicatePairs($rgid, $gid, $reloadCacheIfEmpty, $batchLimit, $isSelected, ($mode == 'aggressive'), $criteria, $checkPermissions, $searchLimit);
723 'cache_key_string' => self
::getMergeCacheKeyString($rgid, $gid, $criteria, $checkPermissions, $searchLimit),
724 // @todo stop passing these parameters in & instead calculate them in the merge function based
725 // on the 'real' params like $isRespectExclusions $batchLimit and $isSelected.
726 'join' => self
::getJoinOnDedupeTable(),
727 'where' => self
::getWhereString($isSelected),
728 'limit' => (int) $batchLimit,
730 return CRM_Dedupe_Merger
::merge($dupePairs, $cacheParams, $mode, $redirectForPerformance, $checkPermissions);
734 * Get the string to join the prevnext cache to the dedupe table.
737 * The join string to join prevnext cache on the dedupe table.
739 public static function getJoinOnDedupeTable() {
741 LEFT JOIN civicrm_dedupe_exception de
743 pn.entity_id1 = de.contact_id1
744 AND pn.entity_id2 = de.contact_id2 )
749 * Get where string for dedupe join.
751 * @param bool $isSelected
755 protected static function getWhereString($isSelected) {
756 $where = "de.id IS NULL";
757 if ($isSelected === 0 ||
$isSelected === 1) {
758 $where .= " AND pn.is_selected = {$isSelected}";
764 * Update the statistics for the merge set.
766 * @param string $cacheKeyString
767 * @param array $result
769 public static function updateMergeStats($cacheKeyString, $result = []) {
770 // gather latest stats
771 $merged = count($result['merged']);
772 $skipped = count($result['skipped']);
774 if ($merged <= 0 && $skipped <= 0) {
778 // get previous stats
779 $previousStats = CRM_Dedupe_Merger
::getMergeStats($cacheKeyString);
780 if (!empty($previousStats)) {
781 if ($previousStats['merged']) {
782 $merged = $merged +
$previousStats['merged'];
784 if ($previousStats['skipped']) {
785 $skipped = $skipped +
$previousStats['skipped'];
790 CRM_Dedupe_Merger
::resetMergeStats($cacheKeyString);
792 // store the updated stats
794 'merged' => (int) $merged,
795 'skipped' => (int) $skipped,
798 CRM_Core_DAO
::executeQuery("INSERT INTO civicrm_prevnext_cache (entity_table, entity_id1, entity_id2, cacheKey, data) VALUES
799 ('civicrm_contact', 0, 0, %1, %2)", [1 => [$cacheKeyString . '_stats', 'String'], 2 => [serialize($data), 'String']]);
803 * Delete information about merges for the given string.
805 * @param $cacheKeyString
807 public static function resetMergeStats($cacheKeyString) {
808 CRM_Core_BAO_PrevNextCache
::deleteItem(NULL, "{$cacheKeyString}_stats");
812 * Get merge outcome statistics.
814 * @param string $cacheKeyString
817 * Array of how many were merged and how many were skipped.
819 * @throws \CiviCRM_API3_Exception
821 public static function getMergeStats($cacheKeyString) {
822 $stats = civicrm_api3('Dedupe', 'get', ['cachekey' => "{$cacheKeyString}_stats", 'sequential' => 1])['values'];
823 if (!empty($stats)) {
824 return $stats[0]['data'];
830 * Get merge statistics message.
832 * @param array $stats
836 public static function getMergeStatsMsg($stats) {
838 if (!empty($stats['merged'])) {
839 $msg = '<p>' . ts('One contact merged.', [
840 'count' => $stats['merged'],
841 'plural' => '%count contacts merged.',
844 if (!empty($stats['skipped'])) {
845 $msg .= '<p>' . ts('One contact was skipped.', [
846 'count' => $stats['skipped'],
847 'plural' => '%count contacts were skipped.',
854 * Merge given set of contacts. Performs core operation.
856 * @param array $dupePairs
857 * Set of pair of contacts for whom merge is to be done.
858 * @param array $cacheParams
859 * Prev-next-cache params based on which next pair of contacts are computed.
860 * Generally used with batch-merge.
861 * @param string $mode
862 * Helps decide how to behave when there are conflicts.
863 * A 'safe' value skips the merge if there are any un-resolved conflicts.
864 * Does a force merge otherwise (aggressive mode).
866 * @param bool $redirectForPerformance
867 * Redirect to a url for batch processing.
869 * @param bool $checkPermissions
870 * Respect logged in user permissions.
874 * @throws \API_Exception
875 * @throws \CRM_Core_Exception
876 * @throws \CiviCRM_API3_Exception
878 public static function merge($dupePairs = [], $cacheParams = [], $mode = 'safe',
879 $redirectForPerformance = FALSE, $checkPermissions = TRUE
881 $cacheKeyString = $cacheParams['cache_key_string'] ??
NULL;
882 $resultStats = ['merged' => [], 'skipped' => []];
884 // we don't want dupe caching to get reset after every-merge, and therefore set the
885 CRM_Core_Config
::setPermitCacheFlushMode(FALSE);
886 $deletedContacts = [];
888 while (!empty($dupePairs)) {
889 foreach ($dupePairs as $index => $dupes) {
890 if (in_array($dupes['dstID'], $deletedContacts) ||
in_array($dupes['srcID'], $deletedContacts)) {
891 unset($dupePairs[$index]);
894 if (($result = self
::dedupePair($dupes, $mode, $checkPermissions, $cacheKeyString)) === FALSE) {
895 unset($dupePairs[$index]);
898 if (!empty($result['merged'])) {
899 $deletedContacts[] = $result['merged'][0]['other_id'];
900 $resultStats['merged'][] = ($result['merged'][0]);
903 $resultStats['skipped'][] = ($result['skipped'][0]);
907 if ($cacheKeyString && !$redirectForPerformance) {
908 // retrieve next pair of dupes
909 // @todo call getDuplicatePairs.
910 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString,
911 $cacheParams['join'],
912 $cacheParams['where'],
914 $cacheParams['limit'],
921 // do not proceed. Terminate the loop
926 CRM_Dedupe_Merger
::updateMergeStats($cacheKeyString, $resultStats);
931 * A function which uses various rules / algorithms for choosing which contact to bias to
932 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
935 * Main contact with whom merge has to happen.
936 * @param int $otherId
937 * Duplicate contact which would be deleted after merge operation.
938 * @param array $migrationInfo
939 * Array of information about which elements to merge.
940 * @param string $mode
941 * Helps decide how to behave when there are conflicts.
942 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
943 * - Does a force merge otherwise (aggressive mode).
945 * @param array $conflicts
946 * An empty array to be filed with conflict information.
950 * @throws \CRM_Core_Exception
951 * @throws \CiviCRM_API3_Exception
952 * @throws \API_Exception
954 public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe', &$conflicts = []) {
956 $conflicts = self
::getConflicts($migrationInfo, $mainId, $otherId, $mode)['conflicts'];
957 // A hook could have set skip_merge in order to alter merge behaviour.
958 // This is a something we might ideally deprecate since they really 'should'
959 // mess with the conflicts array instead.
960 return (bool) ($migrationData['skip_merge'] ??
!empty($conflicts));
964 * Compare 2 addresses to see if they are the same.
966 * @param array $mainAddress
967 * @param array $comparisonAddress
971 public static function locationIsSame($mainAddress, $comparisonAddress) {
972 $keysToIgnore = self
::ignoredFields();
973 foreach ($comparisonAddress as $field => $value) {
974 if (in_array($field, $keysToIgnore)) {
977 if ((!empty($value) ||
$value === '0') && isset($mainAddress[$field]) && $mainAddress[$field] != $value) {
985 * A function to build an array of information about location blocks that is
986 * required when merging location fields
990 public static function getLocationBlockInfo() {
993 'label' => 'Address',
994 'displayField' => 'display',
995 'sortString' => 'location_type_id',
996 'hasLocation' => TRUE,
1001 'displayField' => 'display',
1002 'sortString' => 'location_type_id',
1003 'hasLocation' => TRUE,
1008 'displayField' => 'name',
1009 'sortString' => 'location_type_id,provider_id',
1010 'hasLocation' => TRUE,
1011 'hasType' => 'provider_id',
1015 'displayField' => 'phone',
1016 'sortString' => 'location_type_id,phone_type_id',
1017 'hasLocation' => TRUE,
1018 'hasType' => 'phone_type_id',
1021 'label' => 'Website',
1022 'displayField' => 'url',
1023 'sortString' => 'website_type_id',
1024 'hasLocation' => FALSE,
1025 'hasType' => 'website_type_id',
1028 return $locationBlocks;
1032 * A function to build an array of information required by merge function and the merge UI.
1034 * @param int $mainId
1035 * Main contact with whom merge has to happen.
1036 * @param int $otherId
1037 * Duplicate contact which would be deleted after merge operation.
1038 * @param bool $checkPermissions
1039 * Should the logged in user's permissions be ignore. Setting this to false is
1040 * highly risky as it could cause data to be lost due to conflicts not showing up.
1041 * OTOH there is a risk a merger might view custom data they do not have permission to.
1042 * Hence for now only making this really explicit and making it reflect perms in
1045 * @todo review permissions issue!
1047 * @return array|bool|int
1049 * rows => An array of arrays, each is row of merge information for the table
1050 * Format: move_fieldname, eg: move_contact_type
1051 * main => Value associated with the main contact
1052 * other => Value associated with the other contact
1053 * title => The title of the field to display in the merge table
1055 * elements => An array of form elements for the merge UI
1057 * rel_table_elements => An array of form elements for the merge UI for
1058 * entities related to the contact (eg: checkbox to move 'mailings')
1060 * rel_tables => Stores the tables that have related entities for the contact
1061 * for example mailings, groups
1063 * main_details => An array of core contact field values, eg: first_name, etc.
1064 * location_blocks => An array of location block data for the main contact
1065 * stored as the 'result' of an API call.
1066 * eg: main_details['location_blocks']['address'][0]['id']
1067 * eg: main_details['location_blocks']['email'][1]['id']
1069 * other_details => As above, but for the 'other' contact
1071 * migration_info => Stores the 'default' merge actions for each field which
1072 * is used when programatically merging contacts. It contains instructions
1073 * to move all fields from the 'other' contact to the 'main' contact, as
1074 * though the form had been submitted with those options.
1076 * @throws \CRM_Core_Exception
1077 * @throws \CiviCRM_API3_Exception
1078 * @throws \Exception
1080 public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissions = TRUE) {
1081 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1082 $fields = self
::getMergeFieldsMetadata();
1084 $main = self
::getMergeContactDetails($mainId);
1085 $other = self
::getMergeContactDetails($otherId);
1087 $compareFields = self
::retrieveFields($main, $other);
1089 $rows = $elements = $relTableElements = $migrationInfo = [];
1091 foreach ($compareFields['contact'] as $field) {
1092 if ($field == 'contact_sub_type') {
1093 // CRM-15681 don't display sub-types in UI
1096 $rows["move_$field"] = [
1097 'main' => self
::getFieldValueAndLabel($field, $main)['label'],
1098 'other' => self
::getFieldValueAndLabel($field, $other)['label'],
1099 'title' => $fields[$field]['title'],
1102 $value = self
::getFieldValueAndLabel($field, $other)['value'];
1104 if ($value === NULL ||
$value == '') {
1107 if ($value === 0 or $value === '0') {
1108 $value = $qfZeroBug;
1110 if (is_array($value) && empty($value[1])) {
1114 // Display a checkbox to migrate, only if the values are different
1115 if ($value != $main[$field]) {
1123 'is_checked' => (!isset($main[$field]) ||
$main[$field] === ''),
1127 $migrationInfo["move_$field"] = $value;
1130 // Handle location blocks.
1131 // @todo OpenID not in API yet, so is not supported here.
1133 // Set up useful information about the location blocks
1134 $locationBlocks = self
::getLocationBlockInfo();
1136 $locations = ['main' => [], 'other' => []];
1138 foreach ($locationBlocks as $blockName => $blockInfo) {
1139 list($locations, $rows, $elements, $migrationInfo) = self
::addLocationFieldInfo($mainId, $otherId, $blockInfo, $blockName, $locations, $rows, $elements, $migrationInfo);
1140 } // End loop through each location block entity
1142 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1143 $mergeHandler = new CRM_Dedupe_MergeHandler((int) $mainId, (int) $otherId);
1144 $relTables = $mergeHandler->getTablesRelatedToTheMergePair();
1145 foreach ($relTables as $name => $null) {
1146 $relTableElements[] = ['checkbox', "move_$name"];
1147 $migrationInfo["move_$name"] = 1;
1149 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1150 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1151 if ($name === 'rel_table_users') {
1152 // @todo - this user url stuff is only needed for the form layer - move to CRM_Contact_Form_Merge
1153 $relTables[$name]['main_url'] = str_replace('%ufid', CRM_Core_BAO_UFMatch
::getUFId($otherId), $relTables[$name]['url']);
1154 $relTables[$name]['other_url'] = str_replace('%ufid', CRM_Core_BAO_UFMatch
::getUFId($otherId), $relTables[$name]['url']);
1156 if ($name == 'rel_table_memberships') {
1157 //Enable 'add new' checkbox if main contact does not contain any membership similar to duplicate contact.
1158 $attributes = ['checked' => 'checked'];
1159 $otherContactMemberships = CRM_Member_BAO_Membership
::getAllContactMembership($otherId);
1160 foreach ($otherContactMemberships as $membership) {
1161 $mainMembership = CRM_Member_BAO_Membership
::getContactMembership($mainId, $membership['membership_type_id'], FALSE);
1162 if ($mainMembership) {
1168 "operation[move_{$name}][add]",
1173 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1176 foreach ($relTables as $name => $null) {
1177 $relTables["move_$name"] = $relTables[$name];
1178 unset($relTables[$name]);
1181 // handle custom fields
1182 $mainTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], NULL, $mainId, -1,
1183 CRM_Utils_Array
::value('contact_sub_type', $main), NULL, TRUE, NULL, TRUE, $checkPermissions
1185 $otherTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], NULL, $otherId, -1,
1186 CRM_Utils_Array
::value('contact_sub_type', $other), NULL, TRUE, NULL, TRUE, $checkPermissions
1189 foreach ($otherTree as $gid => $group) {
1190 if (!isset($group['fields'])) {
1194 foreach ($group['fields'] as $fid => $field) {
1195 $mainContactValue = $mainTree[$gid]['fields'][$fid]['customValue'] ??
NULL;
1196 $otherContactValue = $otherTree[$gid]['fields'][$fid]['customValue'] ??
NULL;
1197 if (in_array($fid, $compareFields['custom'])) {
1198 $rows["custom_group_$gid"]['title'] = $rows["custom_group_$gid"]['title'] ??
$group['title'];
1200 if ($mainContactValue) {
1201 foreach ($mainContactValue as $valueId => $values) {
1202 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomField
::displayValue($values['data'], $fid);
1206 if ($otherContactValue) {
1207 foreach ($otherContactValue as $valueId => $values) {
1208 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomField
::displayValue($values['data'], $fid);
1209 if ($values['data'] === 0 ||
$values['data'] === '0') {
1210 $values['data'] = $qfZeroBug;
1212 $value = ($values['data']) ?
$values['data'] : $value;
1215 $rows["move_custom_$fid"]['title'] = $field['label'];
1219 1 => "move_custom_$fid",
1224 'is_checked' => (!isset($rows["move_custom_$fid"]['main']) ||
$rows["move_custom_$fid"]['main'] === ''),
1226 $migrationInfo["move_custom_$fid"] = $value;
1233 'elements' => $elements,
1234 'rel_table_elements' => $relTableElements,
1235 'rel_tables' => $relTables,
1236 'main_details' => $main,
1237 'other_details' => $other,
1238 'migration_info' => $migrationInfo,
1241 $result['main_details']['location_blocks'] = $locations['main'];
1242 $result['other_details']['location_blocks'] = $locations['other'];
1248 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1249 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1250 * A superset of moveContactBelongings() function.
1252 * @param int $mainId
1253 * Main contact with whom merge has to happen.
1254 * @param int $otherId
1255 * Duplicate contact which would be deleted after merge operation.
1257 * @param array $migrationInfo
1259 * @param bool $checkPermissions
1260 * Respect logged in user permissions.
1264 * @throws \API_Exception
1265 * @throws \CRM_Core_Exception
1266 * @throws \CiviCRM_API3_Exception
1267 * @throws \Civi\API\Exception\UnauthorizedException
1269 public static function moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions = TRUE) {
1270 if (empty($migrationInfo)) {
1273 // Encapsulate in a transaction to avoid half-merges.
1274 $transaction = new CRM_Core_Transaction();
1276 $contactType = $migrationInfo['main_details']['contact_type'];
1277 $relTables = CRM_Dedupe_Merger
::relTables();
1278 $submittedCustomFields = $moveTables = $tableOperations = $removeTables = [];
1280 self
::swapOutFieldsAffectedByQFZeroBug($migrationInfo);
1281 foreach ($migrationInfo as $key => $value) {
1283 if (substr($key, 0, 12) == 'move_custom_' && $value != NULL) {
1284 $submitted[substr($key, 5)] = $value;
1285 $submittedCustomFields[] = substr($key, 12);
1287 elseif (in_array(substr($key, 5), CRM_Dedupe_Merger
::getContactFields()) && $value != NULL) {
1288 $submitted[substr($key, 5)] = $value;
1290 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1291 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1292 if (array_key_exists('operation', $migrationInfo)) {
1293 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1294 if (array_key_exists($key, $migrationInfo['operation'])) {
1295 $tableOperations[$table] = $migrationInfo['operation'][$key];
1300 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '0') {
1301 $removeTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1304 self
::mergeLocations($mainId, $otherId, $migrationInfo);
1306 // **** Do contact related migrations
1307 // @todo - move all custom field processing to the move class & eventually have an
1308 // overridable DAO class for it.
1309 $customFieldBAO = new CRM_Core_BAO_CustomField();
1310 $customFieldBAO->move($otherId, $mainId, $submittedCustomFields);
1311 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1312 $mergeHandler = new CRM_Dedupe_MergeHandler((int) $mainId, (int) $otherId);
1313 CRM_Dedupe_Merger
::moveContactBelongings($mergeHandler, $moveTables, $tableOperations);
1314 unset($moveTables, $tableOperations);
1316 // **** Do table related removals
1317 if (!empty($removeTables)) {
1319 CRM_Dedupe_Merger
::removeContactBelongings($otherId, $removeTables);
1323 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
1324 $names['gender'] = ['newName' => 'gender_id', 'groupName' => 'gender'];
1325 $names['individual_prefix'] = [
1326 'newName' => 'prefix_id',
1327 'groupName' => 'individual_prefix',
1329 $names['individual_suffix'] = [
1330 'newName' => 'suffix_id',
1331 'groupName' => 'individual_suffix',
1333 $names['communication_style'] = [
1334 'newName' => 'communication_style_id',
1335 'groupName' => 'communication_style',
1337 $names['addressee'] = [
1338 'newName' => 'addressee_id',
1339 'groupName' => 'addressee',
1341 $names['email_greeting'] = [
1342 'newName' => 'email_greeting_id',
1343 'groupName' => 'email_greeting',
1345 $names['postal_greeting'] = [
1346 'newName' => 'postal_greeting_id',
1347 'groupName' => 'postal_greeting',
1349 CRM_Core_OptionGroup
::lookupValues($submitted, $names, TRUE);
1350 // fix custom fields so they're edible by createProfileContact()
1351 $cFields = self
::getCustomFieldMetadata($contactType);
1353 if (!isset($submitted)) {
1356 foreach ($submitted as $key => $value) {
1357 list($cFields, $submitted) = self
::processCustomFields($mainId, $key, $cFields, $submitted, $value);
1360 // move view only custom fields CRM-5362
1361 $viewOnlyCustomFields = [];
1362 foreach ($submitted as $key => $value) {
1363 $fid = CRM_Core_BAO_CustomField
::getKeyID($key);
1364 if ($fid && array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])
1366 $viewOnlyCustomFields[$key] = $value;
1369 // special case to set values for view only, CRM-5362
1370 if (!empty($viewOnlyCustomFields)) {
1371 $viewOnlyCustomFields['entityID'] = $mainId;
1372 CRM_Core_BAO_CustomValueTable
::setValues($viewOnlyCustomFields);
1375 // dev/core#996 Ensure that the earliest created date is stored against the kept contact id
1376 $mainCreatedDate = civicrm_api3('Contact', 'getsingle', [
1378 'return' => ['created_date'],
1380 $otherCreatedDate = civicrm_api3('Contact', 'getsingle', [
1382 'return' => ['created_date'],
1384 if ($otherCreatedDate < $mainCreatedDate && !empty($otherCreatedDate)) {
1385 CRM_Core_DAO
::executeQuery("UPDATE civicrm_contact SET created_date = %1 WHERE id = %2", [
1386 1 => [$otherCreatedDate, 'String'],
1387 2 => [$mainId, 'Positive'],
1391 if (!$checkPermissions ||
(CRM_Core_Permission
::check('merge duplicate contacts') &&
1392 CRM_Core_Permission
::check('delete contacts'))
1394 // if ext id is submitted then set it null for contact to be deleted
1395 if (!empty($submitted['external_identifier'])) {
1396 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1397 CRM_Core_DAO
::executeQuery($query);
1399 civicrm_api3('contact', 'delete', ['id' => $otherId]);
1402 // CRM-15681 merge sub_types
1403 if ($other_sub_types = CRM_Utils_Array
::value('contact_sub_type', $migrationInfo['other_details'])) {
1404 if ($main_sub_types = CRM_Utils_Array
::value('contact_sub_type', $migrationInfo['main_details'])) {
1405 $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types));
1408 $submitted['contact_sub_type'] = $other_sub_types;
1412 // **** Update contact related info for the main contact
1413 if (!empty($submitted)) {
1414 $submitted['contact_id'] = $mainId;
1416 //update current employer field
1417 if ($currentEmloyerId = CRM_Utils_Array
::value('current_employer_id', $submitted)) {
1418 if (!CRM_Utils_System
::isNull($currentEmloyerId)) {
1419 $submitted['current_employer'] = $submitted['current_employer_id'];
1422 $submitted['current_employer'] = '';
1424 unset($submitted['current_employer_id']);
1427 //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
1428 if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) {
1429 $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
1431 if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) {
1432 $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
1435 CRM_Contact_BAO_Contact
::createProfileContact($submitted, $null, $mainId);
1437 $transaction->commit();
1438 CRM_Utils_Hook
::post('merge', 'Contact', $mainId);
1439 self
::createMergeActivities($mainId, $otherId);
1445 * Get fields in the contact table suitable for merging.
1448 * Array of field names to be potentially merged.
1450 public static function getContactFields() {
1451 $contactFields = CRM_Contact_DAO_Contact
::fields();
1459 'primary_contact_id',
1463 foreach ($contactFields as $field => $value) {
1464 if (in_array($field, $invalidFields)) {
1465 unset($contactFields[$field]);
1468 return array_keys($contactFields);
1472 * Added for CRM-12695
1473 * Based on the contactID provided
1474 * add/update membership(s) to related contacts
1476 * @param int $contactID
1478 public static function addMembershipToRealtedContacts($contactID) {
1479 $dao = new CRM_Member_DAO_Membership();
1480 $dao->contact_id
= $contactID;
1484 //checks membership of contact itself
1485 while ($dao->fetch()) {
1486 $relationshipTypeId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id
, 'relationship_type_id', 'id');
1487 if ($relationshipTypeId) {
1488 $membershipParams = [
1490 'contact_id' => $dao->contact_id
,
1491 'membership_type_id' => $dao->membership_type_id
,
1492 'join_date' => CRM_Utils_Date
::isoToMysql($dao->join_date
),
1493 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
1494 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
1495 'source' => $dao->source
,
1496 'status_id' => $dao->status_id
,
1498 // create/update membership(s) for related contact(s)
1499 CRM_Member_BAO_Membership
::createRelatedMemberships($membershipParams, $dao);
1500 } // end of if relationshipTypeId
1505 * Create activities tracking the merge on affected contacts.
1507 * @param int $mainId
1508 * @param int $otherId
1510 * @throws \CiviCRM_API3_Exception
1512 public static function createMergeActivities($mainId, $otherId) {
1517 $activity = civicrm_api3('activity', 'create', [
1518 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
1520 'subject' => ts('Contact ID %1 has been merged and deleted.', $params),
1521 'target_contact_id' => $mainId,
1522 'activity_type_id' => 'Contact Merged',
1523 'status_id' => 'Completed',
1525 if (civicrm_api3('Setting', 'getvalue', [
1526 'name' => 'contact_undelete',
1527 'group' => 'CiviCRM Preferences',
1529 civicrm_api3('activity', 'create', [
1530 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
1532 'subject' => ts('Contact ID %1 has been merged into Contact ID %2 and deleted.', $params),
1533 'target_contact_id' => $otherId,
1534 'activity_type_id' => 'Contact Deleted by Merge',
1535 'parent_id' => $activity['id'],
1536 'status_id' => 'Completed',
1542 * Get Duplicate Pairs based on a rule for a group.
1544 * @param int $rule_group_id
1545 * @param int $group_id
1546 * @param bool $reloadCacheIfEmpty
1547 * Should the cache be reloaded if empty - this must be false when in a dedupe action!
1548 * @param int $batchLimit
1549 * @param bool $isSelected
1550 * Limit to selected pairs.
1551 * @param bool $includeConflicts
1552 * @param array $criteria
1553 * Additional criteria to narrow down the merge group.
1555 * @param bool $checkPermissions
1556 * Respect logged in user permissions.
1558 * @param int $searchLimit
1559 * Limit to searching for matches against this many contacts.
1561 * @param int $isForceNewSearch
1562 * Should a new search be forced, bypassing any cache retrieval.
1565 * Array of matches meeting the criteria.
1567 * @throws \CRM_Core_Exception
1568 * @throws \CiviCRM_API3_Exception
1570 public static function getDuplicatePairs($rule_group_id, $group_id, $reloadCacheIfEmpty, $batchLimit, $isSelected, $includeConflicts = TRUE, $criteria = [], $checkPermissions = TRUE, $searchLimit = 0, $isForceNewSearch = 0) {
1571 $dupePairs = $isForceNewSearch ?
[] : self
::getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, $includeConflicts, $criteria, $checkPermissions, $searchLimit);
1572 if (empty($dupePairs) && $reloadCacheIfEmpty) {
1573 // If we haven't found any dupes, probably cache is empty.
1574 // Try filling cache and give another try. We don't need to specify include conflicts here are there will not be any
1575 // until we have done some processing.
1576 CRM_Core_BAO_PrevNextCache
::refillCache($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit);
1577 return self
::getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, FALSE, $criteria, $checkPermissions, $searchLimit);
1583 * Get the cache key string for the merge action.
1585 * @param int $rule_group_id
1586 * @param int $group_id
1587 * @param array $criteria
1588 * Additional criteria to narrow down the merge group.
1589 * Currently we are only supporting the key 'contact' within it.
1590 * @param bool $checkPermissions
1591 * Respect the users permissions.
1592 * @param int $searchLimit
1593 * Number of contacts to seek dupes for (we need this because if
1594 * we change it the results won't be refreshed otherwise. Changing the limit
1595 * from 100 to 1000 SHOULD result in a new dedupe search).
1599 public static function getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit) {
1600 $contactType = CRM_Dedupe_BAO_RuleGroup
::getContactTypeForRuleGroup($rule_group_id);
1601 $cacheKeyString = "merge_{$contactType}";
1602 $cacheKeyString .= $rule_group_id ?
"_{$rule_group_id}" : '_0';
1603 $cacheKeyString .= $group_id ?
"_{$group_id}" : '_0';
1604 $cacheKeyString .= '_' . (int) $searchLimit;
1605 $cacheKeyString .= !empty($criteria) ?
md5(serialize($criteria)) : '_0';
1606 if ($checkPermissions) {
1607 $contactID = CRM_Core_Session
::getLoggedInContactID();
1609 // Distinguish between no permission check & no logged in user.
1610 $contactID = 'null';
1612 $cacheKeyString .= '_' . $contactID;
1615 $cacheKeyString .= '_0';
1617 return $cacheKeyString;
1621 * Get the metadata for the merge fields.
1623 * This is basically the contact metadata, augmented with fields to
1624 * represent email greeting, postal greeting & addressee.
1628 public static function getMergeFieldsMetadata() {
1629 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['merge_fields_metadata'])) {
1630 return \Civi
::$statics[__CLASS__
]['merge_fields_metadata'];
1632 $fields = CRM_Contact_DAO_Contact
::fields();
1633 static $optionValueFields = [];
1634 if (empty($optionValueFields)) {
1635 $optionValueFields = CRM_Core_OptionValue
::getFields();
1637 foreach ($optionValueFields as $field => $params) {
1638 $fields[$field]['title'] = $params['title'];
1640 \Civi
::$statics[__CLASS__
]['merge_fields_metadata'] = $fields;
1641 return \Civi
::$statics[__CLASS__
]['merge_fields_metadata'];
1645 * Get the details of the contact to be merged.
1647 * @param int $contact_id
1651 * @throws CRM_Core_Exception
1653 public static function getMergeContactDetails($contact_id) {
1655 'contact_id' => $contact_id,
1657 'return' => array_merge(['display_name'], self
::getContactFields()),
1659 $result = civicrm_api('contact', 'get', $params);
1661 // CRM-18480: Cancel the process if the contact is already deleted
1662 if (isset($result['values'][$contact_id]['contact_is_deleted']) && !empty($result['values'][$contact_id]['contact_is_deleted'])) {
1663 throw new CRM_Core_Exception(ts('Cannot merge because one contact (ID %1) has been deleted.', [
1668 return $result['values'][$contact_id];
1674 * Based on the data in the $locationMigrationInfo merge the locations for 2 contacts.
1676 * The data is in the format received from the merge form (which is a fairly confusing format).
1678 * It is converted into an array of DAOs which is passed to the alterLocationMergeData hook
1679 * before saving or deleting the DAOs. A new hook is added to allow these to be altered after they have
1680 * been calculated and before saving because
1681 * - the existing format & hook combo is so confusing it is hard for developers to change & inherently fragile
1682 * - passing to a hook right before save means calculations only have to be done once
1683 * - the existing pattern of passing dissimilar data to the same (merge) hook with a different 'type' is just
1686 * The use of the new hook is tested, including the fact it is called before contributions are merged, as this
1687 * is likely to be significant data in merge hooks.
1689 * @param int $mainId
1690 * @param int $otherId
1692 * @param array $migrationInfo
1693 * Migration info for the merge. This is passed to the hook as informational only.
1695 public static function mergeLocations($mainId, $otherId, $migrationInfo) {
1696 foreach ($migrationInfo as $key => $value) {
1697 $isLocationField = (substr($key, 0, 14) == 'move_location_' and $value != NULL);
1698 if (!$isLocationField) {
1701 $locField = explode('_', $key);
1702 $fieldName = $locField[2];
1703 $fieldCount = $locField[3];
1705 // Set up the operation type (add/overwrite)
1706 // Ignore operation for websites
1707 // @todo Tidy this up
1709 if ($fieldName != 'website') {
1710 $operation = $migrationInfo['location_blocks'][$fieldName][$fieldCount]['operation'] ??
NULL;
1712 // default operation is overwrite.
1716 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
1720 // @todo Handle OpenID (not currently in API).
1721 if (!empty($locBlocks)) {
1722 $locationBlocks = self
::getLocationBlockInfo();
1724 $primaryBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, ['is_primary' => 1]);
1725 $billingBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, ['is_billing' => 1]);
1727 foreach ($locBlocks as $name => $block) {
1728 $blocksDAO[$name] = ['delete' => [], 'update' => []];
1729 if (!is_array($block) || CRM_Utils_System
::isNull($block)) {
1732 $daoName = 'CRM_Core_DAO_' . $locationBlocks[$name]['label'];
1733 $changePrimary = FALSE;
1734 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ?
array_pop($primaryBlockIds[$name]) : NULL;
1735 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ?
array_pop($billingBlockIds[$name]) : NULL;
1737 foreach ($block as $blkCount => $values) {
1738 $otherBlockId = $migrationInfo['other_details']['location_blocks'][$name][$blkCount]['id'] ??
NULL;
1739 $mainBlockId = CRM_Utils_Array
::value('mainContactBlockId', $migrationInfo['location_blocks'][$name][$blkCount], 0);
1740 if (!$otherBlockId) {
1744 // For the block which belongs to other-contact, link the location block to main-contact
1745 $otherBlockDAO = new $daoName();
1746 $otherBlockDAO->contact_id
= $mainId;
1748 // Get the ID of this block on the 'other' contact, otherwise skip
1749 $otherBlockDAO->id
= $otherBlockId;
1751 // Add/update location and type information from the form, if applicable
1752 if ($locationBlocks[$name]['hasLocation']) {
1753 $locTypeId = $migrationInfo['location_blocks'][$name][$blkCount]['locTypeId'] ??
NULL;
1754 $otherBlockDAO->location_type_id
= $locTypeId;
1756 if ($locationBlocks[$name]['hasType']) {
1757 $typeTypeId = $migrationInfo['location_blocks'][$name][$blkCount]['typeTypeId'] ??
NULL;
1758 $otherBlockDAO->{$locationBlocks[$name]['hasType']} = $typeTypeId;
1761 // If we're deliberately setting this as primary then add the flag
1762 // and remove it from the current primary location (if there is one).
1763 // But only once for each entity.
1764 $set_primary = $migrationInfo['location_blocks'][$name][$blkCount]['set_other_primary'] ??
NULL;
1765 if (!$changePrimary && $set_primary == "1") {
1766 $otherBlockDAO->is_primary
= 1;
1767 if ($primaryDAOId) {
1768 $removePrimaryDAO = new $daoName();
1769 $removePrimaryDAO->id
= $primaryDAOId;
1770 $removePrimaryDAO->is_primary
= 0;
1771 $blocksDAO[$name]['update'][$primaryDAOId] = $removePrimaryDAO;
1773 $changePrimary = TRUE;
1775 // Otherwise, if main contact already has primary, set it to 0.
1776 elseif ($primaryDAOId) {
1777 $otherBlockDAO->is_primary
= 0;
1780 // If the main contact already has a billing location, set this to 0.
1781 if ($billingDAOId) {
1782 $otherBlockDAO->is_billing
= 0;
1785 $operation = CRM_Utils_Array
::value('operation', $values, 2);
1786 // overwrite - need to delete block which belongs to main-contact.
1787 if (!empty($mainBlockId) && ($operation == 2)) {
1788 $deleteDAO = new $daoName();
1789 $deleteDAO->id
= $mainBlockId;
1790 $deleteDAO->find(TRUE);
1792 // if we about to delete a primary / billing block, set the flags for new block
1793 // that we going to assign to main-contact
1794 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id
)) {
1795 $otherBlockDAO->is_primary
= 1;
1797 if ($billingDAOId && ($billingDAOId == $deleteDAO->id
)) {
1798 $otherBlockDAO->is_billing
= 1;
1800 $blocksDAO[$name]['delete'][$deleteDAO->id
] = $deleteDAO;
1802 $blocksDAO[$name]['update'][$otherBlockDAO->id
] = $otherBlockDAO;
1807 CRM_Utils_Hook
::alterLocationMergeData($blocksDAO, $mainId, $otherId, $migrationInfo);
1808 foreach ($blocksDAO as $blockDAOs) {
1809 if (!empty($blockDAOs['update'])) {
1810 foreach ($blockDAOs['update'] as $blockDAO) {
1814 if (!empty($blockDAOs['delete'])) {
1815 foreach ($blockDAOs['delete'] as $blockDAO) {
1816 $blockDAO->delete();
1823 * Dedupe a pair of contacts.
1825 * @param array $dupes
1826 * @param string $mode
1827 * @param bool $checkPermissions
1828 * @param string $cacheKeyString
1830 * @return bool|array
1831 * @throws \CRM_Core_Exception
1832 * @throws \CiviCRM_API3_Exception
1833 * @throws \API_Exception
1835 protected static function dedupePair($dupes, $mode = 'safe', $checkPermissions = TRUE, $cacheKeyString = NULL) {
1836 CRM_Utils_Hook
::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']);
1837 $mainId = $dupes['dstID'];
1838 $otherId = $dupes['srcID'];
1841 if (!$mainId ||
!$otherId) {
1845 $migrationInfo = [];
1847 // Try to lock the contacts before we load the data as we don't want it changing under us.
1848 // https://lab.civicrm.org/dev/core/issues/1355
1849 $locks = self
::getLocksOnContacts([$mainId, $otherId]);
1850 if (!CRM_Dedupe_Merger
::skipMerge($mainId, $otherId, $migrationInfo, $mode, $conflicts)) {
1851 CRM_Dedupe_Merger
::moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions);
1852 $resultStats['merged'][] = [
1853 'main_id' => $mainId,
1854 'other_id' => $otherId,
1858 $resultStats['skipped'][] = [
1859 'main_id' => $mainId,
1860 'other_id' => $otherId,
1864 // store any conflicts
1865 if (!empty($conflicts)) {
1866 CRM_Core_BAO_PrevNextCache
::markConflict($mainId, $otherId, $cacheKeyString, $conflicts, $mode);
1869 CRM_Core_BAO_PrevNextCache
::deletePair($mainId, $otherId, $cacheKeyString);
1871 self
::releaseLocks($locks);
1872 return $resultStats;
1876 * Replace the pseudo QFKey with zero if it is present.
1878 * @todo - on the slim chance this is still relevant it should be moved to the form layer.
1880 * Details about this bug are somewhat obscured by the move from svn but perhaps JIRA
1883 * @param array $migrationInfo
1885 protected static function swapOutFieldsAffectedByQFZeroBug(&$migrationInfo) {
1886 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1887 foreach ($migrationInfo as $key => &$value) {
1888 if ($value == $qfZeroBug) {
1895 * Honestly - what DOES this do - hopefully some refactoring will reveal it's purpose.
1897 * Update this function formats fields in preparation for them to be submitted to the
1898 * 'ProfileContactCreate action. This is a lot of code to do this & for
1899 * - for some fields it fails - e.g Country - per testMergeCustomFields.
1901 * Goal is to move all custom field handling into 'move' functions on the various BAO
1902 * with an underlying DAO function. For custom fields it has been started on the BAO.
1911 * @throws \CRM_Core_Exception
1913 protected static function processCustomFields($mainId, $key, $cFields, $submitted, $value) {
1914 if (substr($key, 0, 7) == 'custom_') {
1915 $fid = (int) substr($key, 7);
1916 if (empty($cFields[$fid])) {
1917 return [$cFields, $submitted];
1919 $htmlType = $cFields[$fid]['attributes']['html_type'];
1920 $isSerialized = CRM_Core_BAO_CustomField
::isSerialized($cFields[$fid]['attributes']);
1922 if ($htmlType === 'File') {
1923 // Handled in CustomField->move(). Tested in testMergeCustomFields.
1924 unset($submitted["custom_$fid"]);
1926 elseif (!$isSerialized && ($htmlType === 'Select Country' ||
$htmlType === 'Select State/Province')) {
1927 // @todo Test in testMergeCustomFields disabled as this does not work, Handle in CustomField->move().
1928 $submitted[$key] = CRM_Core_BAO_CustomField
::displayValue($value, $fid);
1930 elseif ($htmlType === 'Select Date') {
1931 if ($cFields[$fid]['attributes']['is_view']) {
1932 $submitted[$key] = date('YmdHis', strtotime($submitted[$key]));
1935 elseif ($isSerialized) {
1936 // Merge values from both contacts for multivalue fields, CRM-4385
1937 // get the existing custom values from db.
1938 $customParams = ['entityID' => $mainId, $key => TRUE];
1939 $customfieldValues = CRM_Core_BAO_CustomValueTable
::getValues($customParams);
1940 if (!empty($customfieldValues[$key])) {
1941 $existingValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customfieldValues[$key]);
1942 if (is_array($existingValue) && !empty($existingValue)) {
1943 $mergeValue = $submittedCustomFields = [];
1944 if ($value == 'null') {
1945 // CRM-19074 if someone has deliberately chosen to overwrite with 'null', respect it.
1946 $submitted[$key] = $value;
1950 $submittedCustomFields = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1953 // CRM-19653: overwrite or add the existing custom field value with dupicate contact's
1954 // custom field value stored at $submittedCustomValue.
1955 foreach ($submittedCustomFields as $k => $v) {
1956 if ($v != '' && !in_array($v, $mergeValue)) {
1961 //keep state and country as array format.
1962 //for checkbox and m-select format w/ VALUE_SEPARATOR
1963 if (in_array($htmlType, ['CheckBox', 'Select'])) {
1964 $submitted[$key] = CRM_Utils_Array
::implodePadded($mergeValue);
1967 $submitted[$key] = $mergeValue;
1972 elseif (in_array($htmlType, ['Select Country', 'Select State/Province'])) {
1973 //we require submitted values should be in array format
1975 $mergeValueArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1976 //hack to remove null values from array.
1978 foreach ($mergeValueArray as $k => $v) {
1983 $submitted[$key] = $mergeValue;
1988 return [$cFields, $submitted];
1992 * Get metadata for the custom fields for the merge.
1994 * @param string $contactType
1997 * @throws \CRM_Core_Exception
1999 protected static function getCustomFieldMetadata($contactType) {
2001 if (!array_key_exists($contactType, $treeCache)) {
2002 $treeCache[$contactType] = CRM_Core_BAO_CustomGroup
::getTree(
2017 foreach ($treeCache[$contactType] as $key => $group) {
2018 if (!isset($group['fields'])) {
2021 foreach ($group['fields'] as $fid => $field) {
2022 $cFields[$fid]['attributes'] = $field;
2029 * Get conflicts for proposed merge pair.
2031 * @param array $migrationInfo
2032 * This is primarily to inform hooks. The can also modify it which feels
2033 * pretty fragile to do it here - but it is historical.
2034 * @param int $mainId
2035 * Main contact with whom merge has to happen.
2036 * @param int $otherId
2037 * Duplicate contact which would be deleted after merge operation.
2038 * @param string $mode
2039 * Helps decide how to behave when there are conflicts.
2040 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
2041 * - Does a force merge otherwise (aggressive mode).
2045 * @throws \CRM_Core_Exception
2046 * @throws \CiviCRM_API3_Exception
2048 public static function getConflicts(&$migrationInfo, $mainId, $otherId, $mode) {
2050 // Generate var $migrationInfo. The variable structure is exactly same as
2051 // $formValues submitted during a UI merge for a pair of contacts.
2052 $rowsElementsAndInfo = CRM_Dedupe_Merger
::getRowsElementsAndInfo($mainId, $otherId, FALSE);
2053 // add additional details that we might need to resolve conflicts
2054 $migrationInfo = $rowsElementsAndInfo['migration_info'];
2055 $migrationInfo['main_details'] = &$rowsElementsAndInfo['main_details'];
2056 $migrationInfo['other_details'] = &$rowsElementsAndInfo['other_details'];
2057 $migrationInfo['rows'] = &$rowsElementsAndInfo['rows'];
2058 // go ahead with merge if there is no conflict
2059 $originalMigrationInfo = $migrationInfo;
2060 foreach ($migrationInfo as $key => $val) {
2061 if ($val === "null") {
2062 // Rule: Never overwrite with an empty value (in any mode)
2063 unset($migrationInfo[$key]);
2066 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger
::getContactFields()) or
2067 substr($key, 0, 12) == 'move_custom_'
2070 // Rule: If both main-contact, and other-contact have a field with a
2071 // different value, then let $mode decide if to merge it or not
2073 (!empty($migrationInfo['rows'][$key]['main'])
2074 // For custom fields a 0 (e.g in an int field) could be a true conflict. This
2075 // is probably true for other fields too - e.g. 'do_not_email' but
2076 // leaving that investigation as a @todo - until tests can be written.
2077 // Note the handling of this has test coverage - although the data-typing
2078 // of '0' feels flakey we have insurance.
2079 ||
($migrationInfo['rows'][$key]['main'] === '0' && substr($key, 0, 12) == 'move_custom_')
2081 && $migrationInfo['rows'][$key]['main'] != $migrationInfo['rows'][$key]['other']
2084 // note it down & lets wait for response from the hook.
2085 // For no response $mode will decide if to skip this merge
2086 $conflicts[$key] = NULL;
2089 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
2090 $locField = explode('_', $key);
2091 $fieldName = $locField[2];
2092 $fieldCount = $locField[3];
2094 // Rule: Catch address conflicts (same address type on both contacts)
2096 isset($migrationInfo['main_details']['location_blocks'][$fieldName]) &&
2097 !empty($migrationInfo['main_details']['location_blocks'][$fieldName])
2100 // Load the address we're inspecting from the 'other' contact
2101 $addressRecord = $migrationInfo['other_details']['location_blocks'][$fieldName][$fieldCount];
2102 $addressRecordLocTypeId = $addressRecord['location_type_id'] ??
NULL;
2104 // If it exists on the 'main' contact already, skip it. Otherwise
2105 // if the location type exists already, log a conflict.
2106 foreach ($migrationInfo['main_details']['location_blocks'][$fieldName] as $mainAddressKey => $mainAddressRecord) {
2107 if (self
::locationIsSame($addressRecord, $mainAddressRecord)) {
2108 unset($migrationInfo[$key]);
2111 elseif ($addressRecordLocTypeId == $mainAddressRecord['location_type_id']) {
2112 $conflicts[$key] = NULL;
2118 // For other locations, don't merge/add if the values are the same
2119 elseif (CRM_Utils_Array
::value('main', $migrationInfo['rows'][$key]) == $migrationInfo['rows'][$key]['other']) {
2120 unset($migrationInfo[$key]);
2125 // A hook to implement other algorithms for choosing which contact to bias to when
2126 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
2127 // merge happens with new values filled in here. For a particular field / row not to be merged
2128 // field should be unset from fields_in_conflict.
2130 'old_migration_info' => $originalMigrationInfo,
2132 'fields_in_conflict' => $conflicts,
2133 'merge_mode' => $mode,
2134 'migration_info' => $migrationInfo,
2136 CRM_Utils_Hook
::merge('batch', $migrationData, $mainId, $otherId);
2137 $conflicts = $migrationData['fields_in_conflict'];
2138 // allow hook to override / manipulate migrationInfo as well
2139 $migrationInfo = $migrationData['migration_info'];
2140 foreach ($conflicts as $key => $val) {
2141 // Copy over the resolved values. If we are in aggressive mode we update to null
2142 // so as not to copy over. Why it's different to safe mode is a bit murky.
2143 // Working theory is it doesn't matter what we do in safe mode here if $val is NULL.
2144 // as the merge is not gonna happen if $val == NULL
2145 $migrationInfo[$key] = $val ??
($mode === 'safe' ?
$migrationInfo[$key] : NULL);
2147 return self
::formatConflictArray($conflicts, $migrationInfo['rows'], $migrationInfo['main_details']['location_blocks'], $migrationInfo['other_details']['location_blocks'], $mainId, $otherId, $mode);
2151 * @param array $conflicts
2152 * @param array $migrationInfo
2153 * @param $toKeepContactLocationBlocks
2154 * @param $toRemoveContactLocationBlocks
2156 * @param $toRemoveID
2157 * @param string $mode
2160 * @throws \CRM_Core_Exception
2162 protected static function formatConflictArray($conflicts, $migrationInfo, $toKeepContactLocationBlocks, $toRemoveContactLocationBlocks, $toKeepID, $toRemoveID, $mode) {
2165 foreach ($conflicts as $key => $val) {
2166 if ($val !== NULL) {
2167 // copy over the resolved values
2168 $resolved[$key] = $val;
2169 unset($conflicts[$key]);
2171 elseif ($mode === 'aggressive') {
2172 unset($conflicts[$key]);
2173 if (strpos($key, 'move_location_') !== 0) {
2174 // @todo - just handling plain contact fields for now because I think I need a bigger refactor
2175 // of the below to handle locations & will do as a follow up.
2176 $resolved['contact'][substr($key, 5)] = $migrationInfo[$key]['main'];
2180 foreach (array_keys($conflicts) as $index) {
2181 if (substr($index, 0, 14) === 'move_location_') {
2182 $parts = explode('_', $index);
2183 $entity = $parts[2];
2184 $blockIndex = $parts[3];
2185 $locationTypeID = $toKeepContactLocationBlocks[$entity][$blockIndex]['location_type_id'];
2186 $entityConflicts = [
2187 'location_type_id' => $locationTypeID,
2188 'title' => $migrationInfo[$index]['title'],
2190 foreach ($toKeepContactLocationBlocks[$entity][$blockIndex] as $fieldName => $fieldValue) {
2191 if (in_array($fieldName, self
::ignoredFields())) {
2194 $toRemoveValue = $toRemoveContactLocationBlocks[$entity][$blockIndex][$fieldName] ??
NULL;
2195 if ($fieldValue !== $toRemoveValue) {
2196 $entityConflicts[$fieldName] = [
2197 $toKeepID => $fieldValue,
2198 $toRemoveID => $toRemoveValue,
2202 $return[$entity][] = $entityConflicts;
2204 elseif (substr($index, 0, 5) === 'move_') {
2205 $contactFieldsToCompare[] = str_replace('move_', '', $index);
2206 $return['contact'][str_replace('move_', '', $index)] = [
2207 'title' => $migrationInfo[$index]['title'],
2208 $toKeepID => $migrationInfo[$index]['main'],
2209 $toRemoveID => $migrationInfo[$index]['other'],
2213 // Can't think of why this would be the case but perhaps it's ensuring it isn't as we
2215 throw new CRM_Core_Exception(ts('Unknown parameter') . $index);
2218 return ['conflicts' => $return, 'resolved' => $resolved];
2222 * Get any duplicate merge pairs that have been previously cached.
2224 * @param int $rule_group_id
2225 * @param int $group_id
2226 * @param int $batchLimit
2227 * @param bool $isSelected
2228 * @param bool $includeConflicts
2229 * @param array $criteria
2230 * @param int $checkPermissions
2231 * @param int $searchLimit
2235 protected static function getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, $includeConflicts, $criteria, $checkPermissions, $searchLimit = 0) {
2236 return CRM_Core_BAO_PrevNextCache
::retrieve(
2237 self
::getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit),
2238 self
::getJoinOnDedupeTable(),
2239 self
::getWhereString($isSelected),
2249 protected static function ignoredFields(): array {
2259 return $keysToIgnore;
2263 * Get the field value & label for the given field.
2269 * @throws \Exception
2271 private static function getFieldValueAndLabel($field, $contact): array {
2272 $fields = self
::getMergeFieldsMetadata();
2273 $value = $label = $contact[$field] ??
NULL;
2274 $fieldSpec = $fields[$field];
2275 if (!empty($fieldSpec['serialize']) && is_array($value)) {
2276 // In practice this only applies to preferred_communication_method as the sub types are skipped above
2277 // and no others are serialized.
2279 foreach ($value as $individualValue) {
2280 $labels[] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $field, $individualValue);
2282 $label = implode(', ', $labels);
2283 // We serialize this due to historic handling but it's likely that if we just left it as an
2284 // array all would be well & we would have less code.
2285 $value = CRM_Core_DAO
::serializeField($value, $fieldSpec['serialize']);
2287 elseif (!empty($fieldSpec['type']) && $fieldSpec['type'] == CRM_Utils_Type
::T_DATE
) {
2289 $value = str_replace('-', '', $value);
2290 $label = CRM_Utils_Date
::customFormat($label);
2296 elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type
::T_BOOLEAN
) {
2297 if ($label === '0') {
2300 if ($label === '1') {
2304 elseif (!empty($fieldSpec['pseudoconstant'])) {
2305 $label = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $field, $value);
2307 elseif ($field == 'current_employer_id' && !empty($value)) {
2308 $label = "$value (" . CRM_Contact_BAO_Contact
::displayName($value) . ")";
2310 return ['label' => $label, 'value' => $value];
2314 * Build up the location block for the contact in dedupe-screen display format.
2316 * @param integer $cid
2317 * @param array $blockInfo
2318 * @param string $blockName
2322 * @throws \CiviCRM_API3_Exception
2324 private static function buildLocationBlockForContact($cid, $blockInfo, $blockName): array {
2326 'contact_id' => $cid,
2327 // CRM-17556 Order by field-specific criteria
2329 'sort' => $blockInfo['sortString'],
2332 $locationBlock = [];
2333 $values = civicrm_api3($blockName, 'get', $searchParams);
2334 if ($values['count']) {
2336 foreach ($values['values'] as $value) {
2337 $locationBlock[$cnt] = $value;
2338 // Fix address display
2339 if ($blockName == 'address') {
2340 // For performance avoid geocoding while merging https://issues.civicrm.org/jira/browse/CRM-21786
2341 // we can expect existing geocode values to be retained.
2342 $value['skip_geocode'] = TRUE;
2343 CRM_Core_BAO_Address
::fixAddress($value);
2344 unset($value['skip_geocode']);
2345 $locationBlock[$cnt]['display'] = CRM_Utils_Address
::format($value);
2347 // Fix email display
2348 elseif ($blockName == 'email') {
2349 $locationBlock[$cnt]['display'] = CRM_Utils_Mail
::format($value);
2355 return $locationBlock;
2359 * Get a lock on the given contact.
2361 * The lock is like a gentleman's agreement between php & mysql. It is reserved at the
2362 * mysql level so it works across php processes but it doesn't actually lock the database.
2364 * Instead php can check the lock to see if it has been acquired before taking an action.
2366 * In this case we really don't want to attempt to dedupe contacts if another process is
2367 * trying to act on the specific contact as it could result in messy deadlocks & possibly data corruption.
2368 * In most databases this would be a rare event but if multiple dedupe processes are running
2369 * at once (for example) or there is also an import process in play there is potential for them to crash.
2370 * By throwing a specific error the calling process can catch it and determine it is worth trying again later without a lot of
2373 * As of writing no other processes DO grab contact locks but it would be reasonable to consider
2374 * grabbing them doing contact edits in general as well as imports etc.
2376 * @param array $contacts
2380 * @throws \CRM_Core_Exception
2381 * @throws \CRM_Core_Exception_ResourceConflictException
2383 protected static function getLocksOnContacts($contacts):array {
2385 if (!CRM_Utils_SQL
::supportsMultipleLocks()) {
2388 foreach ($contacts as $contactID) {
2389 $lock = Civi
::lockManager()->acquire("data.core.contact.{$contactID}");
2390 if ($lock->isAcquired()) {
2394 self
::releaseLocks($locks);
2395 throw new CRM_Core_Exception_ResourceConflictException(ts('Contact is in Use'), 'contact_lock');
2402 * Release contact locks so another process can alter them if it wants.
2404 * @param array $locks
2406 protected static function releaseLocks(array $locks) {
2407 foreach ($locks as $lock) {
2408 /* @var Civi\Core\Lock\LockInterface $lock */
2418 * @param array $locations
2419 * @param array $rows
2420 * @param array $elements
2421 * @param array $migrationInfo
2424 * @throws \CiviCRM_API3_Exception
2426 protected static function addLocationFieldInfo($mainId, $otherId, $blockInfo, $blockName, array $locations, array $rows, array $elements, array $migrationInfo): array {
2427 // Collect existing fields from both 'main' and 'other' contacts first
2428 // This allows us to match up location/types when building the table rows
2429 $locations['main'][$blockName] = self
::buildLocationBlockForContact($mainId, $blockInfo, $blockName);
2430 $locations['other'][$blockName] = self
::buildLocationBlockForContact($otherId, $blockInfo, $blockName);
2432 // Now, build the table rows appropriately, based off the information on
2433 // the 'other' contact
2434 if (!empty($locations['other']) && !empty($locations['other'][$blockName])) {
2435 foreach ($locations['other'][$blockName] as $count => $value) {
2437 $displayValue = $value[$blockInfo['displayField']];
2439 // Add this value to the table rows
2440 $rows["move_location_{$blockName}_{$count}"]['other'] = $displayValue;
2442 // CRM-17556 Only display 'main' contact value if it's the same location + type
2443 // Look it up from main values...
2445 $lookupLocation = FALSE;
2446 if ($blockInfo['hasLocation']) {
2447 $lookupLocation = $value['location_type_id'];
2450 $lookupType = FALSE;
2451 if ($blockInfo['hasType']) {
2452 $lookupType = $value[$blockInfo['hasType']] ??
NULL;
2455 // Hold ID of main contact's matching block
2456 $mainContactBlockId = 0;
2458 if (!empty($locations['main'][$blockName])) {
2459 foreach ($locations['main'][$blockName] as $mainValueCheck) {
2460 // No location/type, or matching location and type
2462 (empty($lookupLocation) ||
$lookupLocation == $mainValueCheck['location_type_id'])
2463 && (empty($lookupType) ||
$lookupType == $mainValueCheck[$blockInfo['hasType']])
2465 // Set this value as the default against the 'other' contact value
2466 $rows["move_location_{$blockName}_{$count}"]['main'] = $mainValueCheck[$blockInfo['displayField']];
2467 $rows["move_location_{$blockName}_{$count}"]['main_is_primary'] = $mainValueCheck['is_primary'];
2468 $rows["move_location_{$blockName}_{$count}"]['location_entity'] = $blockName;
2469 $mainContactBlockId = $mainValueCheck['id'];
2475 // Add checkbox to migrate data from 'other' to 'main'
2476 $elements[] = ['advcheckbox', "move_location_{$blockName}_{$count}"];
2478 // Add checkbox to set the 'other' location as primary
2481 "location_blocks[$blockName][$count][set_other_primary]",
2483 ts('Set as primary'),
2486 // Flag up this field to skipMerge function (@todo: do we need to?)
2487 $migrationInfo["move_location_{$blockName}_{$count}"] = 1;
2489 // Add a hidden field to store the ID of the target main contact block
2492 "location_blocks[$blockName][$count][mainContactBlockId]",
2493 $mainContactBlockId,
2497 $thisTypeId = FALSE;
2500 // Provide a select drop-down for the location's location type
2501 // eg: Home, Work...
2503 if ($blockInfo['hasLocation']) {
2505 // Load the location options for this entity
2506 $locationOptions = civicrm_api3($blockName, 'getoptions', ['field' => 'location_type_id']);
2508 $thisLocId = $value['location_type_id'];
2510 // Put this field's location type at the top of the list
2511 $tmpIdList = $locationOptions['values'];
2512 $defaultLocId = [$thisLocId => $tmpIdList[$thisLocId]];
2513 unset($tmpIdList[$thisLocId]);
2518 "location_blocks[$blockName][$count][locTypeId]",
2520 $defaultLocId +
$tmpIdList,
2523 // Add the relevant information to the $migrationInfo
2524 // Keep location-type-id same as that of other-contact
2525 // @todo Check this logic out
2526 $migrationInfo['location_blocks'][$blockName][$count]['locTypeId'] = $thisLocId;
2527 if ($blockName != 'address') {
2530 "location_blocks[{$blockName}][$count][operation]",
2534 // always use add operation
2535 $migrationInfo['location_blocks'][$blockName][$count]['operation'] = 1;
2540 // Provide a select drop-down for the location's type/provider
2541 // eg websites: Facebook...
2543 if ($blockInfo['hasType']) {
2545 // Load the type options for this entity
2546 $typeOptions = civicrm_api3($blockName, 'getoptions', ['field' => $blockInfo['hasType']]);
2548 $thisTypeId = $value[$blockInfo['hasType']] ??
NULL;
2550 // Put this field's location type at the top of the list
2551 $tmpIdList = $typeOptions['values'];
2552 $defaultTypeId = [$thisTypeId => CRM_Utils_Array
::value($thisTypeId, $tmpIdList)];
2553 unset($tmpIdList[$thisTypeId]);
2558 "location_blocks[$blockName][$count][typeTypeId]",
2560 $defaultTypeId +
$tmpIdList,
2563 // Add the information to the migrationInfo
2564 $migrationInfo['location_blocks'][$blockName][$count]['typeTypeId'] = $thisTypeId;
2568 // Set the label for this row
2569 $rowTitle = $blockInfo['label'] . ' ' . ($count +
1);
2570 if (!empty($thisLocId)) {
2571 $rowTitle .= ' (' . $locationOptions['values'][$thisLocId] . ')';
2573 if (!empty($thisTypeId)) {
2574 $rowTitle .= ' (' . $typeOptions['values'][$thisTypeId] . ')';
2576 $rows["move_location_{$blockName}_$count"]['title'] = $rowTitle;
2578 } // End loop through 'other' locations of this type
2581 return [$locations, $rows, $elements, $migrationInfo];