3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
12 use Civi\Api4\CustomGroup
;
17 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 class CRM_Dedupe_Merger
{
22 * FIXME: consider creating a common structure with cidRefs() and eidRefs()
23 * FIXME: the sub-pages references by the URLs should
24 * be loaded dynamically on the merge form instead
27 * @throws \CiviCRM_API3_Exception
29 public static function relTables() {
31 if (!isset(Civi
::$statics[__CLASS__
]['relTables'])) {
33 // Setting these merely prevents enotices - but it may be more appropriate not to add the user table below
34 // if the url can't be retrieved. A more standardised way to retrieve them is.
35 // CRM_Core_Config::singleton()->userSystem->getUserRecordUrl() - however that function takes a contact_id &
36 // we may need a different function when it is not known.
37 $title = $userRecordUrl = '';
39 $config = CRM_Core_Config
::singleton();
40 // @todo - this user url stuff is only needed for the form layer - move to CRM_Contact_Form_Merge
41 if ($config->userSystem
->is_drupal
) {
42 $userRecordUrl = CRM_Utils_System
::url('user/%ufid');
43 $title = ts('%1 User: %2; user id: %3', [
44 1 => $config->userFramework
,
49 elseif ($config->userFramework
=== 'Joomla') {
50 $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';
51 $title = ts('%1 User: %2; user id: %3', [
52 1 => $config->userFramework
,
59 'rel_table_contributions' => [
60 'title' => ts('Contributions'),
62 'civicrm_contribution',
63 'civicrm_contribution_recur',
64 'civicrm_contribution_soft',
66 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=contribute'),
68 'rel_table_contribution_page' => [
69 'title' => ts('Contribution Pages'),
70 'tables' => ['civicrm_contribution_page'],
71 'url' => CRM_Utils_System
::url('civicrm/admin/contribute', 'reset=1&cid=$cid'),
73 'rel_table_memberships' => [
74 'title' => ts('Memberships'),
77 'civicrm_membership_log',
78 'civicrm_membership_type',
80 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=member'),
82 'rel_table_participants' => [
83 'title' => ts('Participants'),
84 'tables' => ['civicrm_participant'],
85 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=participant'),
87 'rel_table_events' => [
88 'title' => ts('Events'),
89 'tables' => ['civicrm_event'],
90 'url' => CRM_Utils_System
::url('civicrm/event/manage', 'reset=1&cid=$cid'),
92 'rel_table_activities' => [
93 'title' => ts('Activities'),
94 'tables' => ['civicrm_activity', 'civicrm_activity_contact'],
95 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=activity'),
97 'rel_table_relationships' => [
98 'title' => ts('Relationships'),
99 'tables' => ['civicrm_relationship'],
100 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=rel'),
102 'rel_table_custom_groups' => [
103 'title' => ts('Custom Groups'),
104 'tables' => ['civicrm_custom_group'],
105 'url' => CRM_Utils_System
::url('civicrm/admin/custom/group', 'reset=1'),
107 'rel_table_uf_groups' => [
108 'title' => ts('Profiles'),
109 'tables' => ['civicrm_uf_group'],
110 'url' => CRM_Utils_System
::url('civicrm/admin/uf/group', 'reset=1'),
112 'rel_table_groups' => [
113 'title' => ts('Groups'),
114 'tables' => ['civicrm_group_contact'],
115 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=group'),
117 'rel_table_notes' => [
118 'title' => ts('Notes'),
119 'tables' => ['civicrm_note'],
120 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=note'),
122 'rel_table_tags' => [
123 'title' => ts('Tags'),
124 'tables' => ['civicrm_entity_tag'],
125 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=tag'),
127 'rel_table_mailings' => [
128 'title' => ts('Mailings'),
131 'civicrm_mailing_event_queue',
132 'civicrm_mailing_event_subscribe',
134 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=mailing'),
136 'rel_table_cases' => [
137 'title' => ts('Cases'),
138 'tables' => ['civicrm_case_contact'],
139 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=case'),
141 'rel_table_grants' => [
142 'title' => ts('Grants'),
143 'tables' => ['civicrm_grant'],
144 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=grant'),
147 'title' => ts('PCPs'),
148 'tables' => ['civicrm_pcp'],
149 'url' => CRM_Utils_System
::url('civicrm/contribute/pcp/manage', 'reset=1'),
151 'rel_table_pledges' => [
152 'title' => ts('Pledges'),
153 'tables' => ['civicrm_pledge', 'civicrm_pledge_payment'],
154 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=pledge'),
156 'rel_table_users' => [
158 'tables' => ['civicrm_uf_match'],
159 'url' => $userRecordUrl,
163 $relTables +
= self
::getMultiValueCustomSets('relTables');
165 // Allow hook_civicrm_merge() to adjust $relTables
166 CRM_Utils_Hook
::merge('relTables', $relTables);
168 // Cache the results in a static variable
169 Civi
::$statics[__CLASS__
]['relTables'] = $relTables;
172 return Civi
::$statics[__CLASS__
]['relTables'];
176 * Returns the related tables groups for which a contact has any info entered.
181 * @throws \CiviCRM_API3_Exception
183 public static function getActiveRelTables($cid) {
187 $relTables = self
::relTables();
188 $cidRefs = self
::cidRefs();
189 $eidRefs = self
::eidRefs();
190 foreach ($relTables as $group => $params) {
192 foreach ($params['tables'] as $table) {
193 if (isset($cidRefs[$table])) {
194 foreach ($cidRefs[$table] as $field) {
195 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $field = $cid";
198 if (isset($eidRefs[$table])) {
199 foreach ($eidRefs[$table] as $entityTable => $entityId) {
200 $sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $entityId = $cid AND $entityTable = 'civicrm_contact'";
203 foreach ($sqls as $sql) {
204 if (CRM_Core_DAO
::singleValueQuery($sql) > 0) {
210 return array_unique($groups);
214 * Get array tables and fields that reference civicrm_contact.id.
216 * This function calls the merge hook and only exists to wrap the DAO function to support that deprecated call.
217 * The entityTypes hook is the recommended way to add tables to this result.
219 * I thought about adding another hook to alter tableReferences but decided it was unclear if there
220 * are use cases not covered by entityTables and instead we should wait & see.
222 public static function cidRefs() {
223 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['contact_references'])) {
224 return \Civi
::$statics[__CLASS__
]['contact_references'];
227 $contactReferences = $coreReferences = CRM_Core_DAO
::getReferencesToContactTable();
228 foreach (['civicrm_group_contact_cache', 'civicrm_acl_cache', 'civicrm_acl_contact_cache'] as $tableName) {
229 // Don't merge cache tables. These should be otherwise cleared at some point in the dedupe
230 // but they are prone to locking to let's not touch during the dedupe.
231 unset($contactReferences[$tableName], $coreReferences[$tableName]);
234 CRM_Utils_Hook
::merge('cidRefs', $contactReferences);
235 if ($contactReferences !== $coreReferences) {
236 CRM_Core_Error
::deprecatedWarning("Deprecated hook ::merge in context of 'cidRefs. Use entityTypes instead.");
238 \Civi
::$statics[__CLASS__
]['contact_references'] = $contactReferences;
239 return \Civi
::$statics[__CLASS__
]['contact_references'];
243 * Return tables and their fields referencing civicrm_contact.contact_id with entity_id
245 public static function eidRefs() {
248 // FIXME: this should be generated dynamically from the schema
249 // tables that reference contacts with entity_{id,table}
251 'civicrm_acl' => ['entity_table' => 'entity_id'],
252 'civicrm_acl_entity_role' => ['entity_table' => 'entity_id'],
253 'civicrm_entity_file' => ['entity_table' => 'entity_id'],
254 'civicrm_log' => ['entity_table' => 'entity_id'],
255 'civicrm_mailing_group' => ['entity_table' => 'entity_id'],
256 'civicrm_note' => ['entity_table' => 'entity_id'],
259 // Allow hook_civicrm_merge() to adjust $eidRefs
260 CRM_Utils_Hook
::merge('eidRefs', $eidRefs);
266 * Return tables using locations.
268 public static function locTables() {
271 $locTables = ['civicrm_email', 'civicrm_address', 'civicrm_phone'];
273 // Allow hook_civicrm_merge() to adjust $locTables
274 CRM_Utils_Hook
::merge('locTables', $locTables);
280 * We treat multi-valued custom sets as "related tables" similar to activities, contributions, etc.
282 * @param string $request
283 * 'relTables' or 'cidRefs'.
286 * @throws \CiviCRM_API3_Exception
289 public static function getMultiValueCustomSets($request) {
291 if (!isset(Civi
::$statics[__CLASS__
]['multiValueCustomSets'])) {
296 $result = civicrm_api3('custom_group', 'get', [
306 'return' => ['id', 'title', 'table_name', 'style'],
308 foreach ($result['values'] as $custom) {
309 $data['cidRefs'][$custom['table_name']] = ['entity_id'];
310 $urlSuffix = $custom['style'] === 'Tab' ?
'&selectedChild=custom_' . $custom['id'] : '';
311 $data['relTables']['rel_table_custom_' . $custom['id']] = [
312 'title' => $custom['title'],
313 'tables' => [$custom['table_name']],
314 'url' => CRM_Utils_System
::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid' . $urlSuffix),
318 // Store the result in a static variable cache
319 Civi
::$statics[__CLASS__
]['multiValueCustomSets'] = $data;
322 return Civi
::$statics[__CLASS__
]['multiValueCustomSets'][$request];
326 * Tables which require custom processing should declare functions to call here.
327 * Doing so will override normal processing.
329 public static function cpTables() {
333 'civicrm_case_contact' => ['CRM_Case_BAO_Case' => 'mergeContacts'],
334 'civicrm_group_contact' => ['CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'],
335 // Empty array == do nothing - this table is handled by mergeGroupContact
336 'civicrm_subscription_history' => [],
337 'civicrm_relationship' => ['CRM_Contact_BAO_Relationship' => 'mergeRelationships'],
338 'civicrm_membership' => ['CRM_Member_BAO_Membership' => 'mergeMemberships'],
345 * Return payment related table.
347 public static function paymentTables() {
350 $tables = ['civicrm_pledge', 'civicrm_membership', 'civicrm_participant'];
356 * Return payment update Query.
358 * @param string $tableName
359 * @param int $mainContactId
360 * @param int $otherContactId
364 public static function paymentSql($tableName, $mainContactId, $otherContactId) {
366 if (!$tableName ||
!$mainContactId ||
!$otherContactId) {
370 $paymentTables = self
::paymentTables();
371 if (!in_array($tableName, $paymentTables)) {
375 switch ($tableName) {
376 case 'civicrm_pledge':
378 UPDATE IGNORE civicrm_contribution contribution
379 INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id )
380 INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id )
381 SET contribution.contact_id = $mainContactId
382 WHERE pledge.contact_id = $otherContactId";
385 case 'civicrm_membership':
387 UPDATE IGNORE civicrm_contribution contribution
388 INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id )
389 INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id )
390 SET contribution.contact_id = $mainContactId
391 WHERE membership.contact_id = $otherContactId";
394 case 'civicrm_participant':
396 UPDATE IGNORE civicrm_contribution contribution
397 INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id )
398 INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id )
399 SET contribution.contact_id = $mainContactId
400 WHERE participant.contact_id = $otherContactId";
409 * @param int $otherId
410 * @param string $tableName
411 * @param array $tableOperations
412 * @param string $mode
416 public static function operationSql($mainId, $otherId, $tableName, $tableOperations = [], $mode = 'add') {
418 if (!$tableName ||
!$mainId ||
!$otherId) {
422 switch ($tableName) {
423 case 'civicrm_membership':
424 if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add']) {
427 if ($mode === 'add') {
429 DELETE membership1.* FROM civicrm_membership membership1
430 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
431 AND membership1.contact_id = {$mainId}
432 AND membership2.contact_id = {$otherId} ";
434 if ($mode === 'payment') {
436 DELETE contribution.* FROM civicrm_contribution contribution
437 INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id
438 INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id
439 AND membership1.contact_id = {$mainId}
440 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
441 AND membership2.contact_id = {$otherId}";
445 case 'civicrm_uf_match':
446 // normal queries won't work for uf_match since that will lead to violation of unique constraint,
447 // failing to meet intended result. Therefore we introduce this additional query:
448 $sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}";
456 * Based on the provided two contact_ids and a set of tables, remove the
457 * belongings of the other contact and of their relations.
459 * @param int $otherID
460 * @param array $tables
462 * @throws \CiviCRM_API3_Exception
464 public static function removeContactBelongings($otherID, $tables) {
465 // CRM-20421: Removing Inherited memberships when memberships of parent are not migrated to new contact.
466 if (in_array('civicrm_membership', $tables, TRUE)) {
467 $membershipIDs = CRM_Utils_Array
::collect('id',
468 CRM_Utils_Array
::value('values',
469 civicrm_api3('Membership', "get", [
470 'contact_id' => $otherID,
476 if (!empty($membershipIDs)) {
477 civicrm_api3('Membership', 'get', [
478 'owner_membership_id' => ['IN' => $membershipIDs],
479 'api.Membership.delete' => ['id' => '$value.id'],
486 * Based on the provided two contact_ids and a set of tables, move the
487 * belongings of the other contact to the main one.
489 * @param CRM_Dedupe_MergeHandler $mergeHandler
490 * @param array $tables
491 * @param array $tableOperations
493 * @throws \API_Exception
494 * @throws \CiviCRM_API3_Exception
495 * @throws \Civi\API\Exception\UnauthorizedException
497 public static function moveContactBelongings($mergeHandler, $tables, $tableOperations) {
498 $mainId = $mergeHandler->getToKeepID();
499 $otherId = $mergeHandler->getToRemoveID();
500 $cidRefs = self
::cidRefs();
501 $eidRefs = $mergeHandler->getTablesDynamicallyRelatedToContactTable();
502 $dynamicRefs = CRM_Core_DAO
::getDynamicReferencesToTable('civicrm_contact');
503 $cpTables = self
::cpTables();
504 $paymentTables = self
::paymentTables();
505 self
::filterRowBasedCustomDataFromCustomTables($cidRefs);
506 $multiValueCidRefs = self
::getMultiValueCidRefs();
508 $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
510 // if there aren't any specific tables, don't affect the ones handled by relTables()
511 // also don't affect tables in locTables() CRM-15658
512 $relTables = self
::relTables();
513 // These arrays don't make a lot of sense. For now ensure the tested handling of tags works...
514 // it is moved over further down....
515 unset($relTables['rel_table_tags']);
516 $handled = self
::locTables();
518 foreach ($relTables as $params) {
519 $handled = array_merge($handled, $params['tables']);
521 $affected = array_diff($affected, $handled);
522 $affected = array_unique(array_merge($affected, $tables));
524 $mainId = (int) $mainId;
525 $otherId = (int) $otherId;
528 foreach ($affected as $table) {
529 // Call custom processing function for objects that require it
530 if (isset($cpTables[$table])) {
531 foreach ($cpTables[$table] as $className => $fnName) {
532 $className::$fnName($mainId, $otherId, $sqls, $tables, $tableOperations);
534 // Skip normal processing
538 if ($table === 'civicrm_activity_contact') {
539 $sqls[] = "UPDATE IGNORE civicrm_activity_contact SET contact_id = $mainId WHERE contact_id = $otherId";
540 $sqls[] = "DELETE FROM civicrm_activity_contact WHERE contact_id = $otherId";
544 if ($table === 'civicrm_dashboard_contact') {
545 $sqls[] = "UPDATE IGNORE civicrm_dashboard_contact SET contact_id = $mainId WHERE contact_id = $otherId";
546 $sqls[] = "DELETE FROM civicrm_dashboard_contact WHERE contact_id = $otherId";
550 if ($table === 'civicrm_dedupe_exception') {
551 $sqls[] = "UPDATE IGNORE civicrm_dedupe_exception SET contact_id1 = $mainId WHERE contact_id1 = $otherId";
552 $sqls[] = "UPDATE IGNORE civicrm_dedupe_exception SET contact_id2 = $mainId WHERE contact_id2 = $otherId";
553 $sqls[] = "DELETE FROM civicrm_dedupe_exception WHERE contact_id1 = $otherId OR contact_id2 = $otherId";
557 if ($table === 'civicrm_setting') {
558 // Per https://lab.civicrm.org/dev/core/-/issues/1934
559 // Note this line is not unit tested as yet as a quick-fix for a regression
560 // but it would be better to do a SELECT request & only update if needed (as a general rule
561 // more selects & less UPDATES will result in less deadlocks while de-duping.
562 // Note the delete is not important here - it can stay with the deleted contact on the
563 // off chance they get restored.
564 $sqls[] = "UPDATE IGNORE civicrm_setting SET contact_id = $mainId WHERE contact_id = $otherId";
568 // use UPDATE IGNORE + DELETE query pair to skip on situations when
569 // there's a UNIQUE restriction on ($field, some_other_field) pair
570 if (isset($cidRefs[$table])) {
571 foreach ($cidRefs[$table] as $field) {
572 // carry related contributions CRM-5359
573 if (in_array($table, $paymentTables)) {
574 $paymentSqls = self
::paymentSql($table, $mainId, $otherId);
575 $sqls = array_merge($sqls, $paymentSqls);
577 if (!empty($tables) && !in_array('civicrm_contribution', $tables)) {
578 $payOprSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations, 'payment');
579 $sqls = array_merge($sqls, $payOprSqls);
583 $preOperationSqls = self
::operationSql($mainId, $otherId, $table, $tableOperations);
584 $sqls = array_merge($sqls, $preOperationSqls);
586 if (!empty($multiValueCidRefs[$table][$field])) {
587 $sep = CRM_Core_DAO
::VALUE_SEPARATOR
;
588 $sqls[] = "UPDATE $table SET $field = REPLACE($field, '$sep$otherId$sep', '$sep$mainId$sep') WHERE $field LIKE '%$sep$otherId$sep%'";
591 $sqls[] = "UPDATE $table SET $field = $mainId WHERE $field = $otherId";
596 if (isset($eidRefs[$table])) {
597 foreach ($dynamicRefs[$table] as $dynamicRef) {
598 $sqls[] = "UPDATE IGNORE $table SET {$dynamicRef[0]}= $mainId WHERE {$dynamicRef[0]} = $otherId AND {$dynamicRef[1]} = 'civicrm_contact'";
599 $sqls[] = "DELETE FROM $table WHERE {$dynamicRef[0]} = $otherId AND {$dynamicRef[1]} = 'civicrm_contact'";
604 // Allow hook_civicrm_merge() to add SQL statements for the merge operation.
605 CRM_Utils_Hook
::merge('sqls', $sqls, $mainId, $otherId, $tables);
607 foreach ($sqls as $sql) {
608 CRM_Core_DAO
::executeQuery($sql, [], TRUE, NULL, TRUE);
610 CRM_Dedupe_Merger
::addMembershipToRealtedContacts($mainId);
614 * Filter out custom tables from cidRefs unless they are there due to a contact reference or are a multiple set.
616 * The only fields where we want to move the data by sql is where entity reference fields
617 * on another contact refer to the contact being merged, or it is a multiple record set.
618 * The transference of custom data from one contact to another is done in 2 other places in the dedupe process but should
619 * not be done in moveAllContactData.
621 * Note it's a bit silly the way we build & then cull cidRefs - however, poor hook placement means that
622 * until we fully deprecate calling the hook from cidRefs we are stuck.
624 * It was deprecated in code (via deprecation notices if people altered it) in Mar 2019 but in docs only in Apri 2020.
626 * @param array $cidRefs
628 * @throws \API_Exception
629 * @throws \Civi\API\Exception\UnauthorizedException
631 protected static function filterRowBasedCustomDataFromCustomTables(array &$cidRefs) {
632 $customTables = (array) CustomGroup
::get(FALSE)
633 ->setSelect(['table_name'])
634 ->addWhere('is_multiple', '=', 0)
635 ->addWhere('extends', 'IN', array_merge(['Contact'], CRM_Contact_BAO_ContactType
::contactTypes()))
637 ->indexBy('table_name');
638 foreach (array_intersect_key($cidRefs, $customTables) as $tableName => $cidSpec) {
639 if (in_array('entity_id', $cidSpec, TRUE)) {
640 unset($cidRefs[$tableName][array_search('entity_id', $cidSpec, TRUE)]);
642 if (empty($cidRefs[$tableName])) {
643 unset($cidRefs[$tableName]);
649 * Return an array of tables & fields which hold serialized arrays of contact ids
651 * Return format is ['table_name' => ['field_name' => SERIALIZE_METHOD]]
653 * For now, only custom fields can be serialized and the only
654 * method used is CRM_Core_DAO::SERIALIZE_SEPARATOR_BOOKEND.
656 protected static function getMultiValueCidRefs() {
657 $fields = \Civi\Api4\CustomField
::get(FALSE)
658 ->addSelect('custom_group_id.table_name', 'column_name', 'serialize')
659 ->addWhere('data_type', '=', 'ContactReference')
660 ->addWhere('serialize', 'IS NOT EMPTY')
664 foreach ($fields as $field) {
665 $map[$field['custom_group_id.table_name']][$field['column_name']] = $field['serialize'];
671 * Update the contact with the new parameters.
673 * This function is intended as an interim function, with the intent being
676 * The function was calling the rather-terrifying createProfileContact. I copied all
677 * that code into this function and then removed all the parts that have no effect in this scenario.
679 * @param int $contactID
680 * @param array $params
682 * @throws \CRM_Core_Exception
683 * @throws \CiviCRM_API3_Exception
684 * @throws \Civi\API\Exception\UnauthorizedException
686 protected static function createContact($contactID, $params) {
687 // This parameter causes blank fields to be be emptied out.
688 // We can probably remove.
689 $params['updateBlankLocInfo'] = TRUE;
690 $data = self
::formatProfileContactParams($params, [], $contactID);
691 CRM_Contact_BAO_Contact
::create($data);
695 * Format profile contact parameters.
697 * Note this function has been duplicated from CRM_Contact_BAO_Contact
698 * in order to allow us to unravel all the work this class
699 * does to prepare to call this & create some sanity. Also start to
700 * eliminate a toxic function.
702 * @param array $params
704 * @param int $contactID
705 * @param int $ufGroupId
710 private static function formatProfileContactParams(
718 $data = $contactDetails = [];
720 // get the contact details (hier)
722 $details = CRM_Contact_BAO_Contact
::getHierContactDetails($contactID, $fields);
724 $contactDetails = $details[$contactID];
725 $data['contact_type'] = $contactDetails['contact_type'] ??
NULL;
726 $data['contact_sub_type'] = $contactDetails['contact_sub_type'] ??
NULL;
729 //we should get contact type only if contact
731 $data['contact_type'] = CRM_Core_BAO_UFField
::getProfileType($ufGroupId, TRUE, FALSE, TRUE);
733 //special case to handle profile with only contact fields
734 if ($data['contact_type'] == 'Contact') {
735 $data['contact_type'] = 'Individual';
737 elseif (CRM_Contact_BAO_ContactType
::isaSubType($data['contact_type'])) {
738 $data['contact_type'] = CRM_Contact_BAO_ContactType
::getBasicType($data['contact_type']);
742 $data['contact_type'] = $ctype;
745 $data['contact_type'] = 'Individual';
749 //fix contact sub type CRM-5125
750 if (array_key_exists('contact_sub_type', $params) &&
751 !empty($params['contact_sub_type'])
753 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type']);
755 elseif (array_key_exists('contact_sub_type_hidden', $params) &&
756 !empty($params['contact_sub_type_hidden'])
758 // if profile was used, and had any subtype, we obtain it from there
759 //CRM-13596 - add to existing contact types, rather than overwriting
760 if (empty($data['contact_sub_type'])) {
761 // If we don't have a contact ID the $data['contact_sub_type'] will not be defined...
762 $data['contact_sub_type'] = CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
765 $data_contact_sub_type_arr = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
766 if (!in_array($params['contact_sub_type_hidden'], $data_contact_sub_type_arr)) {
767 //CRM-20517 - make sure contact_sub_type gets the correct delimiters
768 $data['contact_sub_type'] = trim($data['contact_sub_type'], CRM_Core_DAO
::VALUE_SEPARATOR
);
769 $data['contact_sub_type'] = CRM_Core_DAO
::VALUE_SEPARATOR
. $data['contact_sub_type'] . CRM_Utils_Array
::implodePadded($params['contact_sub_type_hidden']);
774 if ($ctype == 'Organization') {
775 $data['organization_name'] = $contactDetails['organization_name'] ??
NULL;
777 elseif ($ctype == 'Household') {
778 $data['household_name'] = $contactDetails['household_name'] ??
NULL;
786 $data['contact_id'] = $contactID;
787 $primaryLocationType = CRM_Contact_BAO_Contact
::getPrimaryLocationType($contactID);
790 $defaultLocation = CRM_Core_BAO_LocationType
::getDefault();
791 $defaultLocationId = $defaultLocation->id
;
794 $billingLocationTypeId = CRM_Core_BAO_LocationType
::getBilling();
796 $blocks = ['email', 'phone', 'im', 'openid'];
798 $multiplFields = ['url'];
799 // prevent overwritten of formatted array, reset all block from
800 // params if it is not in valid format (since import pass valid format)
801 foreach ($blocks as $blk) {
802 if (array_key_exists($blk, $params) &&
803 !is_array($params[$blk])
805 unset($params[$blk]);
809 $primaryPhoneLoc = NULL;
810 $session = CRM_Core_Session
::singleton();
811 foreach ($params as $key => $value) {
812 [$fieldName, $locTypeId, $typeId] = CRM_Utils_System
::explode('-', $key, 3);
814 if ($locTypeId == 'Primary') {
816 if (in_array($fieldName, $blocks)) {
817 $locTypeId = CRM_Contact_BAO_Contact
::getPrimaryLocationType($contactID, FALSE, $fieldName);
820 $locTypeId = CRM_Contact_BAO_Contact
::getPrimaryLocationType($contactID, FALSE, 'address');
822 $primaryLocationType = $locTypeId;
825 $locTypeId = $defaultLocationId;
829 if (is_numeric($locTypeId) &&
830 !in_array($fieldName, $multiplFields) &&
831 substr($fieldName, 0, 7) != 'custom_'
835 if (is_numeric($typeId)) {
836 $index .= '-' . $typeId;
838 if (!in_array($index, $locationType)) {
839 $locationType[$count] = $index;
843 $loc = CRM_Utils_Array
::key($index, $locationType);
845 $blockName = self
::getLocationEntityForKey($fieldName);
847 $data[$blockName][$loc]['location_type_id'] = $locTypeId;
849 //set is_billing true, for location type "Billing"
850 if ($locTypeId == $billingLocationTypeId) {
851 $data[$blockName][$loc]['is_billing'] = 1;
855 //get the primary location type
856 if ($locTypeId == $primaryLocationType) {
857 $data[$blockName][$loc]['is_primary'] = 1;
860 elseif ($locTypeId == $defaultLocationId) {
861 $data[$blockName][$loc]['is_primary'] = 1;
864 if (in_array($fieldName, ['phone'])) {
866 $data['phone'][$loc]['phone_type_id'] = $typeId;
869 $data['phone'][$loc]['phone_type_id'] = '';
871 $data['phone'][$loc]['phone'] = $value;
873 //special case to handle primary phone with different phone types
874 // in this case we make first phone type as primary
875 if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
876 $primaryPhoneLoc = $loc;
879 if ($loc != $primaryPhoneLoc) {
880 unset($data['phone'][$loc]['is_primary']);
883 elseif ($fieldName == 'email') {
884 $data['email'][$loc]['email'] = $value;
885 if (empty($contactID)) {
886 $data['email'][$loc]['is_primary'] = 1;
889 elseif ($fieldName == 'im') {
890 if (isset($params[$key . '-provider_id'])) {
891 $data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
893 if (strpos($key, '-provider_id') !== FALSE) {
894 $data['im'][$loc]['provider_id'] = $params[$key];
897 $data['im'][$loc]['name'] = $value;
900 elseif ($fieldName == 'openid') {
901 $data['openid'][$loc]['openid'] = $value;
904 if ($fieldName === 'state_province') {
906 if (is_numeric($value) && ((int ) $value) >= 1000) {
907 $data['address'][$loc]['state_province_id'] = $value;
909 elseif (empty($value)) {
910 $data['address'][$loc]['state_province_id'] = '';
913 $data['address'][$loc]['state_province'] = $value;
916 elseif ($fieldName === 'country') {
918 if (is_numeric($value) && ((int ) $value) >= 1000
920 $data['address'][$loc]['country_id'] = $value;
922 elseif (empty($value)) {
923 $data['address'][$loc]['country_id'] = '';
926 $data['address'][$loc]['country'] = $value;
929 elseif ($fieldName === 'county') {
930 $data['address'][$loc]['county_id'] = $value;
932 elseif ($fieldName == 'address_name') {
933 $data['address'][$loc]['name'] = $value;
935 elseif (substr($fieldName, 0, 14) === 'address_custom') {
936 $data['address'][$loc][substr($fieldName, 8)] = $value;
939 $data[$blockName][$loc][$fieldName] = $value;
944 if (substr($key, 0, 4) === 'url-') {
945 $websiteField = explode('-', $key);
946 $data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
947 $data['website'][$websiteField[1]]['url'] = $value;
949 elseif (in_array($key, CRM_Contact_BAO_Contact
::$_greetingTypes, TRUE)) {
950 //save email/postal greeting and addressee values if any, CRM-4575
951 $data[$key . '_id'] = $value;
953 elseif (($customFieldId = CRM_Core_BAO_CustomField
::getKeyID($key))) {
954 // for autocomplete transfer hidden value instead of label
955 if ($params[$key] && isset($params[$key . '_id'])) {
956 $value = $params[$key . '_id'];
959 // we need to append time with date
960 if ($params[$key] && isset($params[$key . '_time'])) {
961 $value .= ' ' . $params[$key . '_time'];
964 // if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
965 if (($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 &&
966 ($value == '' ||
!isset($value))
972 if (!empty($params['customRecordValues'])) {
973 if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
974 foreach ($params['customRecordValues'] as $recId => $customFields) {
975 if (is_array($customFields) && !empty($customFields)) {
976 foreach ($customFields as $customFieldName) {
977 if ($customFieldName == $key) {
987 //CRM-13596 - check for contact_sub_type_hidden first
988 if (array_key_exists('contact_sub_type_hidden', $params)) {
989 $type = $params['contact_sub_type_hidden'];
992 $type = $data['contact_type'];
993 if (!empty($data['contact_sub_type'])) {
994 $type = CRM_Utils_Array
::explodePadded($data['contact_sub_type']);
998 CRM_Core_BAO_CustomField
::formatCustomField($customFieldId,
1008 elseif ($key === 'edit') {
1012 if ($key === 'location') {
1013 foreach ($value as $locationTypeId => $field) {
1014 foreach ($field as $block => $val) {
1015 if ($block === 'address' && array_key_exists('address_name', $val)) {
1016 $value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
1021 if ($key === 'phone' && isset($params['phone_ext'])) {
1022 $data[$key] = $value;
1023 foreach ($value as $cnt => $phoneBlock) {
1024 if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) {
1025 $data[$key][$cnt]['phone_ext'] = CRM_Utils_Array
::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
1029 elseif (in_array($key, ['nick_name', 'job_title', 'middle_name', 'birth_date', 'gender_id', 'current_employer', 'prefix_id', 'suffix_id'])
1030 && ($value == '' ||
!isset($value)) &&
1031 ($session->get('authSrc') & (CRM_Core_Permission
::AUTH_SRC_CHECKSUM + CRM_Core_Permission
::AUTH_SRC_LOGIN
)) == 0 ||
1032 ($key === 'current_employer' && empty($params['current_employer']))) {
1033 // CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
1034 // to avoid update with empty values
1038 $data[$key] = $value;
1044 if (!isset($data['contact_type'])) {
1045 $data['contact_type'] = 'Individual';
1048 //set the values for checkboxes (do_not_email, do_not_mail, do_not_trade, do_not_phone)
1049 $privacy = CRM_Core_SelectValues
::privacy();
1050 foreach ($privacy as $key => $value) {
1051 if (array_key_exists($key, $fields)) {
1052 // do not reset values for existing contacts, if fields are added to a profile
1053 if (array_key_exists($key, $params)) {
1054 $data[$key] = $params[$key];
1055 if (empty($params[$key])) {
1059 elseif (!$contactID) {
1069 * Get the relevant location entity for the array key.
1071 * This function is duplicated from CRM_Contact_BAO_Contact to allow cleanup.
1072 * See self::formatProfileContactParams
1074 * Based on the field name we determine which location entity
1075 * we are dealing with. Apart from a few specific ones they
1076 * are mostly 'address' (the default).
1078 * @param string $fieldName
1082 protected static function getLocationEntityForKey($fieldName) {
1083 if (in_array($fieldName, ['email', 'phone', 'im', 'openid'])) {
1086 if ($fieldName === 'phone_ext') {
1093 * Load all non-empty fields for the contacts
1095 * @param array $main
1097 * @param array $other
1102 * @throws \CRM_Core_Exception
1104 public static function retrieveFields($main, $other) {
1109 foreach (self
::getContactFields() as $validField) {
1110 // CRM-17556 Get all non-empty fields, to make comparison easier
1111 if (!empty($main[$validField]) ||
!empty($other[$validField])) {
1112 $result['contact'][] = $validField;
1116 $mainEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($main['id']);
1117 $otherEvs = CRM_Core_BAO_CustomValueTable
::getEntityValues($other['id']);
1118 $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
1119 foreach ($keys as $key) {
1120 // Exclude multi-value fields CRM-13836
1121 if (strpos($key, '_')) {
1124 $key1 = $mainEvs[$key] ??
NULL;
1125 $key2 = $otherEvs[$key] ??
NULL;
1126 // We wish to retain '0' as it has a different meaning than NULL on a checkbox.
1127 // However I can't think of a case where an empty string is more meaningful than null
1128 // or where it would be FALSE or something else nullish.
1129 $valuesToIgnore = [NULL, '', []];
1130 if (!in_array($key1, $valuesToIgnore, TRUE) ||
!in_array($key2, $valuesToIgnore, TRUE)) {
1131 $result['custom'][] = $key;
1138 * Batch merge a set of contacts based on rule-group and group.
1144 * @param string $mode
1145 * Helps decide how to behave when there are conflicts.
1146 * A 'safe' value skips the merge if there are any un-resolved conflicts, wheras 'aggressive'
1147 * mode does a force merge.
1148 * @param int $batchLimit number of merges to carry out in one batch.
1149 * @param int $isSelected if records with is_selected column needs to be processed.
1150 * Note the option of '2' is only used in conjunction with $redirectForPerformance
1151 * to determine when to reload the cache (!). The use of anything other than a boolean is being grandfathered
1152 * out in favour of explicitly passing in $reloadCacheIfEmpty
1154 * @param array $criteria
1155 * Criteria to use in the filter.
1157 * @param bool $checkPermissions
1158 * Respect logged in user permissions.
1159 * @param bool|NULL $reloadCacheIfEmpty
1160 * If not set explicitly this is calculated but it is preferred that it be set
1161 * per comments on isSelected above.
1163 * @param int $searchLimit
1164 * Limit on number of contacts to search for duplicates for.
1165 * This means that if the limit is 1000 then only duplicates for the first 1000 contacts
1166 * matching criteria will be found and batchMerged (the number of merges could be less than or greater than 100)
1168 * @return array|bool
1170 * @throws \CRM_Core_Exception
1171 * @throws \CiviCRM_API3_Exception
1172 * @throws \API_Exception
1174 public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $batchLimit = 1, $isSelected = 2, $criteria = [], $checkPermissions = TRUE, $reloadCacheIfEmpty = NULL, $searchLimit = 0) {
1175 $redirectForPerformance = $batchLimit > 1;
1176 if ($mode === 'aggressive' && $checkPermissions && !CRM_Core_Permission
::check('force merge duplicate contacts')) {
1177 throw new CRM_Core_Exception(ts('Insufficient permissions for aggressive mode batch merge'));
1179 if (!isset($reloadCacheIfEmpty)) {
1180 $reloadCacheIfEmpty = (!$redirectForPerformance && $isSelected == 2);
1182 if ($isSelected !== 0 && $isSelected !== 1) {
1183 // explicitly set to NULL if not 1 or 0 as part of grandfathering out the mystical '2' value.
1186 $dupePairs = self
::getDuplicatePairs($rgid, $gid, $reloadCacheIfEmpty, $batchLimit, $isSelected, ($mode === 'aggressive'), $criteria, $checkPermissions, $searchLimit);
1189 'cache_key_string' => self
::getMergeCacheKeyString($rgid, $gid, $criteria, $checkPermissions, $searchLimit),
1190 // @todo stop passing these parameters in & instead calculate them in the merge function based
1191 // on the 'real' params like $isRespectExclusions $batchLimit and $isSelected.
1192 'join' => self
::getJoinOnDedupeTable(),
1193 'where' => self
::getWhereString($isSelected),
1194 'limit' => (int) $batchLimit,
1196 return CRM_Dedupe_Merger
::merge($dupePairs, $cacheParams, $mode, $redirectForPerformance, $checkPermissions);
1200 * Get the string to join the prevnext cache to the dedupe table.
1203 * The join string to join prevnext cache on the dedupe table.
1205 public static function getJoinOnDedupeTable() {
1207 LEFT JOIN civicrm_dedupe_exception de
1209 pn.entity_id1 = de.contact_id1
1210 AND pn.entity_id2 = de.contact_id2 )
1215 * Get where string for dedupe join.
1217 * @param bool $isSelected
1221 protected static function getWhereString($isSelected) {
1222 $where = 'de.id IS NULL';
1223 if ($isSelected === 0 ||
$isSelected === 1) {
1224 $where .= " AND pn.is_selected = {$isSelected}";
1230 * Update the statistics for the merge set.
1232 * @param string $cacheKeyString
1233 * @param array $result
1235 * @throws \CiviCRM_API3_Exception
1237 public static function updateMergeStats($cacheKeyString, $result = []) {
1238 // gather latest stats
1239 $merged = count($result['merged']);
1240 $skipped = count($result['skipped']);
1242 if ($merged <= 0 && $skipped <= 0) {
1246 // get previous stats
1247 $previousStats = CRM_Dedupe_Merger
::getMergeStats($cacheKeyString);
1248 if (!empty($previousStats)) {
1249 if ($previousStats['merged']) {
1250 $merged = $merged +
$previousStats['merged'];
1252 if ($previousStats['skipped']) {
1253 $skipped = $skipped +
$previousStats['skipped'];
1258 CRM_Dedupe_Merger
::resetMergeStats($cacheKeyString);
1260 // store the updated stats
1262 'merged' => (int) $merged,
1263 'skipped' => (int) $skipped,
1266 CRM_Core_DAO
::executeQuery("INSERT INTO civicrm_prevnext_cache (entity_table, entity_id1, entity_id2, cacheKey, data) VALUES
1267 ('civicrm_contact', 0, 0, %1, %2)", [1 => [$cacheKeyString . '_stats', 'String'], 2 => [serialize($data), 'String']]);
1271 * Delete information about merges for the given string.
1273 * @param $cacheKeyString
1275 public static function resetMergeStats($cacheKeyString) {
1276 CRM_Core_BAO_PrevNextCache
::deleteItem(NULL, "{$cacheKeyString}_stats");
1280 * Get merge outcome statistics.
1282 * @param string $cacheKeyString
1285 * Array of how many were merged and how many were skipped.
1287 * @throws \CiviCRM_API3_Exception
1289 public static function getMergeStats($cacheKeyString) {
1290 $stats = civicrm_api3('Dedupe', 'get', ['cachekey' => "{$cacheKeyString}_stats", 'sequential' => 1])['values'];
1291 if (!empty($stats)) {
1292 return $stats[0]['data'];
1298 * Get merge statistics message.
1300 * @param array $stats
1304 public static function getMergeStatsMsg($stats) {
1306 if (!empty($stats['merged'])) {
1307 $msg = '<p>' . ts('One contact merged.', [
1308 'count' => $stats['merged'],
1309 'plural' => '%count contacts merged.',
1312 if (!empty($stats['skipped'])) {
1313 $msg .= '<p>' . ts('One contact was skipped.', [
1314 'count' => $stats['skipped'],
1315 'plural' => '%count contacts were skipped.',
1322 * Merge given set of contacts. Performs core operation.
1324 * @param array $dupePairs
1325 * Set of pair of contacts for whom merge is to be done.
1326 * @param array $cacheParams
1327 * Prev-next-cache params based on which next pair of contacts are computed.
1328 * Generally used with batch-merge.
1329 * @param string $mode
1330 * Helps decide how to behave when there are conflicts.
1331 * A 'safe' value skips the merge if there are any un-resolved conflicts.
1332 * Does a force merge otherwise (aggressive mode).
1334 * @param bool $redirectForPerformance
1335 * Redirect to a url for batch processing.
1337 * @param bool $checkPermissions
1338 * Respect logged in user permissions.
1340 * @return array|bool
1342 * @throws \API_Exception
1343 * @throws \CRM_Core_Exception
1344 * @throws \CiviCRM_API3_Exception
1346 public static function merge($dupePairs = [], $cacheParams = [], $mode = 'safe',
1347 $redirectForPerformance = FALSE, $checkPermissions = TRUE
1349 $cacheKeyString = $cacheParams['cache_key_string'] ??
NULL;
1350 $resultStats = ['merged' => [], 'skipped' => []];
1352 // we don't want dupe caching to get reset after every-merge, and therefore set the
1353 CRM_Core_Config
::setPermitCacheFlushMode(FALSE);
1354 $deletedContacts = [];
1356 while (!empty($dupePairs)) {
1357 foreach ($dupePairs as $index => $dupes) {
1358 if (in_array($dupes['dstID'], $deletedContacts) ||
in_array($dupes['srcID'], $deletedContacts)) {
1359 unset($dupePairs[$index]);
1362 CRM_Utils_Hook
::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']);
1363 if (($result = self
::dedupePair((int) $dupes['dstID'], (int) $dupes['srcID'], $mode, $checkPermissions, $cacheKeyString)) === FALSE) {
1364 unset($dupePairs[$index]);
1367 if (!empty($result['merged'])) {
1368 $deletedContacts[] = $result['merged'][0]['other_id'];
1369 $resultStats['merged'][] = ($result['merged'][0]);
1372 $resultStats['skipped'][] = ($result['skipped'][0]);
1376 if ($cacheKeyString && !$redirectForPerformance) {
1377 // retrieve next pair of dupes
1378 // @todo call getDuplicatePairs.
1379 $dupePairs = CRM_Core_BAO_PrevNextCache
::retrieve($cacheKeyString,
1380 $cacheParams['join'],
1381 $cacheParams['where'],
1383 $cacheParams['limit'],
1390 // do not proceed. Terminate the loop
1395 CRM_Dedupe_Merger
::updateMergeStats($cacheKeyString, $resultStats);
1396 return $resultStats;
1400 * A function which uses various rules / algorithms for choosing which contact to bias to
1401 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
1403 * @param int $mainId
1404 * Main contact with whom merge has to happen.
1405 * @param int $otherId
1406 * Duplicate contact which would be deleted after merge operation.
1407 * @param array $migrationInfo
1408 * Array of information about which elements to merge.
1409 * @param string $mode
1410 * Helps decide how to behave when there are conflicts.
1411 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
1412 * - Does a force merge otherwise (aggressive mode).
1414 * @param array $conflicts
1415 * An empty array to be filed with conflict information.
1419 * @throws \CRM_Core_Exception
1420 * @throws \CiviCRM_API3_Exception
1421 * @throws \API_Exception
1423 public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe', &$conflicts = []) {
1425 $conflicts = self
::getConflicts($migrationInfo, (int) $mainId, (int) $otherId, $mode)['conflicts'];
1426 // A hook could have set skip_merge in order to alter merge behaviour.
1427 // This is a something we might ideally deprecate since they really 'should'
1428 // mess with the conflicts array instead.
1429 return (bool) ($migrationData['skip_merge'] ??
!empty($conflicts));
1433 * Compare 2 addresses to see if they are the effectively the same.
1435 * Being the same would mean same location type and any populated fields that describe the locationn match.
1437 * Metadata fields such as is_primary, on_hold, manual_geocode may differ.
1439 * @param array $mainAddress
1440 * @param array $comparisonAddress
1444 public static function locationIsSame($mainAddress, $comparisonAddress) {
1445 $keysToIgnore = self
::ignoredFields();
1446 foreach ($comparisonAddress as $field => $value) {
1447 if (in_array($field, $keysToIgnore)) {
1450 if ((!empty($value) ||
$value === '0') && isset($mainAddress[$field]) && $mainAddress[$field] != $value) {
1458 * Does the location array have valid data.
1460 * While not UI-creatable some sites wind up with email or address rows with no actual email or address
1461 * through non core-UI processes.
1463 * @param array $location
1467 public static function locationHasData($location) {
1468 return !empty(self
::getLocationDataFields($location));
1472 * Get the location data from a location array, filtering out metadata.
1474 * This returns data like street_address but not metadata like is_primary, on_hold etc.
1476 * @param array $location
1480 public static function getLocationDataFields($location) {
1481 $keysToIgnore = array_merge(self
::ignoredFields(), ['display', 'location_type_id']);
1482 foreach ($location as $field => $value) {
1483 if (in_array($field, $keysToIgnore, TRUE)) {
1484 unset($location[$field]);
1491 * A function to build an array of information about location blocks that is
1492 * required when merging location fields
1496 public static function getLocationBlockInfo() {
1499 'label' => 'Address',
1500 'displayField' => 'display',
1501 'sortString' => 'location_type_id',
1502 'hasLocation' => TRUE,
1507 'displayField' => 'display',
1508 'sortString' => 'location_type_id',
1509 'hasLocation' => TRUE,
1514 'displayField' => 'name',
1515 'sortString' => 'location_type_id,provider_id',
1516 'hasLocation' => TRUE,
1517 'hasType' => 'provider_id',
1521 'displayField' => 'phone',
1522 'sortString' => 'location_type_id,phone_type_id',
1523 'hasLocation' => TRUE,
1524 'hasType' => 'phone_type_id',
1527 'label' => 'Website',
1528 'displayField' => 'url',
1529 'sortString' => 'website_type_id',
1530 'hasLocation' => FALSE,
1531 'hasType' => 'website_type_id',
1537 * A function to build an array of information required by merge function and the merge UI.
1539 * @param int $mainId
1540 * Main contact with whom merge has to happen.
1541 * @param int $otherId
1542 * Duplicate contact which would be deleted after merge operation.
1543 * @param bool $checkPermissions
1544 * Should the logged in user's permissions be ignore. Setting this to false is
1545 * highly risky as it could cause data to be lost due to conflicts not showing up.
1546 * OTOH there is a risk a merger might view custom data they do not have permission to.
1547 * Hence for now only making this really explicit and making it reflect perms in
1550 * @todo review permissions issue!
1552 * @return array|bool|int
1554 * rows => An array of arrays, each is row of merge information for the table
1555 * Format: move_fieldname, eg: move_contact_type
1556 * main => Value associated with the main contact
1557 * other => Value associated with the other contact
1558 * title => The title of the field to display in the merge table
1560 * elements => An array of form elements for the merge UI
1562 * rel_tables => Stores the tables that have related entities for the contact
1563 * for example mailings, groups
1565 * main_details => An array of core contact field values, eg: first_name, etc.
1566 * location_blocks => An array of location block data for the main contact
1567 * stored as the 'result' of an API call.
1568 * eg: main_details['location_blocks']['address'][0]['id']
1569 * eg: main_details['location_blocks']['email'][1]['id']
1571 * other_details => As above, but for the 'other' contact
1573 * migration_info => Stores the 'default' merge actions for each field which
1574 * is used when programatically merging contacts. It contains instructions
1575 * to move all fields from the 'other' contact to the 'main' contact, as
1576 * though the form had been submitted with those options.
1578 * @throws \CRM_Core_Exception
1579 * @throws \CiviCRM_API3_Exception
1581 public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissions = TRUE) {
1582 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1583 $fields = self
::getMergeFieldsMetadata();
1585 $main = self
::getMergeContactDetails($mainId);
1586 $other = self
::getMergeContactDetails($otherId);
1588 $compareFields = self
::retrieveFields($main, $other);
1590 $rows = $elements = $migrationInfo = [];
1592 foreach ($compareFields['contact'] as $field) {
1593 if ($field === 'contact_sub_type') {
1594 // CRM-15681 don't display sub-types in UI
1597 $rows["move_$field"] = [
1598 'main' => self
::getFieldValueAndLabel($field, $main)['label'],
1599 'other' => self
::getFieldValueAndLabel($field, $other)['label'],
1600 'title' => $fields[$field]['html']['label'] ??
$fields[$field]['title'],
1603 $value = self
::getFieldValueAndLabel($field, $other)['value'];
1605 if ($value === NULL ||
$value == '') {
1608 if ($value === 0 or $value === '0') {
1609 $value = $qfZeroBug;
1611 if (is_array($value) && empty($value[1])) {
1615 // Display a checkbox to migrate, only if the values are different
1616 if ($value != $main[$field]) {
1624 'is_checked' => (!isset($main[$field]) ||
$main[$field] === ''),
1628 $migrationInfo["move_$field"] = $value;
1631 // Handle location blocks.
1632 // @todo OpenID not in API yet, so is not supported here.
1634 // Set up useful information about the location blocks
1635 $locationBlocks = self
::getLocationBlockInfo();
1637 $locations = ['main' => [], 'other' => []];
1639 foreach ($locationBlocks as $blockName => $blockInfo) {
1640 [$locations, $rows, $elements, $migrationInfo] = self
::addLocationFieldInfo($mainId, $otherId, $blockInfo, $blockName, $locations, $rows, $elements, $migrationInfo);
1641 } // End loop through each location block entity
1643 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1644 $mergeHandler = new CRM_Dedupe_MergeHandler((int) $mainId, (int) $otherId);
1645 $relTables = $mergeHandler->getTablesRelatedToTheMergePair();
1646 foreach ($relTables as $name => $null) {
1647 $migrationInfo["move_$name"] = 1;
1649 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1650 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1651 if ($name === 'rel_table_users') {
1652 // @todo - this user url stuff is only needed for the form layer - move to CRM_Contact_Form_Merge
1653 $relTables[$name]['main_url'] = str_replace('%ufid', CRM_Core_BAO_UFMatch
::getUFId($mainId), $relTables[$name]['url']);
1654 $relTables[$name]['other_url'] = str_replace('%ufid', CRM_Core_BAO_UFMatch
::getUFId($otherId), $relTables[$name]['url']);
1656 if ($name === 'rel_table_memberships') {
1657 //Enable 'add new' checkbox if main contact does not contain any membership similar to duplicate contact.
1658 $attributes = ['checked' => 'checked'];
1659 $otherContactMemberships = CRM_Member_BAO_Membership
::getAllContactMembership($otherId);
1660 foreach ($otherContactMemberships as $membership) {
1661 $mainMembership = CRM_Member_BAO_Membership
::getContactMembership($mainId, $membership['membership_type_id'], FALSE);
1662 if ($mainMembership) {
1668 "operation[move_{$name}][add]",
1673 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1676 foreach ($relTables as $name => $null) {
1677 $relTables["move_$name"] = $relTables[$name];
1678 unset($relTables[$name]);
1681 // handle custom fields
1682 $mainTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], NULL, $mainId, -1,
1683 CRM_Utils_Array
::value('contact_sub_type', $main), NULL, TRUE, NULL, TRUE,
1684 $checkPermissions ? CRM_Core_Permission
::EDIT
: FALSE
1686 $otherTree = CRM_Core_BAO_CustomGroup
::getTree($main['contact_type'], NULL, $otherId, -1,
1687 CRM_Utils_Array
::value('contact_sub_type', $other), NULL, TRUE, NULL, TRUE,
1688 $checkPermissions ? CRM_Core_Permission
::EDIT
: FALSE
1691 foreach ($otherTree as $gid => $group) {
1692 if (!isset($group['fields'])) {
1696 foreach ($group['fields'] as $fid => $field) {
1697 $mainContactValue = $mainTree[$gid]['fields'][$fid]['customValue'] ??
NULL;
1698 $otherContactValue = $otherTree[$gid]['fields'][$fid]['customValue'] ??
NULL;
1699 if (in_array($fid, $compareFields['custom'])) {
1700 $rows["custom_group_$gid"]['title'] = $rows["custom_group_$gid"]['title'] ??
$group['title'];
1702 if ($mainContactValue) {
1703 foreach ($mainContactValue as $valueId => $values) {
1704 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomField
::displayValue($values['data'], $fid);
1708 if ($otherContactValue) {
1709 foreach ($otherContactValue as $valueId => $values) {
1710 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomField
::displayValue($values['data'], $fid);
1711 if ($values['data'] === 0 ||
$values['data'] === '0') {
1712 $values['data'] = $qfZeroBug;
1714 $value = ($values['data']) ?
$values['data'] : $value;
1717 $rows["move_custom_$fid"]['title'] = $field['label'];
1721 1 => "move_custom_$fid",
1726 'is_checked' => (!isset($rows["move_custom_$fid"]['main']) ||
$rows["move_custom_$fid"]['main'] === ''),
1728 $migrationInfo["move_custom_$fid"] = $value;
1735 'elements' => $elements,
1736 'rel_tables' => $relTables,
1737 'main_details' => $main,
1738 'other_details' => $other,
1739 'migration_info' => $migrationInfo,
1742 $result['main_details']['location_blocks'] = $locations['main'];
1743 $result['other_details']['location_blocks'] = $locations['other'];
1749 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1750 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1751 * A superset of moveContactBelongings() function.
1753 * @param int $mainId
1754 * Main contact with whom merge has to happen.
1755 * @param int $otherId
1756 * Duplicate contact which would be deleted after merge operation.
1758 * @param array $migrationInfo
1760 * @param bool $checkPermissions
1761 * Respect logged in user permissions.
1765 * @throws \API_Exception
1766 * @throws \CRM_Core_Exception
1767 * @throws \CiviCRM_API3_Exception
1768 * @throws \Civi\API\Exception\UnauthorizedException
1770 public static function moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions = TRUE) {
1771 if (empty($migrationInfo)) {
1774 // Encapsulate in a transaction to avoid half-merges.
1775 $transaction = new CRM_Core_Transaction();
1777 $contactType = $migrationInfo['main_details']['contact_type'];
1778 $relTables = CRM_Dedupe_Merger
::relTables();
1779 $submittedCustomFields = $moveTables = $tableOperations = $removeTables = [];
1781 self
::swapOutFieldsAffectedByQFZeroBug($migrationInfo);
1782 foreach ($migrationInfo as $key => $value) {
1784 if (substr($key, 0, 12) === 'move_custom_' && $value != NULL) {
1785 $submitted[substr($key, 5)] = $value;
1786 $submittedCustomFields[] = substr($key, 12);
1788 elseif (in_array(substr($key, 5), CRM_Dedupe_Merger
::getContactFields()) && $value != NULL) {
1789 $submitted[substr($key, 5)] = $value;
1791 elseif (substr($key, 0, 15) === 'move_rel_table_' and $value == '1') {
1792 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1793 if (array_key_exists('operation', $migrationInfo)) {
1794 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1795 if (array_key_exists($key, $migrationInfo['operation'])) {
1796 $tableOperations[$table] = $migrationInfo['operation'][$key];
1801 elseif (substr($key, 0, 15) === 'move_rel_table_' and $value == '0') {
1802 $removeTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1805 $mergeHandler = new CRM_Dedupe_MergeHandler((int) $mainId, (int) $otherId);
1806 $mergeHandler->setMigrationInfo($migrationInfo);
1807 $mergeHandler->mergeLocations();
1809 // **** Do contact related migrations
1810 // @todo - move all custom field processing to the move class & eventually have an
1811 // overridable DAO class for it.
1812 $customFieldBAO = new CRM_Core_BAO_CustomField();
1813 $customFieldBAO->move($otherId, $mainId, $submittedCustomFields);
1814 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1816 CRM_Dedupe_Merger
::moveContactBelongings($mergeHandler, $moveTables, $tableOperations);
1817 unset($moveTables, $tableOperations);
1819 // **** Do table related removals
1820 if (!empty($removeTables)) {
1822 CRM_Dedupe_Merger
::removeContactBelongings($otherId, $removeTables);
1826 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
1827 $names['gender'] = ['newName' => 'gender_id', 'groupName' => 'gender'];
1828 $names['individual_prefix'] = [
1829 'newName' => 'prefix_id',
1830 'groupName' => 'individual_prefix',
1832 $names['individual_suffix'] = [
1833 'newName' => 'suffix_id',
1834 'groupName' => 'individual_suffix',
1836 $names['communication_style'] = [
1837 'newName' => 'communication_style_id',
1838 'groupName' => 'communication_style',
1840 $names['addressee'] = [
1841 'newName' => 'addressee_id',
1842 'groupName' => 'addressee',
1844 $names['email_greeting'] = [
1845 'newName' => 'email_greeting_id',
1846 'groupName' => 'email_greeting',
1848 $names['postal_greeting'] = [
1849 'newName' => 'postal_greeting_id',
1850 'groupName' => 'postal_greeting',
1852 CRM_Core_OptionGroup
::lookupValues($submitted, $names, TRUE);
1853 // fix custom fields so they're edible by createProfileContact()
1854 $cFields = self
::getCustomFieldMetadata($contactType);
1856 if (!isset($submitted)) {
1859 foreach ($submitted as $key => $value) {
1860 [$cFields, $submitted] = self
::processCustomFields($mainId, $key, $cFields, $submitted, $value);
1863 // move view only custom fields CRM-5362
1864 $viewOnlyCustomFields = [];
1865 foreach ($submitted as $key => $value) {
1866 $fid = CRM_Core_BAO_CustomField
::getKeyID($key);
1867 if ($fid && array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])
1869 $viewOnlyCustomFields[$key] = $value;
1872 // special case to set values for view only, CRM-5362
1873 if (!empty($viewOnlyCustomFields)) {
1874 $viewOnlyCustomFields['entityID'] = $mainId;
1875 CRM_Core_BAO_CustomValueTable
::setValues($viewOnlyCustomFields);
1878 // dev/core#996 Ensure that the earliest created date is stored against the kept contact id
1879 $mainCreatedDate = civicrm_api3('Contact', 'getsingle', [
1881 'return' => ['created_date'],
1883 $otherCreatedDate = civicrm_api3('Contact', 'getsingle', [
1885 'return' => ['created_date'],
1887 if ($otherCreatedDate < $mainCreatedDate && !empty($otherCreatedDate)) {
1888 CRM_Core_DAO
::executeQuery("UPDATE civicrm_contact SET created_date = %1 WHERE id = %2", [
1889 1 => [$otherCreatedDate, 'String'],
1890 2 => [$mainId, 'Positive'],
1894 if (!$checkPermissions ||
(CRM_Core_Permission
::check('merge duplicate contacts') &&
1895 CRM_Core_Permission
::check('delete contacts'))
1897 // if ext id is submitted then set it null for contact to be deleted
1898 if (!empty($submitted['external_identifier'])) {
1899 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1900 CRM_Core_DAO
::executeQuery($query);
1902 civicrm_api3('contact', 'delete', ['id' => $otherId]);
1905 // CRM-15681 merge sub_types
1906 if ($other_sub_types = CRM_Utils_Array
::value('contact_sub_type', $migrationInfo['other_details'])) {
1907 if ($main_sub_types = CRM_Utils_Array
::value('contact_sub_type', $migrationInfo['main_details'])) {
1908 $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types));
1911 $submitted['contact_sub_type'] = $other_sub_types;
1915 // **** Update contact related info for the main contact
1916 if (!empty($submitted)) {
1917 $submitted['contact_id'] = $mainId;
1919 //update current employer field
1920 if ($currentEmloyerId = CRM_Utils_Array
::value('current_employer_id', $submitted)) {
1921 if (!CRM_Utils_System
::isNull($currentEmloyerId)) {
1922 $submitted['current_employer'] = $submitted['current_employer_id'];
1925 $submitted['current_employer'] = '';
1927 unset($submitted['current_employer_id']);
1930 //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
1931 if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) {
1932 $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
1934 if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) {
1935 $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
1937 self
::createContact($mainId, $submitted);
1939 $transaction->commit();
1940 CRM_Utils_Hook
::post('merge', 'Contact', $mainId);
1941 self
::createMergeActivities($mainId, $otherId);
1947 * Get fields in the contact table suitable for merging.
1950 * Array of field names to be potentially merged.
1952 public static function getContactFields() {
1953 $contactFields = CRM_Contact_DAO_Contact
::fields();
1961 'primary_contact_id',
1965 foreach ($contactFields as $field => $value) {
1966 if (in_array($field, $invalidFields)) {
1967 unset($contactFields[$field]);
1970 return array_keys($contactFields);
1974 * Added for CRM-12695
1975 * Based on the contactID provided
1976 * add/update membership(s) to related contacts
1978 * @param int $contactID
1980 * @throws \CRM_Core_Exception
1981 * @throws \CiviCRM_API3_Exception
1983 public static function addMembershipToRealtedContacts($contactID) {
1984 $dao = new CRM_Member_DAO_Membership();
1985 $dao->contact_id
= $contactID;
1989 //checks membership of contact itself
1990 while ($dao->fetch()) {
1991 $relationshipTypeId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id
, 'relationship_type_id', 'id');
1992 if ($relationshipTypeId) {
1993 $membershipParams = [
1995 'contact_id' => $dao->contact_id
,
1996 'membership_type_id' => $dao->membership_type_id
,
1997 'join_date' => CRM_Utils_Date
::isoToMysql($dao->join_date
),
1998 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
1999 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
2000 'source' => $dao->source
,
2001 'status_id' => $dao->status_id
,
2003 // create/update membership(s) for related contact(s)
2004 CRM_Member_BAO_Membership
::createRelatedMemberships($membershipParams, $dao);
2005 } // end of if relationshipTypeId
2010 * Create activities tracking the merge on affected contacts.
2012 * @param int $mainId
2013 * @param int $otherId
2015 * @throws \CiviCRM_API3_Exception
2017 public static function createMergeActivities($mainId, $otherId) {
2022 $activity = civicrm_api3('activity', 'create', [
2023 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
2025 'subject' => ts('Contact ID %1 has been merged and deleted.', $params),
2026 'target_contact_id' => $mainId,
2027 'activity_type_id' => 'Contact Merged',
2028 'status_id' => 'Completed',
2030 if (civicrm_api3('Setting', 'getvalue', [
2031 'name' => 'contact_undelete',
2032 'group' => 'CiviCRM Preferences',
2034 civicrm_api3('activity', 'create', [
2035 'source_contact_id' => CRM_Core_Session
::getLoggedInContactID() ? CRM_Core_Session
::getLoggedInContactID() :
2037 'subject' => ts('Contact ID %1 has been merged into Contact ID %2 and deleted.', $params),
2038 'target_contact_id' => $otherId,
2039 'activity_type_id' => 'Contact Deleted by Merge',
2040 'parent_id' => $activity['id'],
2041 'status_id' => 'Completed',
2047 * Get Duplicate Pairs based on a rule for a group.
2049 * @param int $rule_group_id
2050 * @param int $group_id
2051 * @param bool $reloadCacheIfEmpty
2052 * Should the cache be reloaded if empty - this must be false when in a dedupe action!
2053 * @param int $batchLimit
2054 * @param bool $isSelected
2055 * Limit to selected pairs.
2056 * @param bool $includeConflicts
2057 * @param array $criteria
2058 * Additional criteria to narrow down the merge group.
2060 * @param bool $checkPermissions
2061 * Respect logged in user permissions.
2063 * @param int $searchLimit
2064 * Limit to searching for matches against this many contacts.
2066 * @param int $isForceNewSearch
2067 * Should a new search be forced, bypassing any cache retrieval.
2070 * Array of matches meeting the criteria.
2072 * @throws \CRM_Core_Exception
2073 * @throws \CiviCRM_API3_Exception
2075 public static function getDuplicatePairs($rule_group_id, $group_id, $reloadCacheIfEmpty, $batchLimit, $isSelected, $includeConflicts = TRUE, $criteria = [], $checkPermissions = TRUE, $searchLimit = 0, $isForceNewSearch = 0) {
2076 $dupePairs = $isForceNewSearch ?
[] : self
::getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, $includeConflicts, $criteria, $checkPermissions, $searchLimit);
2077 if (empty($dupePairs) && $reloadCacheIfEmpty) {
2078 // If we haven't found any dupes, probably cache is empty.
2079 // Try filling cache and give another try. We don't need to specify include conflicts here are there will not be any
2080 // until we have done some processing.
2081 CRM_Core_BAO_PrevNextCache
::refillCache($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit);
2082 return self
::getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, FALSE, $criteria, $checkPermissions, $searchLimit);
2088 * Get the cache key string for the merge action.
2090 * @param int $rule_group_id
2091 * @param int $group_id
2092 * @param array $criteria
2093 * Additional criteria to narrow down the merge group.
2094 * Currently we are only supporting the key 'contact' within it.
2095 * @param bool $checkPermissions
2096 * Respect the users permissions.
2097 * @param int $searchLimit
2098 * Number of contacts to seek dupes for (we need this because if
2099 * we change it the results won't be refreshed otherwise. Changing the limit
2100 * from 100 to 1000 SHOULD result in a new dedupe search).
2104 public static function getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit) {
2105 $contactType = CRM_Dedupe_BAO_DedupeRuleGroup
::getContactTypeForRuleGroup($rule_group_id);
2106 $cacheKeyString = "merge_{$contactType}";
2107 $cacheKeyString .= $rule_group_id ?
"_{$rule_group_id}" : '_0';
2108 $cacheKeyString .= $group_id ?
"_{$group_id}" : '_0';
2109 $cacheKeyString .= '_' . (int) $searchLimit;
2110 $cacheKeyString .= !empty($criteria) ?
md5(serialize($criteria)) : '_0';
2111 if ($checkPermissions) {
2112 $contactID = CRM_Core_Session
::getLoggedInContactID();
2114 // Distinguish between no permission check & no logged in user.
2115 $contactID = 'null';
2117 $cacheKeyString .= '_' . $contactID;
2120 $cacheKeyString .= '_0';
2122 return $cacheKeyString;
2126 * Get the metadata for the merge fields.
2128 * This is basically the contact metadata, augmented with fields to
2129 * represent email greeting, postal greeting & addressee.
2133 public static function getMergeFieldsMetadata() {
2134 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['merge_fields_metadata'])) {
2135 return \Civi
::$statics[__CLASS__
]['merge_fields_metadata'];
2137 $fields = CRM_Contact_DAO_Contact
::fields();
2138 static $optionValueFields = [];
2139 if (empty($optionValueFields)) {
2140 $optionValueFields = CRM_Core_OptionValue
::getFields();
2142 foreach ($optionValueFields as $field => $params) {
2143 $fields[$field]['title'] = $params['title'];
2145 \Civi
::$statics[__CLASS__
]['merge_fields_metadata'] = $fields;
2146 return \Civi
::$statics[__CLASS__
]['merge_fields_metadata'];
2150 * Get the details of the contact to be merged.
2152 * @param int $contact_id
2156 * @throws CRM_Core_Exception
2158 public static function getMergeContactDetails($contact_id) {
2160 'contact_id' => $contact_id,
2162 'return' => array_merge(['display_name'], self
::getContactFields()),
2164 $result = civicrm_api('contact', 'get', $params);
2166 // CRM-18480: Cancel the process if the contact is already deleted
2167 if (isset($result['values'][$contact_id]['contact_is_deleted']) && !empty($result['values'][$contact_id]['contact_is_deleted'])) {
2168 throw new CRM_Core_Exception(ts('Cannot merge because one contact (ID %1) has been deleted.', [
2173 return $result['values'][$contact_id];
2177 * Dedupe a pair of contacts.
2179 * @param int $mainId Id of contact to keep.
2180 * @param int $otherId Id of contact to delete.
2181 * @param string $mode
2182 * @param bool $checkPermissions
2183 * @param string $cacheKeyString
2185 * @return bool|array
2186 * @throws \API_Exception
2187 * @throws \CRM_Core_Exception
2188 * @throws \CRM_Core_Exception_ResourceConflictException
2189 * @throws \CiviCRM_API3_Exception
2190 * @throws \Civi\API\Exception\UnauthorizedException
2192 protected static function dedupePair(int $mainId, int $otherId, $mode = 'safe', $checkPermissions = TRUE, $cacheKeyString = NULL) {
2195 $migrationInfo = [];
2197 // Try to lock the contacts before we load the data as we don't want it changing under us.
2198 // https://lab.civicrm.org/dev/core/issues/1355
2199 $locks = self
::getLocksOnContacts([$mainId, $otherId]);
2200 if (!CRM_Dedupe_Merger
::skipMerge($mainId, $otherId, $migrationInfo, $mode, $conflicts)) {
2201 CRM_Dedupe_Merger
::moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions);
2202 $resultStats['merged'][] = [
2203 'main_id' => $mainId,
2204 'other_id' => $otherId,
2208 $resultStats['skipped'][] = [
2209 'main_id' => $mainId,
2210 'other_id' => $otherId,
2214 // store any conflicts
2215 if (!empty($conflicts)) {
2216 CRM_Core_BAO_PrevNextCache
::markConflict($mainId, $otherId, $cacheKeyString, $conflicts, $mode);
2219 self
::deletePairFromPrevNextCache((int) $mainId, (int) $otherId);
2221 self
::releaseLocks($locks);
2222 return $resultStats;
2226 * Delete merged pair from the previous next cache table as the are no longer a merge candidate.
2228 * It's possible there may be more than one set of merge results cached, with different cache keys.
2229 * Once we have merged a pair these should all go (even from a different merge search) as they
2230 * can only be merged once.
2232 * @param int $contactID1
2233 * @param int $contactID2
2235 protected static function deletePairFromPrevNextCache(int $contactID1, int $contactID2) {
2236 CRM_Core_DAO
::executeQuery("
2237 DELETE FROM civicrm_prevnext_cache
2238 WHERE entity_table = 'civicrm_contact'
2239 AND (entity_id1 = %1 AND entity_id2 = %2) OR (entity_id1 = %2 AND entity_id2 = %1)",
2240 [1 => [$contactID1, 'Integer'], 2 => [$contactID2, 'Integer']]
2245 * Replace the pseudo QFKey with zero if it is present.
2247 * @todo - on the slim chance this is still relevant it should be moved to the form layer.
2249 * Details about this bug are somewhat obscured by the move from svn but perhaps JIRA
2252 * @param array $migrationInfo
2254 protected static function swapOutFieldsAffectedByQFZeroBug(&$migrationInfo) {
2255 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
2256 foreach ($migrationInfo as $key => &$value) {
2257 if ($value === $qfZeroBug) {
2264 * Honestly - what DOES this do - hopefully some refactoring will reveal it's purpose.
2266 * Update this function formats fields in preparation for them to be submitted to the
2267 * 'ProfileContactCreate action. This is a lot of code to do this & for
2268 * - for some fields it fails - e.g Country - per testMergeCustomFields.
2270 * Goal is to move all custom field handling into 'move' functions on the various BAO
2271 * with an underlying DAO function. For custom fields it has been started on the BAO.
2273 * @param int $mainId
2274 * @param string $key
2275 * @param array $cFields
2276 * @param array $submitted
2277 * @param mixed $value
2280 * @throws \CRM_Core_Exception
2282 protected static function processCustomFields($mainId, $key, $cFields, $submitted, $value) {
2283 if (substr($key, 0, 7) === 'custom_') {
2284 $fid = (int) substr($key, 7);
2285 if (empty($cFields[$fid])) {
2286 return [$cFields, $submitted];
2288 $htmlType = $cFields[$fid]['attributes']['html_type'];
2289 $isSerialized = CRM_Core_BAO_CustomField
::isSerialized($cFields[$fid]['attributes']);
2291 if ($htmlType === 'File') {
2292 // Handled in CustomField->move(). Tested in testMergeCustomFields.
2293 unset($submitted["custom_$fid"]);
2295 elseif (!$isSerialized && ($htmlType === 'Select Country' ||
$htmlType === 'Select State/Province')) {
2296 // @todo Test in testMergeCustomFields disabled as this does not work, Handle in CustomField->move().
2297 $submitted[$key] = CRM_Core_BAO_CustomField
::displayValue($value, $fid);
2299 elseif ($htmlType === 'Select Date') {
2300 if ($cFields[$fid]['attributes']['is_view']) {
2301 $submitted[$key] = date('YmdHis', strtotime($submitted[$key]));
2304 elseif ($isSerialized) {
2305 // Merge values from both contacts for multivalue fields, CRM-4385
2306 // get the existing custom values from db.
2307 $customParams = ['entityID' => $mainId, $key => TRUE];
2308 $customfieldValues = CRM_Core_BAO_CustomValueTable
::getValues($customParams);
2309 if (!empty($customfieldValues[$key])) {
2310 $existingValue = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $customfieldValues[$key]);
2311 if (is_array($existingValue) && !empty($existingValue)) {
2312 $mergeValue = $submittedCustomFields = [];
2313 if ($value === 'null') {
2314 // CRM-19074 if someone has deliberately chosen to overwrite with 'null', respect it.
2315 $submitted[$key] = $value;
2319 $submittedCustomFields = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2322 // CRM-19653: overwrite or add the existing custom field value with dupicate contact's
2323 // custom field value stored at $submittedCustomValue.
2324 foreach ($submittedCustomFields as $k => $v) {
2325 if ($v != '' && !in_array($v, $mergeValue)) {
2330 //keep state and country as array format.
2331 //for checkbox and m-select format w/ VALUE_SEPARATOR
2332 if (in_array($htmlType, ['CheckBox', 'Select'])) {
2333 $submitted[$key] = CRM_Utils_Array
::implodePadded($mergeValue);
2336 $submitted[$key] = $mergeValue;
2341 elseif (in_array($htmlType, ['Select Country', 'Select State/Province'])) {
2342 //we require submitted values should be in array format
2344 $mergeValueArray = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $value);
2345 //hack to remove null values from array.
2347 foreach ($mergeValueArray as $k => $v) {
2352 $submitted[$key] = $mergeValue;
2357 return [$cFields, $submitted];
2361 * Get metadata for the custom fields for the merge.
2363 * @param string $contactType
2366 * @throws \CRM_Core_Exception
2368 protected static function getCustomFieldMetadata($contactType) {
2370 if (!array_key_exists($contactType, $treeCache)) {
2371 $treeCache[$contactType] = CRM_Core_BAO_CustomGroup
::getTree(
2386 foreach ($treeCache[$contactType] as $key => $group) {
2387 if (!isset($group['fields'])) {
2390 foreach ($group['fields'] as $fid => $field) {
2391 $cFields[$fid]['attributes'] = $field;
2398 * Get conflicts for proposed merge pair.
2400 * @param array $migrationInfo
2401 * This is primarily to inform hooks. The can also modify it which feels
2402 * pretty fragile to do it here - but it is historical.
2403 * @param int $mainId
2404 * Main contact with whom merge has to happen.
2405 * @param int $otherId
2406 * Duplicate contact which would be deleted after merge operation.
2407 * @param string $mode
2408 * Helps decide how to behave when there are conflicts.
2409 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
2410 * - Does a force merge otherwise (aggressive mode).
2414 * @throws \CRM_Core_Exception
2415 * @throws \CiviCRM_API3_Exception
2417 public static function getConflicts(array &$migrationInfo, int $mainId, int $otherId, string $mode): array {
2419 // Generate var $migrationInfo. The variable structure is exactly same as
2420 // $formValues submitted during a UI merge for a pair of contacts.
2421 $rowsElementsAndInfo = CRM_Dedupe_Merger
::getRowsElementsAndInfo($mainId, $otherId, FALSE);
2422 // add additional details that we might need to resolve conflicts
2423 $migrationInfo = $rowsElementsAndInfo['migration_info'];
2424 $migrationInfo['main_details'] = &$rowsElementsAndInfo['main_details'];
2425 $migrationInfo['other_details'] = &$rowsElementsAndInfo['other_details'];
2426 $migrationInfo['rows'] = &$rowsElementsAndInfo['rows'];
2427 // go ahead with merge if there is no conflict
2428 $originalMigrationInfo = $migrationInfo;
2429 foreach ($migrationInfo as $key => $val) {
2430 if ($val === "null") {
2431 // Rule: Never overwrite with an empty value (in any mode)
2432 unset($migrationInfo[$key]);
2435 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger
::getContactFields()) or
2436 strpos($key, 'move_custom_') === 0
2439 // Rule: If both main-contact, and other-contact have a field with a
2440 // different value, then let $mode decide if to merge it or not
2442 (!empty($migrationInfo['rows'][$key]['main'])
2443 // For custom fields a 0 (e.g in an int field) could be a true conflict. This
2444 // is probably true for other fields too - e.g. 'do_not_email' but
2445 // leaving that investigation as a @todo - until tests can be written.
2446 // Note the handling of this has test coverage - although the data-typing
2447 // of '0' feels flakey we have insurance.
2448 ||
($migrationInfo['rows'][$key]['main'] === '0' && substr($key, 0, 12) === 'move_custom_')
2450 && $migrationInfo['rows'][$key]['main'] != $migrationInfo['rows'][$key]['other']
2453 // note it down & lets wait for response from the hook.
2454 // For no response $mode will decide if to skip this merge
2455 $conflicts[$key] = NULL;
2458 elseif (substr($key, 0, 14) === 'move_location_' and $val != NULL) {
2459 $locField = explode('_', $key);
2460 $fieldName = $locField[2];
2461 $fieldCount = $locField[3];
2463 // Rule: Catch address conflicts (same address type on both contacts)
2465 isset($migrationInfo['main_details']['location_blocks'][$fieldName]) &&
2466 !empty($migrationInfo['main_details']['location_blocks'][$fieldName])
2469 // Load the address we're inspecting from the 'other' contact
2470 $addressRecord = $migrationInfo['other_details']['location_blocks'][$fieldName][$fieldCount];
2471 $addressRecordLocTypeId = $addressRecord['location_type_id'] ??
NULL;
2473 // If it exists on the 'main' contact already, skip it. Otherwise
2474 // if the location type exists already, log a conflict.
2475 foreach ($migrationInfo['main_details']['location_blocks'][$fieldName] as $mainAddressKey => $mainAddressRecord) {
2476 if (!self
::locationHasData($mainAddressRecord)) {
2477 // Go ahead & overwrite the main address - it has no data in it.
2478 // if it is the primary address then pass that honour to the address that actually has data.
2479 $migrationInfo['location_blocks'][$fieldName][$mainAddressKey]['set_other_primary'] = $mainAddressRecord['is_primary'];
2482 if (self
::locationIsSame($addressRecord, $mainAddressRecord)) {
2483 unset($migrationInfo[$key]);
2486 if ($addressRecordLocTypeId == $mainAddressRecord['location_type_id']) {
2487 $conflicts[$key] = NULL;
2493 // For other locations, don't merge/add if the values are the same
2494 elseif (CRM_Utils_Array
::value('main', $migrationInfo['rows'][$key]) == $migrationInfo['rows'][$key]['other']) {
2495 unset($migrationInfo[$key]);
2500 // A hook to implement other algorithms for choosing which contact to bias to when
2501 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
2502 // merge happens with new values filled in here. For a particular field / row not to be merged
2503 // field should be unset from fields_in_conflict.
2505 'old_migration_info' => $originalMigrationInfo,
2507 'fields_in_conflict' => $conflicts,
2508 'merge_mode' => $mode,
2509 'migration_info' => $migrationInfo,
2511 CRM_Utils_Hook
::merge('batch', $migrationData, $mainId, $otherId);
2512 $conflicts = $migrationData['fields_in_conflict'];
2513 // allow hook to override / manipulate migrationInfo as well
2514 $migrationInfo = $migrationData['migration_info'];
2515 foreach ($conflicts as $key => $val) {
2516 // Copy over the resolved values. If we are in aggressive mode we update to null
2517 // so as not to copy over. Why it's different to safe mode is a bit murky.
2518 // Working theory is it doesn't matter what we do in safe mode here if $val is NULL.
2519 // as the merge is not gonna happen if $val == NULL
2520 $migrationInfo[$key] = $val ??
($mode === 'safe' ?
$migrationInfo[$key] : NULL);
2522 return self
::formatConflictArray($conflicts, $migrationInfo['rows'], $migrationInfo['main_details']['location_blocks'], $migrationInfo['other_details']['location_blocks'], $mainId, $otherId, $mode);
2526 * @param array $conflicts
2527 * @param array $migrationInfo
2528 * @param $toKeepContactLocationBlocks
2529 * @param $toRemoveContactLocationBlocks
2531 * @param $toRemoveID
2532 * @param string $mode
2535 * @throws \CRM_Core_Exception
2537 protected static function formatConflictArray($conflicts, $migrationInfo, $toKeepContactLocationBlocks, $toRemoveContactLocationBlocks, $toKeepID, $toRemoveID, $mode) {
2540 foreach ($conflicts as $key => $val) {
2541 if ($val !== NULL) {
2542 // copy over the resolved values
2543 $resolved[$key] = $val;
2544 unset($conflicts[$key]);
2546 elseif ($mode === 'aggressive') {
2547 unset($conflicts[$key]);
2548 if (strpos($key, 'move_location_') !== 0) {
2549 // @todo - just handling plain contact fields for now because I think I need a bigger refactor
2550 // of the below to handle locations & will do as a follow up.
2551 $resolved['contact'][substr($key, 5)] = $migrationInfo[$key]['main'];
2555 foreach (array_keys($conflicts) as $index) {
2556 if (substr($index, 0, 14) === 'move_location_') {
2557 $parts = explode('_', $index);
2558 $entity = $parts[2];
2559 $blockIndex = $parts[3];
2560 $locationTypeID = $toKeepContactLocationBlocks[$entity][$blockIndex]['location_type_id'];
2561 $entityConflicts = [
2562 'location_type_id' => $locationTypeID,
2563 'title' => $migrationInfo[$index]['title'],
2565 foreach ($toKeepContactLocationBlocks[$entity][$blockIndex] as $fieldName => $fieldValue) {
2566 if (in_array($fieldName, self
::ignoredFields())) {
2569 $toRemoveValue = $toRemoveContactLocationBlocks[$entity][$blockIndex][$fieldName] ??
NULL;
2570 if ($fieldValue !== $toRemoveValue) {
2571 $entityConflicts[$fieldName] = [
2572 $toKeepID => $fieldValue,
2573 $toRemoveID => $toRemoveValue,
2577 $return[$entity][] = $entityConflicts;
2579 elseif (substr($index, 0, 5) === 'move_') {
2580 $contactFieldsToCompare[] = str_replace('move_', '', $index);
2581 $return['contact'][str_replace('move_', '', $index)] = [
2582 'title' => $migrationInfo[$index]['title'],
2583 $toKeepID => $migrationInfo[$index]['main'],
2584 $toRemoveID => $migrationInfo[$index]['other'],
2588 // Can't think of why this would be the case but perhaps it's ensuring it isn't as we
2590 throw new CRM_Core_Exception(ts('Unknown parameter') . $index);
2593 return ['conflicts' => $return, 'resolved' => $resolved];
2597 * Get any duplicate merge pairs that have been previously cached.
2599 * @param int $rule_group_id
2600 * @param int $group_id
2601 * @param int $batchLimit
2602 * @param bool $isSelected
2603 * @param bool $includeConflicts
2604 * @param array $criteria
2605 * @param int $checkPermissions
2606 * @param int $searchLimit
2610 protected static function getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, $includeConflicts, $criteria, $checkPermissions, $searchLimit = 0) {
2611 return CRM_Core_BAO_PrevNextCache
::retrieve(
2612 self
::getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit),
2613 self
::getJoinOnDedupeTable(),
2614 self
::getWhereString($isSelected),
2624 protected static function ignoredFields(): array {
2634 return $keysToIgnore;
2638 * Get the field value & label for the given field.
2644 * @throws \Exception
2646 private static function getFieldValueAndLabel($field, $contact): array {
2647 $fields = self
::getMergeFieldsMetadata();
2648 $value = $label = $contact[$field] ??
NULL;
2649 $fieldSpec = $fields[$field];
2650 if (!empty($fieldSpec['serialize']) && is_array($value)) {
2651 // In practice this only applies to preferred_communication_method as the sub types are skipped above
2652 // and no others are serialized.
2654 foreach ($value as $individualValue) {
2655 $labels[] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $field, $individualValue);
2657 $label = implode(', ', $labels);
2658 // We serialize this due to historic handling but it's likely that if we just left it as an
2659 // array all would be well & we would have less code.
2660 $value = CRM_Core_DAO
::serializeField($value, $fieldSpec['serialize']);
2662 elseif (!empty($fieldSpec['type']) && $fieldSpec['type'] == CRM_Utils_Type
::T_DATE
) {
2664 $value = str_replace('-', '', $value);
2665 $label = CRM_Utils_Date
::customFormat($label);
2671 elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type
::T_BOOLEAN
) {
2672 if ($label === '0') {
2675 if ($label === '1') {
2679 elseif (!empty($fieldSpec['pseudoconstant'])) {
2680 $label = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $field, $value);
2682 elseif ($field == 'current_employer_id' && !empty($value)) {
2683 $label = "$value (" . CRM_Contact_BAO_Contact
::displayName($value) . ")";
2685 return ['label' => $label, 'value' => $value];
2689 * Build up the location block for the contact in dedupe-screen display format.
2691 * @param integer $cid
2692 * @param array $blockInfo
2693 * @param string $blockName
2697 * @throws \CiviCRM_API3_Exception
2699 private static function buildLocationBlockForContact($cid, $blockInfo, $blockName): array {
2701 'contact_id' => $cid,
2702 // CRM-17556 Order by field-specific criteria
2704 'sort' => $blockInfo['sortString'],
2707 $locationBlock = [];
2708 $values = civicrm_api3($blockName, 'get', $searchParams);
2709 if ($values['count']) {
2711 foreach ($values['values'] as $value) {
2712 $locationBlock[$cnt] = $value;
2713 // Fix address display
2714 if ($blockName == 'address') {
2715 // For performance avoid geocoding while merging https://issues.civicrm.org/jira/browse/CRM-21786
2716 // we can expect existing geocode values to be retained.
2717 $value['skip_geocode'] = TRUE;
2718 CRM_Core_BAO_Address
::fixAddress($value);
2719 unset($value['skip_geocode']);
2720 $locationBlock[$cnt]['display'] = CRM_Utils_Address
::format($value);
2722 // Fix email display
2723 elseif ($blockName == 'email') {
2724 $locationBlock[$cnt]['display'] = CRM_Utils_Mail
::format($value);
2730 return $locationBlock;
2734 * Get a lock on the given contact.
2736 * The lock is like a gentleman's agreement between php & mysql. It is reserved at the
2737 * mysql level so it works across php processes but it doesn't actually lock the database.
2739 * Instead php can check the lock to see if it has been acquired before taking an action.
2741 * In this case we really don't want to attempt to dedupe contacts if another process is
2742 * trying to act on the specific contact as it could result in messy deadlocks & possibly data corruption.
2743 * In most databases this would be a rare event but if multiple dedupe processes are running
2744 * at once (for example) or there is also an import process in play there is potential for them to crash.
2745 * By throwing a specific error the calling process can catch it and determine it is worth trying again later without a lot of
2748 * As of writing no other processes DO grab contact locks but it would be reasonable to consider
2749 * grabbing them doing contact edits in general as well as imports etc.
2751 * @param array $contacts
2755 * @throws \CRM_Core_Exception
2756 * @throws \CRM_Core_Exception_ResourceConflictException
2758 protected static function getLocksOnContacts($contacts):array {
2760 if (!CRM_Utils_SQL
::supportsMultipleLocks()) {
2763 foreach ($contacts as $contactID) {
2764 $lock = Civi
::lockManager()->acquire("data.core.contact.{$contactID}");
2765 if ($lock->isAcquired()) {
2769 self
::releaseLocks($locks);
2770 throw new CRM_Core_Exception_ResourceConflictException(ts('Contact is in Use'), 'contact_lock');
2777 * Release contact locks so another process can alter them if it wants.
2779 * @param array $locks
2781 protected static function releaseLocks(array $locks) {
2782 foreach ($locks as $lock) {
2783 /* @var Civi\Core\Lock\LockInterface $lock */
2793 * @param array $locations
2794 * @param array $rows
2795 * @param array $elements
2796 * @param array $migrationInfo
2799 * @throws \CiviCRM_API3_Exception
2801 protected static function addLocationFieldInfo($mainId, $otherId, $blockInfo, $blockName, array $locations, array $rows, array $elements, array $migrationInfo): array {
2802 // Collect existing fields from both 'main' and 'other' contacts first
2803 // This allows us to match up location/types when building the table rows
2804 $locations['main'][$blockName] = self
::buildLocationBlockForContact($mainId, $blockInfo, $blockName);
2805 $locations['other'][$blockName] = self
::buildLocationBlockForContact($otherId, $blockInfo, $blockName);
2807 // Now, build the table rows appropriately, based off the information on
2808 // the 'other' contact
2809 if (!empty($locations['other']) && !empty($locations['other'][$blockName])) {
2810 foreach ($locations['other'][$blockName] as $count => $value) {
2812 $displayValue = $value[$blockInfo['displayField']];
2814 // Add this value to the table rows
2815 $rows["move_location_{$blockName}_{$count}"]['other'] = $displayValue;
2817 // CRM-17556 Only display 'main' contact value if it's the same location + type
2818 // Look it up from main values...
2820 $lookupLocation = FALSE;
2821 if ($blockInfo['hasLocation']) {
2822 $lookupLocation = $value['location_type_id'];
2825 $lookupType = FALSE;
2826 if ($blockInfo['hasType']) {
2827 $lookupType = $value[$blockInfo['hasType']] ??
NULL;
2830 // Hold ID of main contact's matching block
2831 $mainContactBlockId = 0;
2833 if (!empty($locations['main'][$blockName])) {
2834 foreach ($locations['main'][$blockName] as $mainValueCheck) {
2835 // No location/type, or matching location and type
2837 (empty($lookupLocation) ||
$lookupLocation == $mainValueCheck['location_type_id'])
2838 && (empty($lookupType) ||
$lookupType == $mainValueCheck[$blockInfo['hasType']])
2840 // Set this value as the default against the 'other' contact value
2841 $rows["move_location_{$blockName}_{$count}"]['main'] = $mainValueCheck[$blockInfo['displayField']];
2842 $rows["move_location_{$blockName}_{$count}"]['main_is_primary'] = $mainValueCheck['is_primary'] ??
0;
2843 $rows["move_location_{$blockName}_{$count}"]['location_entity'] = $blockName;
2844 $mainContactBlockId = $mainValueCheck['id'];
2850 // Add checkbox to migrate data from 'other' to 'main'
2851 $elements[] = ['advcheckbox', "move_location_{$blockName}_{$count}"];
2853 // Add checkbox to set the 'other' location as primary
2856 "location_blocks[$blockName][$count][set_other_primary]",
2858 ts('Set as primary'),
2861 // Flag up this field to skipMerge function (@todo: do we need to?)
2862 $migrationInfo["move_location_{$blockName}_{$count}"] = 1;
2864 // Add a hidden field to store the ID of the target main contact block
2867 "location_blocks[$blockName][$count][mainContactBlockId]",
2868 $mainContactBlockId,
2872 $thisTypeId = FALSE;
2875 // Provide a select drop-down for the location's location type
2876 // eg: Home, Work...
2878 if ($blockInfo['hasLocation']) {
2880 // Load the location options for this entity
2881 $locationOptions = civicrm_api3($blockName, 'getoptions', ['field' => 'location_type_id']);
2883 $thisLocId = $value['location_type_id'];
2885 // Put this field's location type at the top of the list
2886 $tmpIdList = $locationOptions['values'];
2887 $defaultLocId = [$thisLocId => $tmpIdList[$thisLocId]];
2888 unset($tmpIdList[$thisLocId]);
2893 "location_blocks[$blockName][$count][locTypeId]",
2895 $defaultLocId +
$tmpIdList,
2898 // Add the relevant information to the $migrationInfo
2899 // Keep location-type-id same as that of other-contact
2900 // @todo Check this logic out
2901 $migrationInfo['location_blocks'][$blockName][$count]['locTypeId'] = $thisLocId;
2902 if ($blockName != 'address') {
2905 "location_blocks[{$blockName}][$count][operation]",
2909 // always use add operation
2910 $migrationInfo['location_blocks'][$blockName][$count]['operation'] = 1;
2915 // Provide a select drop-down for the location's type/provider
2916 // eg websites: Facebook...
2918 if ($blockInfo['hasType']) {
2920 // Load the type options for this entity
2921 $typeOptions = civicrm_api3($blockName, 'getoptions', ['field' => $blockInfo['hasType']]);
2923 $thisTypeId = $value[$blockInfo['hasType']] ??
NULL;
2925 // Put this field's location type at the top of the list
2926 $tmpIdList = $typeOptions['values'];
2927 $defaultTypeId = [$thisTypeId => CRM_Utils_Array
::value($thisTypeId, $tmpIdList)];
2928 unset($tmpIdList[$thisTypeId]);
2933 "location_blocks[$blockName][$count][typeTypeId]",
2935 $defaultTypeId +
$tmpIdList,
2938 // Add the information to the migrationInfo
2939 $migrationInfo['location_blocks'][$blockName][$count]['typeTypeId'] = $thisTypeId;
2943 // Set the label for this row
2944 $rowTitle = $blockInfo['label'] . ' ' . ($count +
1);
2945 if (!empty($thisLocId)) {
2946 $rowTitle .= ' (' . $locationOptions['values'][$thisLocId] . ')';
2948 if (!empty($thisTypeId)) {
2949 $rowTitle .= ' (' . $typeOptions['values'][$thisTypeId] . ')';
2951 $rows["move_location_{$blockName}_$count"]['title'] = $rowTitle;
2953 } // End loop through 'other' locations of this type
2956 return [$locations, $rows, $elements, $migrationInfo];