3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
33 class CRM_Dedupe_Merger
{
36 * FIXME: consider creating a common structure with cidRefs() and eidRefs()
37 * FIXME: the sub-pages references by the URLs should
38 * be loaded dynamically on the merge form instead
41 public static function relTables() {
43 if (!isset(Civi
::$statics[__CLASS__
]['relTables'])) {
45 // Setting these merely prevents enotices - but it may be more appropriate not to add the user table below
46 // if the url can't be retrieved. A more standardised way to retrieve them is.
47 // CRM_Core_Config::singleton()->userSystem->getUserRecordUrl() - however that function takes a contact_id &
48 // we may need a different function when it is not known.
49 $title = $userRecordUrl = '';
51 $config = CRM_Core_Config
::singleton();
52 if ($config->userSystem
->is_drupal
) {
53 $userRecordUrl = CRM_Utils_System
::url('user/%ufid');
54 $title = ts('%1 User: %2; user id: %3', [
55 1 => $config->userFramework
,
60 elseif ($config->userFramework
== 'Joomla') {
61 $userRecordUrl = $config->userSystem
->getVersion() > 1.5 ?
$config->userFrameworkBaseURL
. "index.php?option=com_users&view=user&task=user.edit&id=" . '%ufid' : $config->userFrameworkBaseURL
. "index2.php?option=com_users&view=user&task=edit&id[]=" . '%ufid';
62 $title = ts('%1 User: %2; user id: %3', [
63 1 => $config->userFramework
,
70 'rel_table_contributions' => [
71 'title' => ts('Contributions'),
73 'civicrm_contribution',
74 'civicrm_contribution_recur',
75 'civicrm_contribution_soft',
77 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=contribute'),
79 'rel_table_contribution_page' => [
80 'title' => ts('Contribution Pages'),
81 'tables' => ['civicrm_contribution_page'],
82 'url' => CRM_Utils_System
::url('civicrm/admin/contribute', 'reset=1&cid=$cid'),
84 'rel_table_memberships' => [
85 'title' => ts('Memberships'),
88 'civicrm_membership_log',
89 'civicrm_membership_type',
91 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=member'),
93 'rel_table_participants' => [
94 'title' => ts('Participants'),
95 'tables' => ['civicrm_participant'],
96 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=participant'),
98 'rel_table_events' => [
99 'title' => ts('Events'),
100 'tables' => ['civicrm_event'],
101 'url' => CRM_Utils_System
::url('civicrm/event/manage', 'reset=1&cid=$cid'),
103 'rel_table_activities' => [
104 'title' => ts('Activities'),
105 'tables' => ['civicrm_activity', 'civicrm_activity_contact'],
106 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=activity'),
108 'rel_table_relationships' => [
109 'title' => ts('Relationships'),
110 'tables' => ['civicrm_relationship'],
111 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=rel'),
113 'rel_table_custom_groups' => [
114 'title' => ts('Custom Groups'),
115 'tables' => ['civicrm_custom_group'],
116 'url' => CRM_Utils_System
::url('civicrm/admin/custom/group', 'reset=1'),
118 'rel_table_uf_groups' => [
119 'title' => ts('Profiles'),
120 'tables' => ['civicrm_uf_group'],
121 'url' => CRM_Utils_System
::url('civicrm/admin/uf/group', 'reset=1'),
123 'rel_table_groups' => [
124 'title' => ts('Groups'),
125 'tables' => ['civicrm_group_contact'],
126 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=group'),
128 'rel_table_notes' => [
129 'title' => ts('Notes'),
130 'tables' => ['civicrm_note'],
131 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=note'),
133 'rel_table_tags' => [
134 'title' => ts('Tags'),
135 'tables' => ['civicrm_entity_tag'],
136 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=tag'),
138 'rel_table_mailings' => [
139 'title' => ts('Mailings'),
142 'civicrm_mailing_event_queue',
143 'civicrm_mailing_event_subscribe',
145 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=mailing'),
147 'rel_table_cases' => [
148 'title' => ts('Cases'),
149 'tables' => ['civicrm_case_contact'],
150 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=case'),
152 'rel_table_grants' => [
153 'title' => ts('Grants'),
154 'tables' => ['civicrm_grant'],
155 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=grant'),
158 'title' => ts('PCPs'),
159 'tables' => ['civicrm_pcp'],
160 'url' => CRM_Utils_System
::url('civicrm/contribute/pcp/manage', 'reset=1'),
162 'rel_table_pledges' => [
163 'title' => ts('Pledges'),
164 'tables' => ['civicrm_pledge', 'civicrm_pledge_payment'],
165 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=pledge'),
167 'rel_table_users' => [
169 'tables' => ['civicrm_uf_match'],
170 'url' => $userRecordUrl,
174 $relTables +
= self
::getMultiValueCustomSets('relTables');
176 // Allow hook_civicrm_merge() to adjust $relTables
177 CRM_Utils_Hook
::merge('relTables', $relTables);
179 // Cache the results in a static variable
180 Civi
::$statics[__CLASS__
]['relTables'] = $relTables;
183 return Civi
::$statics[__CLASS__
]['relTables'];
187 * Returns the related tables groups for which a contact has any info entered.
193 public static function getActiveRelTables($cid) {
197 $relTables = self
::relTables();
198 $cidRefs = self
::cidRefs();
199 $eidRefs = self
::eidRefs();
200 foreach ($relTables as $group => $params) {
202 foreach ($params['tables'] as $table) {
203 if (isset($cidRefs[$table])) {
204 foreach ($cidRefs[$table] as $field) {
205 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $field = $cid";
208 if (isset($eidRefs[$table])) {
209 foreach ($eidRefs[$table] as $entityTable => $entityId) {
210 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $entityId = $cid AND $entityTable = 'civicrm_contact'";
213 foreach ($sqls as $sql) {
214 if (CRM_Core_DAO
::singleValueQuery($sql) > 0) {
220 return array_unique($groups);
224 * Get array tables and fields that reference civicrm_contact.id.
226 * This function calls the merge hook and only exists to wrap the DAO function to support that deprecated call.
227 * The entityTypes hook is the recommended way to add tables to this result.
229 * I thought about adding another hook to alter tableReferences but decided it was unclear if there
230 * are use cases not covered by entityTables and instead we should wait & see.
232 public static function cidRefs() {
233 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['contact_references'])) {
234 return \Civi
::$statics[__CLASS__
]['contact_references'];
237 $contactReferences = $coreReferences = CRM_Core_DAO
::getReferencesToContactTable();
239 CRM_Utils_Hook
::merge('cidRefs', $contactReferences);
240 if ($contactReferences !== $coreReferences) {
242 ->warning("Deprecated hook ::merge in context of 'cidRefs. Use entityTypes instead.", ['civi.tag' => 'deprecated']);
244 \Civi
::$statics[__CLASS__
]['contact_references'] = $contactReferences;
245 return \Civi
::$statics[__CLASS__
]['contact_references'];
249 * Return tables and their fields referencing civicrm_contact.contact_id with entity_id
251 public static function eidRefs() {
254 // FIXME: this should be generated dynamically from the schema
255 // tables that reference contacts with entity_{id,table}
257 'civicrm_acl' => ['entity_table' => 'entity_id'],
258 'civicrm_acl_entity_role' => ['entity_table' => 'entity_id'],
259 'civicrm_entity_file' => ['entity_table' => 'entity_id'],
260 'civicrm_log' => ['entity_table' => 'entity_id'],
261 'civicrm_mailing_group' => ['entity_table' => 'entity_id'],
262 'civicrm_note' => ['entity_table' => 'entity_id'],
265 // Allow hook_civicrm_merge() to adjust $eidRefs
266 CRM_Utils_Hook
::merge('eidRefs', $eidRefs);
272 * Return tables using locations.
274 public static function locTables() {
277 $locTables = ['civicrm_email', 'civicrm_address', 'civicrm_phone'];
279 // Allow hook_civicrm_merge() to adjust $locTables
280 CRM_Utils_Hook
::merge('locTables', $locTables);
286 * We treat multi-valued custom sets as "related tables" similar to activities, contributions, etc.
287 * @param string $request
288 * 'relTables' or 'cidRefs'.
292 public static function getMultiValueCustomSets($request) {
294 if (!isset(Civi
::$statics[__CLASS__
]['multiValueCustomSets'])) {
299 $result = civicrm_api3('custom_group', 'get', [
309 'return' => ['id', 'title', 'table_name', 'style'],
311 foreach ($result['values'] as $custom) {
312 $data['cidRefs'][$custom['table_name']] = ['entity_id'];
313 $urlSuffix = $custom['style'] == 'Tab' ?
'&selectedChild=custom_' . $custom['id'] : '';
314 $data['relTables']['rel_table_custom_' . $custom['id']] = [
315 'title' => $custom['title'],
316 'tables' => [$custom['table_name']],
317 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid' . $urlSuffix),
321 // Store the result in a static variable cache
322 Civi
::$statics[__CLASS__
]['multiValueCustomSets'] = $data;
325 return Civi
::$statics[__CLASS__
]['multiValueCustomSets'][$request];
329 * Tables which require custom processing should declare functions to call here.
330 * Doing so will override normal processing.
332 public static function cpTables() {
336 'civicrm_case_contact' => ['CRM_Case_BAO_Case' => 'mergeContacts'],
337 'civicrm_group_contact' => ['CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'],
338 // Empty array == do nothing - this table is handled by mergeGroupContact
339 'civicrm_subscription_history' => [],
340 'civicrm_relationship' => ['CRM_Contact_BAO_Relationship' => 'mergeRelationships'],
341 'civicrm_membership' => ['CRM_Member_BAO_Membership' => 'mergeMemberships'],
348 * Return payment related table.
350 public static function paymentTables() {
353 $tables = ['civicrm_pledge', 'civicrm_membership', 'civicrm_participant'];
359 * Return payment update Query.
361 * @param string $tableName
362 * @param int $mainContactId
363 * @param int $otherContactId
367 public static function paymentSql($tableName, $mainContactId, $otherContactId) {
369 if (!$tableName ||
!$mainContactId ||
!$otherContactId) {
373 $paymentTables = self
::paymentTables();
374 if (!in_array($tableName, $paymentTables)) {
378 switch ($tableName) {
379 case 'civicrm_pledge':
381 UPDATE IGNORE civicrm_contribution contribution
382 INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id )
383 INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id )
384 SET contribution.contact_id = $mainContactId
385 WHERE pledge.contact_id = $otherContactId";
388 case 'civicrm_membership':
390 UPDATE IGNORE civicrm_contribution contribution
391 INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id )
392 INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id )
393 SET contribution.contact_id = $mainContactId
394 WHERE membership.contact_id = $otherContactId";
397 case 'civicrm_participant':
399 UPDATE IGNORE civicrm_contribution contribution
400 INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id )
401 INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id )
402 SET contribution.contact_id = $mainContactId
403 WHERE participant.contact_id = $otherContactId";
412 * @param int $otherId
413 * @param string $tableName
414 * @param array $tableOperations
415 * @param string $mode
419 public static function operationSql($mainId, $otherId, $tableName, $tableOperations = [], $mode = 'add') {
421 if (!$tableName ||
!$mainId ||
!$otherId) {
425 switch ($tableName) {
426 case 'civicrm_membership':
427 if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add']) {
430 if ($mode == 'add') {
432 DELETE membership1.* FROM civicrm_membership membership1
433 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
434 AND membership1.contact_id = {$mainId}
435 AND membership2.contact_id = {$otherId} ";
437 if ($mode == 'payment') {
439 DELETE contribution.* FROM civicrm_contribution contribution
440 INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id
441 INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id
442 AND membership1.contact_id = {$mainId}
443 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
444 AND membership2.contact_id = {$otherId}";
448 case 'civicrm_uf_match':
449 // normal queries won't work for uf_match since that will lead to violation of unique constraint,
450 // failing to meet intended result. Therefore we introduce this additional query:
451 $sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}";
459 * Based on the provided two contact_ids and a set of tables, remove the
460 * belongings of the other contact and of their relations.
462 * @param int $otherID
463 * @param bool $tables
465 public static function removeContactBelongings($otherID, $tables) {
466 // CRM-20421: Removing Inherited memberships when memberships of parent are not migrated to new contact.
467 if (in_array("civicrm_membership", $tables)) {
468 $membershipIDs = CRM_Utils_Array
::collect('id',
469 CRM_Utils_Array
::value('values',
470 civicrm_api3("Membership", "get", [
471 "contact_id" => $otherID,
477 if (!empty($membershipIDs)) {
478 civicrm_api3("Membership", "get", [
479 'owner_membership_id' => ['IN' => $membershipIDs],
480 'api.Membership.delete' => ['id' => '$value.id'],
487 * Based on the provided two contact_ids and a set of tables, move the
488 * belongings of the other contact to the main one.
491 * @param int $otherId
492 * @param bool $tables
493 * @param array $tableOperations
494 * @param array $customTableToCopyFrom
496 public static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = [], $customTableToCopyFrom = NULL) {
497 $cidRefs = self
::cidRefs();
498 $eidRefs = self
::eidRefs();
499 $cpTables = self
::cpTables();
500 $paymentTables = self
::paymentTables();
502 // getting all custom tables
504 if ($customTableToCopyFrom !== NULL) {
505 // @todo this duplicates cidRefs?
506 CRM_Core_DAO
::appendCustomTablesExtendingContacts($customTables);
507 $customTables = array_keys($customTables);
510 $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
512 // if there aren't any specific tables, don't affect the ones handled by relTables()
513 // also don't affect tables in locTables() CRM-15658
514 $relTables = self
::relTables();
515 $handled = self
::locTables();
517 foreach ($relTables as $params) {
518 $handled = array_merge($handled, $params['tables']);
520 $affected = array_diff($affected, $handled);
521 $affected = array_unique(array_merge($affected, $tables));
523 $mainId = (int) $mainId;
524 $otherId = (int) $otherId;
525 $multi_value_tables = array_keys(CRM_Dedupe_Merger
::getMultiValueCustomSets('cidRefs'));
528 foreach ($affected as $table) {
529 // skipping non selected single-value custom table's value migration
530 if (!in_array($table, $multi_value_tables)) {
531 if ($customTableToCopyFrom !== NULL && in_array($table, $customTables) && !in_array($table, $customTableToCopyFrom)) {
536 // Call custom processing function for objects that require it
537 if (isset($cpTables[$table])) {
538 foreach ($cpTables[$table] as $className => $fnName) {
539 $className::$fnName($mainId, $otherId, $sqls, $tables, $tableOperations);
541 // Skip normal processing
545 // use UPDATE IGNORE + DELETE query pair to skip on situations when
546 // there's a UNIQUE restriction on ($field, some_other_field) pair
547 if (isset($cidRefs[$table])) {
548 foreach ($cidRefs[$table] as $field) {
549 // carry related contributions CRM-5359
550 if (in_array($table, $paymentTables)) {
551 $paymentSqls = self
::paymentSql($table, $mainId, $otherId);
552 $sqls = array_merge($sqls, $paymentSqls);
554 if (!empty($tables) && !in_array('civicrm_contribution', $tables)) {
555 $payOprSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations, 'payment');
556 $sqls = array_merge($sqls, $payOprSqls);
560 $preOperationSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations);
561 $sqls = array_merge($sqls, $preOperationSqls);
563 if ($customTableToCopyFrom !== NULL && in_array($table, $customTableToCopyFrom) && !self
::customRecordExists($mainId, $table, $field)) {
564 $sqls[] = "INSERT INTO $table ($field) VALUES ($mainId)";
566 $sqls[] = "UPDATE IGNORE $table SET $field = $mainId WHERE $field = $otherId";
567 $sqls[] = "DELETE FROM $table WHERE $field = $otherId";
571 if (isset($eidRefs[$table])) {
572 foreach ($eidRefs[$table] as $entityTable => $entityId) {
573 $sqls[] = "UPDATE IGNORE $table SET $entityId = $mainId WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
574 $sqls[] = "DELETE FROM $table WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
579 // Allow hook_civicrm_merge() to add SQL statements for the merge operation.
580 CRM_Utils_Hook
::merge('sqls', $sqls, $mainId, $otherId, $tables);
582 foreach ($sqls as $sql) {
583 CRM_Core_DAO
::executeQuery($sql, [], TRUE, NULL, TRUE);
585 CRM_Dedupe_Merger
::addMembershipToRealtedContacts($mainId);
589 * Given a contact ID, will check if a record exists in given table.
594 * Field where the contact's ID is stored in the table
597 * True if a record is found for the given contact ID, false otherwise
599 private static function customRecordExists($contactID, $table, $idField) {
601 SELECT COUNT(*) AS count
603 WHERE $idField = $contactID
605 $dbResult = CRM_Core_DAO
::executeQuery($sql);
608 if ($dbResult->count
> 0) {
616 * Load all non-empty fields for the contacts
620 * @param array $other
625 public static function retrieveFields($main, $other) {
630 foreach (self
::getContactFields() as $validField) {
631 // CRM-17556 Get all non-empty fields, to make comparison easier
632 if (!empty($main[$validField]) ||
!empty($other[$validField])) {
633 $result['contact'][] = $validField;
637 $mainEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($main['id']);
638 $otherEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($other['id']);
639 $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
640 foreach ($keys as $key) {
641 // Exclude multi-value fields CRM-13836
642 if (strpos($key, '_')) {
645 $key1 = CRM_Utils_Array
::value($key, $mainEvs);
646 $key2 = CRM_Utils_Array
::value($key, $otherEvs);
647 // We wish to retain '0' as it has a different meaning than NULL on a checkbox.
648 // However I can't think of a case where an empty string is more meaningful than null
649 // or where it would be FALSE or something else nullish.
650 $valuesToIgnore = [NULL, '', []];
651 if (!in_array($key1, $valuesToIgnore, TRUE) ||
!in_array($key2, $valuesToIgnore, TRUE)) {
652 $result['custom'][] = $key;
659 * Batch merge a set of contacts based on rule-group and group.
665 * @param string $mode
666 * Helps decide how to behave when there are conflicts.
667 * A 'safe' value skips the merge if there are any un-resolved conflicts, wheras 'aggressive'
668 * mode does a force merge.
669 * @param int $batchLimit number of merges to carry out in one batch.
670 * @param int $isSelected if records with is_selected column needs to be processed.
671 * Note the option of '2' is only used in conjunction with $redirectForPerformance
672 * to determine when to reload the cache (!). The use of anything other than a boolean is being grandfathered
673 * out in favour of explicitly passing in $reloadCacheIfEmpty
675 * @param array $criteria
676 * Criteria to use in the filter.
678 * @param bool $checkPermissions
679 * Respect logged in user permissions.
680 * @param bool|NULL $reloadCacheIfEmpty
681 * If not set explicitly this is calculated but it is preferred that it be set
682 * per comments on isSelected above.
686 public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $batchLimit = 1, $isSelected = 2, $criteria = [], $checkPermissions = TRUE, $reloadCacheIfEmpty = NULL) {
687 $redirectForPerformance = ($batchLimit > 1) ?
TRUE : FALSE;
689 if (!isset($reloadCacheIfEmpty)) {
690 $reloadCacheIfEmpty = (!$redirectForPerformance && $isSelected == 2);
692 if ($isSelected !== 0 && $isSelected !== 1) {
693 // explicitly set to NULL if not 1 or 0 as part of grandfathering out the mystical '2' value.
696 $dupePairs = self
::getDuplicatePairs($rgid, $gid, $reloadCacheIfEmpty, $batchLimit, $isSelected, ($mode == 'aggressive'), $criteria, $checkPermissions);
699 'cache_key_string' => self
::getMergeCacheKeyString($rgid, $gid, $criteria, $checkPermissions),
700 // @todo stop passing these parameters in & instead calculate them in the merge function based
701 // on the 'real' params like $isRespectExclusions $batchLimit and $isSelected.
702 'join' => self
::getJoinOnDedupeTable(),
703 'where' => self
::getWhereString($isSelected),
704 'limit' => (int) $batchLimit,
706 return CRM_Dedupe_Merger
::merge($dupePairs, $cacheParams, $mode, $redirectForPerformance, $checkPermissions);
710 * Get the string to join the prevnext cache to the dedupe table.
713 * The join string to join prevnext cache on the dedupe table.
715 public static function getJoinOnDedupeTable() {
717 LEFT JOIN civicrm_dedupe_exception de
719 pn.entity_id1 = de.contact_id1
720 AND pn.entity_id2 = de.contact_id2 )
725 * Get where string for dedupe join.
727 * @param bool $isSelected
731 protected static function getWhereString($isSelected) {
732 $where = "de.id IS NULL";
733 if ($isSelected === 0 ||
$isSelected === 1) {
734 $where .= " AND pn.is_selected = {$isSelected}";
740 * Update the statistics for the merge set.
742 * @param string $cacheKeyString
743 * @param array $result
745 public static function updateMergeStats($cacheKeyString, $result = []) {
746 // gather latest stats
747 $merged = count($result['merged']);
748 $skipped = count($result['skipped']);
750 if ($merged <= 0 && $skipped <= 0) {
754 // get previous stats
755 $previousStats = CRM_Dedupe_Merger
::getMergeStats($cacheKeyString);
756 if (!empty($previousStats)) {
757 if ($previousStats['merged']) {
758 $merged = $merged +
$previousStats['merged'];
760 if ($previousStats['skipped']) {
761 $skipped = $skipped +
$previousStats['skipped'];
766 CRM_Dedupe_Merger
::resetMergeStats($cacheKeyString);
768 // store the updated stats
771 'skipped' => $skipped,
773 $data = CRM_Core_DAO
::escapeString(serialize($data));
776 $values[] = " ( 'civicrm_contact', 0, 0, '{$cacheKeyString}_stats', '$data' ) ";
777 CRM_Core_BAO_PrevNextCache
::setItem($values);
781 * Delete information about merges for the given string.
783 * @param $cacheKeyString
785 public static function resetMergeStats($cacheKeyString) {
786 CRM_Core_BAO_PrevNextCache
::deleteItem(NULL, "{$cacheKeyString}_stats");
790 * Get merge outcome statistics.
792 * @param string $cacheKeyString
795 * Array of how many were merged and how many were skipped.
797 * @throws \CiviCRM_API3_Exception
799 public static function getMergeStats($cacheKeyString) {
800 $stats = civicrm_api3('Dedupe', 'get', ['cachekey' => "{$cacheKeyString}_stats", 'sequential' => 1])['values'];
801 if (!empty($stats)) {
802 return $stats[0]['data'];
808 * Get merge statistics message.
810 * @param array $stats
814 public static function getMergeStatsMsg($stats) {
816 if (!empty($stats['merged'])) {
817 $msg = '<p>' . ts('One contact merged.', [
818 'count' => $stats['merged'],
819 'plural' => '%count contacts merged.',
822 if (!empty($stats['skipped'])) {
823 $msg .= '<p>' . ts('One contact was skipped.', [
824 'count' => $stats['skipped'],
825 'plural' => '%count contacts were skipped.',
832 * Merge given set of contacts. Performs core operation.
834 * @param array $dupePairs
835 * Set of pair of contacts for whom merge is to be done.
836 * @param array $cacheParams
837 * Prev-next-cache params based on which next pair of contacts are computed.
838 * Generally used with batch-merge.
839 * @param string $mode
840 * Helps decide how to behave when there are conflicts.
841 * A 'safe' value skips the merge if there are any un-resolved conflicts.
842 * Does a force merge otherwise (aggressive mode).
844 * @param bool $redirectForPerformance
845 * Redirect to a url for batch processing.
847 * @param bool $checkPermissions
848 * Respect logged in user permissions.
852 public static function merge($dupePairs = [], $cacheParams = [], $mode = 'safe',
853 $redirectForPerformance = FALSE, $checkPermissions = TRUE
855 $cacheKeyString = CRM_Utils_Array
::value('cache_key_string', $cacheParams);
856 $resultStats = ['merged' => [], 'skipped' => []];
858 // we don't want dupe caching to get reset after every-merge, and therefore set the
859 CRM_Core_Config
::setPermitCacheFlushMode(FALSE);
860 $deletedContacts = [];
862 while (!empty($dupePairs)) {
863 foreach ($dupePairs as $index => $dupes) {
864 if (in_array($dupes['dstID'], $deletedContacts) ||
in_array($dupes['srcID'], $deletedContacts)) {
865 unset($dupePairs[$index]);
868 CRM_Utils_Hook
::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']);
869 $mainId = $dupes['dstID'];
870 $otherId = $dupes['srcID'];
872 if (!$mainId ||
!$otherId) {
877 self
::dedupePair($resultStats, $deletedContacts, $mode, $checkPermissions, $mainId, $otherId, $cacheKeyString);
880 if ($cacheKeyString && !$redirectForPerformance) {
881 // retrieve next pair of dupes
882 // @todo call getDuplicatePairs.
883 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString,
884 $cacheParams['join'],
885 $cacheParams['where'],
887 $cacheParams['limit'],
894 // do not proceed. Terminate the loop
899 CRM_Dedupe_Merger
::updateMergeStats($cacheKeyString, $resultStats);
904 * A function which uses various rules / algorithms for choosing which contact to bias to
905 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
908 * Main contact with whom merge has to happen.
909 * @param int $otherId
910 * Duplicate contact which would be deleted after merge operation.
911 * @param array $migrationInfo
912 * Array of information about which elements to merge.
913 * @param string $mode
914 * Helps decide how to behave when there are conflicts.
915 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
916 * - Does a force merge otherwise (aggressive mode).
918 * @param array $conflicts
919 * An empty array to be filed with conflict information.
923 public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe', &$conflicts = []) {
925 $conflicts = self
::getConflicts($migrationInfo, $mainId, $otherId, $mode);
927 if (!empty($conflicts)) {
928 foreach ($conflicts as $key => $val) {
929 if ($val === NULL and $mode == 'safe') {
930 // un-resolved conflicts still present. Lets skip this merge after saving the conflict / reason.
934 // copy over the resolved values
935 $migrationInfo[$key] = $val;
938 // if there are conflicts and mode is aggressive, allow hooks to decide if to skip merges
939 return (bool) $migrationInfo['skip_merge'];
945 * Compare 2 addresses to see if they are the same.
947 * @param array $mainAddress
948 * @param array $comparisonAddress
952 public static function locationIsSame($mainAddress, $comparisonAddress) {
962 foreach ($comparisonAddress as $field => $value) {
963 if (in_array($field, $keysToIgnore)) {
966 if ((!empty($value) ||
$value === '0') && isset($mainAddress[$field]) && $mainAddress[$field] != $value) {
974 * A function to build an array of information about location blocks that is
975 * required when merging location fields
979 public static function getLocationBlockInfo() {
982 'label' => 'Address',
983 'displayField' => 'display',
984 'sortString' => 'location_type_id',
985 'hasLocation' => TRUE,
990 'displayField' => 'display',
991 'sortString' => 'location_type_id',
992 'hasLocation' => TRUE,
997 'displayField' => 'name',
998 'sortString' => 'location_type_id,provider_id',
999 'hasLocation' => TRUE,
1000 'hasType' => 'provider_id',
1004 'displayField' => 'phone',
1005 'sortString' => 'location_type_id,phone_type_id',
1006 'hasLocation' => TRUE,
1007 'hasType' => 'phone_type_id',
1010 'label' => 'Website',
1011 'displayField' => 'url',
1012 'sortString' => 'website_type_id',
1013 'hasLocation' => FALSE,
1014 'hasType' => 'website_type_id',
1017 return $locationBlocks;
1021 * A function to build an array of information required by merge function and the merge UI.
1023 * @param int $mainId
1024 * Main contact with whom merge has to happen.
1025 * @param int $otherId
1026 * Duplicate contact which would be deleted after merge operation.
1027 * @param bool $checkPermissions
1028 * Should the logged in user's permissions be ignore. Setting this to false is
1029 * highly risky as it could cause data to be lost due to conflicts not showing up.
1030 * OTOH there is a risk a merger might view custom data they do not have permission to.
1031 * Hence for now only making this really explicit and making it reflect perms in
1034 * @todo review permissions issue!
1036 * @return array|bool|int
1038 * rows => An array of arrays, each is row of merge information for the table
1039 * Format: move_fieldname, eg: move_contact_type
1040 * main => Value associated with the main contact
1041 * other => Value associated with the other contact
1042 * title => The title of the field to display in the merge table
1044 * elements => An array of form elements for the merge UI
1046 * rel_table_elements => An array of form elements for the merge UI for
1047 * entities related to the contact (eg: checkbox to move 'mailings')
1049 * rel_tables => Stores the tables that have related entities for the contact
1050 * for example mailings, groups
1052 * main_details => An array of core contact field values, eg: first_name, etc.
1053 * location_blocks => An array of location block data for the main contact
1054 * stored as the 'result' of an API call.
1055 * eg: main_details['location_blocks']['address'][0]['id']
1056 * eg: main_details['location_blocks']['email'][1]['id']
1058 * other_details => As above, but for the 'other' contact
1060 * migration_info => Stores the 'default' merge actions for each field which
1061 * is used when programatically merging contacts. It contains instructions
1062 * to move all fields from the 'other' contact to the 'main' contact, as
1063 * though the form had been submitted with those options.
1065 * @throws \CRM_Core_Exception
1066 * @throws \CiviCRM_API3_Exception
1067 * @throws \Exception
1069 public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissions = TRUE) {
1070 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1071 $fields = self
::getMergeFieldsMetadata();
1073 $main = self
::getMergeContactDetails($mainId);
1074 $other = self
::getMergeContactDetails($otherId);
1076 $compareFields = self
::retrieveFields($main, $other);
1078 $rows = $elements = $relTableElements = $migrationInfo = [];
1080 foreach ($compareFields['contact'] as $field) {
1081 if ($field == 'contact_sub_type') {
1082 // CRM-15681 don't display sub-types in UI
1085 foreach (['main' => $main, 'other' => $other] as $moniker => $contact) {
1086 $value = $label = CRM_Utils_Array
::value($field, $contact);
1087 $fieldSpec = $fields[$field];
1088 if (!empty($fieldSpec['serialize']) && is_array($value)) {
1089 // In practice this only applies to preferred_communication_method as the sub types are skipped above
1090 // and no others are serialized.
1092 foreach ($value as $individualValue) {
1093 $labels[] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $field, $individualValue);
1095 $label = implode(', ', $labels);
1096 // We serialize this due to historic handling but it's likely that if we just left it as an
1097 // array all would be well & we would have less code.
1098 $value = CRM_Core_DAO
::serializeField($value, $fieldSpec['serialize']);
1100 elseif (!empty($fieldSpec['type']) && $fieldSpec['type'] == CRM_Utils_Type
::T_DATE
) {
1102 $value = str_replace('-', '', $value);
1103 $label = CRM_Utils_Date
::customFormat($label);
1109 elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type
::T_BOOLEAN
) {
1110 if ($label === '0') {
1113 if ($label === '1') {
1117 elseif (!empty($fieldSpec['pseudoconstant'])) {
1118 $label = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $field, $value);
1120 elseif ($field == 'current_employer_id' && !empty($value)) {
1121 $label = "$value (" . CRM_Contact_BAO_Contact
::displayName($value) . ")";
1123 $rows["move_$field"][$moniker] = $label;
1124 if ($moniker == 'other') {
1126 if ($value === NULL ||
$value == '') {
1129 if ($value === 0 or $value === '0') {
1130 $value = $qfZeroBug;
1132 if (is_array($value) && empty($value[1])) {
1136 // Display a checkbox to migrate, only if the values are different
1137 if ($value != $main[$field]) {
1148 $migrationInfo["move_$field"] = $value;
1151 $rows["move_$field"]['title'] = $fields[$field]['title'];
1154 // Handle location blocks.
1155 // @todo OpenID not in API yet, so is not supported here.
1157 // Set up useful information about the location blocks
1158 $locationBlocks = self
::getLocationBlockInfo();
1165 // @todo This could probably be defined and used earlier
1168 'other' => $otherId,
1171 foreach ($locationBlocks as $blockName => $blockInfo) {
1173 // Collect existing fields from both 'main' and 'other' contacts first
1174 // This allows us to match up location/types when building the table rows
1175 foreach ($mergeTargets as $moniker => $cid) {
1177 'contact_id' => $cid,
1178 // CRM-17556 Order by field-specific criteria
1180 'sort' => $blockInfo['sortString'],
1183 $values = civicrm_api3($blockName, 'get', $searchParams);
1184 if ($values['count']) {
1186 foreach ($values['values'] as $value) {
1187 $locations[$moniker][$blockName][$cnt] = $value;
1188 // Fix address display
1189 if ($blockName == 'address') {
1190 CRM_Core_BAO_Address
::fixAddress($value);
1191 $locations[$moniker][$blockName][$cnt]['display'] = CRM_Utils_Address
::format($value);
1193 // Fix email display
1194 elseif ($blockName == 'email') {
1195 $locations[$moniker][$blockName][$cnt]['display'] = CRM_Utils_Mail
::format($value);
1203 // Now, build the table rows appropriately, based off the information on
1204 // the 'other' contact
1205 if (!empty($locations['other']) && !empty($locations['other'][$blockName])) {
1206 foreach ($locations['other'][$blockName] as $count => $value) {
1208 $displayValue = $value[$blockInfo['displayField']];
1210 // Add this value to the table rows
1211 $rows["move_location_{$blockName}_{$count}"]['other'] = $displayValue;
1213 // CRM-17556 Only display 'main' contact value if it's the same location + type
1214 // Look it up from main values...
1216 $lookupLocation = FALSE;
1217 if ($blockInfo['hasLocation']) {
1218 $lookupLocation = $value['location_type_id'];
1221 $lookupType = FALSE;
1222 if ($blockInfo['hasType']) {
1223 $lookupType = CRM_Utils_Array
::value($blockInfo['hasType'], $value);
1226 // Hold ID of main contact's matching block
1227 $mainContactBlockId = 0;
1229 if (!empty($locations['main'][$blockName])) {
1230 foreach ($locations['main'][$blockName] as $mainValueCheck) {
1231 // No location/type, or matching location and type
1233 (empty($lookupLocation) ||
$lookupLocation == $mainValueCheck['location_type_id'])
1234 && (empty($lookupType) ||
$lookupType == $mainValueCheck[$blockInfo['hasType']])
1236 // Set this value as the default against the 'other' contact value
1237 $rows["move_location_{$blockName}_{$count}"]['main'] = $mainValueCheck[$blockInfo['displayField']];
1238 $rows["move_location_{$blockName}_{$count}"]['main_is_primary'] = $mainValueCheck['is_primary'];
1239 $rows["move_location_{$blockName}_{$count}"]['location_entity'] = $blockName;
1240 $mainContactBlockId = $mainValueCheck['id'];
1246 // Add checkbox to migrate data from 'other' to 'main'
1247 $elements[] = ['advcheckbox', "move_location_{$blockName}_{$count}"];
1249 // Add checkbox to set the 'other' location as primary
1252 "location_blocks[$blockName][$count][set_other_primary]",
1254 ts('Set as primary'),
1257 // Flag up this field to skipMerge function (@todo: do we need to?)
1258 $migrationInfo["move_location_{$blockName}_{$count}"] = 1;
1260 // Add a hidden field to store the ID of the target main contact block
1263 "location_blocks[$blockName][$count][mainContactBlockId]",
1264 $mainContactBlockId,
1268 $thisTypeId = FALSE;
1271 // Provide a select drop-down for the location's location type
1272 // eg: Home, Work...
1274 if ($blockInfo['hasLocation']) {
1276 // Load the location options for this entity
1277 $locationOptions = civicrm_api3($blockName, 'getoptions', ['field' => 'location_type_id']);
1279 $thisLocId = $value['location_type_id'];
1281 // Put this field's location type at the top of the list
1282 $tmpIdList = $locationOptions['values'];
1283 $defaultLocId = [$thisLocId => $tmpIdList[$thisLocId]];
1284 unset($tmpIdList[$thisLocId]);
1289 "location_blocks[$blockName][$count][locTypeId]",
1291 $defaultLocId +
$tmpIdList,
1294 // Add the relevant information to the $migrationInfo
1295 // Keep location-type-id same as that of other-contact
1296 // @todo Check this logic out
1297 $migrationInfo['location_blocks'][$blockName][$count]['locTypeId'] = $thisLocId;
1298 if ($blockName != 'address') {
1301 "location_blocks[{$blockName}][$count][operation]",
1305 // always use add operation
1306 $migrationInfo['location_blocks'][$blockName][$count]['operation'] = 1;
1311 // Provide a select drop-down for the location's type/provider
1312 // eg websites: Google+, Facebook...
1314 if ($blockInfo['hasType']) {
1316 // Load the type options for this entity
1317 $typeOptions = civicrm_api3($blockName, 'getoptions', ['field' => $blockInfo['hasType']]);
1319 $thisTypeId = CRM_Utils_Array
::value($blockInfo['hasType'], $value);
1321 // Put this field's location type at the top of the list
1322 $tmpIdList = $typeOptions['values'];
1323 $defaultTypeId = [$thisTypeId => CRM_Utils_Array
::value($thisTypeId, $tmpIdList)];
1324 unset($tmpIdList[$thisTypeId]);
1329 "location_blocks[$blockName][$count][typeTypeId]",
1331 $defaultTypeId +
$tmpIdList,
1334 // Add the information to the migrationInfo
1335 $migrationInfo['location_blocks'][$blockName][$count]['typeTypeId'] = $thisTypeId;
1339 // Set the label for this row
1340 $rowTitle = $blockInfo['label'] . ' ' . ($count +
1);
1341 if (!empty($thisLocId)) {
1342 $rowTitle .= ' (' . $locationOptions['values'][$thisLocId] . ')';
1344 if (!empty($thisTypeId)) {
1345 $rowTitle .= ' (' . $typeOptions['values'][$thisTypeId] . ')';
1347 $rows["move_location_{$blockName}_$count"]['title'] = $rowTitle;
1349 } // End loop through 'other' locations of this type
1351 } // End if 'other' location for this type exists
1353 } // End loop through each location block entity
1355 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1356 $config = CRM_Core_Config
::singleton();
1357 $mainUfId = CRM_Core_BAO_UFMatch
::getUFId($mainId);
1361 if ($config->userSystem
->is_drupal
== '1' && function_exists($mainUser)) {
1362 $mainUser = user_load($mainUfId);
1364 elseif ($config->userFramework
== 'Joomla') {
1365 $mainUser = JFactory
::getUser($mainUfId);
1368 $otherUfId = CRM_Core_BAO_UFMatch
::getUFId($otherId);
1372 if ($config->userSystem
->is_drupal
== '1' && function_exists($mainUser)) {
1373 $otherUser = user_load($otherUfId);
1375 elseif ($config->userFramework
== 'Joomla') {
1376 $otherUser = JFactory
::getUser($otherUfId);
1380 $relTables = CRM_Dedupe_Merger
::relTables();
1381 $activeRelTables = CRM_Dedupe_Merger
::getActiveRelTables($otherId);
1382 $activeMainRelTables = CRM_Dedupe_Merger
::getActiveRelTables($mainId);
1383 foreach ($relTables as $name => $null) {
1384 if (!in_array($name, $activeRelTables) &&
1385 !(($name == 'rel_table_users') && in_array($name, $activeMainRelTables))
1387 unset($relTables[$name]);
1391 $relTableElements[] = ['checkbox', "move_$name"];
1392 $migrationInfo["move_$name"] = 1;
1394 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1395 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1396 if ($name == 'rel_table_users') {
1397 $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
1398 $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
1399 $find = ['$ufid', '$ufname'];
1401 $replace = [$mainUfId, $mainUser->name
];
1402 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1405 $replace = [$otherUfId, $otherUser->name
];
1406 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1409 if ($name == 'rel_table_memberships') {
1410 //Enable 'add new' checkbox if main contact does not contain any membership similar to duplicate contact.
1411 $attributes = ['checked' => 'checked'];
1412 $otherContactMemberships = CRM_Member_BAO_Membership
::getAllContactMembership($otherId);
1413 foreach ($otherContactMemberships as $membership) {
1414 $mainMembership = CRM_Member_BAO_Membership
::getContactMembership($mainId, $membership['membership_type_id'], FALSE);
1415 if ($mainMembership) {
1421 "operation[move_{$name}][add]",
1426 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1429 foreach ($relTables as $name => $null) {
1430 $relTables["move_$name"] = $relTables[$name];
1431 unset($relTables[$name]);
1434 // handle custom fields
1435 $mainTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], NULL, $mainId, -1,
1436 CRM_Utils_Array
::value('contact_sub_type', $main), NULL, TRUE, NULL, TRUE, $checkPermissions
1438 $otherTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], NULL, $otherId, -1,
1439 CRM_Utils_Array
::value('contact_sub_type', $other), NULL, TRUE, NULL, TRUE, $checkPermissions
1442 foreach ($otherTree as $gid => $group) {
1443 $foundField = FALSE;
1444 if (!isset($group['fields'])) {
1448 foreach ($group['fields'] as $fid => $field) {
1449 if (in_array($fid, $compareFields['custom'])) {
1451 $rows["custom_group_$gid"]['title'] = $group['title'];
1454 if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) {
1455 foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1456 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomField
::displayValue($values['data'], $fid);
1460 if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) {
1461 foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1462 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomField
::displayValue($values['data'], $fid);
1463 if ($values['data'] === 0 ||
$values['data'] === '0') {
1464 $values['data'] = $qfZeroBug;
1466 $value = ($values['data']) ?
$values['data'] : $value;
1469 $rows["move_custom_$fid"]['title'] = $field['label'];
1479 $migrationInfo["move_custom_$fid"] = $value;
1486 'elements' => $elements,
1487 'rel_table_elements' => $relTableElements,
1488 'rel_tables' => $relTables,
1489 'main_details' => $main,
1490 'other_details' => $other,
1491 'migration_info' => $migrationInfo,
1494 $result['main_details']['location_blocks'] = $locations['main'];
1495 $result['other_details']['location_blocks'] = $locations['other'];
1501 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1502 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1503 * A superset of moveContactBelongings() function.
1505 * @param int $mainId
1506 * Main contact with whom merge has to happen.
1507 * @param int $otherId
1508 * Duplicate contact which would be deleted after merge operation.
1510 * @param $migrationInfo
1512 * @param bool $checkPermissions
1513 * Respect logged in user permissions.
1517 public static function moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions = TRUE) {
1518 if (empty($migrationInfo)) {
1521 // Encapsulate in a transaction to avoid half-merges.
1522 $transaction = new CRM_Core_Transaction();
1524 $contactType = $migrationInfo['main_details']['contact_type'];
1525 $relTables = CRM_Dedupe_Merger
::relTables();
1526 $submittedCustomFields = $moveTables = $tableOperations = $removeTables = [];
1528 self
::swapOutFieldsAffectedByQFZeroBug($migrationInfo);
1529 foreach ($migrationInfo as $key => $value) {
1531 if (substr($key, 0, 12) == 'move_custom_' && $value != NULL) {
1532 $submitted[substr($key, 5)] = $value;
1533 $submittedCustomFields[] = substr($key, 12);
1535 elseif (in_array(substr($key, 5), CRM_Dedupe_Merger
::getContactFields()) && $value != NULL) {
1536 $submitted[substr($key, 5)] = $value;
1538 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1539 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1540 if (array_key_exists('operation', $migrationInfo)) {
1541 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1542 if (array_key_exists($key, $migrationInfo['operation'])) {
1543 $tableOperations[$table] = $migrationInfo['operation'][$key];
1548 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '0') {
1549 $removeTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1552 self
::mergeLocations($mainId, $otherId, $migrationInfo);
1554 // **** Do contact related migrations
1555 $customTablesToCopyValues = self
::getAffectedCustomTables($submittedCustomFields);
1556 CRM_Dedupe_Merger
::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations, $customTablesToCopyValues);
1557 unset($moveTables, $tableOperations);
1559 // **** Do table related removals
1560 if (!empty($removeTables)) {
1562 CRM_Dedupe_Merger
::removeContactBelongings($otherId, $removeTables);
1566 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
1567 $names['gender'] = ['newName' => 'gender_id', 'groupName' => 'gender'];
1568 $names['individual_prefix'] = [
1569 'newName' => 'prefix_id',
1570 'groupName' => 'individual_prefix',
1572 $names['individual_suffix'] = [
1573 'newName' => 'suffix_id',
1574 'groupName' => 'individual_suffix',
1576 $names['communication_style'] = [
1577 'newName' => 'communication_style_id',
1578 'groupName' => 'communication_style',
1580 $names['addressee'] = [
1581 'newName' => 'addressee_id',
1582 'groupName' => 'addressee',
1584 $names['email_greeting'] = [
1585 'newName' => 'email_greeting_id',
1586 'groupName' => 'email_greeting',
1588 $names['postal_greeting'] = [
1589 'newName' => 'postal_greeting_id',
1590 'groupName' => 'postal_greeting',
1592 CRM_Core_OptionGroup
::lookupValues($submitted, $names, TRUE);
1593 // fix custom fields so they're edible by createProfileContact()
1594 $cFields = self
::getCustomFieldMetadata($contactType);
1596 if (!isset($submitted)) {
1600 foreach ($submitted as $key => $value) {
1601 list($cFields, $customFiles, $submitted) = self
::processCustomFields($mainId, $key, $cFields, $customFiles, $submitted, $value);
1604 self
::processCustomFieldFiles($mainId, $otherId, $customFiles);
1606 // move view only custom fields CRM-5362
1607 $viewOnlyCustomFields = [];
1608 foreach ($submitted as $key => $value) {
1609 $fid = CRM_Core_BAO_CustomField
::getKeyID($key);
1610 if ($fid && array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])
1612 $viewOnlyCustomFields[$key] = $value;
1615 // special case to set values for view only, CRM-5362
1616 if (!empty($viewOnlyCustomFields)) {
1617 $viewOnlyCustomFields['entityID'] = $mainId;
1618 CRM_Core_BAO_CustomValueTable
::setValues($viewOnlyCustomFields);
1621 if (!$checkPermissions ||
(CRM_Core_Permission
::check('merge duplicate contacts') &&
1622 CRM_Core_Permission
::check('delete contacts'))
1624 // if ext id is submitted then set it null for contact to be deleted
1625 if (!empty($submitted['external_identifier'])) {
1626 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1627 CRM_Core_DAO
::executeQuery($query);
1629 civicrm_api3('contact', 'delete', ['id' => $otherId]);
1632 // CRM-15681 merge sub_types
1633 if ($other_sub_types = CRM_Utils_Array
::value('contact_sub_type', $migrationInfo['other_details'])) {
1634 if ($main_sub_types = CRM_Utils_Array
::value('contact_sub_type', $migrationInfo['main_details'])) {
1635 $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types));
1638 $submitted['contact_sub_type'] = $other_sub_types;
1642 // **** Update contact related info for the main contact
1643 if (!empty($submitted)) {
1644 $submitted['contact_id'] = $mainId;
1646 //update current employer field
1647 if ($currentEmloyerId = CRM_Utils_Array
::value('current_employer_id', $submitted)) {
1648 if (!CRM_Utils_System
::isNull($currentEmloyerId)) {
1649 $submitted['current_employer'] = $submitted['current_employer_id'];
1652 $submitted['current_employer'] = '';
1654 unset($submitted['current_employer_id']);
1657 //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
1658 if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) {
1659 $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
1661 if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) {
1662 $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
1665 CRM_Contact_BAO_Contact
::createProfileContact($submitted, CRM_Core_DAO
::$_nullArray, $mainId);
1667 $transaction->commit();
1668 CRM_Utils_Hook
::post('merge', 'Contact', $mainId);
1669 self
::createMergeActivities($mainId, $otherId);
1675 * Builds an Array of Custom tables for given custom field ID's.
1677 * @param $customFieldIDs
1680 * Array of custom table names
1682 private static function getAffectedCustomTables($customFieldIDs) {
1683 $customTableToCopyValues = [];
1685 foreach ($customFieldIDs as $fieldID) {
1686 if (!empty($fieldID)) {
1687 $customField = civicrm_api3('custom_field', 'getsingle', [
1689 'is_active' => TRUE,
1691 if (!civicrm_error($customField) && !empty($customField['custom_group_id'])) {
1692 $customGroup = civicrm_api3('custom_group', 'getsingle', [
1693 'id' => $customField['custom_group_id'],
1694 'is_active' => TRUE,
1697 if (!civicrm_error($customGroup) && !empty($customGroup['table_name'])) {
1698 $customTableToCopyValues[] = $customGroup['table_name'];
1704 return $customTableToCopyValues;
1708 * Get fields in the contact table suitable for merging.
1711 * Array of field names to be potentially merged.
1713 public static function getContactFields() {
1714 $contactFields = CRM_Contact_DAO_Contact
::fields();
1722 'primary_contact_id',
1726 foreach ($contactFields as $field => $value) {
1727 if (in_array($field, $invalidFields)) {
1728 unset($contactFields[$field]);
1731 return array_keys($contactFields);
1735 * Added for CRM-12695
1736 * Based on the contactID provided
1737 * add/update membership(s) to related contacts
1739 * @param int $contactID
1741 public static function addMembershipToRealtedContacts($contactID) {
1742 $dao = new CRM_Member_DAO_Membership();
1743 $dao->contact_id
= $contactID;
1747 //checks membership of contact itself
1748 while ($dao->fetch()) {
1749 $relationshipTypeId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id
, 'relationship_type_id', 'id');
1750 if ($relationshipTypeId) {
1751 $membershipParams = [
1753 'contact_id' => $dao->contact_id
,
1754 'membership_type_id' => $dao->membership_type_id
,
1755 'join_date' => CRM_Utils_Date
::isoToMysql($dao->join_date
),
1756 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
1757 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
1758 'source' => $dao->source
,
1759 'status_id' => $dao->status_id
,
1761 // create/update membership(s) for related contact(s)
1762 CRM_Member_BAO_Membership
::createRelatedMemberships($membershipParams, $dao);
1763 } // end of if relationshipTypeId
1768 * Create activities tracking the merge on affected contacts.
1770 * @param int $mainId
1771 * @param int $otherId
1773 * @throws \CiviCRM_API3_Exception
1775 public static function createMergeActivities($mainId, $otherId) {
1780 $activity = civicrm_api3('activity', 'create', [
1781 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
1783 'subject' => ts('Contact ID %1 has been merged and deleted.', $params),
1784 'target_contact_id' => $mainId,
1785 'activity_type_id' => 'Contact Merged',
1786 'status_id' => 'Completed',
1788 if (civicrm_api3('Setting', 'getvalue', [
1789 'name' => 'contact_undelete',
1790 'group' => 'CiviCRM Preferences',
1792 civicrm_api3('activity', 'create', [
1793 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
1795 'subject' => ts('Contact ID %1 has been merged into Contact ID %2 and deleted.', $params),
1796 'target_contact_id' => $otherId,
1797 'activity_type_id' => 'Contact Deleted by Merge',
1798 'parent_id' => $activity['id'],
1799 'status_id' => 'Completed',
1805 * Get Duplicate Pairs based on a rule for a group.
1807 * @param int $rule_group_id
1808 * @param int $group_id
1809 * @param bool $reloadCacheIfEmpty
1810 * Should the cache be reloaded if empty - this must be false when in a dedupe action!
1811 * @param int $batchLimit
1812 * @param bool $isSelected
1813 * Limit to selected pairs.
1814 * @param bool $includeConflicts
1815 * @param array $criteria
1816 * Additional criteria to narrow down the merge group.
1818 * @param bool $checkPermissions
1819 * Respect logged in user permissions.
1821 * @param int $searchLimit
1822 * Limit to searching for matches against this many contacts.
1825 * Array of matches meeting the criteria.
1827 * @throws \CRM_Core_Exception
1828 * @throws \CiviCRM_API3_Exception
1830 public static function getDuplicatePairs($rule_group_id, $group_id, $reloadCacheIfEmpty, $batchLimit, $isSelected, $includeConflicts = TRUE, $criteria = [], $checkPermissions = TRUE, $searchLimit = 0) {
1831 $dupePairs = self
::getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, $includeConflicts, $criteria, $checkPermissions);
1832 if (empty($dupePairs) && $reloadCacheIfEmpty) {
1833 $cacheKeyString = CRM_Dedupe_Merger
::getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions);
1834 // If we haven't found any dupes, probably cache is empty.
1835 // Try filling cache and give another try. We don't need to specify include conflicts here are there will not be any
1836 // until we have done some processing.
1837 CRM_Core_BAO_PrevNextCache
::refillCache($rule_group_id, $group_id, $cacheKeyString, $criteria, $checkPermissions, $searchLimit);
1838 return self
::getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, FALSE, $criteria, $checkPermissions);
1844 * Get the cache key string for the merge action.
1846 * @param int $rule_group_id
1847 * @param int $group_id
1848 * @param array $criteria
1849 * Additional criteria to narrow down the merge group.
1850 * Currently we are only supporting the key 'contact' within it.
1852 * @param bool $checkPermissions
1853 * Respect the users permissions.
1857 public static function getMergeCacheKeyString($rule_group_id, $group_id, $criteria = [], $checkPermissions = TRUE) {
1858 $contactType = CRM_Dedupe_BAO_RuleGroup
::getContactTypeForRuleGroup($rule_group_id);
1859 $cacheKeyString = "merge_{$contactType}";
1860 $cacheKeyString .= $rule_group_id ?
"_{$rule_group_id}" : '_0';
1861 $cacheKeyString .= $group_id ?
"_{$group_id}" : '_0';
1862 $cacheKeyString .= !empty($criteria) ?
md5(serialize($criteria)) : '_0';
1863 if ($checkPermissions) {
1864 $contactID = CRM_Core_Session
::getLoggedInContactID();
1866 // Distinguish between no permission check & no logged in user.
1867 $contactID = 'null';
1869 $cacheKeyString .= '_' . $contactID;
1872 $cacheKeyString .= '_0';
1874 return $cacheKeyString;
1878 * Get the metadata for the merge fields.
1880 * This is basically the contact metadata, augmented with fields to
1881 * represent email greeting, postal greeting & addressee.
1885 public static function getMergeFieldsMetadata() {
1886 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['merge_fields_metadata'])) {
1887 return \Civi
::$statics[__CLASS__
]['merge_fields_metadata'];
1889 $fields = CRM_Contact_DAO_Contact
::fields();
1890 static $optionValueFields = [];
1891 if (empty($optionValueFields)) {
1892 $optionValueFields = CRM_Core_OptionValue
::getFields();
1894 foreach ($optionValueFields as $field => $params) {
1895 $fields[$field]['title'] = $params['title'];
1897 \Civi
::$statics[__CLASS__
]['merge_fields_metadata'] = $fields;
1898 return \Civi
::$statics[__CLASS__
]['merge_fields_metadata'];
1902 * Get the details of the contact to be merged.
1904 * @param int $contact_id
1908 * @throws CRM_Core_Exception
1910 public static function getMergeContactDetails($contact_id) {
1912 'contact_id' => $contact_id,
1914 'return' => array_merge(['display_name'], self
::getContactFields()),
1916 $result = civicrm_api('contact', 'get', $params);
1918 // CRM-18480: Cancel the process if the contact is already deleted
1919 if (isset($result['values'][$contact_id]['contact_is_deleted']) && !empty($result['values'][$contact_id]['contact_is_deleted'])) {
1920 throw new CRM_Core_Exception(ts('Cannot merge because one contact (ID %1) has been deleted.', [
1925 return $result['values'][$contact_id];
1931 * Based on the data in the $locationMigrationInfo merge the locations for 2 contacts.
1933 * The data is in the format received from the merge form (which is a fairly confusing format).
1935 * It is converted into an array of DAOs which is passed to the alterLocationMergeData hook
1936 * before saving or deleting the DAOs. A new hook is added to allow these to be altered after they have
1937 * been calculated and before saving because
1938 * - the existing format & hook combo is so confusing it is hard for developers to change & inherently fragile
1939 * - passing to a hook right before save means calculations only have to be done once
1940 * - the existing pattern of passing dissimilar data to the same (merge) hook with a different 'type' is just
1943 * The use of the new hook is tested, including the fact it is called before contributions are merged, as this
1944 * is likely to be significant data in merge hooks.
1946 * @param int $mainId
1947 * @param int $otherId
1949 * @param array $migrationInfo
1950 * Migration info for the merge. This is passed to the hook as informational only.
1952 public static function mergeLocations($mainId, $otherId, $migrationInfo) {
1953 foreach ($migrationInfo as $key => $value) {
1954 $isLocationField = (substr($key, 0, 14) == 'move_location_' and $value != NULL);
1955 if (!$isLocationField) {
1958 $locField = explode('_', $key);
1959 $fieldName = $locField[2];
1960 $fieldCount = $locField[3];
1962 // Set up the operation type (add/overwrite)
1963 // Ignore operation for websites
1964 // @todo Tidy this up
1966 if ($fieldName != 'website') {
1967 $operation = CRM_Utils_Array
::value('operation', $migrationInfo['location_blocks'][$fieldName][$fieldCount]);
1969 // default operation is overwrite.
1973 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
1977 // @todo Handle OpenID (not currently in API).
1978 if (!empty($locBlocks)) {
1979 $locationBlocks = self
::getLocationBlockInfo();
1981 $primaryBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, ['is_primary' => 1]);
1982 $billingBlockIds = CRM_Contact_BAO_Contact
::getLocBlockIds($mainId, ['is_billing' => 1]);
1984 foreach ($locBlocks as $name => $block) {
1985 $blocksDAO[$name] = ['delete' => [], 'update' => []];
1986 if (!is_array($block) || CRM_Utils_System
::isNull($block)) {
1989 $daoName = 'CRM_Core_DAO_' . $locationBlocks[$name]['label'];
1990 $changePrimary = FALSE;
1991 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ?
array_pop($primaryBlockIds[$name]) : NULL;
1992 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ?
array_pop($billingBlockIds[$name]) : NULL;
1994 foreach ($block as $blkCount => $values) {
1995 $otherBlockId = CRM_Utils_Array
::value('id', $migrationInfo['other_details']['location_blocks'][$name][$blkCount]);
1996 $mainBlockId = CRM_Utils_Array
::value('mainContactBlockId', $migrationInfo['location_blocks'][$name][$blkCount], 0);
1997 if (!$otherBlockId) {
2001 // For the block which belongs to other-contact, link the location block to main-contact
2002 $otherBlockDAO = new $daoName();
2003 $otherBlockDAO->contact_id
= $mainId;
2005 // Get the ID of this block on the 'other' contact, otherwise skip
2006 $otherBlockDAO->id
= $otherBlockId;
2008 // Add/update location and type information from the form, if applicable
2009 if ($locationBlocks[$name]['hasLocation']) {
2010 $locTypeId = CRM_Utils_Array
::value('locTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
2011 $otherBlockDAO->location_type_id
= $locTypeId;
2013 if ($locationBlocks[$name]['hasType']) {
2014 $typeTypeId = CRM_Utils_Array
::value('typeTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
2015 $otherBlockDAO->{$locationBlocks[$name]['hasType']} = $typeTypeId;
2018 // If we're deliberately setting this as primary then add the flag
2019 // and remove it from the current primary location (if there is one).
2020 // But only once for each entity.
2021 $set_primary = CRM_Utils_Array
::value('set_other_primary', $migrationInfo['location_blocks'][$name][$blkCount]);
2022 if (!$changePrimary && $set_primary == "1") {
2023 $otherBlockDAO->is_primary
= 1;
2024 if ($primaryDAOId) {
2025 $removePrimaryDAO = new $daoName();
2026 $removePrimaryDAO->id
= $primaryDAOId;
2027 $removePrimaryDAO->is_primary
= 0;
2028 $blocksDAO[$name]['update'][$primaryDAOId] = $removePrimaryDAO;
2030 $changePrimary = TRUE;
2032 // Otherwise, if main contact already has primary, set it to 0.
2033 elseif ($primaryDAOId) {
2034 $otherBlockDAO->is_primary
= 0;
2037 // If the main contact already has a billing location, set this to 0.
2038 if ($billingDAOId) {
2039 $otherBlockDAO->is_billing
= 0;
2042 $operation = CRM_Utils_Array
::value('operation', $values, 2);
2043 // overwrite - need to delete block which belongs to main-contact.
2044 if (!empty($mainBlockId) && ($operation == 2)) {
2045 $deleteDAO = new $daoName();
2046 $deleteDAO->id
= $mainBlockId;
2047 $deleteDAO->find(TRUE);
2049 // if we about to delete a primary / billing block, set the flags for new block
2050 // that we going to assign to main-contact
2051 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id
)) {
2052 $otherBlockDAO->is_primary
= 1;
2054 if ($billingDAOId && ($billingDAOId == $deleteDAO->id
)) {
2055 $otherBlockDAO->is_billing
= 1;
2057 $blocksDAO[$name]['delete'][$deleteDAO->id
] = $deleteDAO;
2059 $blocksDAO[$name]['update'][$otherBlockDAO->id
] = $otherBlockDAO;
2064 CRM_Utils_Hook
::alterLocationMergeData($blocksDAO, $mainId, $otherId, $migrationInfo);
2065 foreach ($blocksDAO as $blockDAOs) {
2066 if (!empty($blockDAOs['update'])) {
2067 foreach ($blockDAOs['update'] as $blockDAO) {
2071 if (!empty($blockDAOs['delete'])) {
2072 foreach ($blockDAOs['delete'] as $blockDAO) {
2073 $blockDAO->delete();
2080 * Dedupe a pair of contacts.
2082 * @param array $resultStats
2083 * @param array $deletedContacts
2084 * @param string $mode
2085 * @param bool $checkPermissions
2086 * @param int $mainId
2087 * @param int $otherId
2088 * @param string $cacheKeyString
2090 * @throws \CRM_Core_Exception
2091 * @throws \CiviCRM_API3_Exception
2093 protected static function dedupePair(&$resultStats, &$deletedContacts, $mode, $checkPermissions, $mainId, $otherId, $cacheKeyString) {
2095 // Generate var $migrationInfo. The variable structure is exactly same as
2096 // $formValues submitted during a UI merge for a pair of contacts.
2097 $rowsElementsAndInfo = CRM_Dedupe_Merger
::getRowsElementsAndInfo($mainId, $otherId, $checkPermissions);
2098 // add additional details that we might need to resolve conflicts
2099 $rowsElementsAndInfo['migration_info']['main_details'] = &$rowsElementsAndInfo['main_details'];
2100 $rowsElementsAndInfo['migration_info']['other_details'] = &$rowsElementsAndInfo['other_details'];
2101 $rowsElementsAndInfo['migration_info']['rows'] = &$rowsElementsAndInfo['rows'];
2102 $migrationInfo = $rowsElementsAndInfo['migration_info'];
2103 // go ahead with merge if there is no conflict
2105 if (!CRM_Dedupe_Merger
::skipMerge($mainId, $otherId, $migrationInfo, $mode, $conflicts)) {
2106 CRM_Dedupe_Merger
::moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions);
2107 $resultStats['merged'][] = [
2108 'main_id' => $mainId,
2109 'other_id' => $otherId,
2111 $deletedContacts[] = $otherId;
2114 $resultStats['skipped'][] = [
2115 'main_id' => $mainId,
2116 'other_id' => $otherId,
2120 // store any conflicts
2121 if (!empty($conflicts)) {
2122 foreach ($conflicts as $key => $dnc) {
2123 $conflicts[$key] = "{$migrationInfo['rows'][$key]['title']}: '{$migrationInfo['rows'][$key]['main']}' vs. '{$migrationInfo['rows'][$key]['other']}'";
2125 CRM_Core_BAO_PrevNextCache
::markConflict($mainId, $otherId, $cacheKeyString, $conflicts);
2128 CRM_Core_BAO_PrevNextCache
::deletePair($mainId, $otherId, $cacheKeyString);
2133 * Replace the pseudo QFKey with zero if it is present.
2135 * @todo - on the slim chance this is still relevant it should be moved to the form layer.
2137 * Details about this bug are somewhat obscured by the move from svn but perhaps JIRA
2140 * @param array $migrationInfo
2142 protected static function swapOutFieldsAffectedByQFZeroBug(&$migrationInfo) {
2143 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
2144 foreach ($migrationInfo as $key => &$value) {
2145 if ($value == $qfZeroBug) {
2152 * Honestly - what DOES this do - hopefully some refactoring will reveal it's purpose.
2157 * @param $customFiles
2163 protected static function processCustomFields($mainId, $key, $cFields, $customFiles, $submitted, $value) {
2164 if (substr($key, 0, 7) == 'custom_') {
2165 $fid = (int) substr($key, 7);
2166 if (empty($cFields[$fid])) {
2167 return [$cFields, $customFiles, $submitted];
2169 $htmlType = $cFields[$fid]['attributes']['html_type'];
2170 switch ($htmlType) {
2172 $customFiles[] = $fid;
2173 unset($submitted["custom_$fid"]);
2176 case 'Select Country':
2177 case 'Select State/Province':
2178 $submitted[$key] = CRM_Core_BAO_CustomField
::displayValue($value, $fid);
2182 if ($cFields[$fid]['attributes']['is_view']) {
2183 $submitted[$key] = date('YmdHis', strtotime($submitted[$key]));
2188 case 'Multi-Select':
2189 case 'Multi-Select Country':
2190 case 'Multi-Select State/Province':
2191 // Merge values from both contacts for multivalue fields, CRM-4385
2192 // get the existing custom values from db.
2193 $customParams = ['entityID' => $mainId, $key => TRUE];
2194 $customfieldValues = CRM_Core_BAO_CustomValueTable
::getValues($customParams);
2195 if (!empty($customfieldValues[$key])) {
2196 $existingValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customfieldValues[$key]);
2197 if (is_array($existingValue) && !empty($existingValue)) {
2198 $mergeValue = $submittedCustomFields = [];
2199 if ($value == 'null') {
2200 // CRM-19074 if someone has deliberately chosen to overwrite with 'null', respect it.
2201 $submitted[$key] = $value;
2205 $submittedCustomFields = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2208 // CRM-19653: overwrite or add the existing custom field value with dupicate contact's
2209 // custom field value stored at $submittedCustomValue.
2210 foreach ($submittedCustomFields as $k => $v) {
2211 if ($v != '' && !in_array($v, $mergeValue)) {
2216 //keep state and country as array format.
2217 //for checkbox and m-select format w/ VALUE_SEPARATOR
2218 if (in_array($htmlType, [
2222 $submitted[$key] = CRM_Core_DAO
::VALUE_SEPARATOR
. implode(CRM_Core_DAO
::VALUE_SEPARATOR
,
2224 ) . CRM_Core_DAO
::VALUE_SEPARATOR
;
2227 $submitted[$key] = $mergeValue;
2232 elseif (in_array($htmlType, [
2233 'Multi-Select Country',
2234 'Multi-Select State/Province',
2236 //we require submitted values should be in array format
2238 $mergeValueArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2239 //hack to remove null values from array.
2241 foreach ($mergeValueArray as $k => $v) {
2246 $submitted[$key] = $mergeValue;
2255 return [$cFields, $customFiles, $submitted];
2259 * Get metadata for the custom fields for the merge.
2261 * @param string $contactType
2265 protected static function getCustomFieldMetadata($contactType) {
2267 if (!array_key_exists($contactType, $treeCache)) {
2268 $treeCache[$contactType] = CRM_Core_BAO_CustomGroup
::getTree(
2283 foreach ($treeCache[$contactType] as $key => $group) {
2284 if (!isset($group['fields'])) {
2287 foreach ($group['fields'] as $fid => $field) {
2288 $cFields[$fid]['attributes'] = $field;
2295 * Get conflicts for proposed merge pair.
2297 * @param array $migrationInfo
2298 * This is primarily to inform hooks. The can also modify it which feels
2299 * pretty fragile to do it here - but it is historical.
2300 * @param int $mainId
2301 * Main contact with whom merge has to happen.
2302 * @param int $otherId
2303 * Duplicate contact which would be deleted after merge operation.
2304 * @param string $mode
2305 * Helps decide how to behave when there are conflicts.
2306 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
2307 * - Does a force merge otherwise (aggressive mode).
2311 public static function getConflicts(&$migrationInfo, $mainId, $otherId, $mode) {
2313 $originalMigrationInfo = $migrationInfo;
2314 foreach ($migrationInfo as $key => $val) {
2315 if ($val === "null") {
2316 // Rule: Never overwrite with an empty value (in any mode)
2317 unset($migrationInfo[$key]);
2320 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger
::getContactFields()) or
2321 substr($key, 0, 12) == 'move_custom_'
2324 // Rule: If both main-contact, and other-contact have a field with a
2325 // different value, then let $mode decide if to merge it or not
2327 (!empty($migrationInfo['rows'][$key]['main'])
2328 // For custom fields a 0 (e.g in an int field) could be a true conflict. This
2329 // is probably true for other fields too - e.g. 'do_not_email' but
2330 // leaving that investigation as a @todo - until tests can be written.
2331 // Note the handling of this has test coverage - although the data-typing
2332 // of '0' feels flakey we have insurance.
2333 ||
($migrationInfo['rows'][$key]['main'] === '0' && substr($key, 0, 12) == 'move_custom_')
2335 && $migrationInfo['rows'][$key]['main'] != $migrationInfo['rows'][$key]['other']
2338 // note it down & lets wait for response from the hook.
2339 // For no response $mode will decide if to skip this merge
2340 $conflicts[$key] = NULL;
2343 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
2344 $locField = explode('_', $key);
2345 $fieldName = $locField[2];
2346 $fieldCount = $locField[3];
2348 // Rule: Catch address conflicts (same address type on both contacts)
2350 isset($migrationInfo['main_details']['location_blocks'][$fieldName]) &&
2351 !empty($migrationInfo['main_details']['location_blocks'][$fieldName])
2354 // Load the address we're inspecting from the 'other' contact
2355 $addressRecord = $migrationInfo['other_details']['location_blocks'][$fieldName][$fieldCount];
2356 $addressRecordLocTypeId = CRM_Utils_Array
::value('location_type_id', $addressRecord);
2358 // If it exists on the 'main' contact already, skip it. Otherwise
2359 // if the location type exists already, log a conflict.
2360 foreach ($migrationInfo['main_details']['location_blocks'][$fieldName] as $mainAddressKey => $mainAddressRecord) {
2361 if (self
::locationIsSame($addressRecord, $mainAddressRecord)) {
2362 unset($migrationInfo[$key]);
2365 elseif ($addressRecordLocTypeId == $mainAddressRecord['location_type_id']) {
2366 $conflicts[$key] = NULL;
2372 // For other locations, don't merge/add if the values are the same
2373 elseif (CRM_Utils_Array
::value('main', $migrationInfo['rows'][$key]) == $migrationInfo['rows'][$key]['other']) {
2374 unset($migrationInfo[$key]);
2379 // A hook to implement other algorithms for choosing which contact to bias to when
2380 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
2381 // merge happens with new values filled in here. For a particular field / row not to be merged
2382 // field should be unset from fields_in_conflict.
2384 'old_migration_info' => $originalMigrationInfo,
2386 'fields_in_conflict' => $conflicts,
2387 'merge_mode' => $mode,
2388 'migration_info' => $migrationInfo,
2390 CRM_Utils_Hook
::merge('batch', $migrationData, $mainId, $otherId);
2391 $conflicts = $migrationData['fields_in_conflict'];
2392 // allow hook to override / manipulate migrationInfo as well
2393 $migrationInfo = $migrationData['migration_info'];
2394 $migrationInfo['skip_merge'] = CRM_Utils_Array
::value('skip_merge', $migrationData);
2399 * Do file custom fields related migrations.
2400 * FIXME: move this someplace else (one of the BAOs) after discussing
2401 * where to, and whether CRM_Core_BAO_File::deleteFileReferences() shouldn't actually,
2402 * like, delete a file...
2404 * Note outstanding bug https://lab.civicrm.org/dev/core/issues/723
2405 * relates to this code....
2409 * @param $customFiles
2411 protected static function processCustomFieldFiles($mainId, $otherId, $customFiles) {
2412 foreach ($customFiles as $customId) {
2413 list($tableName, $columnName, $groupID) = CRM_Core_BAO_CustomField
::getTableColumnGroup($customId);
2415 // get the contact_id -> file_id mapping
2417 $sql = "SELECT entity_id, {$columnName} AS file_id FROM {$tableName} WHERE entity_id IN ({$mainId}, {$otherId})";
2418 $dao = CRM_Core_DAO
::executeQuery($sql);
2419 while ($dao->fetch()) {
2420 // @todo - this is actually broken - fix & or remove - see testMergeCustomFields
2421 $fileIds[$dao->entity_id
] = $dao->file_id
;
2422 if ($dao->entity_id
== $mainId) {
2423 CRM_Core_BAO_File
::deleteFileReferences($fileIds[$mainId], $mainId, $customId);
2427 // move the other contact's file to main contact
2428 //NYSS need to INSERT or UPDATE depending on whether main contact has an existing record
2429 if (CRM_Core_DAO
::singleValueQuery("SELECT id FROM {$tableName} WHERE entity_id = {$mainId}")) {
2430 $sql = "UPDATE {$tableName} SET {$columnName} = {$fileIds[$otherId]} WHERE entity_id = {$mainId}";
2433 $sql = "INSERT INTO {$tableName} ( entity_id, {$columnName} ) VALUES ( {$mainId}, {$fileIds[$otherId]} )";
2435 CRM_Core_DAO
::executeQuery($sql);
2437 if (CRM_Core_DAO
::singleValueQuery("
2439 FROM civicrm_entity_file
2440 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}")
2443 UPDATE civicrm_entity_file
2444 SET entity_id = {$mainId}
2445 WHERE entity_table = '{$tableName}' AND file_id = {$fileIds[$otherId]}";
2449 INSERT INTO civicrm_entity_file ( entity_table, entity_id, file_id )
2450 VALUES ( '{$tableName}', {$mainId}, {$fileIds[$otherId]} )";
2452 CRM_Core_DAO
::executeQuery($sql);
2457 * @param $rule_group_id
2459 * @param $batchLimit
2460 * @param $isSelected
2461 * @param $includeConflicts
2463 * @param $checkPermissions
2467 protected static function getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, $includeConflicts, $criteria, $checkPermissions) {
2468 return CRM_Core_BAO_PrevNextCache
::retrieve(
2469 self
::getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions),
2470 self
::getJoinOnDedupeTable(),
2471 self
::getWhereString($isSelected),