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 // @todo - this user url stuff is only needed for the form layer - move to CRM_Contact_Form_Merge
37 if ($config->userSystem
->is_drupal
) {
38 $userRecordUrl = CRM_Utils_System
::url('user/%ufid');
39 $title = ts('%1 User: %2; user id: %3', [
40 1 => $config->userFramework
,
45 elseif ($config->userFramework
== 'Joomla') {
46 $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';
47 $title = ts('%1 User: %2; user id: %3', [
48 1 => $config->userFramework
,
55 'rel_table_contributions' => [
56 'title' => ts('Contributions'),
58 'civicrm_contribution',
59 'civicrm_contribution_recur',
60 'civicrm_contribution_soft',
62 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=contribute'),
64 'rel_table_contribution_page' => [
65 'title' => ts('Contribution Pages'),
66 'tables' => ['civicrm_contribution_page'],
67 'url' => CRM_Utils_System
::url('civicrm/admin/contribute', 'reset=1&cid=$cid'),
69 'rel_table_memberships' => [
70 'title' => ts('Memberships'),
73 'civicrm_membership_log',
74 'civicrm_membership_type',
76 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=member'),
78 'rel_table_participants' => [
79 'title' => ts('Participants'),
80 'tables' => ['civicrm_participant'],
81 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=participant'),
83 'rel_table_events' => [
84 'title' => ts('Events'),
85 'tables' => ['civicrm_event'],
86 'url' => CRM_Utils_System
::url('civicrm/event/manage', 'reset=1&cid=$cid'),
88 'rel_table_activities' => [
89 'title' => ts('Activities'),
90 'tables' => ['civicrm_activity', 'civicrm_activity_contact'],
91 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=activity'),
93 'rel_table_relationships' => [
94 'title' => ts('Relationships'),
95 'tables' => ['civicrm_relationship'],
96 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=rel'),
98 'rel_table_custom_groups' => [
99 'title' => ts('Custom Groups'),
100 'tables' => ['civicrm_custom_group'],
101 'url' => CRM_Utils_System
::url('civicrm/admin/custom/group', 'reset=1'),
103 'rel_table_uf_groups' => [
104 'title' => ts('Profiles'),
105 'tables' => ['civicrm_uf_group'],
106 'url' => CRM_Utils_System
::url('civicrm/admin/uf/group', 'reset=1'),
108 'rel_table_groups' => [
109 'title' => ts('Groups'),
110 'tables' => ['civicrm_group_contact'],
111 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=group'),
113 'rel_table_notes' => [
114 'title' => ts('Notes'),
115 'tables' => ['civicrm_note'],
116 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=note'),
118 'rel_table_tags' => [
119 'title' => ts('Tags'),
120 'tables' => ['civicrm_entity_tag'],
121 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=tag'),
123 'rel_table_mailings' => [
124 'title' => ts('Mailings'),
127 'civicrm_mailing_event_queue',
128 'civicrm_mailing_event_subscribe',
130 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=mailing'),
132 'rel_table_cases' => [
133 'title' => ts('Cases'),
134 'tables' => ['civicrm_case_contact'],
135 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=case'),
137 'rel_table_grants' => [
138 'title' => ts('Grants'),
139 'tables' => ['civicrm_grant'],
140 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=grant'),
143 'title' => ts('PCPs'),
144 'tables' => ['civicrm_pcp'],
145 'url' => CRM_Utils_System
::url('civicrm/contribute/pcp/manage', 'reset=1'),
147 'rel_table_pledges' => [
148 'title' => ts('Pledges'),
149 'tables' => ['civicrm_pledge', 'civicrm_pledge_payment'],
150 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=pledge'),
152 'rel_table_users' => [
154 'tables' => ['civicrm_uf_match'],
155 'url' => $userRecordUrl,
159 $relTables +
= self
::getMultiValueCustomSets('relTables');
161 // Allow hook_civicrm_merge() to adjust $relTables
162 CRM_Utils_Hook
::merge('relTables', $relTables);
164 // Cache the results in a static variable
165 Civi
::$statics[__CLASS__
]['relTables'] = $relTables;
168 return Civi
::$statics[__CLASS__
]['relTables'];
172 * Returns the related tables groups for which a contact has any info entered.
178 public static function getActiveRelTables($cid) {
182 $relTables = self
::relTables();
183 $cidRefs = self
::cidRefs();
184 $eidRefs = self
::eidRefs();
185 foreach ($relTables as $group => $params) {
187 foreach ($params['tables'] as $table) {
188 if (isset($cidRefs[$table])) {
189 foreach ($cidRefs[$table] as $field) {
190 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $field = $cid";
193 if (isset($eidRefs[$table])) {
194 foreach ($eidRefs[$table] as $entityTable => $entityId) {
195 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $entityId = $cid AND $entityTable = 'civicrm_contact'";
198 foreach ($sqls as $sql) {
199 if (CRM_Core_DAO
::singleValueQuery($sql) > 0) {
205 return array_unique($groups);
209 * Get array tables and fields that reference civicrm_contact.id.
211 * This function calls the merge hook and only exists to wrap the DAO function to support that deprecated call.
212 * The entityTypes hook is the recommended way to add tables to this result.
214 * I thought about adding another hook to alter tableReferences but decided it was unclear if there
215 * are use cases not covered by entityTables and instead we should wait & see.
217 public static function cidRefs() {
218 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['contact_references'])) {
219 return \Civi
::$statics[__CLASS__
]['contact_references'];
222 $contactReferences = $coreReferences = CRM_Core_DAO
::getReferencesToContactTable();
224 CRM_Utils_Hook
::merge('cidRefs', $contactReferences);
225 if ($contactReferences !== $coreReferences) {
227 ->warning("Deprecated hook ::merge in context of 'cidRefs. Use entityTypes instead.", ['civi.tag' => 'deprecated']);
229 \Civi
::$statics[__CLASS__
]['contact_references'] = $contactReferences;
230 return \Civi
::$statics[__CLASS__
]['contact_references'];
234 * Return tables and their fields referencing civicrm_contact.contact_id with entity_id
236 public static function eidRefs() {
239 // FIXME: this should be generated dynamically from the schema
240 // tables that reference contacts with entity_{id,table}
242 'civicrm_acl' => ['entity_table' => 'entity_id'],
243 'civicrm_acl_entity_role' => ['entity_table' => 'entity_id'],
244 'civicrm_entity_file' => ['entity_table' => 'entity_id'],
245 'civicrm_log' => ['entity_table' => 'entity_id'],
246 'civicrm_mailing_group' => ['entity_table' => 'entity_id'],
247 'civicrm_note' => ['entity_table' => 'entity_id'],
250 // Allow hook_civicrm_merge() to adjust $eidRefs
251 CRM_Utils_Hook
::merge('eidRefs', $eidRefs);
257 * Return tables using locations.
259 public static function locTables() {
262 $locTables = ['civicrm_email', 'civicrm_address', 'civicrm_phone'];
264 // Allow hook_civicrm_merge() to adjust $locTables
265 CRM_Utils_Hook
::merge('locTables', $locTables);
271 * We treat multi-valued custom sets as "related tables" similar to activities, contributions, etc.
272 * @param string $request
273 * 'relTables' or 'cidRefs'.
277 public static function getMultiValueCustomSets($request) {
279 if (!isset(Civi
::$statics[__CLASS__
]['multiValueCustomSets'])) {
284 $result = civicrm_api3('custom_group', 'get', [
294 'return' => ['id', 'title', 'table_name', 'style'],
296 foreach ($result['values'] as $custom) {
297 $data['cidRefs'][$custom['table_name']] = ['entity_id'];
298 $urlSuffix = $custom['style'] == 'Tab' ?
'&selectedChild=custom_' . $custom['id'] : '';
299 $data['relTables']['rel_table_custom_' . $custom['id']] = [
300 'title' => $custom['title'],
301 'tables' => [$custom['table_name']],
302 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid' . $urlSuffix),
306 // Store the result in a static variable cache
307 Civi
::$statics[__CLASS__
]['multiValueCustomSets'] = $data;
310 return Civi
::$statics[__CLASS__
]['multiValueCustomSets'][$request];
314 * Tables which require custom processing should declare functions to call here.
315 * Doing so will override normal processing.
317 public static function cpTables() {
321 'civicrm_case_contact' => ['CRM_Case_BAO_Case' => 'mergeContacts'],
322 'civicrm_group_contact' => ['CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'],
323 // Empty array == do nothing - this table is handled by mergeGroupContact
324 'civicrm_subscription_history' => [],
325 'civicrm_relationship' => ['CRM_Contact_BAO_Relationship' => 'mergeRelationships'],
326 'civicrm_membership' => ['CRM_Member_BAO_Membership' => 'mergeMemberships'],
333 * Return payment related table.
335 public static function paymentTables() {
338 $tables = ['civicrm_pledge', 'civicrm_membership', 'civicrm_participant'];
344 * Return payment update Query.
346 * @param string $tableName
347 * @param int $mainContactId
348 * @param int $otherContactId
352 public static function paymentSql($tableName, $mainContactId, $otherContactId) {
354 if (!$tableName ||
!$mainContactId ||
!$otherContactId) {
358 $paymentTables = self
::paymentTables();
359 if (!in_array($tableName, $paymentTables)) {
363 switch ($tableName) {
364 case 'civicrm_pledge':
366 UPDATE IGNORE civicrm_contribution contribution
367 INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id )
368 INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id )
369 SET contribution.contact_id = $mainContactId
370 WHERE pledge.contact_id = $otherContactId";
373 case 'civicrm_membership':
375 UPDATE IGNORE civicrm_contribution contribution
376 INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id )
377 INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id )
378 SET contribution.contact_id = $mainContactId
379 WHERE membership.contact_id = $otherContactId";
382 case 'civicrm_participant':
384 UPDATE IGNORE civicrm_contribution contribution
385 INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id )
386 INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id )
387 SET contribution.contact_id = $mainContactId
388 WHERE participant.contact_id = $otherContactId";
397 * @param int $otherId
398 * @param string $tableName
399 * @param array $tableOperations
400 * @param string $mode
404 public static function operationSql($mainId, $otherId, $tableName, $tableOperations = [], $mode = 'add') {
406 if (!$tableName ||
!$mainId ||
!$otherId) {
410 switch ($tableName) {
411 case 'civicrm_membership':
412 if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add']) {
415 if ($mode == 'add') {
417 DELETE membership1.* FROM civicrm_membership membership1
418 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
419 AND membership1.contact_id = {$mainId}
420 AND membership2.contact_id = {$otherId} ";
422 if ($mode == 'payment') {
424 DELETE contribution.* FROM civicrm_contribution contribution
425 INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id
426 INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id
427 AND membership1.contact_id = {$mainId}
428 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
429 AND membership2.contact_id = {$otherId}";
433 case 'civicrm_uf_match':
434 // normal queries won't work for uf_match since that will lead to violation of unique constraint,
435 // failing to meet intended result. Therefore we introduce this additional query:
436 $sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}";
444 * Based on the provided two contact_ids and a set of tables, remove the
445 * belongings of the other contact and of their relations.
447 * @param int $otherID
448 * @param bool $tables
450 public static function removeContactBelongings($otherID, $tables) {
451 // CRM-20421: Removing Inherited memberships when memberships of parent are not migrated to new contact.
452 if (in_array("civicrm_membership", $tables)) {
453 $membershipIDs = CRM_Utils_Array
::collect('id',
454 CRM_Utils_Array
::value('values',
455 civicrm_api3("Membership", "get", [
456 "contact_id" => $otherID,
462 if (!empty($membershipIDs)) {
463 civicrm_api3("Membership", "get", [
464 'owner_membership_id' => ['IN' => $membershipIDs],
465 'api.Membership.delete' => ['id' => '$value.id'],
472 * Based on the provided two contact_ids and a set of tables, move the
473 * belongings of the other contact to the main one.
476 * @param int $otherId
477 * @param bool $tables
478 * @param array $tableOperations
479 * @param array $customTableToCopyFrom
481 public static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = [], $customTableToCopyFrom = NULL) {
482 $cidRefs = self
::cidRefs();
483 $eidRefs = self
::eidRefs();
484 $cpTables = self
::cpTables();
485 $paymentTables = self
::paymentTables();
487 // getting all custom tables
489 if ($customTableToCopyFrom !== NULL) {
490 // @todo this duplicates cidRefs?
491 CRM_Core_DAO
::appendCustomTablesExtendingContacts($customTables);
492 CRM_Core_DAO
::appendCustomContactReferenceFields($customTables);
493 $customTables = array_keys($customTables);
496 $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
498 // if there aren't any specific tables, don't affect the ones handled by relTables()
499 // also don't affect tables in locTables() CRM-15658
500 $relTables = self
::relTables();
501 $handled = self
::locTables();
503 foreach ($relTables as $params) {
504 $handled = array_merge($handled, $params['tables']);
506 $affected = array_diff($affected, $handled);
507 $affected = array_unique(array_merge($affected, $tables));
509 $mainId = (int) $mainId;
510 $otherId = (int) $otherId;
511 $multi_value_tables = array_keys(CRM_Dedupe_Merger
::getMultiValueCustomSets('cidRefs'));
514 foreach ($affected as $table) {
515 // skipping non selected single-value custom table's value migration
516 if (!in_array($table, $multi_value_tables)) {
517 if ($customTableToCopyFrom !== NULL && in_array($table, $customTables) && !in_array($table, $customTableToCopyFrom)) {
518 if (isset($cidRefs[$table]) && ($delCol = array_search('entity_id', $cidRefs[$table])) !== FALSE) {
519 // remove entity_id from the field list
520 unset($cidRefs[$table][$delCol]);
525 // Call custom processing function for objects that require it
526 if (isset($cpTables[$table])) {
527 foreach ($cpTables[$table] as $className => $fnName) {
528 $className::$fnName($mainId, $otherId, $sqls, $tables, $tableOperations);
530 // Skip normal processing
534 // use UPDATE IGNORE + DELETE query pair to skip on situations when
535 // there's a UNIQUE restriction on ($field, some_other_field) pair
536 if (isset($cidRefs[$table])) {
537 foreach ($cidRefs[$table] as $field) {
538 // carry related contributions CRM-5359
539 if (in_array($table, $paymentTables)) {
540 $paymentSqls = self
::paymentSql($table, $mainId, $otherId);
541 $sqls = array_merge($sqls, $paymentSqls);
543 if (!empty($tables) && !in_array('civicrm_contribution', $tables)) {
544 $payOprSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations, 'payment');
545 $sqls = array_merge($sqls, $payOprSqls);
549 $preOperationSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations);
550 $sqls = array_merge($sqls, $preOperationSqls);
552 if ($customTableToCopyFrom !== NULL && in_array($table, $customTableToCopyFrom) && !self
::customRecordExists($mainId, $table, $field) && $field == 'entity_id') {
553 // this is the entity_id column of a custom field group where:
554 // - the custom table should be copied as indicated by $customTableToCopyFrom
555 // e.g. because a field in the group was selected in a form
556 // - AND no record exists yet for the $mainId contact
557 // we only do this for column "entity_id" as we wouldn't want to
558 // run this INSERT for ContactReference fields
559 $sqls[] = "INSERT INTO $table ($field) VALUES ($mainId)";
561 $sqls[] = "UPDATE IGNORE $table SET $field = $mainId WHERE $field = $otherId";
562 $sqls[] = "DELETE FROM $table WHERE $field = $otherId";
566 if (isset($eidRefs[$table])) {
567 foreach ($eidRefs[$table] as $entityTable => $entityId) {
568 $sqls[] = "UPDATE IGNORE $table SET $entityId = $mainId WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
569 $sqls[] = "DELETE FROM $table WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
574 // Allow hook_civicrm_merge() to add SQL statements for the merge operation.
575 CRM_Utils_Hook
::merge('sqls', $sqls, $mainId, $otherId, $tables);
577 foreach ($sqls as $sql) {
578 CRM_Core_DAO
::executeQuery($sql, [], TRUE, NULL, TRUE);
580 CRM_Dedupe_Merger
::addMembershipToRealtedContacts($mainId);
584 * Given a contact ID, will check if a record exists in given table.
589 * Field where the contact's ID is stored in the table
592 * True if a record is found for the given contact ID, false otherwise
594 private static function customRecordExists($contactID, $table, $idField) {
596 SELECT COUNT(*) AS count
598 WHERE $idField = $contactID
600 $dbResult = CRM_Core_DAO
::executeQuery($sql);
603 if ($dbResult->count
> 0) {
611 * Load all non-empty fields for the contacts
615 * @param array $other
620 public static function retrieveFields($main, $other) {
625 foreach (self
::getContactFields() as $validField) {
626 // CRM-17556 Get all non-empty fields, to make comparison easier
627 if (!empty($main[$validField]) ||
!empty($other[$validField])) {
628 $result['contact'][] = $validField;
632 $mainEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($main['id']);
633 $otherEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($other['id']);
634 $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
635 foreach ($keys as $key) {
636 // Exclude multi-value fields CRM-13836
637 if (strpos($key, '_')) {
640 $key1 = CRM_Utils_Array
::value($key, $mainEvs);
641 $key2 = CRM_Utils_Array
::value($key, $otherEvs);
642 // We wish to retain '0' as it has a different meaning than NULL on a checkbox.
643 // However I can't think of a case where an empty string is more meaningful than null
644 // or where it would be FALSE or something else nullish.
645 $valuesToIgnore = [NULL, '', []];
646 if (!in_array($key1, $valuesToIgnore, TRUE) ||
!in_array($key2, $valuesToIgnore, TRUE)) {
647 $result['custom'][] = $key;
654 * Batch merge a set of contacts based on rule-group and group.
660 * @param string $mode
661 * Helps decide how to behave when there are conflicts.
662 * A 'safe' value skips the merge if there are any un-resolved conflicts, wheras 'aggressive'
663 * mode does a force merge.
664 * @param int $batchLimit number of merges to carry out in one batch.
665 * @param int $isSelected if records with is_selected column needs to be processed.
666 * Note the option of '2' is only used in conjunction with $redirectForPerformance
667 * to determine when to reload the cache (!). The use of anything other than a boolean is being grandfathered
668 * out in favour of explicitly passing in $reloadCacheIfEmpty
670 * @param array $criteria
671 * Criteria to use in the filter.
673 * @param bool $checkPermissions
674 * Respect logged in user permissions.
675 * @param bool|NULL $reloadCacheIfEmpty
676 * If not set explicitly this is calculated but it is preferred that it be set
677 * per comments on isSelected above.
679 * @param int $searchLimit
680 * Limit on number of contacts to search for duplicates for.
681 * This means that if the limit is 1000 then only duplicates for the first 1000 contacts
682 * matching criteria will be found and batchMerged (the number of merges could be less than or greater than 100)
686 * @throws \CRM_Core_Exception
687 * @throws \CiviCRM_API3_Exception
689 public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $batchLimit = 1, $isSelected = 2, $criteria = [], $checkPermissions = TRUE, $reloadCacheIfEmpty = NULL, $searchLimit = 0) {
690 $redirectForPerformance = ($batchLimit > 1) ?
TRUE : FALSE;
691 if ($mode === 'aggressive' && $checkPermissions && !CRM_Core_Permission
::check('force merge duplicate contacts')) {
692 throw new CRM_Core_Exception(ts('Insufficient permissions for aggressive mode batch merge'));
694 if (!isset($reloadCacheIfEmpty)) {
695 $reloadCacheIfEmpty = (!$redirectForPerformance && $isSelected == 2);
697 if ($isSelected !== 0 && $isSelected !== 1) {
698 // explicitly set to NULL if not 1 or 0 as part of grandfathering out the mystical '2' value.
701 $dupePairs = self
::getDuplicatePairs($rgid, $gid, $reloadCacheIfEmpty, $batchLimit, $isSelected, ($mode == 'aggressive'), $criteria, $checkPermissions, $searchLimit);
704 'cache_key_string' => self
::getMergeCacheKeyString($rgid, $gid, $criteria, $checkPermissions, $searchLimit),
705 // @todo stop passing these parameters in & instead calculate them in the merge function based
706 // on the 'real' params like $isRespectExclusions $batchLimit and $isSelected.
707 'join' => self
::getJoinOnDedupeTable(),
708 'where' => self
::getWhereString($isSelected),
709 'limit' => (int) $batchLimit,
711 return CRM_Dedupe_Merger
::merge($dupePairs, $cacheParams, $mode, $redirectForPerformance, $checkPermissions);
715 * Get the string to join the prevnext cache to the dedupe table.
718 * The join string to join prevnext cache on the dedupe table.
720 public static function getJoinOnDedupeTable() {
722 LEFT JOIN civicrm_dedupe_exception de
724 pn.entity_id1 = de.contact_id1
725 AND pn.entity_id2 = de.contact_id2 )
730 * Get where string for dedupe join.
732 * @param bool $isSelected
736 protected static function getWhereString($isSelected) {
737 $where = "de.id IS NULL";
738 if ($isSelected === 0 ||
$isSelected === 1) {
739 $where .= " AND pn.is_selected = {$isSelected}";
745 * Update the statistics for the merge set.
747 * @param string $cacheKeyString
748 * @param array $result
750 public static function updateMergeStats($cacheKeyString, $result = []) {
751 // gather latest stats
752 $merged = count($result['merged']);
753 $skipped = count($result['skipped']);
755 if ($merged <= 0 && $skipped <= 0) {
759 // get previous stats
760 $previousStats = CRM_Dedupe_Merger
::getMergeStats($cacheKeyString);
761 if (!empty($previousStats)) {
762 if ($previousStats['merged']) {
763 $merged = $merged +
$previousStats['merged'];
765 if ($previousStats['skipped']) {
766 $skipped = $skipped +
$previousStats['skipped'];
771 CRM_Dedupe_Merger
::resetMergeStats($cacheKeyString);
773 // store the updated stats
775 'merged' => (int) $merged,
776 'skipped' => (int) $skipped,
778 $data = serialize($data);
780 CRM_Core_DAO
::executeQuery("INSERT INTO civicrm_prevnext_cache (entity_table, entity_id1, entity_id2, cacheKey, data) VALUES
781 ('civicrm_contact', 0, 0, %1, '{$data}')", [1 => [$cacheKeyString . '_stats', 'String']]);
785 * Delete information about merges for the given string.
787 * @param $cacheKeyString
789 public static function resetMergeStats($cacheKeyString) {
790 CRM_Core_BAO_PrevNextCache
::deleteItem(NULL, "{$cacheKeyString}_stats");
794 * Get merge outcome statistics.
796 * @param string $cacheKeyString
799 * Array of how many were merged and how many were skipped.
801 * @throws \CiviCRM_API3_Exception
803 public static function getMergeStats($cacheKeyString) {
804 $stats = civicrm_api3('Dedupe', 'get', ['cachekey' => "{$cacheKeyString}_stats", 'sequential' => 1])['values'];
805 if (!empty($stats)) {
806 return $stats[0]['data'];
812 * Get merge statistics message.
814 * @param array $stats
818 public static function getMergeStatsMsg($stats) {
820 if (!empty($stats['merged'])) {
821 $msg = '<p>' . ts('One contact merged.', [
822 'count' => $stats['merged'],
823 'plural' => '%count contacts merged.',
826 if (!empty($stats['skipped'])) {
827 $msg .= '<p>' . ts('One contact was skipped.', [
828 'count' => $stats['skipped'],
829 'plural' => '%count contacts were skipped.',
836 * Merge given set of contacts. Performs core operation.
838 * @param array $dupePairs
839 * Set of pair of contacts for whom merge is to be done.
840 * @param array $cacheParams
841 * Prev-next-cache params based on which next pair of contacts are computed.
842 * Generally used with batch-merge.
843 * @param string $mode
844 * Helps decide how to behave when there are conflicts.
845 * A 'safe' value skips the merge if there are any un-resolved conflicts.
846 * Does a force merge otherwise (aggressive mode).
848 * @param bool $redirectForPerformance
849 * Redirect to a url for batch processing.
851 * @param bool $checkPermissions
852 * Respect logged in user permissions.
856 * @throws \API_Exception
857 * @throws \CRM_Core_Exception
858 * @throws \CiviCRM_API3_Exception
860 public static function merge($dupePairs = [], $cacheParams = [], $mode = 'safe',
861 $redirectForPerformance = FALSE, $checkPermissions = TRUE
863 $cacheKeyString = CRM_Utils_Array
::value('cache_key_string', $cacheParams);
864 $resultStats = ['merged' => [], 'skipped' => []];
866 // we don't want dupe caching to get reset after every-merge, and therefore set the
867 CRM_Core_Config
::setPermitCacheFlushMode(FALSE);
868 $deletedContacts = [];
870 while (!empty($dupePairs)) {
871 foreach ($dupePairs as $index => $dupes) {
872 if (in_array($dupes['dstID'], $deletedContacts) ||
in_array($dupes['srcID'], $deletedContacts)) {
873 unset($dupePairs[$index]);
876 if (($result = self
::dedupePair($dupes, $mode, $checkPermissions, $cacheKeyString)) === FALSE) {
877 unset($dupePairs[$index]);
880 if (!empty($result['merged'])) {
881 $deletedContacts[] = $result['merged'][0]['other_id'];
882 $resultStats['merged'][] = ($result['merged'][0]);
885 $resultStats['skipped'][] = ($result['skipped'][0]);
889 if ($cacheKeyString && !$redirectForPerformance) {
890 // retrieve next pair of dupes
891 // @todo call getDuplicatePairs.
892 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString,
893 $cacheParams['join'],
894 $cacheParams['where'],
896 $cacheParams['limit'],
903 // do not proceed. Terminate the loop
908 CRM_Dedupe_Merger
::updateMergeStats($cacheKeyString, $resultStats);
913 * A function which uses various rules / algorithms for choosing which contact to bias to
914 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
917 * Main contact with whom merge has to happen.
918 * @param int $otherId
919 * Duplicate contact which would be deleted after merge operation.
920 * @param array $migrationInfo
921 * Array of information about which elements to merge.
922 * @param string $mode
923 * Helps decide how to behave when there are conflicts.
924 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
925 * - Does a force merge otherwise (aggressive mode).
927 * @param array $conflicts
928 * An empty array to be filed with conflict information.
932 * @throws \CRM_Core_Exception
933 * @throws \CiviCRM_API3_Exception
934 * @throws \API_Exception
936 public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe', &$conflicts = []) {
938 $conflicts = self
::getConflicts($migrationInfo, $mainId, $otherId, $mode)['conflicts'];
939 // A hook could have set skip_merge in order to alter merge behaviour.
940 // This is a something we might ideally deprecate since they really 'should'
941 // mess with the conflicts array instead.
942 return (bool) ($migrationData['skip_merge'] ??
!empty($conflicts));
946 * Compare 2 addresses to see if they are the same.
948 * @param array $mainAddress
949 * @param array $comparisonAddress
953 public static function locationIsSame($mainAddress, $comparisonAddress) {
954 $keysToIgnore = self
::ignoredFields();
955 foreach ($comparisonAddress as $field => $value) {
956 if (in_array($field, $keysToIgnore)) {
959 if ((!empty($value) ||
$value === '0') && isset($mainAddress[$field]) && $mainAddress[$field] != $value) {
967 * A function to build an array of information about location blocks that is
968 * required when merging location fields
972 public static function getLocationBlockInfo() {
975 'label' => 'Address',
976 'displayField' => 'display',
977 'sortString' => 'location_type_id',
978 'hasLocation' => TRUE,
983 'displayField' => 'display',
984 'sortString' => 'location_type_id',
985 'hasLocation' => TRUE,
990 'displayField' => 'name',
991 'sortString' => 'location_type_id,provider_id',
992 'hasLocation' => TRUE,
993 'hasType' => 'provider_id',
997 'displayField' => 'phone',
998 'sortString' => 'location_type_id,phone_type_id',
999 'hasLocation' => TRUE,
1000 'hasType' => 'phone_type_id',
1003 'label' => 'Website',
1004 'displayField' => 'url',
1005 'sortString' => 'website_type_id',
1006 'hasLocation' => FALSE,
1007 'hasType' => 'website_type_id',
1010 return $locationBlocks;
1014 * A function to build an array of information required by merge function and the merge UI.
1016 * @param int $mainId
1017 * Main contact with whom merge has to happen.
1018 * @param int $otherId
1019 * Duplicate contact which would be deleted after merge operation.
1020 * @param bool $checkPermissions
1021 * Should the logged in user's permissions be ignore. Setting this to false is
1022 * highly risky as it could cause data to be lost due to conflicts not showing up.
1023 * OTOH there is a risk a merger might view custom data they do not have permission to.
1024 * Hence for now only making this really explicit and making it reflect perms in
1027 * @todo review permissions issue!
1029 * @return array|bool|int
1031 * rows => An array of arrays, each is row of merge information for the table
1032 * Format: move_fieldname, eg: move_contact_type
1033 * main => Value associated with the main contact
1034 * other => Value associated with the other contact
1035 * title => The title of the field to display in the merge table
1037 * elements => An array of form elements for the merge UI
1039 * rel_table_elements => An array of form elements for the merge UI for
1040 * entities related to the contact (eg: checkbox to move 'mailings')
1042 * rel_tables => Stores the tables that have related entities for the contact
1043 * for example mailings, groups
1045 * main_details => An array of core contact field values, eg: first_name, etc.
1046 * location_blocks => An array of location block data for the main contact
1047 * stored as the 'result' of an API call.
1048 * eg: main_details['location_blocks']['address'][0]['id']
1049 * eg: main_details['location_blocks']['email'][1]['id']
1051 * other_details => As above, but for the 'other' contact
1053 * migration_info => Stores the 'default' merge actions for each field which
1054 * is used when programatically merging contacts. It contains instructions
1055 * to move all fields from the 'other' contact to the 'main' contact, as
1056 * though the form had been submitted with those options.
1058 * @throws \CRM_Core_Exception
1059 * @throws \CiviCRM_API3_Exception
1060 * @throws \Exception
1062 public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissions = TRUE) {
1063 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1064 $fields = self
::getMergeFieldsMetadata();
1066 $main = self
::getMergeContactDetails($mainId);
1067 $other = self
::getMergeContactDetails($otherId);
1069 $compareFields = self
::retrieveFields($main, $other);
1071 $rows = $elements = $relTableElements = $migrationInfo = [];
1073 foreach ($compareFields['contact'] as $field) {
1074 if ($field == 'contact_sub_type') {
1075 // CRM-15681 don't display sub-types in UI
1078 $rows["move_$field"] = [
1079 'main' => self
::getFieldValueAndLabel($field, $main)['label'],
1080 'other' => self
::getFieldValueAndLabel($field, $other)['label'],
1081 'title' => $fields[$field]['title'],
1084 $value = self
::getFieldValueAndLabel($field, $other)['value'];
1086 if ($value === NULL ||
$value == '') {
1089 if ($value === 0 or $value === '0') {
1090 $value = $qfZeroBug;
1092 if (is_array($value) && empty($value[1])) {
1096 // Display a checkbox to migrate, only if the values are different
1097 if ($value != $main[$field]) {
1105 'is_checked' => (!isset($main[$field]) ||
$main[$field] === ''),
1109 $migrationInfo["move_$field"] = $value;
1112 // Handle location blocks.
1113 // @todo OpenID not in API yet, so is not supported here.
1115 // Set up useful information about the location blocks
1116 $locationBlocks = self
::getLocationBlockInfo();
1118 $locations = ['main' => [], 'other' => []];
1120 foreach ($locationBlocks as $blockName => $blockInfo) {
1121 list($locations, $rows, $elements, $migrationInfo) = self
::addLocationFieldInfo($mainId, $otherId, $blockInfo, $blockName, $locations, $rows, $elements, $migrationInfo);
1122 } // End loop through each location block entity
1124 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1125 $mergeHandler = new CRM_Dedupe_MergeHandler((int) $mainId, (int) $otherId);
1126 $relTables = $mergeHandler->getTablesRelatedToTheMergePair();
1127 foreach ($relTables as $name => $null) {
1128 $relTableElements[] = ['checkbox', "move_$name"];
1129 $migrationInfo["move_$name"] = 1;
1131 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1132 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1133 if ($name === 'rel_table_users') {
1134 // @todo - this user url stuff is only needed for the form layer - move to CRM_Contact_Form_Merge
1135 $relTables[$name]['main_url'] = str_replace('%ufid', CRM_Core_BAO_UFMatch
::getUFId($otherId), $relTables[$name]['url']);
1136 $relTables[$name]['other_url'] = str_replace('%ufid', CRM_Core_BAO_UFMatch
::getUFId($otherId), $relTables[$name]['url']);
1138 if ($name == 'rel_table_memberships') {
1139 //Enable 'add new' checkbox if main contact does not contain any membership similar to duplicate contact.
1140 $attributes = ['checked' => 'checked'];
1141 $otherContactMemberships = CRM_Member_BAO_Membership
::getAllContactMembership($otherId);
1142 foreach ($otherContactMemberships as $membership) {
1143 $mainMembership = CRM_Member_BAO_Membership
::getContactMembership($mainId, $membership['membership_type_id'], FALSE);
1144 if ($mainMembership) {
1150 "operation[move_{$name}][add]",
1155 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1158 foreach ($relTables as $name => $null) {
1159 $relTables["move_$name"] = $relTables[$name];
1160 unset($relTables[$name]);
1163 // handle custom fields
1164 $mainTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], NULL, $mainId, -1,
1165 CRM_Utils_Array
::value('contact_sub_type', $main), NULL, TRUE, NULL, TRUE, $checkPermissions
1167 $otherTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], NULL, $otherId, -1,
1168 CRM_Utils_Array
::value('contact_sub_type', $other), NULL, TRUE, NULL, TRUE, $checkPermissions
1171 foreach ($otherTree as $gid => $group) {
1172 if (!isset($group['fields'])) {
1176 foreach ($group['fields'] as $fid => $field) {
1177 $mainContactValue = $mainTree[$gid]['fields'][$fid]['customValue'] ??
NULL;
1178 $otherContactValue = $otherTree[$gid]['fields'][$fid]['customValue'] ??
NULL;
1179 if (in_array($fid, $compareFields['custom'])) {
1180 $rows["custom_group_$gid"]['title'] = $rows["custom_group_$gid"]['title'] ??
$group['title'];
1182 if ($mainContactValue) {
1183 foreach ($mainContactValue as $valueId => $values) {
1184 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomField
::displayValue($values['data'], $fid);
1188 if ($otherContactValue) {
1189 foreach ($otherContactValue as $valueId => $values) {
1190 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomField
::displayValue($values['data'], $fid);
1191 if ($values['data'] === 0 ||
$values['data'] === '0') {
1192 $values['data'] = $qfZeroBug;
1194 $value = ($values['data']) ?
$values['data'] : $value;
1197 $rows["move_custom_$fid"]['title'] = $field['label'];
1201 1 => "move_custom_$fid",
1206 'is_checked' => (!isset($rows["move_custom_$fid"]['main']) ||
$rows["move_custom_$fid"]['main'] === ''),
1208 $migrationInfo["move_custom_$fid"] = $value;
1215 'elements' => $elements,
1216 'rel_table_elements' => $relTableElements,
1217 'rel_tables' => $relTables,
1218 'main_details' => $main,
1219 'other_details' => $other,
1220 'migration_info' => $migrationInfo,
1223 $result['main_details']['location_blocks'] = $locations['main'];
1224 $result['other_details']['location_blocks'] = $locations['other'];
1230 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1231 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1232 * A superset of moveContactBelongings() function.
1234 * @param int $mainId
1235 * Main contact with whom merge has to happen.
1236 * @param int $otherId
1237 * Duplicate contact which would be deleted after merge operation.
1239 * @param array $migrationInfo
1241 * @param bool $checkPermissions
1242 * Respect logged in user permissions.
1245 * @throws \CiviCRM_API3_Exception
1247 public static function moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions = TRUE) {
1248 if (empty($migrationInfo)) {
1251 // Encapsulate in a transaction to avoid half-merges.
1252 $transaction = new CRM_Core_Transaction();
1254 $contactType = $migrationInfo['main_details']['contact_type'];
1255 $relTables = CRM_Dedupe_Merger
::relTables();
1256 $submittedCustomFields = $moveTables = $tableOperations = $removeTables = [];
1258 self
::swapOutFieldsAffectedByQFZeroBug($migrationInfo);
1259 foreach ($migrationInfo as $key => $value) {
1261 if (substr($key, 0, 12) == 'move_custom_' && $value != NULL) {
1262 $submitted[substr($key, 5)] = $value;
1263 $submittedCustomFields[] = substr($key, 12);
1265 elseif (in_array(substr($key, 5), CRM_Dedupe_Merger
::getContactFields()) && $value != NULL) {
1266 $submitted[substr($key, 5)] = $value;
1268 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1269 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1270 if (array_key_exists('operation', $migrationInfo)) {
1271 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1272 if (array_key_exists($key, $migrationInfo['operation'])) {
1273 $tableOperations[$table] = $migrationInfo['operation'][$key];
1278 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '0') {
1279 $removeTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1282 self
::mergeLocations($mainId, $otherId, $migrationInfo);
1284 // **** Do contact related migrations
1285 $customTablesToCopyValues = self
::getAffectedCustomTables($submittedCustomFields);
1286 // @todo - move all custom field processing to the move class & eventually have an
1287 // overridable DAO class for it.
1288 $customFieldBAO = new CRM_Core_BAO_CustomField();
1289 $customFieldBAO->move($otherId, $mainId, $submittedCustomFields);
1290 CRM_Dedupe_Merger
::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations, $customTablesToCopyValues);
1291 unset($moveTables, $tableOperations);
1293 // **** Do table related removals
1294 if (!empty($removeTables)) {
1296 CRM_Dedupe_Merger
::removeContactBelongings($otherId, $removeTables);
1300 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
1301 $names['gender'] = ['newName' => 'gender_id', 'groupName' => 'gender'];
1302 $names['individual_prefix'] = [
1303 'newName' => 'prefix_id',
1304 'groupName' => 'individual_prefix',
1306 $names['individual_suffix'] = [
1307 'newName' => 'suffix_id',
1308 'groupName' => 'individual_suffix',
1310 $names['communication_style'] = [
1311 'newName' => 'communication_style_id',
1312 'groupName' => 'communication_style',
1314 $names['addressee'] = [
1315 'newName' => 'addressee_id',
1316 'groupName' => 'addressee',
1318 $names['email_greeting'] = [
1319 'newName' => 'email_greeting_id',
1320 'groupName' => 'email_greeting',
1322 $names['postal_greeting'] = [
1323 'newName' => 'postal_greeting_id',
1324 'groupName' => 'postal_greeting',
1326 CRM_Core_OptionGroup
::lookupValues($submitted, $names, TRUE);
1327 // fix custom fields so they're edible by createProfileContact()
1328 $cFields = self
::getCustomFieldMetadata($contactType);
1330 if (!isset($submitted)) {
1333 foreach ($submitted as $key => $value) {
1334 list($cFields, $submitted) = self
::processCustomFields($mainId, $key, $cFields, $submitted, $value);
1337 // move view only custom fields CRM-5362
1338 $viewOnlyCustomFields = [];
1339 foreach ($submitted as $key => $value) {
1340 $fid = CRM_Core_BAO_CustomField
::getKeyID($key);
1341 if ($fid && array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])
1343 $viewOnlyCustomFields[$key] = $value;
1346 // special case to set values for view only, CRM-5362
1347 if (!empty($viewOnlyCustomFields)) {
1348 $viewOnlyCustomFields['entityID'] = $mainId;
1349 CRM_Core_BAO_CustomValueTable
::setValues($viewOnlyCustomFields);
1352 // dev/core#996 Ensure that the earliest created date is stored against the kept contact id
1353 $mainCreatedDate = civicrm_api3('Contact', 'getsingle', [
1355 'return' => ['created_date'],
1357 $otherCreatedDate = civicrm_api3('Contact', 'getsingle', [
1359 'return' => ['created_date'],
1361 if ($otherCreatedDate < $mainCreatedDate && !empty($otherCreatedDate)) {
1362 CRM_Core_DAO
::executeQuery("UPDATE civicrm_contact SET created_date = %1 WHERE id = %2", [
1363 1 => [$otherCreatedDate, 'String'],
1364 2 => [$mainId, 'Positive'],
1368 if (!$checkPermissions ||
(CRM_Core_Permission
::check('merge duplicate contacts') &&
1369 CRM_Core_Permission
::check('delete contacts'))
1371 // if ext id is submitted then set it null for contact to be deleted
1372 if (!empty($submitted['external_identifier'])) {
1373 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1374 CRM_Core_DAO
::executeQuery($query);
1376 civicrm_api3('contact', 'delete', ['id' => $otherId]);
1379 // CRM-15681 merge sub_types
1380 if ($other_sub_types = CRM_Utils_Array
::value('contact_sub_type', $migrationInfo['other_details'])) {
1381 if ($main_sub_types = CRM_Utils_Array
::value('contact_sub_type', $migrationInfo['main_details'])) {
1382 $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types));
1385 $submitted['contact_sub_type'] = $other_sub_types;
1389 // **** Update contact related info for the main contact
1390 if (!empty($submitted)) {
1391 $submitted['contact_id'] = $mainId;
1393 //update current employer field
1394 if ($currentEmloyerId = CRM_Utils_Array
::value('current_employer_id', $submitted)) {
1395 if (!CRM_Utils_System
::isNull($currentEmloyerId)) {
1396 $submitted['current_employer'] = $submitted['current_employer_id'];
1399 $submitted['current_employer'] = '';
1401 unset($submitted['current_employer_id']);
1404 //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
1405 if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) {
1406 $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
1408 if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) {
1409 $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
1412 CRM_Contact_BAO_Contact
::createProfileContact($submitted, $null, $mainId);
1414 $transaction->commit();
1415 CRM_Utils_Hook
::post('merge', 'Contact', $mainId);
1416 self
::createMergeActivities($mainId, $otherId);
1422 * Builds an Array of Custom tables for given custom field ID's.
1424 * @param $customFieldIDs
1427 * Array of custom table names
1429 private static function getAffectedCustomTables($customFieldIDs) {
1430 $customTableToCopyValues = [];
1432 foreach ($customFieldIDs as $fieldID) {
1433 if (!empty($fieldID)) {
1434 $customField = civicrm_api3('custom_field', 'getsingle', [
1436 'is_active' => TRUE,
1438 if (!civicrm_error($customField) && !empty($customField['custom_group_id'])) {
1439 $customGroup = civicrm_api3('custom_group', 'getsingle', [
1440 'id' => $customField['custom_group_id'],
1441 'is_active' => TRUE,
1444 if (!civicrm_error($customGroup) && !empty($customGroup['table_name'])) {
1445 $customTableToCopyValues[] = $customGroup['table_name'];
1451 return $customTableToCopyValues;
1455 * Get fields in the contact table suitable for merging.
1458 * Array of field names to be potentially merged.
1460 public static function getContactFields() {
1461 $contactFields = CRM_Contact_DAO_Contact
::fields();
1469 'primary_contact_id',
1473 foreach ($contactFields as $field => $value) {
1474 if (in_array($field, $invalidFields)) {
1475 unset($contactFields[$field]);
1478 return array_keys($contactFields);
1482 * Added for CRM-12695
1483 * Based on the contactID provided
1484 * add/update membership(s) to related contacts
1486 * @param int $contactID
1488 public static function addMembershipToRealtedContacts($contactID) {
1489 $dao = new CRM_Member_DAO_Membership();
1490 $dao->contact_id
= $contactID;
1494 //checks membership of contact itself
1495 while ($dao->fetch()) {
1496 $relationshipTypeId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id
, 'relationship_type_id', 'id');
1497 if ($relationshipTypeId) {
1498 $membershipParams = [
1500 'contact_id' => $dao->contact_id
,
1501 'membership_type_id' => $dao->membership_type_id
,
1502 'join_date' => CRM_Utils_Date
::isoToMysql($dao->join_date
),
1503 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
1504 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
1505 'source' => $dao->source
,
1506 'status_id' => $dao->status_id
,
1508 // create/update membership(s) for related contact(s)
1509 CRM_Member_BAO_Membership
::createRelatedMemberships($membershipParams, $dao);
1510 } // end of if relationshipTypeId
1515 * Create activities tracking the merge on affected contacts.
1517 * @param int $mainId
1518 * @param int $otherId
1520 * @throws \CiviCRM_API3_Exception
1522 public static function createMergeActivities($mainId, $otherId) {
1527 $activity = civicrm_api3('activity', 'create', [
1528 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
1530 'subject' => ts('Contact ID %1 has been merged and deleted.', $params),
1531 'target_contact_id' => $mainId,
1532 'activity_type_id' => 'Contact Merged',
1533 'status_id' => 'Completed',
1535 if (civicrm_api3('Setting', 'getvalue', [
1536 'name' => 'contact_undelete',
1537 'group' => 'CiviCRM Preferences',
1539 civicrm_api3('activity', 'create', [
1540 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
1542 'subject' => ts('Contact ID %1 has been merged into Contact ID %2 and deleted.', $params),
1543 'target_contact_id' => $otherId,
1544 'activity_type_id' => 'Contact Deleted by Merge',
1545 'parent_id' => $activity['id'],
1546 'status_id' => 'Completed',
1552 * Get Duplicate Pairs based on a rule for a group.
1554 * @param int $rule_group_id
1555 * @param int $group_id
1556 * @param bool $reloadCacheIfEmpty
1557 * Should the cache be reloaded if empty - this must be false when in a dedupe action!
1558 * @param int $batchLimit
1559 * @param bool $isSelected
1560 * Limit to selected pairs.
1561 * @param bool $includeConflicts
1562 * @param array $criteria
1563 * Additional criteria to narrow down the merge group.
1565 * @param bool $checkPermissions
1566 * Respect logged in user permissions.
1568 * @param int $searchLimit
1569 * Limit to searching for matches against this many contacts.
1571 * @param int $isForceNewSearch
1572 * Should a new search be forced, bypassing any cache retrieval.
1575 * Array of matches meeting the criteria.
1577 * @throws \CRM_Core_Exception
1578 * @throws \CiviCRM_API3_Exception
1580 public static function getDuplicatePairs($rule_group_id, $group_id, $reloadCacheIfEmpty, $batchLimit, $isSelected, $includeConflicts = TRUE, $criteria = [], $checkPermissions = TRUE, $searchLimit = 0, $isForceNewSearch = 0) {
1581 $dupePairs = $isForceNewSearch ?
[] : self
::getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, $includeConflicts, $criteria, $checkPermissions, $searchLimit);
1582 if (empty($dupePairs) && $reloadCacheIfEmpty) {
1583 // If we haven't found any dupes, probably cache is empty.
1584 // Try filling cache and give another try. We don't need to specify include conflicts here are there will not be any
1585 // until we have done some processing.
1586 CRM_Core_BAO_PrevNextCache
::refillCache($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit);
1587 return self
::getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, FALSE, $criteria, $checkPermissions, $searchLimit);
1593 * Get the cache key string for the merge action.
1595 * @param int $rule_group_id
1596 * @param int $group_id
1597 * @param array $criteria
1598 * Additional criteria to narrow down the merge group.
1599 * Currently we are only supporting the key 'contact' within it.
1600 * @param bool $checkPermissions
1601 * Respect the users permissions.
1602 * @param int $searchLimit
1603 * Number of contacts to seek dupes for (we need this because if
1604 * we change it the results won't be refreshed otherwise. Changing the limit
1605 * from 100 to 1000 SHOULD result in a new dedupe search).
1609 public static function getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit) {
1610 $contactType = CRM_Dedupe_BAO_RuleGroup
::getContactTypeForRuleGroup($rule_group_id);
1611 $cacheKeyString = "merge_{$contactType}";
1612 $cacheKeyString .= $rule_group_id ?
"_{$rule_group_id}" : '_0';
1613 $cacheKeyString .= $group_id ?
"_{$group_id}" : '_0';
1614 $cacheKeyString .= '_' . (int) $searchLimit;
1615 $cacheKeyString .= !empty($criteria) ?
md5(serialize($criteria)) : '_0';
1616 if ($checkPermissions) {
1617 $contactID = CRM_Core_Session
::getLoggedInContactID();
1619 // Distinguish between no permission check & no logged in user.
1620 $contactID = 'null';
1622 $cacheKeyString .= '_' . $contactID;
1625 $cacheKeyString .= '_0';
1627 return $cacheKeyString;
1631 * Get the metadata for the merge fields.
1633 * This is basically the contact metadata, augmented with fields to
1634 * represent email greeting, postal greeting & addressee.
1638 public static function getMergeFieldsMetadata() {
1639 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['merge_fields_metadata'])) {
1640 return \Civi
::$statics[__CLASS__
]['merge_fields_metadata'];
1642 $fields = CRM_Contact_DAO_Contact
::fields();
1643 static $optionValueFields = [];
1644 if (empty($optionValueFields)) {
1645 $optionValueFields = CRM_Core_OptionValue
::getFields();
1647 foreach ($optionValueFields as $field => $params) {
1648 $fields[$field]['title'] = $params['title'];
1650 \Civi
::$statics[__CLASS__
]['merge_fields_metadata'] = $fields;
1651 return \Civi
::$statics[__CLASS__
]['merge_fields_metadata'];
1655 * Get the details of the contact to be merged.
1657 * @param int $contact_id
1661 * @throws CRM_Core_Exception
1663 public static function getMergeContactDetails($contact_id) {
1665 'contact_id' => $contact_id,
1667 'return' => array_merge(['display_name'], self
::getContactFields()),
1669 $result = civicrm_api('contact', 'get', $params);
1671 // CRM-18480: Cancel the process if the contact is already deleted
1672 if (isset($result['values'][$contact_id]['contact_is_deleted']) && !empty($result['values'][$contact_id]['contact_is_deleted'])) {
1673 throw new CRM_Core_Exception(ts('Cannot merge because one contact (ID %1) has been deleted.', [
1678 return $result['values'][$contact_id];
1684 * Based on the data in the $locationMigrationInfo merge the locations for 2 contacts.
1686 * The data is in the format received from the merge form (which is a fairly confusing format).
1688 * It is converted into an array of DAOs which is passed to the alterLocationMergeData hook
1689 * before saving or deleting the DAOs. A new hook is added to allow these to be altered after they have
1690 * been calculated and before saving because
1691 * - the existing format & hook combo is so confusing it is hard for developers to change & inherently fragile
1692 * - passing to a hook right before save means calculations only have to be done once
1693 * - the existing pattern of passing dissimilar data to the same (merge) hook with a different 'type' is just
1696 * The use of the new hook is tested, including the fact it is called before contributions are merged, as this
1697 * is likely to be significant data in merge hooks.
1699 * @param int $mainId
1700 * @param int $otherId
1702 * @param array $migrationInfo
1703 * Migration info for the merge. This is passed to the hook as informational only.
1705 public static function mergeLocations($mainId, $otherId, $migrationInfo) {
1706 foreach ($migrationInfo as $key => $value) {
1707 $isLocationField = (substr($key, 0, 14) == 'move_location_' and $value != NULL);
1708 if (!$isLocationField) {
1711 $locField = explode('_', $key);
1712 $fieldName = $locField[2];
1713 $fieldCount = $locField[3];
1715 // Set up the operation type (add/overwrite)
1716 // Ignore operation for websites
1717 // @todo Tidy this up
1719 if ($fieldName != 'website') {
1720 $operation = CRM_Utils_Array
::value('operation', $migrationInfo['location_blocks'][$fieldName][$fieldCount]);
1722 // default operation is overwrite.
1726 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
1730 // @todo Handle OpenID (not currently in API).
1731 if (!empty($locBlocks)) {
1732 $locationBlocks = self
::getLocationBlockInfo();
1734 $primaryBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, ['is_primary' => 1]);
1735 $billingBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, ['is_billing' => 1]);
1737 foreach ($locBlocks as $name => $block) {
1738 $blocksDAO[$name] = ['delete' => [], 'update' => []];
1739 if (!is_array($block) || CRM_Utils_System
::isNull($block)) {
1742 $daoName = 'CRM_Core_DAO_' . $locationBlocks[$name]['label'];
1743 $changePrimary = FALSE;
1744 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ?
array_pop($primaryBlockIds[$name]) : NULL;
1745 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ?
array_pop($billingBlockIds[$name]) : NULL;
1747 foreach ($block as $blkCount => $values) {
1748 $otherBlockId = CRM_Utils_Array
::value('id', $migrationInfo['other_details']['location_blocks'][$name][$blkCount]);
1749 $mainBlockId = CRM_Utils_Array
::value('mainContactBlockId', $migrationInfo['location_blocks'][$name][$blkCount], 0);
1750 if (!$otherBlockId) {
1754 // For the block which belongs to other-contact, link the location block to main-contact
1755 $otherBlockDAO = new $daoName();
1756 $otherBlockDAO->contact_id
= $mainId;
1758 // Get the ID of this block on the 'other' contact, otherwise skip
1759 $otherBlockDAO->id
= $otherBlockId;
1761 // Add/update location and type information from the form, if applicable
1762 if ($locationBlocks[$name]['hasLocation']) {
1763 $locTypeId = CRM_Utils_Array
::value('locTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
1764 $otherBlockDAO->location_type_id
= $locTypeId;
1766 if ($locationBlocks[$name]['hasType']) {
1767 $typeTypeId = CRM_Utils_Array
::value('typeTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
1768 $otherBlockDAO->{$locationBlocks[$name]['hasType']} = $typeTypeId;
1771 // If we're deliberately setting this as primary then add the flag
1772 // and remove it from the current primary location (if there is one).
1773 // But only once for each entity.
1774 $set_primary = CRM_Utils_Array
::value('set_other_primary', $migrationInfo['location_blocks'][$name][$blkCount]);
1775 if (!$changePrimary && $set_primary == "1") {
1776 $otherBlockDAO->is_primary
= 1;
1777 if ($primaryDAOId) {
1778 $removePrimaryDAO = new $daoName();
1779 $removePrimaryDAO->id
= $primaryDAOId;
1780 $removePrimaryDAO->is_primary
= 0;
1781 $blocksDAO[$name]['update'][$primaryDAOId] = $removePrimaryDAO;
1783 $changePrimary = TRUE;
1785 // Otherwise, if main contact already has primary, set it to 0.
1786 elseif ($primaryDAOId) {
1787 $otherBlockDAO->is_primary
= 0;
1790 // If the main contact already has a billing location, set this to 0.
1791 if ($billingDAOId) {
1792 $otherBlockDAO->is_billing
= 0;
1795 $operation = CRM_Utils_Array
::value('operation', $values, 2);
1796 // overwrite - need to delete block which belongs to main-contact.
1797 if (!empty($mainBlockId) && ($operation == 2)) {
1798 $deleteDAO = new $daoName();
1799 $deleteDAO->id
= $mainBlockId;
1800 $deleteDAO->find(TRUE);
1802 // if we about to delete a primary / billing block, set the flags for new block
1803 // that we going to assign to main-contact
1804 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id
)) {
1805 $otherBlockDAO->is_primary
= 1;
1807 if ($billingDAOId && ($billingDAOId == $deleteDAO->id
)) {
1808 $otherBlockDAO->is_billing
= 1;
1810 $blocksDAO[$name]['delete'][$deleteDAO->id
] = $deleteDAO;
1812 $blocksDAO[$name]['update'][$otherBlockDAO->id
] = $otherBlockDAO;
1817 CRM_Utils_Hook
::alterLocationMergeData($blocksDAO, $mainId, $otherId, $migrationInfo);
1818 foreach ($blocksDAO as $blockDAOs) {
1819 if (!empty($blockDAOs['update'])) {
1820 foreach ($blockDAOs['update'] as $blockDAO) {
1824 if (!empty($blockDAOs['delete'])) {
1825 foreach ($blockDAOs['delete'] as $blockDAO) {
1826 $blockDAO->delete();
1833 * Dedupe a pair of contacts.
1835 * @param array $dupes
1836 * @param string $mode
1837 * @param bool $checkPermissions
1838 * @param string $cacheKeyString
1840 * @return bool|array
1841 * @throws \CRM_Core_Exception
1842 * @throws \CiviCRM_API3_Exception
1843 * @throws \API_Exception
1845 protected static function dedupePair($dupes, $mode = 'safe', $checkPermissions = TRUE, $cacheKeyString = NULL) {
1846 CRM_Utils_Hook
::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']);
1847 $mainId = $dupes['dstID'];
1848 $otherId = $dupes['srcID'];
1851 if (!$mainId ||
!$otherId) {
1855 $migrationInfo = [];
1857 // Try to lock the contacts before we load the data as we don't want it changing under us.
1858 // https://lab.civicrm.org/dev/core/issues/1355
1859 $locks = self
::getLocksOnContacts([$mainId, $otherId]);
1860 if (!CRM_Dedupe_Merger
::skipMerge($mainId, $otherId, $migrationInfo, $mode, $conflicts)) {
1861 CRM_Dedupe_Merger
::moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions);
1862 $resultStats['merged'][] = [
1863 'main_id' => $mainId,
1864 'other_id' => $otherId,
1868 $resultStats['skipped'][] = [
1869 'main_id' => $mainId,
1870 'other_id' => $otherId,
1874 // store any conflicts
1875 if (!empty($conflicts)) {
1876 CRM_Core_BAO_PrevNextCache
::markConflict($mainId, $otherId, $cacheKeyString, $conflicts, $mode);
1879 CRM_Core_BAO_PrevNextCache
::deletePair($mainId, $otherId, $cacheKeyString);
1881 self
::releaseLocks($locks);
1882 return $resultStats;
1886 * Replace the pseudo QFKey with zero if it is present.
1888 * @todo - on the slim chance this is still relevant it should be moved to the form layer.
1890 * Details about this bug are somewhat obscured by the move from svn but perhaps JIRA
1893 * @param array $migrationInfo
1895 protected static function swapOutFieldsAffectedByQFZeroBug(&$migrationInfo) {
1896 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1897 foreach ($migrationInfo as $key => &$value) {
1898 if ($value == $qfZeroBug) {
1905 * Honestly - what DOES this do - hopefully some refactoring will reveal it's purpose.
1907 * Update this function formats fields in preparation for them to be submitted to the
1908 * 'ProfileContactCreate action. This is a lot of code to do this & for
1909 * - for some fields it fails - e.g Country - per testMergeCustomFields.
1911 * Goal is to move all custom field handling into 'move' functions on the various BAO
1912 * with an underlying DAO function. For custom fields it has been started on the BAO.
1921 * @throws \Exception
1923 protected static function processCustomFields($mainId, $key, $cFields, $submitted, $value) {
1924 if (substr($key, 0, 7) == 'custom_') {
1925 $fid = (int) substr($key, 7);
1926 if (empty($cFields[$fid])) {
1927 return [$cFields, $submitted];
1929 $htmlType = $cFields[$fid]['attributes']['html_type'];
1930 switch ($htmlType) {
1932 // Handled in CustomField->move(). Tested in testMergeCustomFields.
1933 unset($submitted["custom_$fid"]);
1936 case 'Select Country':
1937 // @todo Test in testMergeCustomFields disabled as this does not work, Handle in CustomField->move().
1938 case 'Select State/Province':
1939 $submitted[$key] = CRM_Core_BAO_CustomField
::displayValue($value, $fid);
1943 if ($cFields[$fid]['attributes']['is_view']) {
1944 $submitted[$key] = date('YmdHis', strtotime($submitted[$key]));
1949 case 'Multi-Select':
1950 case 'Multi-Select Country':
1951 case 'Multi-Select State/Province':
1952 // Merge values from both contacts for multivalue fields, CRM-4385
1953 // get the existing custom values from db.
1954 $customParams = ['entityID' => $mainId, $key => TRUE];
1955 $customfieldValues = CRM_Core_BAO_CustomValueTable
::getValues($customParams);
1956 if (!empty($customfieldValues[$key])) {
1957 $existingValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customfieldValues[$key]);
1958 if (is_array($existingValue) && !empty($existingValue)) {
1959 $mergeValue = $submittedCustomFields = [];
1960 if ($value == 'null') {
1961 // CRM-19074 if someone has deliberately chosen to overwrite with 'null', respect it.
1962 $submitted[$key] = $value;
1966 $submittedCustomFields = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
1969 // CRM-19653: overwrite or add the existing custom field value with dupicate contact's
1970 // custom field value stored at $submittedCustomValue.
1971 foreach ($submittedCustomFields as $k => $v) {
1972 if ($v != '' && !in_array($v, $mergeValue)) {
1977 //keep state and country as array format.
1978 //for checkbox and m-select format w/ VALUE_SEPARATOR
1979 if (in_array($htmlType, [
1983 $submitted[$key] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1985 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
1988 $submitted[$key] = $mergeValue;
1993 elseif (in_array($htmlType, [
1994 'Multi-Select Country',
1995 'Multi-Select State/Province',
1997 //we require submitted values should be in array format
1999 $mergeValueArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2000 //hack to remove null values from array.
2002 foreach ($mergeValueArray as $k => $v) {
2007 $submitted[$key] = $mergeValue;
2016 return [$cFields, $submitted];
2020 * Get metadata for the custom fields for the merge.
2022 * @param string $contactType
2026 protected static function getCustomFieldMetadata($contactType) {
2028 if (!array_key_exists($contactType, $treeCache)) {
2029 $treeCache[$contactType] = CRM_Core_BAO_CustomGroup
::getTree(
2044 foreach ($treeCache[$contactType] as $key => $group) {
2045 if (!isset($group['fields'])) {
2048 foreach ($group['fields'] as $fid => $field) {
2049 $cFields[$fid]['attributes'] = $field;
2056 * Get conflicts for proposed merge pair.
2058 * @param array $migrationInfo
2059 * This is primarily to inform hooks. The can also modify it which feels
2060 * pretty fragile to do it here - but it is historical.
2061 * @param int $mainId
2062 * Main contact with whom merge has to happen.
2063 * @param int $otherId
2064 * Duplicate contact which would be deleted after merge operation.
2065 * @param string $mode
2066 * Helps decide how to behave when there are conflicts.
2067 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
2068 * - Does a force merge otherwise (aggressive mode).
2072 * @throws \CRM_Core_Exception
2073 * @throws \CiviCRM_API3_Exception
2075 public static function getConflicts(&$migrationInfo, $mainId, $otherId, $mode) {
2077 // Generate var $migrationInfo. The variable structure is exactly same as
2078 // $formValues submitted during a UI merge for a pair of contacts.
2079 $rowsElementsAndInfo = CRM_Dedupe_Merger
::getRowsElementsAndInfo($mainId, $otherId, FALSE);
2080 // add additional details that we might need to resolve conflicts
2081 $migrationInfo = $rowsElementsAndInfo['migration_info'];
2082 $migrationInfo['main_details'] = &$rowsElementsAndInfo['main_details'];
2083 $migrationInfo['other_details'] = &$rowsElementsAndInfo['other_details'];
2084 $migrationInfo['rows'] = &$rowsElementsAndInfo['rows'];
2085 // go ahead with merge if there is no conflict
2086 $originalMigrationInfo = $migrationInfo;
2087 foreach ($migrationInfo as $key => $val) {
2088 if ($val === "null") {
2089 // Rule: Never overwrite with an empty value (in any mode)
2090 unset($migrationInfo[$key]);
2093 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger
::getContactFields()) or
2094 substr($key, 0, 12) == 'move_custom_'
2097 // Rule: If both main-contact, and other-contact have a field with a
2098 // different value, then let $mode decide if to merge it or not
2100 (!empty($migrationInfo['rows'][$key]['main'])
2101 // For custom fields a 0 (e.g in an int field) could be a true conflict. This
2102 // is probably true for other fields too - e.g. 'do_not_email' but
2103 // leaving that investigation as a @todo - until tests can be written.
2104 // Note the handling of this has test coverage - although the data-typing
2105 // of '0' feels flakey we have insurance.
2106 ||
($migrationInfo['rows'][$key]['main'] === '0' && substr($key, 0, 12) == 'move_custom_')
2108 && $migrationInfo['rows'][$key]['main'] != $migrationInfo['rows'][$key]['other']
2111 // note it down & lets wait for response from the hook.
2112 // For no response $mode will decide if to skip this merge
2113 $conflicts[$key] = NULL;
2116 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
2117 $locField = explode('_', $key);
2118 $fieldName = $locField[2];
2119 $fieldCount = $locField[3];
2121 // Rule: Catch address conflicts (same address type on both contacts)
2123 isset($migrationInfo['main_details']['location_blocks'][$fieldName]) &&
2124 !empty($migrationInfo['main_details']['location_blocks'][$fieldName])
2127 // Load the address we're inspecting from the 'other' contact
2128 $addressRecord = $migrationInfo['other_details']['location_blocks'][$fieldName][$fieldCount];
2129 $addressRecordLocTypeId = CRM_Utils_Array
::value('location_type_id', $addressRecord);
2131 // If it exists on the 'main' contact already, skip it. Otherwise
2132 // if the location type exists already, log a conflict.
2133 foreach ($migrationInfo['main_details']['location_blocks'][$fieldName] as $mainAddressKey => $mainAddressRecord) {
2134 if (self
::locationIsSame($addressRecord, $mainAddressRecord)) {
2135 unset($migrationInfo[$key]);
2138 elseif ($addressRecordLocTypeId == $mainAddressRecord['location_type_id']) {
2139 $conflicts[$key] = NULL;
2145 // For other locations, don't merge/add if the values are the same
2146 elseif (CRM_Utils_Array
::value('main', $migrationInfo['rows'][$key]) == $migrationInfo['rows'][$key]['other']) {
2147 unset($migrationInfo[$key]);
2152 // A hook to implement other algorithms for choosing which contact to bias to when
2153 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
2154 // merge happens with new values filled in here. For a particular field / row not to be merged
2155 // field should be unset from fields_in_conflict.
2157 'old_migration_info' => $originalMigrationInfo,
2159 'fields_in_conflict' => $conflicts,
2160 'merge_mode' => $mode,
2161 'migration_info' => $migrationInfo,
2163 CRM_Utils_Hook
::merge('batch', $migrationData, $mainId, $otherId);
2164 $conflicts = $migrationData['fields_in_conflict'];
2165 // allow hook to override / manipulate migrationInfo as well
2166 $migrationInfo = $migrationData['migration_info'];
2167 foreach ($conflicts as $key => $val) {
2168 // Copy over the resolved values. If we are in aggressive mode we update to null
2169 // so as not to copy over. Why it's different to safe mode is a bit murky.
2170 // Working theory is it doesn't matter what we do in safe mode here if $val is NULL.
2171 // as the merge is not gonna happen if $val == NULL
2172 $migrationInfo[$key] = $val ??
($mode === 'safe' ?
$migrationInfo[$key] : NULL);
2174 return self
::formatConflictArray($conflicts, $migrationInfo['rows'], $migrationInfo['main_details']['location_blocks'], $migrationInfo['other_details']['location_blocks'], $mainId, $otherId, $mode);
2178 * @param array $conflicts
2179 * @param array $migrationInfo
2180 * @param $toKeepContactLocationBlocks
2181 * @param $toRemoveContactLocationBlocks
2183 * @param $toRemoveID
2184 * @param string $mode
2187 * @throws \CRM_Core_Exception
2189 protected static function formatConflictArray($conflicts, $migrationInfo, $toKeepContactLocationBlocks, $toRemoveContactLocationBlocks, $toKeepID, $toRemoveID, $mode) {
2192 foreach ($conflicts as $key => $val) {
2193 if ($val !== NULL) {
2194 // copy over the resolved values
2195 $resolved[$key] = $val;
2196 unset($conflicts[$key]);
2198 elseif ($mode === 'aggressive') {
2199 unset($conflicts[$key]);
2200 if (strpos($key, 'move_location_') !== 0) {
2201 // @todo - just handling plain contact fields for now because I think I need a bigger refactor
2202 // of the below to handle locations & will do as a follow up.
2203 $resolved['contact'][substr($key, 5)] = $migrationInfo[$key]['main'];
2207 foreach (array_keys($conflicts) as $index) {
2208 if (substr($index, 0, 14) === 'move_location_') {
2209 $parts = explode('_', $index);
2210 $entity = $parts[2];
2211 $blockIndex = $parts[3];
2212 $locationTypeID = $toKeepContactLocationBlocks[$entity][$blockIndex]['location_type_id'];
2213 $entityConflicts = [
2214 'location_type_id' => $locationTypeID,
2215 'title' => $migrationInfo[$index]['title'],
2217 foreach ($toKeepContactLocationBlocks[$entity][$blockIndex] as $fieldName => $fieldValue) {
2218 if (in_array($fieldName, self
::ignoredFields())) {
2221 $toRemoveValue = CRM_Utils_Array
::value($fieldName, $toRemoveContactLocationBlocks[$entity][$blockIndex]);
2222 if ($fieldValue !== $toRemoveValue) {
2223 $entityConflicts[$fieldName] = [
2224 $toKeepID => $fieldValue,
2225 $toRemoveID => $toRemoveValue,
2229 $return[$entity][] = $entityConflicts;
2231 elseif (substr($index, 0, 5) === 'move_') {
2232 $contactFieldsToCompare[] = str_replace('move_', '', $index);
2233 $return['contact'][str_replace('move_', '', $index)] = [
2234 'title' => $migrationInfo[$index]['title'],
2235 $toKeepID => $migrationInfo[$index]['main'],
2236 $toRemoveID => $migrationInfo[$index]['other'],
2240 // Can't think of why this would be the case but perhaps it's ensuring it isn't as we
2242 throw new CRM_Core_Exception(ts('Unknown parameter') . $index);
2245 return ['conflicts' => $return, 'resolved' => $resolved];
2249 * Get any duplicate merge pairs that have been previously cached.
2251 * @param int $rule_group_id
2252 * @param int $group_id
2253 * @param int $batchLimit
2254 * @param bool $isSelected
2255 * @param bool $includeConflicts
2256 * @param array $criteria
2257 * @param int $checkPermissions
2258 * @param int $searchLimit
2262 protected static function getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, $includeConflicts, $criteria, $checkPermissions, $searchLimit = 0) {
2263 return CRM_Core_BAO_PrevNextCache
::retrieve(
2264 self
::getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit),
2265 self
::getJoinOnDedupeTable(),
2266 self
::getWhereString($isSelected),
2276 protected static function ignoredFields(): array {
2286 return $keysToIgnore;
2290 * Get the field value & label for the given field.
2296 * @throws \Exception
2298 private static function getFieldValueAndLabel($field, $contact): array {
2299 $fields = self
::getMergeFieldsMetadata();
2300 $value = $label = CRM_Utils_Array
::value($field, $contact);
2301 $fieldSpec = $fields[$field];
2302 if (!empty($fieldSpec['serialize']) && is_array($value)) {
2303 // In practice this only applies to preferred_communication_method as the sub types are skipped above
2304 // and no others are serialized.
2306 foreach ($value as $individualValue) {
2307 $labels[] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $field, $individualValue);
2309 $label = implode(', ', $labels);
2310 // We serialize this due to historic handling but it's likely that if we just left it as an
2311 // array all would be well & we would have less code.
2312 $value = CRM_Core_DAO
::serializeField($value, $fieldSpec['serialize']);
2314 elseif (!empty($fieldSpec['type']) && $fieldSpec['type'] == CRM_Utils_Type
::T_DATE
) {
2316 $value = str_replace('-', '', $value);
2317 $label = CRM_Utils_Date
::customFormat($label);
2323 elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type
::T_BOOLEAN
) {
2324 if ($label === '0') {
2327 if ($label === '1') {
2331 elseif (!empty($fieldSpec['pseudoconstant'])) {
2332 $label = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $field, $value);
2334 elseif ($field == 'current_employer_id' && !empty($value)) {
2335 $label = "$value (" . CRM_Contact_BAO_Contact
::displayName($value) . ")";
2337 return ['label' => $label, 'value' => $value];
2341 * Build up the location block for the contact in dedupe-screen display format.
2343 * @param integer $cid
2344 * @param array $blockInfo
2345 * @param string $blockName
2349 * @throws \CiviCRM_API3_Exception
2351 private static function buildLocationBlockForContact($cid, $blockInfo, $blockName): array {
2353 'contact_id' => $cid,
2354 // CRM-17556 Order by field-specific criteria
2356 'sort' => $blockInfo['sortString'],
2359 $locationBlock = [];
2360 $values = civicrm_api3($blockName, 'get', $searchParams);
2361 if ($values['count']) {
2363 foreach ($values['values'] as $value) {
2364 $locationBlock[$cnt] = $value;
2365 // Fix address display
2366 if ($blockName == 'address') {
2367 // For performance avoid geocoding while merging https://issues.civicrm.org/jira/browse/CRM-21786
2368 // we can expect existing geocode values to be retained.
2369 $value['skip_geocode'] = TRUE;
2370 CRM_Core_BAO_Address
::fixAddress($value);
2371 unset($value['skip_geocode']);
2372 $locationBlock[$cnt]['display'] = CRM_Utils_Address
::format($value);
2374 // Fix email display
2375 elseif ($blockName == 'email') {
2376 $locationBlock[$cnt]['display'] = CRM_Utils_Mail
::format($value);
2382 return $locationBlock;
2386 * Get a lock on the given contact.
2388 * The lock is like a gentleman's agreement between php & mysql. It is reserved at the
2389 * mysql level so it works across php processes but it doesn't actually lock the database.
2391 * Instead php can check the lock to see if it has been acquired before taking an action.
2393 * In this case we really don't want to attempt to dedupe contacts if another process is
2394 * trying to act on the specific contact as it could result in messy deadlocks & possibly data corruption.
2395 * In most databases this would be a rare event but if multiple dedupe processes are running
2396 * at once (for example) or there is also an import process in play there is potential for them to crash.
2397 * By throwing a specific error the calling process can catch it and determine it is worth trying again later without a lot of
2400 * As of writing no other processes DO grab contact locks but it would be reasonable to consider
2401 * grabbing them doing contact edits in general as well as imports etc.
2403 * @param array $contacts
2407 * @throws \CRM_Core_Exception
2408 * @throws \CRM_Core_Exception_ResourceConflictException
2410 protected static function getLocksOnContacts($contacts):array {
2412 if (!CRM_Utils_SQL
::supportsMultipleLocks()) {
2415 foreach ($contacts as $contactID) {
2416 $lock = Civi
::lockManager()->acquire("data.core.contact.{$contactID}");
2417 if ($lock->isAcquired()) {
2421 self
::releaseLocks($locks);
2422 throw new CRM_Core_Exception_ResourceConflictException(ts('Contact is in Use'), 'contact_lock');
2429 * Release contact locks so another process can alter them if it wants.
2431 * @param array $locks
2433 protected static function releaseLocks(array $locks) {
2434 foreach ($locks as $lock) {
2435 /* @var Civi\Core\Lock\LockInterface $lock */
2445 * @param array $locations
2446 * @param array $rows
2447 * @param array $elements
2448 * @param array $migrationInfo
2451 * @throws \CiviCRM_API3_Exception
2453 protected static function addLocationFieldInfo($mainId, $otherId, $blockInfo, $blockName, array $locations, array $rows, array $elements, array $migrationInfo): array {
2454 // Collect existing fields from both 'main' and 'other' contacts first
2455 // This allows us to match up location/types when building the table rows
2456 $locations['main'][$blockName] = self
::buildLocationBlockForContact($mainId, $blockInfo, $blockName);
2457 $locations['other'][$blockName] = self
::buildLocationBlockForContact($otherId, $blockInfo, $blockName);
2459 // Now, build the table rows appropriately, based off the information on
2460 // the 'other' contact
2461 if (!empty($locations['other']) && !empty($locations['other'][$blockName])) {
2462 foreach ($locations['other'][$blockName] as $count => $value) {
2464 $displayValue = $value[$blockInfo['displayField']];
2466 // Add this value to the table rows
2467 $rows["move_location_{$blockName}_{$count}"]['other'] = $displayValue;
2469 // CRM-17556 Only display 'main' contact value if it's the same location + type
2470 // Look it up from main values...
2472 $lookupLocation = FALSE;
2473 if ($blockInfo['hasLocation']) {
2474 $lookupLocation = $value['location_type_id'];
2477 $lookupType = FALSE;
2478 if ($blockInfo['hasType']) {
2479 $lookupType = CRM_Utils_Array
::value($blockInfo['hasType'], $value);
2482 // Hold ID of main contact's matching block
2483 $mainContactBlockId = 0;
2485 if (!empty($locations['main'][$blockName])) {
2486 foreach ($locations['main'][$blockName] as $mainValueCheck) {
2487 // No location/type, or matching location and type
2489 (empty($lookupLocation) ||
$lookupLocation == $mainValueCheck['location_type_id'])
2490 && (empty($lookupType) ||
$lookupType == $mainValueCheck[$blockInfo['hasType']])
2492 // Set this value as the default against the 'other' contact value
2493 $rows["move_location_{$blockName}_{$count}"]['main'] = $mainValueCheck[$blockInfo['displayField']];
2494 $rows["move_location_{$blockName}_{$count}"]['main_is_primary'] = $mainValueCheck['is_primary'];
2495 $rows["move_location_{$blockName}_{$count}"]['location_entity'] = $blockName;
2496 $mainContactBlockId = $mainValueCheck['id'];
2502 // Add checkbox to migrate data from 'other' to 'main'
2503 $elements[] = ['advcheckbox', "move_location_{$blockName}_{$count}"];
2505 // Add checkbox to set the 'other' location as primary
2508 "location_blocks[$blockName][$count][set_other_primary]",
2510 ts('Set as primary'),
2513 // Flag up this field to skipMerge function (@todo: do we need to?)
2514 $migrationInfo["move_location_{$blockName}_{$count}"] = 1;
2516 // Add a hidden field to store the ID of the target main contact block
2519 "location_blocks[$blockName][$count][mainContactBlockId]",
2520 $mainContactBlockId,
2524 $thisTypeId = FALSE;
2527 // Provide a select drop-down for the location's location type
2528 // eg: Home, Work...
2530 if ($blockInfo['hasLocation']) {
2532 // Load the location options for this entity
2533 $locationOptions = civicrm_api3($blockName, 'getoptions', ['field' => 'location_type_id']);
2535 $thisLocId = $value['location_type_id'];
2537 // Put this field's location type at the top of the list
2538 $tmpIdList = $locationOptions['values'];
2539 $defaultLocId = [$thisLocId => $tmpIdList[$thisLocId]];
2540 unset($tmpIdList[$thisLocId]);
2545 "location_blocks[$blockName][$count][locTypeId]",
2547 $defaultLocId +
$tmpIdList,
2550 // Add the relevant information to the $migrationInfo
2551 // Keep location-type-id same as that of other-contact
2552 // @todo Check this logic out
2553 $migrationInfo['location_blocks'][$blockName][$count]['locTypeId'] = $thisLocId;
2554 if ($blockName != 'address') {
2557 "location_blocks[{$blockName}][$count][operation]",
2561 // always use add operation
2562 $migrationInfo['location_blocks'][$blockName][$count]['operation'] = 1;
2567 // Provide a select drop-down for the location's type/provider
2568 // eg websites: Facebook...
2570 if ($blockInfo['hasType']) {
2572 // Load the type options for this entity
2573 $typeOptions = civicrm_api3($blockName, 'getoptions', ['field' => $blockInfo['hasType']]);
2575 $thisTypeId = CRM_Utils_Array
::value($blockInfo['hasType'], $value);
2577 // Put this field's location type at the top of the list
2578 $tmpIdList = $typeOptions['values'];
2579 $defaultTypeId = [$thisTypeId => CRM_Utils_Array
::value($thisTypeId, $tmpIdList)];
2580 unset($tmpIdList[$thisTypeId]);
2585 "location_blocks[$blockName][$count][typeTypeId]",
2587 $defaultTypeId +
$tmpIdList,
2590 // Add the information to the migrationInfo
2591 $migrationInfo['location_blocks'][$blockName][$count]['typeTypeId'] = $thisTypeId;
2595 // Set the label for this row
2596 $rowTitle = $blockInfo['label'] . ' ' . ($count +
1);
2597 if (!empty($thisLocId)) {
2598 $rowTitle .= ' (' . $locationOptions['values'][$thisLocId] . ')';
2600 if (!empty($thisTypeId)) {
2601 $rowTitle .= ' (' . $typeOptions['values'][$thisTypeId] . ')';
2603 $rows["move_location_{$blockName}_$count"]['title'] = $rowTitle;
2605 } // End loop through 'other' locations of this type
2608 return [$locations, $rows, $elements, $migrationInfo];