3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Dedupe_Merger
{
20 * FIXME: consider creating a common structure with cidRefs() and eidRefs()
21 * FIXME: the sub-pages references by the URLs should
22 * be loaded dynamically on the merge form instead
25 public static function relTables() {
27 if (!isset(Civi
::$statics[__CLASS__
]['relTables'])) {
29 // Setting these merely prevents enotices - but it may be more appropriate not to add the user table below
30 // if the url can't be retrieved. A more standardised way to retrieve them is.
31 // CRM_Core_Config::singleton()->userSystem->getUserRecordUrl() - however that function takes a contact_id &
32 // we may need a different function when it is not known.
33 $title = $userRecordUrl = '';
35 $config = CRM_Core_Config
::singleton();
36 if ($config->userSystem
->is_drupal
) {
37 $userRecordUrl = CRM_Utils_System
::url('user/%ufid');
38 $title = ts('%1 User: %2; user id: %3', [
39 1 => $config->userFramework
,
44 elseif ($config->userFramework
== 'Joomla') {
45 $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';
46 $title = ts('%1 User: %2; user id: %3', [
47 1 => $config->userFramework
,
54 'rel_table_contributions' => [
55 'title' => ts('Contributions'),
57 'civicrm_contribution',
58 'civicrm_contribution_recur',
59 'civicrm_contribution_soft',
61 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=contribute'),
63 'rel_table_contribution_page' => [
64 'title' => ts('Contribution Pages'),
65 'tables' => ['civicrm_contribution_page'],
66 'url' => CRM_Utils_System
::url('civicrm/admin/contribute', 'reset=1&cid=$cid'),
68 'rel_table_memberships' => [
69 'title' => ts('Memberships'),
72 'civicrm_membership_log',
73 'civicrm_membership_type',
75 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=member'),
77 'rel_table_participants' => [
78 'title' => ts('Participants'),
79 'tables' => ['civicrm_participant'],
80 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=participant'),
82 'rel_table_events' => [
83 'title' => ts('Events'),
84 'tables' => ['civicrm_event'],
85 'url' => CRM_Utils_System
::url('civicrm/event/manage', 'reset=1&cid=$cid'),
87 'rel_table_activities' => [
88 'title' => ts('Activities'),
89 'tables' => ['civicrm_activity', 'civicrm_activity_contact'],
90 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=activity'),
92 'rel_table_relationships' => [
93 'title' => ts('Relationships'),
94 'tables' => ['civicrm_relationship'],
95 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=rel'),
97 'rel_table_custom_groups' => [
98 'title' => ts('Custom Groups'),
99 'tables' => ['civicrm_custom_group'],
100 'url' => CRM_Utils_System
::url('civicrm/admin/custom/group', 'reset=1'),
102 'rel_table_uf_groups' => [
103 'title' => ts('Profiles'),
104 'tables' => ['civicrm_uf_group'],
105 'url' => CRM_Utils_System
::url('civicrm/admin/uf/group', 'reset=1'),
107 'rel_table_groups' => [
108 'title' => ts('Groups'),
109 'tables' => ['civicrm_group_contact'],
110 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=group'),
112 'rel_table_notes' => [
113 'title' => ts('Notes'),
114 'tables' => ['civicrm_note'],
115 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=note'),
117 'rel_table_tags' => [
118 'title' => ts('Tags'),
119 'tables' => ['civicrm_entity_tag'],
120 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=tag'),
122 'rel_table_mailings' => [
123 'title' => ts('Mailings'),
126 'civicrm_mailing_event_queue',
127 'civicrm_mailing_event_subscribe',
129 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=mailing'),
131 'rel_table_cases' => [
132 'title' => ts('Cases'),
133 'tables' => ['civicrm_case_contact'],
134 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=case'),
136 'rel_table_grants' => [
137 'title' => ts('Grants'),
138 'tables' => ['civicrm_grant'],
139 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=grant'),
142 'title' => ts('PCPs'),
143 'tables' => ['civicrm_pcp'],
144 'url' => CRM_Utils_System
::url('civicrm/contribute/pcp/manage', 'reset=1'),
146 'rel_table_pledges' => [
147 'title' => ts('Pledges'),
148 'tables' => ['civicrm_pledge', 'civicrm_pledge_payment'],
149 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=pledge'),
151 'rel_table_users' => [
153 'tables' => ['civicrm_uf_match'],
154 'url' => $userRecordUrl,
158 $relTables +
= self
::getMultiValueCustomSets('relTables');
160 // Allow hook_civicrm_merge() to adjust $relTables
161 CRM_Utils_Hook
::merge('relTables', $relTables);
163 // Cache the results in a static variable
164 Civi
::$statics[__CLASS__
]['relTables'] = $relTables;
167 return Civi
::$statics[__CLASS__
]['relTables'];
171 * Returns the related tables groups for which a contact has any info entered.
177 public static function getActiveRelTables($cid) {
181 $relTables = self
::relTables();
182 $cidRefs = self
::cidRefs();
183 $eidRefs = self
::eidRefs();
184 foreach ($relTables as $group => $params) {
186 foreach ($params['tables'] as $table) {
187 if (isset($cidRefs[$table])) {
188 foreach ($cidRefs[$table] as $field) {
189 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $field = $cid";
192 if (isset($eidRefs[$table])) {
193 foreach ($eidRefs[$table] as $entityTable => $entityId) {
194 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $entityId = $cid AND $entityTable = 'civicrm_contact'";
197 foreach ($sqls as $sql) {
198 if (CRM_Core_DAO
::singleValueQuery($sql) > 0) {
204 return array_unique($groups);
208 * Get array tables and fields that reference civicrm_contact.id.
210 * This function calls the merge hook and only exists to wrap the DAO function to support that deprecated call.
211 * The entityTypes hook is the recommended way to add tables to this result.
213 * I thought about adding another hook to alter tableReferences but decided it was unclear if there
214 * are use cases not covered by entityTables and instead we should wait & see.
216 public static function cidRefs() {
217 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['contact_references'])) {
218 return \Civi
::$statics[__CLASS__
]['contact_references'];
221 $contactReferences = $coreReferences = CRM_Core_DAO
::getReferencesToContactTable();
223 CRM_Utils_Hook
::merge('cidRefs', $contactReferences);
224 if ($contactReferences !== $coreReferences) {
226 ->warning("Deprecated hook ::merge in context of 'cidRefs. Use entityTypes instead.", ['civi.tag' => 'deprecated']);
228 \Civi
::$statics[__CLASS__
]['contact_references'] = $contactReferences;
229 return \Civi
::$statics[__CLASS__
]['contact_references'];
233 * Return tables and their fields referencing civicrm_contact.contact_id with entity_id
235 public static function eidRefs() {
238 // FIXME: this should be generated dynamically from the schema
239 // tables that reference contacts with entity_{id,table}
241 'civicrm_acl' => ['entity_table' => 'entity_id'],
242 'civicrm_acl_entity_role' => ['entity_table' => 'entity_id'],
243 'civicrm_entity_file' => ['entity_table' => 'entity_id'],
244 'civicrm_log' => ['entity_table' => 'entity_id'],
245 'civicrm_mailing_group' => ['entity_table' => 'entity_id'],
246 'civicrm_note' => ['entity_table' => 'entity_id'],
249 // Allow hook_civicrm_merge() to adjust $eidRefs
250 CRM_Utils_Hook
::merge('eidRefs', $eidRefs);
256 * Return tables using locations.
258 public static function locTables() {
261 $locTables = ['civicrm_email', 'civicrm_address', 'civicrm_phone'];
263 // Allow hook_civicrm_merge() to adjust $locTables
264 CRM_Utils_Hook
::merge('locTables', $locTables);
270 * We treat multi-valued custom sets as "related tables" similar to activities, contributions, etc.
271 * @param string $request
272 * 'relTables' or 'cidRefs'.
276 public static function getMultiValueCustomSets($request) {
278 if (!isset(Civi
::$statics[__CLASS__
]['multiValueCustomSets'])) {
283 $result = civicrm_api3('custom_group', 'get', [
293 'return' => ['id', 'title', 'table_name', 'style'],
295 foreach ($result['values'] as $custom) {
296 $data['cidRefs'][$custom['table_name']] = ['entity_id'];
297 $urlSuffix = $custom['style'] == 'Tab' ?
'&selectedChild=custom_' . $custom['id'] : '';
298 $data['relTables']['rel_table_custom_' . $custom['id']] = [
299 'title' => $custom['title'],
300 'tables' => [$custom['table_name']],
301 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid' . $urlSuffix),
305 // Store the result in a static variable cache
306 Civi
::$statics[__CLASS__
]['multiValueCustomSets'] = $data;
309 return Civi
::$statics[__CLASS__
]['multiValueCustomSets'][$request];
313 * Tables which require custom processing should declare functions to call here.
314 * Doing so will override normal processing.
316 public static function cpTables() {
320 'civicrm_case_contact' => ['CRM_Case_BAO_Case' => 'mergeContacts'],
321 'civicrm_group_contact' => ['CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'],
322 // Empty array == do nothing - this table is handled by mergeGroupContact
323 'civicrm_subscription_history' => [],
324 'civicrm_relationship' => ['CRM_Contact_BAO_Relationship' => 'mergeRelationships'],
325 'civicrm_membership' => ['CRM_Member_BAO_Membership' => 'mergeMemberships'],
332 * Return payment related table.
334 public static function paymentTables() {
337 $tables = ['civicrm_pledge', 'civicrm_membership', 'civicrm_participant'];
343 * Return payment update Query.
345 * @param string $tableName
346 * @param int $mainContactId
347 * @param int $otherContactId
351 public static function paymentSql($tableName, $mainContactId, $otherContactId) {
353 if (!$tableName ||
!$mainContactId ||
!$otherContactId) {
357 $paymentTables = self
::paymentTables();
358 if (!in_array($tableName, $paymentTables)) {
362 switch ($tableName) {
363 case 'civicrm_pledge':
365 UPDATE IGNORE civicrm_contribution contribution
366 INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id )
367 INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id )
368 SET contribution.contact_id = $mainContactId
369 WHERE pledge.contact_id = $otherContactId";
372 case 'civicrm_membership':
374 UPDATE IGNORE civicrm_contribution contribution
375 INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id )
376 INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id )
377 SET contribution.contact_id = $mainContactId
378 WHERE membership.contact_id = $otherContactId";
381 case 'civicrm_participant':
383 UPDATE IGNORE civicrm_contribution contribution
384 INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id )
385 INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id )
386 SET contribution.contact_id = $mainContactId
387 WHERE participant.contact_id = $otherContactId";
396 * @param int $otherId
397 * @param string $tableName
398 * @param array $tableOperations
399 * @param string $mode
403 public static function operationSql($mainId, $otherId, $tableName, $tableOperations = [], $mode = 'add') {
405 if (!$tableName ||
!$mainId ||
!$otherId) {
409 switch ($tableName) {
410 case 'civicrm_membership':
411 if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add']) {
414 if ($mode == 'add') {
416 DELETE membership1.* FROM civicrm_membership membership1
417 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
418 AND membership1.contact_id = {$mainId}
419 AND membership2.contact_id = {$otherId} ";
421 if ($mode == 'payment') {
423 DELETE contribution.* FROM civicrm_contribution contribution
424 INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id
425 INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id
426 AND membership1.contact_id = {$mainId}
427 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
428 AND membership2.contact_id = {$otherId}";
432 case 'civicrm_uf_match':
433 // normal queries won't work for uf_match since that will lead to violation of unique constraint,
434 // failing to meet intended result. Therefore we introduce this additional query:
435 $sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}";
443 * Based on the provided two contact_ids and a set of tables, remove the
444 * belongings of the other contact and of their relations.
446 * @param int $otherID
447 * @param bool $tables
449 public static function removeContactBelongings($otherID, $tables) {
450 // CRM-20421: Removing Inherited memberships when memberships of parent are not migrated to new contact.
451 if (in_array("civicrm_membership", $tables)) {
452 $membershipIDs = CRM_Utils_Array
::collect('id',
453 CRM_Utils_Array
::value('values',
454 civicrm_api3("Membership", "get", [
455 "contact_id" => $otherID,
461 if (!empty($membershipIDs)) {
462 civicrm_api3("Membership", "get", [
463 'owner_membership_id' => ['IN' => $membershipIDs],
464 'api.Membership.delete' => ['id' => '$value.id'],
471 * Based on the provided two contact_ids and a set of tables, move the
472 * belongings of the other contact to the main one.
475 * @param int $otherId
476 * @param bool $tables
477 * @param array $tableOperations
478 * @param array $customTableToCopyFrom
480 public static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = [], $customTableToCopyFrom = NULL) {
481 $cidRefs = self
::cidRefs();
482 $eidRefs = self
::eidRefs();
483 $cpTables = self
::cpTables();
484 $paymentTables = self
::paymentTables();
486 // getting all custom tables
488 if ($customTableToCopyFrom !== NULL) {
489 // @todo this duplicates cidRefs?
490 CRM_Core_DAO
::appendCustomTablesExtendingContacts($customTables);
491 CRM_Core_DAO
::appendCustomContactReferenceFields($customTables);
492 $customTables = array_keys($customTables);
495 $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
497 // if there aren't any specific tables, don't affect the ones handled by relTables()
498 // also don't affect tables in locTables() CRM-15658
499 $relTables = self
::relTables();
500 $handled = self
::locTables();
502 foreach ($relTables as $params) {
503 $handled = array_merge($handled, $params['tables']);
505 $affected = array_diff($affected, $handled);
506 $affected = array_unique(array_merge($affected, $tables));
508 $mainId = (int) $mainId;
509 $otherId = (int) $otherId;
510 $multi_value_tables = array_keys(CRM_Dedupe_Merger
::getMultiValueCustomSets('cidRefs'));
513 foreach ($affected as $table) {
514 // skipping non selected single-value custom table's value migration
515 if (!in_array($table, $multi_value_tables)) {
516 if ($customTableToCopyFrom !== NULL && in_array($table, $customTables) && !in_array($table, $customTableToCopyFrom)) {
517 if (isset($cidRefs[$table]) && ($delCol = array_search('entity_id', $cidRefs[$table])) !== FALSE) {
518 // remove entity_id from the field list
519 unset($cidRefs[$table][$delCol]);
524 // Call custom processing function for objects that require it
525 if (isset($cpTables[$table])) {
526 foreach ($cpTables[$table] as $className => $fnName) {
527 $className::$fnName($mainId, $otherId, $sqls, $tables, $tableOperations);
529 // Skip normal processing
533 // use UPDATE IGNORE + DELETE query pair to skip on situations when
534 // there's a UNIQUE restriction on ($field, some_other_field) pair
535 if (isset($cidRefs[$table])) {
536 foreach ($cidRefs[$table] as $field) {
537 // carry related contributions CRM-5359
538 if (in_array($table, $paymentTables)) {
539 $paymentSqls = self
::paymentSql($table, $mainId, $otherId);
540 $sqls = array_merge($sqls, $paymentSqls);
542 if (!empty($tables) && !in_array('civicrm_contribution', $tables)) {
543 $payOprSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations, 'payment');
544 $sqls = array_merge($sqls, $payOprSqls);
548 $preOperationSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations);
549 $sqls = array_merge($sqls, $preOperationSqls);
551 if ($customTableToCopyFrom !== NULL && in_array($table, $customTableToCopyFrom) && !self
::customRecordExists($mainId, $table, $field) && $field == 'entity_id') {
552 // this is the entity_id column of a custom field group where:
553 // - the custom table should be copied as indicated by $customTableToCopyFrom
554 // e.g. because a field in the group was selected in a form
555 // - AND no record exists yet for the $mainId contact
556 // we only do this for column "entity_id" as we wouldn't want to
557 // run this INSERT for ContactReference fields
558 $sqls[] = "INSERT INTO $table ($field) VALUES ($mainId)";
560 $sqls[] = "UPDATE IGNORE $table SET $field = $mainId WHERE $field = $otherId";
561 $sqls[] = "DELETE FROM $table WHERE $field = $otherId";
565 if (isset($eidRefs[$table])) {
566 foreach ($eidRefs[$table] as $entityTable => $entityId) {
567 $sqls[] = "UPDATE IGNORE $table SET $entityId = $mainId WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
568 $sqls[] = "DELETE FROM $table WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
573 // Allow hook_civicrm_merge() to add SQL statements for the merge operation.
574 CRM_Utils_Hook
::merge('sqls', $sqls, $mainId, $otherId, $tables);
576 foreach ($sqls as $sql) {
577 CRM_Core_DAO
::executeQuery($sql, [], TRUE, NULL, TRUE);
579 CRM_Dedupe_Merger
::addMembershipToRealtedContacts($mainId);
583 * Given a contact ID, will check if a record exists in given table.
588 * Field where the contact's ID is stored in the table
591 * True if a record is found for the given contact ID, false otherwise
593 private static function customRecordExists($contactID, $table, $idField) {
595 SELECT COUNT(*) AS count
597 WHERE $idField = $contactID
599 $dbResult = CRM_Core_DAO
::executeQuery($sql);
602 if ($dbResult->count
> 0) {
610 * Load all non-empty fields for the contacts
614 * @param array $other
619 public static function retrieveFields($main, $other) {
624 foreach (self
::getContactFields() as $validField) {
625 // CRM-17556 Get all non-empty fields, to make comparison easier
626 if (!empty($main[$validField]) ||
!empty($other[$validField])) {
627 $result['contact'][] = $validField;
631 $mainEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($main['id']);
632 $otherEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($other['id']);
633 $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
634 foreach ($keys as $key) {
635 // Exclude multi-value fields CRM-13836
636 if (strpos($key, '_')) {
639 $key1 = CRM_Utils_Array
::value($key, $mainEvs);
640 $key2 = CRM_Utils_Array
::value($key, $otherEvs);
641 // We wish to retain '0' as it has a different meaning than NULL on a checkbox.
642 // However I can't think of a case where an empty string is more meaningful than null
643 // or where it would be FALSE or something else nullish.
644 $valuesToIgnore = [NULL, '', []];
645 if (!in_array($key1, $valuesToIgnore, TRUE) ||
!in_array($key2, $valuesToIgnore, TRUE)) {
646 $result['custom'][] = $key;
653 * Batch merge a set of contacts based on rule-group and group.
659 * @param string $mode
660 * Helps decide how to behave when there are conflicts.
661 * A 'safe' value skips the merge if there are any un-resolved conflicts, wheras 'aggressive'
662 * mode does a force merge.
663 * @param int $batchLimit number of merges to carry out in one batch.
664 * @param int $isSelected if records with is_selected column needs to be processed.
665 * Note the option of '2' is only used in conjunction with $redirectForPerformance
666 * to determine when to reload the cache (!). The use of anything other than a boolean is being grandfathered
667 * out in favour of explicitly passing in $reloadCacheIfEmpty
669 * @param array $criteria
670 * Criteria to use in the filter.
672 * @param bool $checkPermissions
673 * Respect logged in user permissions.
674 * @param bool|NULL $reloadCacheIfEmpty
675 * If not set explicitly this is calculated but it is preferred that it be set
676 * per comments on isSelected above.
678 * @param int $searchLimit
679 * Limit on number of contacts to search for duplicates for.
680 * This means that if the limit is 1000 then only duplicates for the first 1000 contacts
681 * matching criteria will be found and batchMerged (the number of merges could be less than or greater than 100)
685 * @throws \CRM_Core_Exception
686 * @throws \CiviCRM_API3_Exception
688 public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $batchLimit = 1, $isSelected = 2, $criteria = [], $checkPermissions = TRUE, $reloadCacheIfEmpty = NULL, $searchLimit = 0) {
689 $redirectForPerformance = ($batchLimit > 1) ?
TRUE : FALSE;
690 if ($mode === 'aggressive' && $checkPermissions && !CRM_Core_Permission
::check('force merge duplicate contacts')) {
691 throw new CRM_Core_Exception(ts('Insufficient permissions for aggressive mode batch merge'));
693 if (!isset($reloadCacheIfEmpty)) {
694 $reloadCacheIfEmpty = (!$redirectForPerformance && $isSelected == 2);
696 if ($isSelected !== 0 && $isSelected !== 1) {
697 // explicitly set to NULL if not 1 or 0 as part of grandfathering out the mystical '2' value.
700 $dupePairs = self
::getDuplicatePairs($rgid, $gid, $reloadCacheIfEmpty, $batchLimit, $isSelected, ($mode == 'aggressive'), $criteria, $checkPermissions, $searchLimit);
703 'cache_key_string' => self
::getMergeCacheKeyString($rgid, $gid, $criteria, $checkPermissions, $searchLimit),
704 // @todo stop passing these parameters in & instead calculate them in the merge function based
705 // on the 'real' params like $isRespectExclusions $batchLimit and $isSelected.
706 'join' => self
::getJoinOnDedupeTable(),
707 'where' => self
::getWhereString($isSelected),
708 'limit' => (int) $batchLimit,
710 return CRM_Dedupe_Merger
::merge($dupePairs, $cacheParams, $mode, $redirectForPerformance, $checkPermissions);
714 * Get the string to join the prevnext cache to the dedupe table.
717 * The join string to join prevnext cache on the dedupe table.
719 public static function getJoinOnDedupeTable() {
721 LEFT JOIN civicrm_dedupe_exception de
723 pn.entity_id1 = de.contact_id1
724 AND pn.entity_id2 = de.contact_id2 )
729 * Get where string for dedupe join.
731 * @param bool $isSelected
735 protected static function getWhereString($isSelected) {
736 $where = "de.id IS NULL";
737 if ($isSelected === 0 ||
$isSelected === 1) {
738 $where .= " AND pn.is_selected = {$isSelected}";
744 * Update the statistics for the merge set.
746 * @param string $cacheKeyString
747 * @param array $result
749 public static function updateMergeStats($cacheKeyString, $result = []) {
750 // gather latest stats
751 $merged = count($result['merged']);
752 $skipped = count($result['skipped']);
754 if ($merged <= 0 && $skipped <= 0) {
758 // get previous stats
759 $previousStats = CRM_Dedupe_Merger
::getMergeStats($cacheKeyString);
760 if (!empty($previousStats)) {
761 if ($previousStats['merged']) {
762 $merged = $merged +
$previousStats['merged'];
764 if ($previousStats['skipped']) {
765 $skipped = $skipped +
$previousStats['skipped'];
770 CRM_Dedupe_Merger
::resetMergeStats($cacheKeyString);
772 // store the updated stats
775 'skipped' => $skipped,
777 $data = CRM_Core_DAO
::escapeString(serialize($data));
779 CRM_Core_BAO_PrevNextCache
::setItem('civicrm_contact', 0, 0, $cacheKeyString . '_stats', $data);
783 * Delete information about merges for the given string.
785 * @param $cacheKeyString
787 public static function resetMergeStats($cacheKeyString) {
788 CRM_Core_BAO_PrevNextCache
::deleteItem(NULL, "{$cacheKeyString}_stats");
792 * Get merge outcome statistics.
794 * @param string $cacheKeyString
797 * Array of how many were merged and how many were skipped.
799 * @throws \CiviCRM_API3_Exception
801 public static function getMergeStats($cacheKeyString) {
802 $stats = civicrm_api3('Dedupe', 'get', ['cachekey' => "{$cacheKeyString}_stats", 'sequential' => 1])['values'];
803 if (!empty($stats)) {
804 return $stats[0]['data'];
810 * Get merge statistics message.
812 * @param array $stats
816 public static function getMergeStatsMsg($stats) {
818 if (!empty($stats['merged'])) {
819 $msg = '<p>' . ts('One contact merged.', [
820 'count' => $stats['merged'],
821 'plural' => '%count contacts merged.',
824 if (!empty($stats['skipped'])) {
825 $msg .= '<p>' . ts('One contact was skipped.', [
826 'count' => $stats['skipped'],
827 'plural' => '%count contacts were skipped.',
834 * Merge given set of contacts. Performs core operation.
836 * @param array $dupePairs
837 * Set of pair of contacts for whom merge is to be done.
838 * @param array $cacheParams
839 * Prev-next-cache params based on which next pair of contacts are computed.
840 * Generally used with batch-merge.
841 * @param string $mode
842 * Helps decide how to behave when there are conflicts.
843 * A 'safe' value skips the merge if there are any un-resolved conflicts.
844 * Does a force merge otherwise (aggressive mode).
846 * @param bool $redirectForPerformance
847 * Redirect to a url for batch processing.
849 * @param bool $checkPermissions
850 * Respect logged in user permissions.
854 * @throws \API_Exception
855 * @throws \CRM_Core_Exception
856 * @throws \CiviCRM_API3_Exception
858 public static function merge($dupePairs = [], $cacheParams = [], $mode = 'safe',
859 $redirectForPerformance = FALSE, $checkPermissions = TRUE
861 $cacheKeyString = CRM_Utils_Array
::value('cache_key_string', $cacheParams);
862 $resultStats = ['merged' => [], 'skipped' => []];
864 // we don't want dupe caching to get reset after every-merge, and therefore set the
865 CRM_Core_Config
::setPermitCacheFlushMode(FALSE);
866 $deletedContacts = [];
868 while (!empty($dupePairs)) {
869 foreach ($dupePairs as $index => $dupes) {
870 if (in_array($dupes['dstID'], $deletedContacts) ||
in_array($dupes['srcID'], $deletedContacts)) {
871 unset($dupePairs[$index]);
874 if (($result = self
::dedupePair($dupes, $mode, $checkPermissions, $cacheKeyString)) === FALSE) {
875 unset($dupePairs[$index]);
878 if (!empty($result['merged'])) {
879 $deletedContacts[] = $result['merged'][0]['other_id'];
880 $resultStats['merged'][] = ($result['merged'][0]);
883 $resultStats['skipped'][] = ($result['skipped'][0]);
887 if ($cacheKeyString && !$redirectForPerformance) {
888 // retrieve next pair of dupes
889 // @todo call getDuplicatePairs.
890 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString,
891 $cacheParams['join'],
892 $cacheParams['where'],
894 $cacheParams['limit'],
901 // do not proceed. Terminate the loop
906 CRM_Dedupe_Merger
::updateMergeStats($cacheKeyString, $resultStats);
911 * A function which uses various rules / algorithms for choosing which contact to bias to
912 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
915 * Main contact with whom merge has to happen.
916 * @param int $otherId
917 * Duplicate contact which would be deleted after merge operation.
918 * @param array $migrationInfo
919 * Array of information about which elements to merge.
920 * @param string $mode
921 * Helps decide how to behave when there are conflicts.
922 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
923 * - Does a force merge otherwise (aggressive mode).
925 * @param array $conflicts
926 * An empty array to be filed with conflict information.
930 * @throws \CRM_Core_Exception
931 * @throws \CiviCRM_API3_Exception
932 * @throws \API_Exception
934 public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe', &$conflicts = []) {
936 $conflicts = self
::getConflicts($migrationInfo, $mainId, $otherId, $mode);
937 // A hook could have set skip_merge in order to alter merge behaviour.
938 // This is a something we might ideally deprecate since they really 'should'
939 // mess with the conflicts array instead.
940 return (bool) ($migrationData['skip_merge'] ??
!empty($conflicts));
944 * Compare 2 addresses to see if they are the same.
946 * @param array $mainAddress
947 * @param array $comparisonAddress
951 public static function locationIsSame($mainAddress, $comparisonAddress) {
952 $keysToIgnore = self
::ignoredFields();
953 foreach ($comparisonAddress as $field => $value) {
954 if (in_array($field, $keysToIgnore)) {
957 if ((!empty($value) ||
$value === '0') && isset($mainAddress[$field]) && $mainAddress[$field] != $value) {
965 * A function to build an array of information about location blocks that is
966 * required when merging location fields
970 public static function getLocationBlockInfo() {
973 'label' => 'Address',
974 'displayField' => 'display',
975 'sortString' => 'location_type_id',
976 'hasLocation' => TRUE,
981 'displayField' => 'display',
982 'sortString' => 'location_type_id',
983 'hasLocation' => TRUE,
988 'displayField' => 'name',
989 'sortString' => 'location_type_id,provider_id',
990 'hasLocation' => TRUE,
991 'hasType' => 'provider_id',
995 'displayField' => 'phone',
996 'sortString' => 'location_type_id,phone_type_id',
997 'hasLocation' => TRUE,
998 'hasType' => 'phone_type_id',
1001 'label' => 'Website',
1002 'displayField' => 'url',
1003 'sortString' => 'website_type_id',
1004 'hasLocation' => FALSE,
1005 'hasType' => 'website_type_id',
1008 return $locationBlocks;
1012 * A function to build an array of information required by merge function and the merge UI.
1014 * @param int $mainId
1015 * Main contact with whom merge has to happen.
1016 * @param int $otherId
1017 * Duplicate contact which would be deleted after merge operation.
1018 * @param bool $checkPermissions
1019 * Should the logged in user's permissions be ignore. Setting this to false is
1020 * highly risky as it could cause data to be lost due to conflicts not showing up.
1021 * OTOH there is a risk a merger might view custom data they do not have permission to.
1022 * Hence for now only making this really explicit and making it reflect perms in
1025 * @todo review permissions issue!
1027 * @return array|bool|int
1029 * rows => An array of arrays, each is row of merge information for the table
1030 * Format: move_fieldname, eg: move_contact_type
1031 * main => Value associated with the main contact
1032 * other => Value associated with the other contact
1033 * title => The title of the field to display in the merge table
1035 * elements => An array of form elements for the merge UI
1037 * rel_table_elements => An array of form elements for the merge UI for
1038 * entities related to the contact (eg: checkbox to move 'mailings')
1040 * rel_tables => Stores the tables that have related entities for the contact
1041 * for example mailings, groups
1043 * main_details => An array of core contact field values, eg: first_name, etc.
1044 * location_blocks => An array of location block data for the main contact
1045 * stored as the 'result' of an API call.
1046 * eg: main_details['location_blocks']['address'][0]['id']
1047 * eg: main_details['location_blocks']['email'][1]['id']
1049 * other_details => As above, but for the 'other' contact
1051 * migration_info => Stores the 'default' merge actions for each field which
1052 * is used when programatically merging contacts. It contains instructions
1053 * to move all fields from the 'other' contact to the 'main' contact, as
1054 * though the form had been submitted with those options.
1056 * @throws \CRM_Core_Exception
1057 * @throws \CiviCRM_API3_Exception
1058 * @throws \Exception
1060 public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissions = TRUE) {
1061 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1062 $fields = self
::getMergeFieldsMetadata();
1064 $main = self
::getMergeContactDetails($mainId);
1065 $other = self
::getMergeContactDetails($otherId);
1067 $compareFields = self
::retrieveFields($main, $other);
1069 $rows = $elements = $relTableElements = $migrationInfo = [];
1071 foreach ($compareFields['contact'] as $field) {
1072 if ($field == 'contact_sub_type') {
1073 // CRM-15681 don't display sub-types in UI
1076 $rows["move_$field"] = [
1077 'main' => self
::getFieldValueAndLabel($field, $main)['label'],
1078 'other' => self
::getFieldValueAndLabel($field, $other)['label'],
1079 'title' => $fields[$field]['title'],
1082 $value = self
::getFieldValueAndLabel($field, $other)['value'];
1084 if ($value === NULL ||
$value == '') {
1087 if ($value === 0 or $value === '0') {
1088 $value = $qfZeroBug;
1090 if (is_array($value) && empty($value[1])) {
1094 // Display a checkbox to migrate, only if the values are different
1095 if ($value != $main[$field]) {
1103 'is_checked' => (!isset($main[$field]) ||
$main[$field] === ''),
1107 $migrationInfo["move_$field"] = $value;
1110 // Handle location blocks.
1111 // @todo OpenID not in API yet, so is not supported here.
1113 // Set up useful information about the location blocks
1114 $locationBlocks = self
::getLocationBlockInfo();
1116 $locations = ['main' => [], 'other' => []];
1118 foreach ($locationBlocks as $blockName => $blockInfo) {
1120 // Collect existing fields from both 'main' and 'other' contacts first
1121 // This allows us to match up location/types when building the table rows
1122 $locations['main'][$blockName] = self
::buildLocationBlockForContact($mainId, $blockInfo, $blockName);
1123 $locations['other'][$blockName] = self
::buildLocationBlockForContact($otherId, $blockInfo, $blockName);
1125 // Now, build the table rows appropriately, based off the information on
1126 // the 'other' contact
1127 if (!empty($locations['other']) && !empty($locations['other'][$blockName])) {
1128 foreach ($locations['other'][$blockName] as $count => $value) {
1130 $displayValue = $value[$blockInfo['displayField']];
1132 // Add this value to the table rows
1133 $rows["move_location_{$blockName}_{$count}"]['other'] = $displayValue;
1135 // CRM-17556 Only display 'main' contact value if it's the same location + type
1136 // Look it up from main values...
1138 $lookupLocation = FALSE;
1139 if ($blockInfo['hasLocation']) {
1140 $lookupLocation = $value['location_type_id'];
1143 $lookupType = FALSE;
1144 if ($blockInfo['hasType']) {
1145 $lookupType = CRM_Utils_Array
::value($blockInfo['hasType'], $value);
1148 // Hold ID of main contact's matching block
1149 $mainContactBlockId = 0;
1151 if (!empty($locations['main'][$blockName])) {
1152 foreach ($locations['main'][$blockName] as $mainValueCheck) {
1153 // No location/type, or matching location and type
1155 (empty($lookupLocation) ||
$lookupLocation == $mainValueCheck['location_type_id'])
1156 && (empty($lookupType) ||
$lookupType == $mainValueCheck[$blockInfo['hasType']])
1158 // Set this value as the default against the 'other' contact value
1159 $rows["move_location_{$blockName}_{$count}"]['main'] = $mainValueCheck[$blockInfo['displayField']];
1160 $rows["move_location_{$blockName}_{$count}"]['main_is_primary'] = $mainValueCheck['is_primary'];
1161 $rows["move_location_{$blockName}_{$count}"]['location_entity'] = $blockName;
1162 $mainContactBlockId = $mainValueCheck['id'];
1168 // Add checkbox to migrate data from 'other' to 'main'
1169 $elements[] = ['advcheckbox', "move_location_{$blockName}_{$count}"];
1171 // Add checkbox to set the 'other' location as primary
1174 "location_blocks[$blockName][$count][set_other_primary]",
1176 ts('Set as primary'),
1179 // Flag up this field to skipMerge function (@todo: do we need to?)
1180 $migrationInfo["move_location_{$blockName}_{$count}"] = 1;
1182 // Add a hidden field to store the ID of the target main contact block
1185 "location_blocks[$blockName][$count][mainContactBlockId]",
1186 $mainContactBlockId,
1190 $thisTypeId = FALSE;
1193 // Provide a select drop-down for the location's location type
1194 // eg: Home, Work...
1196 if ($blockInfo['hasLocation']) {
1198 // Load the location options for this entity
1199 $locationOptions = civicrm_api3($blockName, 'getoptions', ['field' => 'location_type_id']);
1201 $thisLocId = $value['location_type_id'];
1203 // Put this field's location type at the top of the list
1204 $tmpIdList = $locationOptions['values'];
1205 $defaultLocId = [$thisLocId => $tmpIdList[$thisLocId]];
1206 unset($tmpIdList[$thisLocId]);
1211 "location_blocks[$blockName][$count][locTypeId]",
1213 $defaultLocId +
$tmpIdList,
1216 // Add the relevant information to the $migrationInfo
1217 // Keep location-type-id same as that of other-contact
1218 // @todo Check this logic out
1219 $migrationInfo['location_blocks'][$blockName][$count]['locTypeId'] = $thisLocId;
1220 if ($blockName != 'address') {
1223 "location_blocks[{$blockName}][$count][operation]",
1227 // always use add operation
1228 $migrationInfo['location_blocks'][$blockName][$count]['operation'] = 1;
1233 // Provide a select drop-down for the location's type/provider
1234 // eg websites: Facebook...
1236 if ($blockInfo['hasType']) {
1238 // Load the type options for this entity
1239 $typeOptions = civicrm_api3($blockName, 'getoptions', ['field' => $blockInfo['hasType']]);
1241 $thisTypeId = CRM_Utils_Array
::value($blockInfo['hasType'], $value);
1243 // Put this field's location type at the top of the list
1244 $tmpIdList = $typeOptions['values'];
1245 $defaultTypeId = [$thisTypeId => CRM_Utils_Array
::value($thisTypeId, $tmpIdList)];
1246 unset($tmpIdList[$thisTypeId]);
1251 "location_blocks[$blockName][$count][typeTypeId]",
1253 $defaultTypeId +
$tmpIdList,
1256 // Add the information to the migrationInfo
1257 $migrationInfo['location_blocks'][$blockName][$count]['typeTypeId'] = $thisTypeId;
1261 // Set the label for this row
1262 $rowTitle = $blockInfo['label'] . ' ' . ($count +
1);
1263 if (!empty($thisLocId)) {
1264 $rowTitle .= ' (' . $locationOptions['values'][$thisLocId] . ')';
1266 if (!empty($thisTypeId)) {
1267 $rowTitle .= ' (' . $typeOptions['values'][$thisTypeId] . ')';
1269 $rows["move_location_{$blockName}_$count"]['title'] = $rowTitle;
1271 } // End loop through 'other' locations of this type
1273 } // End if 'other' location for this type exists
1275 } // End loop through each location block entity
1277 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1278 $config = CRM_Core_Config
::singleton();
1279 $mainUfId = CRM_Core_BAO_UFMatch
::getUFId($mainId);
1283 if ($config->userSystem
->is_drupal
== '1' && function_exists($mainUser)) {
1284 $mainUser = user_load($mainUfId);
1286 elseif ($config->userFramework
== 'Joomla') {
1287 $mainUser = JFactory
::getUser($mainUfId);
1290 $otherUfId = CRM_Core_BAO_UFMatch
::getUFId($otherId);
1294 if ($config->userSystem
->is_drupal
== '1' && function_exists($mainUser)) {
1295 $otherUser = user_load($otherUfId);
1297 elseif ($config->userFramework
== 'Joomla') {
1298 $otherUser = JFactory
::getUser($otherUfId);
1302 $mergeHandler = new CRM_Dedupe_MergeHandler((int) $mainId, (int) $otherId);
1303 $relTables = $mergeHandler->getTablesRelatedToTheMergePair();
1304 foreach ($relTables as $name => $null) {
1305 $relTableElements[] = ['checkbox', "move_$name"];
1306 $migrationInfo["move_$name"] = 1;
1308 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1309 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1310 if ($name == 'rel_table_users') {
1311 $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
1312 $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
1313 $find = ['$ufid', '$ufname'];
1315 $replace = [$mainUfId, $mainUser->name
];
1316 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1319 $replace = [$otherUfId, $otherUser->name
];
1320 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1323 if ($name == 'rel_table_memberships') {
1324 //Enable 'add new' checkbox if main contact does not contain any membership similar to duplicate contact.
1325 $attributes = ['checked' => 'checked'];
1326 $otherContactMemberships = CRM_Member_BAO_Membership
::getAllContactMembership($otherId);
1327 foreach ($otherContactMemberships as $membership) {
1328 $mainMembership = CRM_Member_BAO_Membership
::getContactMembership($mainId, $membership['membership_type_id'], FALSE);
1329 if ($mainMembership) {
1335 "operation[move_{$name}][add]",
1340 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1343 foreach ($relTables as $name => $null) {
1344 $relTables["move_$name"] = $relTables[$name];
1345 unset($relTables[$name]);
1348 // handle custom fields
1349 $mainTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], NULL, $mainId, -1,
1350 CRM_Utils_Array
::value('contact_sub_type', $main), NULL, TRUE, NULL, TRUE, $checkPermissions
1352 $otherTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], NULL, $otherId, -1,
1353 CRM_Utils_Array
::value('contact_sub_type', $other), NULL, TRUE, NULL, TRUE, $checkPermissions
1356 foreach ($otherTree as $gid => $group) {
1357 $foundField = FALSE;
1358 if (!isset($group['fields'])) {
1362 foreach ($group['fields'] as $fid => $field) {
1363 if (in_array($fid, $compareFields['custom'])) {
1365 $rows["custom_group_$gid"]['title'] = $group['title'];
1368 if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) {
1369 foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1370 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomField
::displayValue($values['data'], $fid);
1374 if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) {
1375 foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1376 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomField
::displayValue($values['data'], $fid);
1377 if ($values['data'] === 0 ||
$values['data'] === '0') {
1378 $values['data'] = $qfZeroBug;
1380 $value = ($values['data']) ?
$values['data'] : $value;
1383 $rows["move_custom_$fid"]['title'] = $field['label'];
1393 $migrationInfo["move_custom_$fid"] = $value;
1400 'elements' => $elements,
1401 'rel_table_elements' => $relTableElements,
1402 'rel_tables' => $relTables,
1403 'main_details' => $main,
1404 'other_details' => $other,
1405 'migration_info' => $migrationInfo,
1408 $result['main_details']['location_blocks'] = $locations['main'];
1409 $result['other_details']['location_blocks'] = $locations['other'];
1415 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1416 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1417 * A superset of moveContactBelongings() function.
1419 * @param int $mainId
1420 * Main contact with whom merge has to happen.
1421 * @param int $otherId
1422 * Duplicate contact which would be deleted after merge operation.
1424 * @param array $migrationInfo
1426 * @param bool $checkPermissions
1427 * Respect logged in user permissions.
1430 * @throws \CiviCRM_API3_Exception
1432 public static function moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions = TRUE) {
1433 if (empty($migrationInfo)) {
1436 // Encapsulate in a transaction to avoid half-merges.
1437 $transaction = new CRM_Core_Transaction();
1439 $contactType = $migrationInfo['main_details']['contact_type'];
1440 $relTables = CRM_Dedupe_Merger
::relTables();
1441 $submittedCustomFields = $moveTables = $tableOperations = $removeTables = [];
1443 self
::swapOutFieldsAffectedByQFZeroBug($migrationInfo);
1444 foreach ($migrationInfo as $key => $value) {
1446 if (substr($key, 0, 12) == 'move_custom_' && $value != NULL) {
1447 $submitted[substr($key, 5)] = $value;
1448 $submittedCustomFields[] = substr($key, 12);
1450 elseif (in_array(substr($key, 5), CRM_Dedupe_Merger
::getContactFields()) && $value != NULL) {
1451 $submitted[substr($key, 5)] = $value;
1453 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1454 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1455 if (array_key_exists('operation', $migrationInfo)) {
1456 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1457 if (array_key_exists($key, $migrationInfo['operation'])) {
1458 $tableOperations[$table] = $migrationInfo['operation'][$key];
1463 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '0') {
1464 $removeTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1467 self
::mergeLocations($mainId, $otherId, $migrationInfo);
1469 // **** Do contact related migrations
1470 $customTablesToCopyValues = self
::getAffectedCustomTables($submittedCustomFields);
1471 // @todo - move all custom field processing to the move class & eventually have an
1472 // overridable DAO class for it.
1473 $customFieldBAO = new CRM_Core_BAO_CustomField();
1474 $customFieldBAO->move($otherId, $mainId, $submittedCustomFields);
1475 CRM_Dedupe_Merger
::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations, $customTablesToCopyValues);
1476 unset($moveTables, $tableOperations);
1478 // **** Do table related removals
1479 if (!empty($removeTables)) {
1481 CRM_Dedupe_Merger
::removeContactBelongings($otherId, $removeTables);
1485 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
1486 $names['gender'] = ['newName' => 'gender_id', 'groupName' => 'gender'];
1487 $names['individual_prefix'] = [
1488 'newName' => 'prefix_id',
1489 'groupName' => 'individual_prefix',
1491 $names['individual_suffix'] = [
1492 'newName' => 'suffix_id',
1493 'groupName' => 'individual_suffix',
1495 $names['communication_style'] = [
1496 'newName' => 'communication_style_id',
1497 'groupName' => 'communication_style',
1499 $names['addressee'] = [
1500 'newName' => 'addressee_id',
1501 'groupName' => 'addressee',
1503 $names['email_greeting'] = [
1504 'newName' => 'email_greeting_id',
1505 'groupName' => 'email_greeting',
1507 $names['postal_greeting'] = [
1508 'newName' => 'postal_greeting_id',
1509 'groupName' => 'postal_greeting',
1511 CRM_Core_OptionGroup
::lookupValues($submitted, $names, TRUE);
1512 // fix custom fields so they're edible by createProfileContact()
1513 $cFields = self
::getCustomFieldMetadata($contactType);
1515 if (!isset($submitted)) {
1518 foreach ($submitted as $key => $value) {
1519 list($cFields, $submitted) = self
::processCustomFields($mainId, $key, $cFields, $submitted, $value);
1522 // move view only custom fields CRM-5362
1523 $viewOnlyCustomFields = [];
1524 foreach ($submitted as $key => $value) {
1525 $fid = CRM_Core_BAO_CustomField
::getKeyID($key);
1526 if ($fid && array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])
1528 $viewOnlyCustomFields[$key] = $value;
1531 // special case to set values for view only, CRM-5362
1532 if (!empty($viewOnlyCustomFields)) {
1533 $viewOnlyCustomFields['entityID'] = $mainId;
1534 CRM_Core_BAO_CustomValueTable
::setValues($viewOnlyCustomFields);
1537 // dev/core#996 Ensure that the earliest created date is stored against the kept contact id
1538 $mainCreatedDate = civicrm_api3('Contact', 'getsingle', [
1540 'return' => ['created_date'],
1542 $otherCreatedDate = civicrm_api3('Contact', 'getsingle', [
1544 'return' => ['created_date'],
1546 if ($otherCreatedDate < $mainCreatedDate) {
1547 CRM_Core_DAO
::executeQuery("UPDATE civicrm_contact SET created_date = %1 WHERE id = %2", [
1548 1 => [$otherCreatedDate, 'String'],
1549 2 => [$mainId, 'Positive'],
1553 if (!$checkPermissions ||
(CRM_Core_Permission
::check('merge duplicate contacts') &&
1554 CRM_Core_Permission
::check('delete contacts'))
1556 // if ext id is submitted then set it null for contact to be deleted
1557 if (!empty($submitted['external_identifier'])) {
1558 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1559 CRM_Core_DAO
::executeQuery($query);
1561 civicrm_api3('contact', 'delete', ['id' => $otherId]);
1564 // CRM-15681 merge sub_types
1565 if ($other_sub_types = CRM_Utils_Array
::value('contact_sub_type', $migrationInfo['other_details'])) {
1566 if ($main_sub_types = CRM_Utils_Array
::value('contact_sub_type', $migrationInfo['main_details'])) {
1567 $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types));
1570 $submitted['contact_sub_type'] = $other_sub_types;
1574 // **** Update contact related info for the main contact
1575 if (!empty($submitted)) {
1576 $submitted['contact_id'] = $mainId;
1578 //update current employer field
1579 if ($currentEmloyerId = CRM_Utils_Array
::value('current_employer_id', $submitted)) {
1580 if (!CRM_Utils_System
::isNull($currentEmloyerId)) {
1581 $submitted['current_employer'] = $submitted['current_employer_id'];
1584 $submitted['current_employer'] = '';
1586 unset($submitted['current_employer_id']);
1589 //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
1590 if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) {
1591 $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
1593 if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) {
1594 $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
1597 CRM_Contact_BAO_Contact
::createProfileContact($submitted, $null, $mainId);
1599 $transaction->commit();
1600 CRM_Utils_Hook
::post('merge', 'Contact', $mainId);
1601 self
::createMergeActivities($mainId, $otherId);
1607 * Builds an Array of Custom tables for given custom field ID's.
1609 * @param $customFieldIDs
1612 * Array of custom table names
1614 private static function getAffectedCustomTables($customFieldIDs) {
1615 $customTableToCopyValues = [];
1617 foreach ($customFieldIDs as $fieldID) {
1618 if (!empty($fieldID)) {
1619 $customField = civicrm_api3('custom_field', 'getsingle', [
1621 'is_active' => TRUE,
1623 if (!civicrm_error($customField) && !empty($customField['custom_group_id'])) {
1624 $customGroup = civicrm_api3('custom_group', 'getsingle', [
1625 'id' => $customField['custom_group_id'],
1626 'is_active' => TRUE,
1629 if (!civicrm_error($customGroup) && !empty($customGroup['table_name'])) {
1630 $customTableToCopyValues[] = $customGroup['table_name'];
1636 return $customTableToCopyValues;
1640 * Get fields in the contact table suitable for merging.
1643 * Array of field names to be potentially merged.
1645 public static function getContactFields() {
1646 $contactFields = CRM_Contact_DAO_Contact
::fields();
1654 'primary_contact_id',
1658 foreach ($contactFields as $field => $value) {
1659 if (in_array($field, $invalidFields)) {
1660 unset($contactFields[$field]);
1663 return array_keys($contactFields);
1667 * Added for CRM-12695
1668 * Based on the contactID provided
1669 * add/update membership(s) to related contacts
1671 * @param int $contactID
1673 public static function addMembershipToRealtedContacts($contactID) {
1674 $dao = new CRM_Member_DAO_Membership();
1675 $dao->contact_id
= $contactID;
1679 //checks membership of contact itself
1680 while ($dao->fetch()) {
1681 $relationshipTypeId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id
, 'relationship_type_id', 'id');
1682 if ($relationshipTypeId) {
1683 $membershipParams = [
1685 'contact_id' => $dao->contact_id
,
1686 'membership_type_id' => $dao->membership_type_id
,
1687 'join_date' => CRM_Utils_Date
::isoToMysql($dao->join_date
),
1688 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
1689 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
1690 'source' => $dao->source
,
1691 'status_id' => $dao->status_id
,
1693 // create/update membership(s) for related contact(s)
1694 CRM_Member_BAO_Membership
::createRelatedMemberships($membershipParams, $dao);
1695 } // end of if relationshipTypeId
1700 * Create activities tracking the merge on affected contacts.
1702 * @param int $mainId
1703 * @param int $otherId
1705 * @throws \CiviCRM_API3_Exception
1707 public static function createMergeActivities($mainId, $otherId) {
1712 $activity = civicrm_api3('activity', 'create', [
1713 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
1715 'subject' => ts('Contact ID %1 has been merged and deleted.', $params),
1716 'target_contact_id' => $mainId,
1717 'activity_type_id' => 'Contact Merged',
1718 'status_id' => 'Completed',
1720 if (civicrm_api3('Setting', 'getvalue', [
1721 'name' => 'contact_undelete',
1722 'group' => 'CiviCRM Preferences',
1724 civicrm_api3('activity', 'create', [
1725 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
1727 'subject' => ts('Contact ID %1 has been merged into Contact ID %2 and deleted.', $params),
1728 'target_contact_id' => $otherId,
1729 'activity_type_id' => 'Contact Deleted by Merge',
1730 'parent_id' => $activity['id'],
1731 'status_id' => 'Completed',
1737 * Get Duplicate Pairs based on a rule for a group.
1739 * @param int $rule_group_id
1740 * @param int $group_id
1741 * @param bool $reloadCacheIfEmpty
1742 * Should the cache be reloaded if empty - this must be false when in a dedupe action!
1743 * @param int $batchLimit
1744 * @param bool $isSelected
1745 * Limit to selected pairs.
1746 * @param bool $includeConflicts
1747 * @param array $criteria
1748 * Additional criteria to narrow down the merge group.
1750 * @param bool $checkPermissions
1751 * Respect logged in user permissions.
1753 * @param int $searchLimit
1754 * Limit to searching for matches against this many contacts.
1756 * @param int $isForceNewSearch
1757 * Should a new search be forced, bypassing any cache retrieval.
1760 * Array of matches meeting the criteria.
1762 * @throws \CRM_Core_Exception
1763 * @throws \CiviCRM_API3_Exception
1765 public static function getDuplicatePairs($rule_group_id, $group_id, $reloadCacheIfEmpty, $batchLimit, $isSelected, $includeConflicts = TRUE, $criteria = [], $checkPermissions = TRUE, $searchLimit = 0, $isForceNewSearch = 0) {
1766 $dupePairs = $isForceNewSearch ?
[] : self
::getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, $includeConflicts, $criteria, $checkPermissions, $searchLimit);
1767 if (empty($dupePairs) && $reloadCacheIfEmpty) {
1768 // If we haven't found any dupes, probably cache is empty.
1769 // Try filling cache and give another try. We don't need to specify include conflicts here are there will not be any
1770 // until we have done some processing.
1771 CRM_Core_BAO_PrevNextCache
::refillCache($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit);
1772 return self
::getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, FALSE, $criteria, $checkPermissions, $searchLimit);
1778 * Get the cache key string for the merge action.
1780 * @param int $rule_group_id
1781 * @param int $group_id
1782 * @param array $criteria
1783 * Additional criteria to narrow down the merge group.
1784 * Currently we are only supporting the key 'contact' within it.
1785 * @param bool $checkPermissions
1786 * Respect the users permissions.
1787 * @param int $searchLimit
1788 * Number of contacts to seek dupes for (we need this because if
1789 * we change it the results won't be refreshed otherwise. Changing the limit
1790 * from 100 to 1000 SHOULD result in a new dedupe search).
1794 public static function getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit) {
1795 $contactType = CRM_Dedupe_BAO_RuleGroup
::getContactTypeForRuleGroup($rule_group_id);
1796 $cacheKeyString = "merge_{$contactType}";
1797 $cacheKeyString .= $rule_group_id ?
"_{$rule_group_id}" : '_0';
1798 $cacheKeyString .= $group_id ?
"_{$group_id}" : '_0';
1799 $cacheKeyString .= '_' . (int) $searchLimit;
1800 $cacheKeyString .= !empty($criteria) ?
md5(serialize($criteria)) : '_0';
1801 if ($checkPermissions) {
1802 $contactID = CRM_Core_Session
::getLoggedInContactID();
1804 // Distinguish between no permission check & no logged in user.
1805 $contactID = 'null';
1807 $cacheKeyString .= '_' . $contactID;
1810 $cacheKeyString .= '_0';
1812 return $cacheKeyString;
1816 * Get the metadata for the merge fields.
1818 * This is basically the contact metadata, augmented with fields to
1819 * represent email greeting, postal greeting & addressee.
1823 public static function getMergeFieldsMetadata() {
1824 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['merge_fields_metadata'])) {
1825 return \Civi
::$statics[__CLASS__
]['merge_fields_metadata'];
1827 $fields = CRM_Contact_DAO_Contact
::fields();
1828 static $optionValueFields = [];
1829 if (empty($optionValueFields)) {
1830 $optionValueFields = CRM_Core_OptionValue
::getFields();
1832 foreach ($optionValueFields as $field => $params) {
1833 $fields[$field]['title'] = $params['title'];
1835 \Civi
::$statics[__CLASS__
]['merge_fields_metadata'] = $fields;
1836 return \Civi
::$statics[__CLASS__
]['merge_fields_metadata'];
1840 * Get the details of the contact to be merged.
1842 * @param int $contact_id
1846 * @throws CRM_Core_Exception
1848 public static function getMergeContactDetails($contact_id) {
1850 'contact_id' => $contact_id,
1852 'return' => array_merge(['display_name'], self
::getContactFields()),
1854 $result = civicrm_api('contact', 'get', $params);
1856 // CRM-18480: Cancel the process if the contact is already deleted
1857 if (isset($result['values'][$contact_id]['contact_is_deleted']) && !empty($result['values'][$contact_id]['contact_is_deleted'])) {
1858 throw new CRM_Core_Exception(ts('Cannot merge because one contact (ID %1) has been deleted.', [
1863 return $result['values'][$contact_id];
1869 * Based on the data in the $locationMigrationInfo merge the locations for 2 contacts.
1871 * The data is in the format received from the merge form (which is a fairly confusing format).
1873 * It is converted into an array of DAOs which is passed to the alterLocationMergeData hook
1874 * before saving or deleting the DAOs. A new hook is added to allow these to be altered after they have
1875 * been calculated and before saving because
1876 * - the existing format & hook combo is so confusing it is hard for developers to change & inherently fragile
1877 * - passing to a hook right before save means calculations only have to be done once
1878 * - the existing pattern of passing dissimilar data to the same (merge) hook with a different 'type' is just
1881 * The use of the new hook is tested, including the fact it is called before contributions are merged, as this
1882 * is likely to be significant data in merge hooks.
1884 * @param int $mainId
1885 * @param int $otherId
1887 * @param array $migrationInfo
1888 * Migration info for the merge. This is passed to the hook as informational only.
1890 public static function mergeLocations($mainId, $otherId, $migrationInfo) {
1891 foreach ($migrationInfo as $key => $value) {
1892 $isLocationField = (substr($key, 0, 14) == 'move_location_' and $value != NULL);
1893 if (!$isLocationField) {
1896 $locField = explode('_', $key);
1897 $fieldName = $locField[2];
1898 $fieldCount = $locField[3];
1900 // Set up the operation type (add/overwrite)
1901 // Ignore operation for websites
1902 // @todo Tidy this up
1904 if ($fieldName != 'website') {
1905 $operation = CRM_Utils_Array
::value('operation', $migrationInfo['location_blocks'][$fieldName][$fieldCount]);
1907 // default operation is overwrite.
1911 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
1915 // @todo Handle OpenID (not currently in API).
1916 if (!empty($locBlocks)) {
1917 $locationBlocks = self
::getLocationBlockInfo();
1919 $primaryBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, ['is_primary' => 1]);
1920 $billingBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, ['is_billing' => 1]);
1922 foreach ($locBlocks as $name => $block) {
1923 $blocksDAO[$name] = ['delete' => [], 'update' => []];
1924 if (!is_array($block) || CRM_Utils_System
::isNull($block)) {
1927 $daoName = 'CRM_Core_DAO_' . $locationBlocks[$name]['label'];
1928 $changePrimary = FALSE;
1929 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ?
array_pop($primaryBlockIds[$name]) : NULL;
1930 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ?
array_pop($billingBlockIds[$name]) : NULL;
1932 foreach ($block as $blkCount => $values) {
1933 $otherBlockId = CRM_Utils_Array
::value('id', $migrationInfo['other_details']['location_blocks'][$name][$blkCount]);
1934 $mainBlockId = CRM_Utils_Array
::value('mainContactBlockId', $migrationInfo['location_blocks'][$name][$blkCount], 0);
1935 if (!$otherBlockId) {
1939 // For the block which belongs to other-contact, link the location block to main-contact
1940 $otherBlockDAO = new $daoName();
1941 $otherBlockDAO->contact_id
= $mainId;
1943 // Get the ID of this block on the 'other' contact, otherwise skip
1944 $otherBlockDAO->id
= $otherBlockId;
1946 // Add/update location and type information from the form, if applicable
1947 if ($locationBlocks[$name]['hasLocation']) {
1948 $locTypeId = CRM_Utils_Array
::value('locTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
1949 $otherBlockDAO->location_type_id
= $locTypeId;
1951 if ($locationBlocks[$name]['hasType']) {
1952 $typeTypeId = CRM_Utils_Array
::value('typeTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
1953 $otherBlockDAO->{$locationBlocks[$name]['hasType']} = $typeTypeId;
1956 // If we're deliberately setting this as primary then add the flag
1957 // and remove it from the current primary location (if there is one).
1958 // But only once for each entity.
1959 $set_primary = CRM_Utils_Array
::value('set_other_primary', $migrationInfo['location_blocks'][$name][$blkCount]);
1960 if (!$changePrimary && $set_primary == "1") {
1961 $otherBlockDAO->is_primary
= 1;
1962 if ($primaryDAOId) {
1963 $removePrimaryDAO = new $daoName();
1964 $removePrimaryDAO->id
= $primaryDAOId;
1965 $removePrimaryDAO->is_primary
= 0;
1966 $blocksDAO[$name]['update'][$primaryDAOId] = $removePrimaryDAO;
1968 $changePrimary = TRUE;
1970 // Otherwise, if main contact already has primary, set it to 0.
1971 elseif ($primaryDAOId) {
1972 $otherBlockDAO->is_primary
= 0;
1975 // If the main contact already has a billing location, set this to 0.
1976 if ($billingDAOId) {
1977 $otherBlockDAO->is_billing
= 0;
1980 $operation = CRM_Utils_Array
::value('operation', $values, 2);
1981 // overwrite - need to delete block which belongs to main-contact.
1982 if (!empty($mainBlockId) && ($operation == 2)) {
1983 $deleteDAO = new $daoName();
1984 $deleteDAO->id
= $mainBlockId;
1985 $deleteDAO->find(TRUE);
1987 // if we about to delete a primary / billing block, set the flags for new block
1988 // that we going to assign to main-contact
1989 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id
)) {
1990 $otherBlockDAO->is_primary
= 1;
1992 if ($billingDAOId && ($billingDAOId == $deleteDAO->id
)) {
1993 $otherBlockDAO->is_billing
= 1;
1995 $blocksDAO[$name]['delete'][$deleteDAO->id
] = $deleteDAO;
1997 $blocksDAO[$name]['update'][$otherBlockDAO->id
] = $otherBlockDAO;
2002 CRM_Utils_Hook
::alterLocationMergeData($blocksDAO, $mainId, $otherId, $migrationInfo);
2003 foreach ($blocksDAO as $blockDAOs) {
2004 if (!empty($blockDAOs['update'])) {
2005 foreach ($blockDAOs['update'] as $blockDAO) {
2009 if (!empty($blockDAOs['delete'])) {
2010 foreach ($blockDAOs['delete'] as $blockDAO) {
2011 $blockDAO->delete();
2018 * Dedupe a pair of contacts.
2020 * @param array $dupes
2021 * @param string $mode
2022 * @param bool $checkPermissions
2023 * @param string $cacheKeyString
2025 * @return bool|array
2026 * @throws \CRM_Core_Exception
2027 * @throws \CiviCRM_API3_Exception
2028 * @throws \API_Exception
2030 protected static function dedupePair($dupes, $mode = 'safe', $checkPermissions = TRUE, $cacheKeyString = NULL) {
2031 CRM_Utils_Hook
::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']);
2032 $mainId = $dupes['dstID'];
2033 $otherId = $dupes['srcID'];
2036 if (!$mainId ||
!$otherId) {
2040 $migrationInfo = [];
2042 // Try to lock the contacts before we load the data as we don't want it changing under us.
2043 // https://lab.civicrm.org/dev/core/issues/1355
2044 $locks = self
::getLocksOnContacts([$mainId, $otherId]);
2045 if (!CRM_Dedupe_Merger
::skipMerge($mainId, $otherId, $migrationInfo, $mode, $conflicts)) {
2046 CRM_Dedupe_Merger
::moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions);
2047 $resultStats['merged'][] = [
2048 'main_id' => $mainId,
2049 'other_id' => $otherId,
2053 $resultStats['skipped'][] = [
2054 'main_id' => $mainId,
2055 'other_id' => $otherId,
2059 // store any conflicts
2060 if (!empty($conflicts)) {
2061 CRM_Core_BAO_PrevNextCache
::markConflict($mainId, $otherId, $cacheKeyString, $conflicts, $mode);
2064 CRM_Core_BAO_PrevNextCache
::deletePair($mainId, $otherId, $cacheKeyString);
2066 self
::releaseLocks($locks);
2067 return $resultStats;
2071 * Replace the pseudo QFKey with zero if it is present.
2073 * @todo - on the slim chance this is still relevant it should be moved to the form layer.
2075 * Details about this bug are somewhat obscured by the move from svn but perhaps JIRA
2078 * @param array $migrationInfo
2080 protected static function swapOutFieldsAffectedByQFZeroBug(&$migrationInfo) {
2081 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
2082 foreach ($migrationInfo as $key => &$value) {
2083 if ($value == $qfZeroBug) {
2090 * Honestly - what DOES this do - hopefully some refactoring will reveal it's purpose.
2092 * Update this function formats fields in preparation for them to be submitted to the
2093 * 'ProfileContactCreate action. This is a lot of code to do this & for
2094 * - for some fields it fails - e.g Country - per testMergeCustomFields.
2096 * Goal is to move all custom field handling into 'move' functions on the various BAO
2097 * with an underlying DAO function. For custom fields it has been started on the BAO.
2106 * @throws \Exception
2108 protected static function processCustomFields($mainId, $key, $cFields, $submitted, $value) {
2109 if (substr($key, 0, 7) == 'custom_') {
2110 $fid = (int) substr($key, 7);
2111 if (empty($cFields[$fid])) {
2112 return [$cFields, $submitted];
2114 $htmlType = $cFields[$fid]['attributes']['html_type'];
2115 switch ($htmlType) {
2117 // Handled in CustomField->move(). Tested in testMergeCustomFields.
2118 unset($submitted["custom_$fid"]);
2121 case 'Select Country':
2122 // @todo Test in testMergeCustomFields disabled as this does not work, Handle in CustomField->move().
2123 case 'Select State/Province':
2124 $submitted[$key] = CRM_Core_BAO_CustomField
::displayValue($value, $fid);
2128 if ($cFields[$fid]['attributes']['is_view']) {
2129 $submitted[$key] = date('YmdHis', strtotime($submitted[$key]));
2134 case 'Multi-Select':
2135 case 'Multi-Select Country':
2136 case 'Multi-Select State/Province':
2137 // Merge values from both contacts for multivalue fields, CRM-4385
2138 // get the existing custom values from db.
2139 $customParams = ['entityID' => $mainId, $key => TRUE];
2140 $customfieldValues = CRM_Core_BAO_CustomValueTable
::getValues($customParams);
2141 if (!empty($customfieldValues[$key])) {
2142 $existingValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customfieldValues[$key]);
2143 if (is_array($existingValue) && !empty($existingValue)) {
2144 $mergeValue = $submittedCustomFields = [];
2145 if ($value == 'null') {
2146 // CRM-19074 if someone has deliberately chosen to overwrite with 'null', respect it.
2147 $submitted[$key] = $value;
2151 $submittedCustomFields = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2154 // CRM-19653: overwrite or add the existing custom field value with dupicate contact's
2155 // custom field value stored at $submittedCustomValue.
2156 foreach ($submittedCustomFields as $k => $v) {
2157 if ($v != '' && !in_array($v, $mergeValue)) {
2162 //keep state and country as array format.
2163 //for checkbox and m-select format w/ VALUE_SEPARATOR
2164 if (in_array($htmlType, [
2168 $submitted[$key] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2170 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
2173 $submitted[$key] = $mergeValue;
2178 elseif (in_array($htmlType, [
2179 'Multi-Select Country',
2180 'Multi-Select State/Province',
2182 //we require submitted values should be in array format
2184 $mergeValueArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2185 //hack to remove null values from array.
2187 foreach ($mergeValueArray as $k => $v) {
2192 $submitted[$key] = $mergeValue;
2201 return [$cFields, $submitted];
2205 * Get metadata for the custom fields for the merge.
2207 * @param string $contactType
2211 protected static function getCustomFieldMetadata($contactType) {
2213 if (!array_key_exists($contactType, $treeCache)) {
2214 $treeCache[$contactType] = CRM_Core_BAO_CustomGroup
::getTree(
2229 foreach ($treeCache[$contactType] as $key => $group) {
2230 if (!isset($group['fields'])) {
2233 foreach ($group['fields'] as $fid => $field) {
2234 $cFields[$fid]['attributes'] = $field;
2241 * Get conflicts for proposed merge pair.
2243 * @param array $migrationInfo
2244 * This is primarily to inform hooks. The can also modify it which feels
2245 * pretty fragile to do it here - but it is historical.
2246 * @param int $mainId
2247 * Main contact with whom merge has to happen.
2248 * @param int $otherId
2249 * Duplicate contact which would be deleted after merge operation.
2250 * @param string $mode
2251 * Helps decide how to behave when there are conflicts.
2252 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
2253 * - Does a force merge otherwise (aggressive mode).
2257 * @throws \CRM_Core_Exception
2258 * @throws \CiviCRM_API3_Exception
2260 public static function getConflicts(&$migrationInfo, $mainId, $otherId, $mode) {
2262 // Generate var $migrationInfo. The variable structure is exactly same as
2263 // $formValues submitted during a UI merge for a pair of contacts.
2264 $rowsElementsAndInfo = CRM_Dedupe_Merger
::getRowsElementsAndInfo($mainId, $otherId, FALSE);
2265 // add additional details that we might need to resolve conflicts
2266 $migrationInfo = $rowsElementsAndInfo['migration_info'];
2267 $migrationInfo['main_details'] = &$rowsElementsAndInfo['main_details'];
2268 $migrationInfo['other_details'] = &$rowsElementsAndInfo['other_details'];
2269 $migrationInfo['rows'] = &$rowsElementsAndInfo['rows'];
2270 // go ahead with merge if there is no conflict
2271 $originalMigrationInfo = $migrationInfo;
2272 foreach ($migrationInfo as $key => $val) {
2273 if ($val === "null") {
2274 // Rule: Never overwrite with an empty value (in any mode)
2275 unset($migrationInfo[$key]);
2278 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger
::getContactFields()) or
2279 substr($key, 0, 12) == 'move_custom_'
2282 // Rule: If both main-contact, and other-contact have a field with a
2283 // different value, then let $mode decide if to merge it or not
2285 (!empty($migrationInfo['rows'][$key]['main'])
2286 // For custom fields a 0 (e.g in an int field) could be a true conflict. This
2287 // is probably true for other fields too - e.g. 'do_not_email' but
2288 // leaving that investigation as a @todo - until tests can be written.
2289 // Note the handling of this has test coverage - although the data-typing
2290 // of '0' feels flakey we have insurance.
2291 ||
($migrationInfo['rows'][$key]['main'] === '0' && substr($key, 0, 12) == 'move_custom_')
2293 && $migrationInfo['rows'][$key]['main'] != $migrationInfo['rows'][$key]['other']
2296 // note it down & lets wait for response from the hook.
2297 // For no response $mode will decide if to skip this merge
2298 $conflicts[$key] = NULL;
2301 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
2302 $locField = explode('_', $key);
2303 $fieldName = $locField[2];
2304 $fieldCount = $locField[3];
2306 // Rule: Catch address conflicts (same address type on both contacts)
2308 isset($migrationInfo['main_details']['location_blocks'][$fieldName]) &&
2309 !empty($migrationInfo['main_details']['location_blocks'][$fieldName])
2312 // Load the address we're inspecting from the 'other' contact
2313 $addressRecord = $migrationInfo['other_details']['location_blocks'][$fieldName][$fieldCount];
2314 $addressRecordLocTypeId = CRM_Utils_Array
::value('location_type_id', $addressRecord);
2316 // If it exists on the 'main' contact already, skip it. Otherwise
2317 // if the location type exists already, log a conflict.
2318 foreach ($migrationInfo['main_details']['location_blocks'][$fieldName] as $mainAddressKey => $mainAddressRecord) {
2319 if (self
::locationIsSame($addressRecord, $mainAddressRecord)) {
2320 unset($migrationInfo[$key]);
2323 elseif ($addressRecordLocTypeId == $mainAddressRecord['location_type_id']) {
2324 $conflicts[$key] = NULL;
2330 // For other locations, don't merge/add if the values are the same
2331 elseif (CRM_Utils_Array
::value('main', $migrationInfo['rows'][$key]) == $migrationInfo['rows'][$key]['other']) {
2332 unset($migrationInfo[$key]);
2337 // A hook to implement other algorithms for choosing which contact to bias to when
2338 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
2339 // merge happens with new values filled in here. For a particular field / row not to be merged
2340 // field should be unset from fields_in_conflict.
2342 'old_migration_info' => $originalMigrationInfo,
2344 'fields_in_conflict' => $conflicts,
2345 'merge_mode' => $mode,
2346 'migration_info' => $migrationInfo,
2348 CRM_Utils_Hook
::merge('batch', $migrationData, $mainId, $otherId);
2349 $conflicts = $migrationData['fields_in_conflict'];
2350 // allow hook to override / manipulate migrationInfo as well
2351 $migrationInfo = $migrationData['migration_info'];
2352 foreach ($conflicts as $key => $val) {
2353 if ($val !== NULL ||
$mode !== 'safe') {
2354 // copy over the resolved values
2355 $migrationInfo[$key] = $val;
2356 unset($conflicts[$key]);
2359 return self
::formatConflictArray($conflicts, $migrationInfo['rows'], $migrationInfo['main_details']['location_blocks'], $migrationInfo['other_details']['location_blocks'], $mainId, $otherId);
2363 * @param array $conflicts
2364 * @param array $migrationInfo
2365 * @param $toKeepContactLocationBlocks
2366 * @param $toRemoveContactLocationBlocks
2368 * @param $toRemoveID
2371 * @throws \CRM_Core_Exception
2373 protected static function formatConflictArray($conflicts, $migrationInfo, $toKeepContactLocationBlocks, $toRemoveContactLocationBlocks, $toKeepID, $toRemoveID) {
2375 foreach (array_keys($conflicts) as $index) {
2376 if (substr($index, 0, 14) === 'move_location_') {
2377 $parts = explode('_', $index);
2378 $entity = $parts[2];
2379 $blockIndex = $parts[3];
2380 $locationTypeID = $toKeepContactLocationBlocks[$entity][$blockIndex]['location_type_id'];
2381 $entityConflicts = [
2382 'location_type_id' => $locationTypeID,
2383 'title' => $migrationInfo[$index]['title'],
2385 foreach ($toKeepContactLocationBlocks[$entity][$blockIndex] as $fieldName => $fieldValue) {
2386 if (in_array($fieldName, self
::ignoredFields())) {
2389 $toRemoveValue = CRM_Utils_Array
::value($fieldName, $toRemoveContactLocationBlocks[$entity][$blockIndex]);
2390 if ($fieldValue !== $toRemoveValue) {
2391 $entityConflicts[$fieldName] = [
2392 $toKeepID => $fieldValue,
2393 $toRemoveID => $toRemoveValue,
2397 $return[$entity][] = $entityConflicts;
2399 elseif (substr($index, 0, 5) === 'move_') {
2400 $contactFieldsToCompare[] = str_replace('move_', '', $index);
2401 $return['contact'][str_replace('move_', '', $index)] = [
2402 'title' => $migrationInfo[$index]['title'],
2403 $toKeepID => $migrationInfo[$index]['main'],
2404 $toRemoveID => $migrationInfo[$index]['other'],
2408 // Can't think of why this would be the case but perhaps it's ensuring it isn't as we
2410 throw new CRM_Core_Exception(ts('Unknown parameter') . $index);
2417 * Get any duplicate merge pairs that have been previously cached.
2419 * @param int $rule_group_id
2420 * @param int $group_id
2421 * @param int $batchLimit
2422 * @param bool $isSelected
2423 * @param bool $includeConflicts
2424 * @param array $criteria
2425 * @param int $checkPermissions
2426 * @param int $searchLimit
2430 protected static function getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, $includeConflicts, $criteria, $checkPermissions, $searchLimit = 0) {
2431 return CRM_Core_BAO_PrevNextCache
::retrieve(
2432 self
::getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit),
2433 self
::getJoinOnDedupeTable(),
2434 self
::getWhereString($isSelected),
2444 protected static function ignoredFields(): array {
2454 return $keysToIgnore;
2458 * Get the field value & label for the given field.
2464 * @throws \Exception
2466 private static function getFieldValueAndLabel($field, $contact): array {
2467 $fields = self
::getMergeFieldsMetadata();
2468 $value = $label = CRM_Utils_Array
::value($field, $contact);
2469 $fieldSpec = $fields[$field];
2470 if (!empty($fieldSpec['serialize']) && is_array($value)) {
2471 // In practice this only applies to preferred_communication_method as the sub types are skipped above
2472 // and no others are serialized.
2474 foreach ($value as $individualValue) {
2475 $labels[] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $field, $individualValue);
2477 $label = implode(', ', $labels);
2478 // We serialize this due to historic handling but it's likely that if we just left it as an
2479 // array all would be well & we would have less code.
2480 $value = CRM_Core_DAO
::serializeField($value, $fieldSpec['serialize']);
2482 elseif (!empty($fieldSpec['type']) && $fieldSpec['type'] == CRM_Utils_Type
::T_DATE
) {
2484 $value = str_replace('-', '', $value);
2485 $label = CRM_Utils_Date
::customFormat($label);
2491 elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type
::T_BOOLEAN
) {
2492 if ($label === '0') {
2495 if ($label === '1') {
2499 elseif (!empty($fieldSpec['pseudoconstant'])) {
2500 $label = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $field, $value);
2502 elseif ($field == 'current_employer_id' && !empty($value)) {
2503 $label = "$value (" . CRM_Contact_BAO_Contact
::displayName($value) . ")";
2505 return ['label' => $label, 'value' => $value];
2509 * Build up the location block for the contact in dedupe-screen display format.
2511 * @param integer $cid
2512 * @param array $blockInfo
2513 * @param string $blockName
2517 * @throws \CiviCRM_API3_Exception
2519 private static function buildLocationBlockForContact($cid, $blockInfo, $blockName): array {
2521 'contact_id' => $cid,
2522 // CRM-17556 Order by field-specific criteria
2524 'sort' => $blockInfo['sortString'],
2527 $locationBlock = [];
2528 $values = civicrm_api3($blockName, 'get', $searchParams);
2529 if ($values['count']) {
2531 foreach ($values['values'] as $value) {
2532 $locationBlock[$cnt] = $value;
2533 // Fix address display
2534 if ($blockName == 'address') {
2535 // For performance avoid geocoding while merging https://issues.civicrm.org/jira/browse/CRM-21786
2536 // we can expect existing geocode values to be retained.
2537 $value['skip_geocode'] = TRUE;
2538 CRM_Core_BAO_Address
::fixAddress($value);
2539 unset($value['skip_geocode']);
2540 $locationBlock[$cnt]['display'] = CRM_Utils_Address
::format($value);
2542 // Fix email display
2543 elseif ($blockName == 'email') {
2544 $locationBlock[$cnt]['display'] = CRM_Utils_Mail
::format($value);
2550 return $locationBlock;
2554 * Get a lock on the given contact.
2556 * The lock is like a gentleman's agreement between php & mysql. It is reserved at the
2557 * mysql level so it works across php processes but it doesn't actually lock the database.
2559 * Instead php can check the lock to see if it has been acquired before taking an action.
2561 * In this case we really don't want to attempt to dedupe contacts if another process is
2562 * trying to act on the specific contact as it could result in messy deadlocks & possibly data corruption.
2563 * In most databases this would be a rare event but if multiple dedupe processes are running
2564 * at once (for example) or there is also an import process in play there is potential for them to crash.
2565 * By throwing a specific error the calling process can catch it and determine it is worth trying again later without a lot of
2568 * As of writing no other processes DO grab contact locks but it would be reasonable to consider
2569 * grabbing them doing contact edits in general as well as imports etc.
2571 * @param array $contacts
2575 * @throws \CRM_Core_Exception
2576 * @throws \CRM_Core_Exception_ResourceConflictException
2578 protected static function getLocksOnContacts($contacts):array {
2580 if (!CRM_Utils_SQL
::supportsMultipleLocks()) {
2583 foreach ($contacts as $contactID) {
2584 $lock = Civi
::lockManager()->acquire("data.core.contact.{$contactID}");
2585 if ($lock->isAcquired()) {
2589 self
::releaseLocks($locks);
2590 throw new CRM_Core_Exception_ResourceConflictException(ts('Contact is in Use'), 'contact_lock');
2597 * Release contact locks so another process can alter them if it wants.
2599 * @param array $locks
2601 protected static function releaseLocks(array $locks) {
2602 foreach ($locks as $lock) {
2603 /* @var Civi\Core\Lock\LockInterface $lock */