[REF] Tighten up function signature for dedupePair
[civicrm-core.git] / CRM / Dedupe / Merger.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035 11
fe3b8caf 12use Civi\Api4\CustomGroup;
13
6a488035
TO
14/**
15 *
16 * @package CRM
ca5cec67 17 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
18 */
19class CRM_Dedupe_Merger {
6a488035 20
e0ef6999 21 /**
4f1f1f2a
CW
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
723c5a81 25 *
e0ef6999 26 * @return array
723c5a81 27 * @throws \CiviCRM_API3_Exception
e0ef6999 28 */
00be9182 29 public static function relTables() {
6a488035 30
641a8cb5 31 if (!isset(Civi::$statics[__CLASS__]['relTables'])) {
12d73bba 32
641a8cb5
J
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 = '';
38
39 $config = CRM_Core_Config::singleton();
8372e605 40 // @todo - this user url stuff is only needed for the form layer - move to CRM_Contact_Form_Merge
641a8cb5
J
41 if ($config->userSystem->is_drupal) {
42 $userRecordUrl = CRM_Utils_System::url('user/%ufid');
2c16165a 43 $title = ts('%1 User: %2; user id: %3', [
44 1 => $config->userFramework,
45 2 => '$ufname',
46 3 => '$ufid',
47 ]);
641a8cb5 48 }
723c5a81 49 elseif ($config->userFramework === 'Joomla') {
641a8cb5 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';
2c16165a 51 $title = ts('%1 User: %2; user id: %3', [
52 1 => $config->userFramework,
53 2 => '$ufname',
54 3 => '$ufid',
55 ]);
641a8cb5 56 }
6a488035 57
2c16165a 58 $relTables = [
59 'rel_table_contributions' => [
6a488035 60 'title' => ts('Contributions'),
2c16165a 61 'tables' => [
62 'civicrm_contribution',
63 'civicrm_contribution_recur',
64 'civicrm_contribution_soft',
65 ],
6a488035 66 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=contribute'),
2c16165a 67 ],
68 'rel_table_contribution_page' => [
6a488035 69 'title' => ts('Contribution Pages'),
2c16165a 70 'tables' => ['civicrm_contribution_page'],
6a488035 71 'url' => CRM_Utils_System::url('civicrm/admin/contribute', 'reset=1&cid=$cid'),
2c16165a 72 ],
73 'rel_table_memberships' => [
6a488035 74 'title' => ts('Memberships'),
2c16165a 75 'tables' => [
76 'civicrm_membership',
77 'civicrm_membership_log',
78 'civicrm_membership_type',
79 ],
6a488035 80 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=member'),
2c16165a 81 ],
82 'rel_table_participants' => [
6a488035 83 'title' => ts('Participants'),
2c16165a 84 'tables' => ['civicrm_participant'],
6a488035 85 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=participant'),
2c16165a 86 ],
87 'rel_table_events' => [
6a488035 88 'title' => ts('Events'),
2c16165a 89 'tables' => ['civicrm_event'],
6a488035 90 'url' => CRM_Utils_System::url('civicrm/event/manage', 'reset=1&cid=$cid'),
2c16165a 91 ],
92 'rel_table_activities' => [
6a488035 93 'title' => ts('Activities'),
2c16165a 94 'tables' => ['civicrm_activity', 'civicrm_activity_contact'],
6a488035 95 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=activity'),
2c16165a 96 ],
97 'rel_table_relationships' => [
6a488035 98 'title' => ts('Relationships'),
2c16165a 99 'tables' => ['civicrm_relationship'],
6a488035 100 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=rel'),
2c16165a 101 ],
102 'rel_table_custom_groups' => [
6a488035 103 'title' => ts('Custom Groups'),
2c16165a 104 'tables' => ['civicrm_custom_group'],
6a488035 105 'url' => CRM_Utils_System::url('civicrm/admin/custom/group', 'reset=1'),
2c16165a 106 ],
107 'rel_table_uf_groups' => [
6a488035 108 'title' => ts('Profiles'),
2c16165a 109 'tables' => ['civicrm_uf_group'],
6a488035 110 'url' => CRM_Utils_System::url('civicrm/admin/uf/group', 'reset=1'),
2c16165a 111 ],
112 'rel_table_groups' => [
6a488035 113 'title' => ts('Groups'),
2c16165a 114 'tables' => ['civicrm_group_contact'],
6a488035 115 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=group'),
2c16165a 116 ],
117 'rel_table_notes' => [
6a488035 118 'title' => ts('Notes'),
2c16165a 119 'tables' => ['civicrm_note'],
6a488035 120 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=note'),
2c16165a 121 ],
122 'rel_table_tags' => [
6a488035 123 'title' => ts('Tags'),
2c16165a 124 'tables' => ['civicrm_entity_tag'],
6a488035 125 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=tag'),
2c16165a 126 ],
127 'rel_table_mailings' => [
6a488035 128 'title' => ts('Mailings'),
2c16165a 129 'tables' => [
130 'civicrm_mailing',
131 'civicrm_mailing_event_queue',
132 'civicrm_mailing_event_subscribe',
133 ],
f521f375 134 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=mailing'),
2c16165a 135 ],
136 'rel_table_cases' => [
6a488035 137 'title' => ts('Cases'),
2c16165a 138 'tables' => ['civicrm_case_contact'],
6a488035 139 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=case'),
2c16165a 140 ],
141 'rel_table_grants' => [
6a488035 142 'title' => ts('Grants'),
2c16165a 143 'tables' => ['civicrm_grant'],
6a488035 144 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=grant'),
2c16165a 145 ],
146 'rel_table_pcp' => [
6a488035 147 'title' => ts('PCPs'),
2c16165a 148 'tables' => ['civicrm_pcp'],
6a488035 149 'url' => CRM_Utils_System::url('civicrm/contribute/pcp/manage', 'reset=1'),
2c16165a 150 ],
151 'rel_table_pledges' => [
6a488035 152 'title' => ts('Pledges'),
2c16165a 153 'tables' => ['civicrm_pledge', 'civicrm_pledge_payment'],
6a488035 154 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=pledge'),
2c16165a 155 ],
156 'rel_table_users' => [
6a488035 157 'title' => $title,
2c16165a 158 'tables' => ['civicrm_uf_match'],
6a488035 159 'url' => $userRecordUrl,
2c16165a 160 ],
161 ];
6a488035 162
76c53278
CW
163 $relTables += self::getMultiValueCustomSets('relTables');
164
6a488035
TO
165 // Allow hook_civicrm_merge() to adjust $relTables
166 CRM_Utils_Hook::merge('relTables', $relTables);
641a8cb5
J
167
168 // Cache the results in a static variable
169 Civi::$statics[__CLASS__]['relTables'] = $relTables;
6a488035 170 }
641a8cb5
J
171
172 return Civi::$statics[__CLASS__]['relTables'];
6a488035
TO
173 }
174
175 /**
fe482240 176 * Returns the related tables groups for which a contact has any info entered.
ad37ac8e 177 *
178 * @param int $cid
179 *
180 * @return array
723c5a81 181 * @throws \CiviCRM_API3_Exception
6a488035 182 */
00be9182 183 public static function getActiveRelTables($cid) {
6a488035 184 $cid = (int) $cid;
2c16165a 185 $groups = [];
6a488035
TO
186
187 $relTables = self::relTables();
188 $cidRefs = self::cidRefs();
189 $eidRefs = self::eidRefs();
190 foreach ($relTables as $group => $params) {
2c16165a 191 $sqls = [];
6a488035
TO
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";
196 }
197 }
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'";
201 }
202 }
203 foreach ($sqls as $sql) {
204 if (CRM_Core_DAO::singleValueQuery($sql) > 0) {
205 $groups[] = $group;
206 }
207 }
208 }
209 }
210 return array_unique($groups);
211 }
212
213 /**
3ae0ae3d 214 * Get array tables and fields that reference civicrm_contact.id.
215 *
e3e87c73 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.
3ae0ae3d 218 *
e3e87c73 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.
6a488035 221 */
00be9182 222 public static function cidRefs() {
e31c3de1 223 if (isset(\Civi::$statics[__CLASS__]) && isset(\Civi::$statics[__CLASS__]['contact_references'])) {
224 return \Civi::$statics[__CLASS__]['contact_references'];
225 }
64b3569d 226
e3e87c73 227 $contactReferences = $coreReferences = CRM_Core_DAO::getReferencesToContactTable();
05fe457a 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]);
232 }
6a488035 233
e31c3de1 234 CRM_Utils_Hook::merge('cidRefs', $contactReferences);
e3e87c73 235 if ($contactReferences !== $coreReferences) {
2c16165a 236 Civi::log()
237 ->warning("Deprecated hook ::merge in context of 'cidRefs. Use entityTypes instead.", ['civi.tag' => 'deprecated']);
e3e87c73 238 }
e31c3de1 239 \Civi::$statics[__CLASS__]['contact_references'] = $contactReferences;
240 return \Civi::$statics[__CLASS__]['contact_references'];
6a488035
TO
241 }
242
243 /**
244 * Return tables and their fields referencing civicrm_contact.contact_id with entity_id
245 */
00be9182 246 public static function eidRefs() {
6a488035
TO
247 static $eidRefs;
248 if (!$eidRefs) {
249 // FIXME: this should be generated dynamically from the schema
250 // tables that reference contacts with entity_{id,table}
2c16165a 251 $eidRefs = [
252 'civicrm_acl' => ['entity_table' => 'entity_id'],
253 'civicrm_acl_entity_role' => ['entity_table' => 'entity_id'],
254 'civicrm_entity_file' => ['entity_table' => 'entity_id'],
255 'civicrm_log' => ['entity_table' => 'entity_id'],
256 'civicrm_mailing_group' => ['entity_table' => 'entity_id'],
257 'civicrm_note' => ['entity_table' => 'entity_id'],
258 ];
6a488035
TO
259
260 // Allow hook_civicrm_merge() to adjust $eidRefs
261 CRM_Utils_Hook::merge('eidRefs', $eidRefs);
262 }
263 return $eidRefs;
264 }
265
9da04f20 266 /**
fe482240 267 * Return tables using locations.
9da04f20 268 */
00be9182 269 public static function locTables() {
9da04f20
AS
270 static $locTables;
271 if (!$locTables) {
2c16165a 272 $locTables = ['civicrm_email', 'civicrm_address', 'civicrm_phone'];
9da04f20
AS
273
274 // Allow hook_civicrm_merge() to adjust $locTables
275 CRM_Utils_Hook::merge('locTables', $locTables);
276 }
277 return $locTables;
278 }
279
76c53278
CW
280 /**
281 * We treat multi-valued custom sets as "related tables" similar to activities, contributions, etc.
6d277089 282 *
98997235
TO
283 * @param string $request
284 * 'relTables' or 'cidRefs'.
6d277089 285 *
641a8cb5 286 * @return array
6d277089 287 * @throws \CiviCRM_API3_Exception
76c53278
CW
288 * @see CRM-13836
289 */
00be9182 290 public static function getMultiValueCustomSets($request) {
641a8cb5
J
291
292 if (!isset(Civi::$statics[__CLASS__]['multiValueCustomSets'])) {
2c16165a 293 $data = [
294 'relTables' => [],
295 'cidRefs' => [],
296 ];
297 $result = civicrm_api3('custom_group', 'get', [
76c53278 298 'is_multiple' => 1,
2c16165a 299 'extends' => [
300 'IN' => [
301 'Individual',
302 'Organization',
303 'Household',
304 'Contact',
305 ],
306 ],
307 'return' => ['id', 'title', 'table_name', 'style'],
308 ]);
22e263ad 309 foreach ($result['values'] as $custom) {
2c16165a 310 $data['cidRefs'][$custom['table_name']] = ['entity_id'];
723c5a81 311 $urlSuffix = $custom['style'] === 'Tab' ? '&selectedChild=custom_' . $custom['id'] : '';
2c16165a 312 $data['relTables']['rel_table_custom_' . $custom['id']] = [
76c53278 313 'title' => $custom['title'],
2c16165a 314 'tables' => [$custom['table_name']],
76c53278 315 'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid' . $urlSuffix),
2c16165a 316 ];
76c53278 317 }
641a8cb5
J
318
319 // Store the result in a static variable cache
320 Civi::$statics[__CLASS__]['multiValueCustomSets'] = $data;
76c53278 321 }
641a8cb5
J
322
323 return Civi::$statics[__CLASS__]['multiValueCustomSets'][$request];
76c53278
CW
324 }
325
6a488035
TO
326 /**
327 * Tables which require custom processing should declare functions to call here.
328 * Doing so will override normal processing.
329 */
00be9182 330 public static function cpTables() {
6a488035
TO
331 static $tables;
332 if (!$tables) {
2c16165a 333 $tables = [
334 'civicrm_case_contact' => ['CRM_Case_BAO_Case' => 'mergeContacts'],
335 'civicrm_group_contact' => ['CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'],
6a488035 336 // Empty array == do nothing - this table is handled by mergeGroupContact
2c16165a 337 'civicrm_subscription_history' => [],
338 'civicrm_relationship' => ['CRM_Contact_BAO_Relationship' => 'mergeRelationships'],
339 'civicrm_membership' => ['CRM_Member_BAO_Membership' => 'mergeMemberships'],
340 ];
6a488035
TO
341 }
342 return $tables;
343 }
344
345 /**
100fef9d 346 * Return payment related table.
6a488035 347 */
00be9182 348 public static function paymentTables() {
6a488035
TO
349 static $tables;
350 if (!$tables) {
2c16165a 351 $tables = ['civicrm_pledge', 'civicrm_membership', 'civicrm_participant'];
6a488035 352 }
6a488035
TO
353 return $tables;
354 }
355
356 /**
100fef9d 357 * Return payment update Query.
54957108 358 *
359 * @param string $tableName
360 * @param int $mainContactId
361 * @param int $otherContactId
362 *
363 * @return array
6a488035 364 */
00be9182 365 public static function paymentSql($tableName, $mainContactId, $otherContactId) {
2c16165a 366 $sqls = [];
6a488035
TO
367 if (!$tableName || !$mainContactId || !$otherContactId) {
368 return $sqls;
369 }
370
371 $paymentTables = self::paymentTables();
372 if (!in_array($tableName, $paymentTables)) {
373 return $sqls;
374 }
375
376 switch ($tableName) {
377 case 'civicrm_pledge':
378 $sqls[] = "
379 UPDATE IGNORE civicrm_contribution contribution
380INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id )
381INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id )
382 SET contribution.contact_id = $mainContactId
383 WHERE pledge.contact_id = $otherContactId";
384 break;
385
386 case 'civicrm_membership':
387 $sqls[] = "
388 UPDATE IGNORE civicrm_contribution contribution
389INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id )
390INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id )
391 SET contribution.contact_id = $mainContactId
392 WHERE membership.contact_id = $otherContactId";
393 break;
394
395 case 'civicrm_participant':
396 $sqls[] = "
397 UPDATE IGNORE civicrm_contribution contribution
398INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id )
399INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id )
400 SET contribution.contact_id = $mainContactId
401 WHERE participant.contact_id = $otherContactId";
402 break;
403 }
404
405 return $sqls;
406 }
407
e0ef6999 408 /**
100fef9d
CW
409 * @param int $mainId
410 * @param int $otherId
411 * @param string $tableName
e0ef6999
EM
412 * @param array $tableOperations
413 * @param string $mode
414 *
415 * @return array
416 */
2c16165a 417 public static function operationSql($mainId, $otherId, $tableName, $tableOperations = [], $mode = 'add') {
418 $sqls = [];
6a488035
TO
419 if (!$tableName || !$mainId || !$otherId) {
420 return $sqls;
421 }
422
6a488035
TO
423 switch ($tableName) {
424 case 'civicrm_membership':
d58a19a1
TO
425 if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add']) {
426 break;
427 }
723c5a81 428 if ($mode === 'add') {
d58a19a1 429 $sqls[] = "
6a488035
TO
430DELETE membership1.* FROM civicrm_membership membership1
431 INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
432 AND membership1.contact_id = {$mainId}
433 AND membership2.contact_id = {$otherId} ";
d58a19a1 434 }
723c5a81 435 if ($mode === 'payment') {
d58a19a1 436 $sqls[] = "
6a488035
TO
437DELETE contribution.* FROM civicrm_contribution contribution
438INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id
439INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id
440 AND membership1.contact_id = {$mainId}
441INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
442 AND membership2.contact_id = {$otherId}";
d58a19a1
TO
443 }
444 break;
6a488035
TO
445
446 case 'civicrm_uf_match':
447 // normal queries won't work for uf_match since that will lead to violation of unique constraint,
b44e3f84 448 // failing to meet intended result. Therefore we introduce this additional query:
6a488035
TO
449 $sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}";
450 break;
451 }
452
453 return $sqls;
454 }
455
4099a9c5
AP
456 /**
457 * Based on the provided two contact_ids and a set of tables, remove the
458 * belongings of the other contact and of their relations.
459 *
460 * @param int $otherID
6d277089 461 * @param array $tables
462 *
463 * @throws \CiviCRM_API3_Exception
4099a9c5
AP
464 */
465 public static function removeContactBelongings($otherID, $tables) {
466 // CRM-20421: Removing Inherited memberships when memberships of parent are not migrated to new contact.
6d277089 467 if (in_array('civicrm_membership', $tables, TRUE)) {
4099a9c5
AP
468 $membershipIDs = CRM_Utils_Array::collect('id',
469 CRM_Utils_Array::value('values',
6d277089 470 civicrm_api3('Membership', "get", [
471 'contact_id' => $otherID,
472 'return' => 'id',
518fa0ee 473 ])
e122e55d
TO
474 )
475 );
4099a9c5
AP
476
477 if (!empty($membershipIDs)) {
6d277089 478 civicrm_api3('Membership', 'get', [
2c16165a 479 'owner_membership_id' => ['IN' => $membershipIDs],
480 'api.Membership.delete' => ['id' => '$value.id'],
481 ]);
4099a9c5
AP
482 }
483 }
484 }
485
6a488035
TO
486 /**
487 * Based on the provided two contact_ids and a set of tables, move the
488 * belongings of the other contact to the main one.
489 *
eca28463 490 * @param CRM_Dedupe_MergeHandler $mergeHandler
fe3b8caf 491 * @param array $tables
54957108 492 * @param array $tableOperations
6d277089 493 *
fe3b8caf 494 * @throws \API_Exception
6d277089 495 * @throws \CiviCRM_API3_Exception
fe3b8caf 496 * @throws \Civi\API\Exception\UnauthorizedException
6a488035 497 */
eca28463 498 public static function moveContactBelongings($mergeHandler, $tables, $tableOperations) {
499 $mainId = $mergeHandler->getToKeepID();
500 $otherId = $mergeHandler->getToRemoveID();
6a488035 501 $cidRefs = self::cidRefs();
eca28463 502 $eidRefs = $mergeHandler->getTablesDynamicallyRelatedToContactTable();
9811efd4 503 $dynamicRefs = CRM_Core_DAO::getDynamicReferencesToTable('civicrm_contact');
6a488035
TO
504 $cpTables = self::cpTables();
505 $paymentTables = self::paymentTables();
fe3b8caf 506 self::filterRowBasedCustomDataFromCustomTables($cidRefs);
674920ca
ES
507
508 $affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
0556db5d
CR
509
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();
eca28463 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']);
0556db5d
CR
516 $handled = self::locTables();
517
518 foreach ($relTables as $params) {
519 $handled = array_merge($handled, $params['tables']);
6a488035 520 }
0556db5d 521 $affected = array_diff($affected, $handled);
e3159b07 522 $affected = array_unique(array_merge($affected, $tables));
6a488035
TO
523
524 $mainId = (int) $mainId;
525 $otherId = (int) $otherId;
526
2c16165a 527 $sqls = [];
6a488035
TO
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) {
43d4ad93 532 $className::$fnName($mainId, $otherId, $sqls, $tables, $tableOperations);
6a488035
TO
533 }
534 // Skip normal processing
535 continue;
536 }
b3fdbf3d 537
59041f88 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";
541 continue;
542 }
543
6a488035
TO
544 // use UPDATE IGNORE + DELETE query pair to skip on situations when
545 // there's a UNIQUE restriction on ($field, some_other_field) pair
546 if (isset($cidRefs[$table])) {
547 foreach ($cidRefs[$table] as $field) {
548 // carry related contributions CRM-5359
549 if (in_array($table, $paymentTables)) {
6a488035
TO
550 $paymentSqls = self::paymentSql($table, $mainId, $otherId);
551 $sqls = array_merge($sqls, $paymentSqls);
71560cf3
C
552
553 if (!empty($tables) && !in_array('civicrm_contribution', $tables)) {
554 $payOprSqls = self::operationSql($mainId, $otherId, $table, $tableOperations, 'payment');
555 $sqls = array_merge($sqls, $payOprSqls);
556 }
6a488035
TO
557 }
558
559 $preOperationSqls = self::operationSql($mainId, $otherId, $table, $tableOperations);
560 $sqls = array_merge($sqls, $preOperationSqls);
bbc11d19 561 $sqls[] = "UPDATE $table SET $field = $mainId WHERE $field = $otherId";
6a488035
TO
562 }
563 }
ae2346d4 564
6a488035 565 if (isset($eidRefs[$table])) {
9811efd4
JG
566 foreach ($dynamicRefs[$table] as $dynamicRef) {
567 $sqls[] = "UPDATE IGNORE $table SET {$dynamicRef[0]}= $mainId WHERE {$dynamicRef[0]} = $otherId AND {$dynamicRef[1]} = 'civicrm_contact'";
568 $sqls[] = "DELETE FROM $table WHERE {$dynamicRef[0]} = $otherId AND {$dynamicRef[1]} = 'civicrm_contact'";
569 }
6a488035
TO
570 }
571 }
572
573 // Allow hook_civicrm_merge() to add SQL statements for the merge operation.
574 CRM_Utils_Hook::merge('sqls', $sqls, $mainId, $otherId, $tables);
575
6a488035 576 foreach ($sqls as $sql) {
2c16165a 577 CRM_Core_DAO::executeQuery($sql, [], TRUE, NULL, TRUE);
6a488035 578 }
0556db5d 579 CRM_Dedupe_Merger::addMembershipToRealtedContacts($mainId);
6a488035
TO
580 }
581
fe3b8caf 582 /**
583 * Filter out custom tables from cidRefs unless they are there due to a contact reference or are a multiple set.
584 *
585 * The only fields where we want to move the data by sql is where entity reference fields
586 * on another contact refer to the contact being merged, or it is a multiple record set.
587 * The transference of custom data from one contact to another is done in 2 other places in the dedupe process but should
588 * not be done in moveAllContactData.
589 *
590 * Note it's a bit silly the way we build & then cull cidRefs - however, poor hook placement means that
591 * until we fully deprecate calling the hook from cidRefs we are stuck.
592 *
593 * It was deprecated in code (via deprecation notices if people altered it) in Mar 2019 but in docs only in Apri 2020.
594 *
595 * @param array $cidRefs
596 *
597 * @throws \API_Exception
598 * @throws \Civi\API\Exception\UnauthorizedException
599 */
600 protected static function filterRowBasedCustomDataFromCustomTables(array &$cidRefs) {
fe806431 601 $customTables = (array) CustomGroup::get(FALSE)
fe3b8caf 602 ->setSelect(['table_name'])
603 ->addWhere('is_multiple', '=', 0)
96a118e6 604 ->addWhere('extends', 'IN', array_merge(['Contact'], CRM_Contact_BAO_ContactType::contactTypes()))
fe3b8caf 605 ->execute()
606 ->indexBy('table_name');
607 foreach (array_intersect_key($cidRefs, $customTables) as $tableName => $cidSpec) {
608 if (in_array('entity_id', $cidSpec, TRUE)) {
609 unset($cidRefs[$tableName][array_search('entity_id', $cidSpec, TRUE)]);
610 }
611 if (empty($cidRefs[$tableName])) {
612 unset($cidRefs[$tableName]);
613 }
614 }
615 }
616
4f751978
CR
617 /**
618 * Given a contact ID, will check if a record exists in given table.
619 *
723c5a81 620 * @param int $contactID
621 * @param string $table
622 * @param string $idField
4f751978
CR
623 * Field where the contact's ID is stored in the table
624 *
625 * @return bool
626 * True if a record is found for the given contact ID, false otherwise
627 */
ae2346d4
CR
628 private static function customRecordExists($contactID, $table, $idField) {
629 $sql = "
630 SELECT COUNT(*) AS count
631 FROM $table
632 WHERE $idField = $contactID
633 ";
634 $dbResult = CRM_Core_DAO::executeQuery($sql);
635 $dbResult->fetch();
636
637 if ($dbResult->count > 0) {
ee3b1d86 638 return TRUE;
ae2346d4
CR
639 }
640
ee3b1d86 641 return FALSE;
ae2346d4
CR
642 }
643
6a488035 644 /**
4eea8606 645 * Load all non-empty fields for the contacts
b3fdbf3d 646 *
98997235
TO
647 * @param array $main
648 * Contact details.
649 * @param array $other
650 * Contact details.
6a488035 651 *
77b97be7 652 * @return array
723c5a81 653 *
654 * @throws \CRM_Core_Exception
6a488035 655 */
4eea8606 656 public static function retrieveFields($main, $other) {
2c16165a 657 $result = [
658 'contact' => [],
659 'custom' => [],
660 ];
16254ae1 661 foreach (self::getContactFields() as $validField) {
eb61dc07
J
662 // CRM-17556 Get all non-empty fields, to make comparison easier
663 if (!empty($main[$validField]) || !empty($other[$validField])) {
6a488035
TO
664 $result['contact'][] = $validField;
665 }
666 }
667
668 $mainEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($main['id']);
669 $otherEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($other['id']);
670 $keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
671 foreach ($keys as $key) {
76c53278
CW
672 // Exclude multi-value fields CRM-13836
673 if (strpos($key, '_')) {
674 continue;
675 }
9c1bc317
CW
676 $key1 = $mainEvs[$key] ?? NULL;
677 $key2 = $otherEvs[$key] ?? NULL;
26b7ff28 678 // We wish to retain '0' as it has a different meaning than NULL on a checkbox.
679 // However I can't think of a case where an empty string is more meaningful than null
680 // or where it would be FALSE or something else nullish.
681 $valuesToIgnore = [NULL, '', []];
682 if (!in_array($key1, $valuesToIgnore, TRUE) || !in_array($key2, $valuesToIgnore, TRUE)) {
6a488035
TO
683 $result['custom'][] = $key;
684 }
685 }
686 return $result;
687 }
688
689 /**
100fef9d 690 * Batch merge a set of contacts based on rule-group and group.
6a488035 691 *
98997235
TO
692 * @param int $rgid
693 * Rule group id.
694 * @param int $gid
695 * Group id.
696 * @param string $mode
697 * Helps decide how to behave when there are conflicts.
15a793bb
EM
698 * A 'safe' value skips the merge if there are any un-resolved conflicts, wheras 'aggressive'
699 * mode does a force merge.
f931b74c 700 * @param int $batchLimit number of merges to carry out in one batch.
701 * @param int $isSelected if records with is_selected column needs to be processed.
bb22928b 702 * Note the option of '2' is only used in conjunction with $redirectForPerformance
b5a6c6c5 703 * to determine when to reload the cache (!). The use of anything other than a boolean is being grandfathered
704 * out in favour of explicitly passing in $reloadCacheIfEmpty
6a488035 705 *
e23e26ec 706 * @param array $criteria
707 * Criteria to use in the filter.
708 *
3058f4d9 709 * @param bool $checkPermissions
710 * Respect logged in user permissions.
bb22928b 711 * @param bool|NULL $reloadCacheIfEmpty
712 * If not set explicitly this is calculated but it is preferred that it be set
713 * per comments on isSelected above.
3058f4d9 714 *
997a03fe 715 * @param int $searchLimit
716 * Limit on number of contacts to search for duplicates for.
717 * This means that if the limit is 1000 then only duplicates for the first 1000 contacts
718 * matching criteria will be found and batchMerged (the number of merges could be less than or greater than 100)
719 *
77b97be7 720 * @return array|bool
997a03fe 721 *
722 * @throws \CRM_Core_Exception
723 * @throws \CiviCRM_API3_Exception
96a118e6 724 * @throws \API_Exception
6a488035 725 */
997a03fe 726 public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $batchLimit = 1, $isSelected = 2, $criteria = [], $checkPermissions = TRUE, $reloadCacheIfEmpty = NULL, $searchLimit = 0) {
f7dbf5d9 727 $redirectForPerformance = $batchLimit > 1;
418ffc5b 728 if ($mode === 'aggressive' && $checkPermissions && !CRM_Core_Permission::check('force merge duplicate contacts')) {
729 throw new CRM_Core_Exception(ts('Insufficient permissions for aggressive mode batch merge'));
730 }
bb22928b 731 if (!isset($reloadCacheIfEmpty)) {
732 $reloadCacheIfEmpty = (!$redirectForPerformance && $isSelected == 2);
733 }
734 if ($isSelected !== 0 && $isSelected !== 1) {
735 // explicitly set to NULL if not 1 or 0 as part of grandfathering out the mystical '2' value.
736 $isSelected = NULL;
737 }
723c5a81 738 $dupePairs = self::getDuplicatePairs($rgid, $gid, $reloadCacheIfEmpty, $batchLimit, $isSelected, ($mode === 'aggressive'), $criteria, $checkPermissions, $searchLimit);
6a488035 739
2c16165a 740 $cacheParams = [
997a03fe 741 'cache_key_string' => self::getMergeCacheKeyString($rgid, $gid, $criteria, $checkPermissions, $searchLimit),
2988f5c7 742 // @todo stop passing these parameters in & instead calculate them in the merge function based
743 // on the 'real' params like $isRespectExclusions $batchLimit and $isSelected.
744 'join' => self::getJoinOnDedupeTable(),
ed3c1599 745 'where' => self::getWhereString($isSelected),
746 'limit' => (int) $batchLimit,
2c16165a 747 ];
d238756a 748 return CRM_Dedupe_Merger::merge($dupePairs, $cacheParams, $mode, $redirectForPerformance, $checkPermissions);
6a488035
TO
749 }
750
2ae26001 751 /**
752 * Get the string to join the prevnext cache to the dedupe table.
753 *
754 * @return string
755 * The join string to join prevnext cache on the dedupe table.
756 */
757 public static function getJoinOnDedupeTable() {
723c5a81 758 return '
2ae26001 759 LEFT JOIN civicrm_dedupe_exception de
760 ON (
761 pn.entity_id1 = de.contact_id1
762 AND pn.entity_id2 = de.contact_id2 )
723c5a81 763 ';
2ae26001 764 }
765
2988f5c7 766 /**
767 * Get where string for dedupe join.
768 *
2988f5c7 769 * @param bool $isSelected
770 *
771 * @return string
772 */
ed3c1599 773 protected static function getWhereString($isSelected) {
723c5a81 774 $where = 'de.id IS NULL';
2988f5c7 775 if ($isSelected === 0 || $isSelected === 1) {
776 $where .= " AND pn.is_selected = {$isSelected}";
777 }
2988f5c7 778 return $where;
779 }
780
bc854509 781 /**
782 * Update the statistics for the merge set.
783 *
784 * @param string $cacheKeyString
785 * @param array $result
723c5a81 786 *
787 * @throws \CiviCRM_API3_Exception
bc854509 788 */
2c16165a 789 public static function updateMergeStats($cacheKeyString, $result = []) {
63ef778e 790 // gather latest stats
2c16165a 791 $merged = count($result['merged']);
63ef778e 792 $skipped = count($result['skipped']);
793
794 if ($merged <= 0 && $skipped <= 0) {
795 return;
796 }
797
798 // get previous stats
e13fa54b 799 $previousStats = CRM_Dedupe_Merger::getMergeStats($cacheKeyString);
63ef778e 800 if (!empty($previousStats)) {
e13fa54b 801 if ($previousStats['merged']) {
802 $merged = $merged + $previousStats['merged'];
63ef778e 803 }
e13fa54b 804 if ($previousStats['skipped']) {
805 $skipped = $skipped + $previousStats['skipped'];
63ef778e 806 }
807 }
808
809 // delete old stats
810 CRM_Dedupe_Merger::resetMergeStats($cacheKeyString);
811
812 // store the updated stats
2c16165a 813 $data = [
3bcde7f1 814 'merged' => (int) $merged,
815 'skipped' => (int) $skipped,
2c16165a 816 ];
63ef778e 817
3bcde7f1 818 CRM_Core_DAO::executeQuery("INSERT INTO civicrm_prevnext_cache (entity_table, entity_id1, entity_id2, cacheKey, data) VALUES
2e09a60f 819 ('civicrm_contact', 0, 0, %1, %2)", [1 => [$cacheKeyString . '_stats', 'String'], 2 => [serialize($data), 'String']]);
63ef778e 820 }
821
ae6455b2 822 /**
823 * Delete information about merges for the given string.
824 *
825 * @param $cacheKeyString
826 */
f931b74c 827 public static function resetMergeStats($cacheKeyString) {
ae6455b2 828 CRM_Core_BAO_PrevNextCache::deleteItem(NULL, "{$cacheKeyString}_stats");
63ef778e 829 }
830
bc854509 831 /**
832 * Get merge outcome statistics.
833 *
834 * @param string $cacheKeyString
835 *
836 * @return array
837 * Array of how many were merged and how many were skipped.
e13fa54b 838 *
839 * @throws \CiviCRM_API3_Exception
bc854509 840 */
f931b74c 841 public static function getMergeStats($cacheKeyString) {
e13fa54b 842 $stats = civicrm_api3('Dedupe', 'get', ['cachekey' => "{$cacheKeyString}_stats", 'sequential' => 1])['values'];
63ef778e 843 if (!empty($stats)) {
e13fa54b 844 return $stats[0]['data'];
63ef778e 845 }
e13fa54b 846 return [];
63ef778e 847 }
848
bc854509 849 /**
850 * Get merge statistics message.
851 *
3743fd3d 852 * @param array $stats
bc854509 853 *
854 * @return string
855 */
3743fd3d
CW
856 public static function getMergeStatsMsg($stats) {
857 $msg = '';
63ef778e 858 if (!empty($stats['merged'])) {
2c16165a 859 $msg = '<p>' . ts('One contact merged.', [
518fa0ee
SL
860 'count' => $stats['merged'],
861 'plural' => '%count contacts merged.',
862 ]) . '</p>';
63ef778e 863 }
864 if (!empty($stats['skipped'])) {
2c16165a 865 $msg .= '<p>' . ts('One contact was skipped.', [
518fa0ee
SL
866 'count' => $stats['skipped'],
867 'plural' => '%count contacts were skipped.',
868 ]) . '</p>';
63ef778e 869 }
870 return $msg;
871 }
872
6a488035 873 /**
100fef9d 874 * Merge given set of contacts. Performs core operation.
6a488035 875 *
98997235
TO
876 * @param array $dupePairs
877 * Set of pair of contacts for whom merge is to be done.
878 * @param array $cacheParams
879 * Prev-next-cache params based on which next pair of contacts are computed.
6a488035 880 * Generally used with batch-merge.
98997235
TO
881 * @param string $mode
882 * Helps decide how to behave when there are conflicts.
6a488035
TO
883 * A 'safe' value skips the merge if there are any un-resolved conflicts.
884 * Does a force merge otherwise (aggressive mode).
6a488035 885 *
77b97be7 886 * @param bool $redirectForPerformance
3058f4d9 887 * Redirect to a url for batch processing.
888 *
889 * @param bool $checkPermissions
890 * Respect logged in user permissions.
77b97be7
EM
891 *
892 * @return array|bool
b068bfde 893 *
894 * @throws \API_Exception
895 * @throws \CRM_Core_Exception
896 * @throws \CiviCRM_API3_Exception
6a488035 897 */
2c16165a 898 public static function merge($dupePairs = [], $cacheParams = [], $mode = 'safe',
899 $redirectForPerformance = FALSE, $checkPermissions = TRUE
6a488035 900 ) {
9c1bc317 901 $cacheKeyString = $cacheParams['cache_key_string'] ?? NULL;
2c16165a 902 $resultStats = ['merged' => [], 'skipped' => []];
6a488035
TO
903
904 // we don't want dupe caching to get reset after every-merge, and therefore set the
0626851e 905 CRM_Core_Config::setPermitCacheFlushMode(FALSE);
2c16165a 906 $deletedContacts = [];
6a488035
TO
907
908 while (!empty($dupePairs)) {
78272750 909 foreach ($dupePairs as $index => $dupes) {
910 if (in_array($dupes['dstID'], $deletedContacts) || in_array($dupes['srcID'], $deletedContacts)) {
911 unset($dupePairs[$index]);
912 continue;
913 }
a6b7cfc6 914 CRM_Utils_Hook::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']);
915 if (($result = self::dedupePair((int) $dupes['dstID'], (int) $dupes['srcID'], $mode, $checkPermissions, $cacheKeyString)) === FALSE) {
b068bfde 916 unset($dupePairs[$index]);
917 continue;
918 }
919 if (!empty($result['merged'])) {
920 $deletedContacts[] = $result['merged'][0]['other_id'];
921 $resultStats['merged'][] = ($result['merged'][0]);
922 }
923 else {
924 $resultStats['skipped'][] = ($result['skipped'][0]);
6a488035 925 }
6a488035
TO
926 }
927
928 if ($cacheKeyString && !$redirectForPerformance) {
929 // retrieve next pair of dupes
2988f5c7 930 // @todo call getDuplicatePairs.
6a488035
TO
931 $dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString,
932 $cacheParams['join'],
66eceb0b 933 $cacheParams['where'],
934 0,
ed3c1599 935 $cacheParams['limit'],
2c16165a 936 [],
66eceb0b 937 '',
938 FALSE
6a488035
TO
939 );
940 }
941 else {
942 // do not proceed. Terminate the loop
943 unset($dupePairs);
944 }
945 }
63ef778e 946
947 CRM_Dedupe_Merger::updateMergeStats($cacheKeyString, $resultStats);
6a488035
TO
948 return $resultStats;
949 }
950
951 /**
952 * A function which uses various rules / algorithms for choosing which contact to bias to
953 * when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
954 *
98997235
TO
955 * @param int $mainId
956 * Main contact with whom merge has to happen.
957 * @param int $otherId
958 * Duplicate contact which would be deleted after merge operation.
959 * @param array $migrationInfo
960 * Array of information about which elements to merge.
961 * @param string $mode
962 * Helps decide how to behave when there are conflicts.
13919cf8
J
963 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
964 * - Does a force merge otherwise (aggressive mode).
6a488035 965 *
ad37ac8e 966 * @param array $conflicts
a2abc387 967 * An empty array to be filed with conflict information.
ad37ac8e 968 *
77b97be7 969 * @return bool
ffa59d18 970 *
971 * @throws \CRM_Core_Exception
972 * @throws \CiviCRM_API3_Exception
973 * @throws \API_Exception
6a488035 974 */
2c16165a 975 public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe', &$conflicts = []) {
0971143c 976
403400d9 977 $conflicts = self::getConflicts($migrationInfo, $mainId, $otherId, $mode)['conflicts'];
d73a022b 978 // A hook could have set skip_merge in order to alter merge behaviour.
979 // This is a something we might ideally deprecate since they really 'should'
980 // mess with the conflicts array instead.
981 return (bool) ($migrationData['skip_merge'] ?? !empty($conflicts));
6a488035
TO
982 }
983
d48ad2c0 984 /**
985 * Compare 2 addresses to see if they are the same.
986 *
987 * @param array $mainAddress
988 * @param array $comparisonAddress
989 *
990 * @return bool
991 */
518fa0ee 992 public static function locationIsSame($mainAddress, $comparisonAddress) {
ffa59d18 993 $keysToIgnore = self::ignoredFields();
d48ad2c0 994 foreach ($comparisonAddress as $field => $value) {
995 if (in_array($field, $keysToIgnore)) {
996 continue;
997 }
00443529 998 if ((!empty($value) || $value === '0') && isset($mainAddress[$field]) && $mainAddress[$field] != $value) {
d48ad2c0 999 return FALSE;
1000 }
1001 }
1002 return TRUE;
1003 }
1004
34917198
J
1005 /**
1006 * A function to build an array of information about location blocks that is
1007 * required when merging location fields
1008 *
1009 * @return array
1010 */
1011 public static function getLocationBlockInfo() {
723c5a81 1012 return [
2c16165a 1013 'address' => [
34917198
J
1014 'label' => 'Address',
1015 'displayField' => 'display',
1016 'sortString' => 'location_type_id',
1017 'hasLocation' => TRUE,
1018 'hasType' => FALSE,
2c16165a 1019 ],
1020 'email' => [
34917198 1021 'label' => 'Email',
2a7e1ddc 1022 'displayField' => 'display',
34917198
J
1023 'sortString' => 'location_type_id',
1024 'hasLocation' => TRUE,
1025 'hasType' => FALSE,
2c16165a 1026 ],
1027 'im' => [
34917198
J
1028 'label' => 'IM',
1029 'displayField' => 'name',
1030 'sortString' => 'location_type_id,provider_id',
1031 'hasLocation' => TRUE,
1032 'hasType' => 'provider_id',
2c16165a 1033 ],
1034 'phone' => [
34917198
J
1035 'label' => 'Phone',
1036 'displayField' => 'phone',
1037 'sortString' => 'location_type_id,phone_type_id',
1038 'hasLocation' => TRUE,
1039 'hasType' => 'phone_type_id',
2c16165a 1040 ],
1041 'website' => [
34917198
J
1042 'label' => 'Website',
1043 'displayField' => 'url',
1044 'sortString' => 'website_type_id',
1045 'hasLocation' => FALSE,
1046 'hasType' => 'website_type_id',
2c16165a 1047 ],
1048 ];
34917198
J
1049 }
1050
6a488035
TO
1051 /**
1052 * A function to build an array of information required by merge function and the merge UI.
1053 *
98997235
TO
1054 * @param int $mainId
1055 * Main contact with whom merge has to happen.
1056 * @param int $otherId
1057 * Duplicate contact which would be deleted after merge operation.
201057c0 1058 * @param bool $checkPermissions
1059 * Should the logged in user's permissions be ignore. Setting this to false is
1060 * highly risky as it could cause data to be lost due to conflicts not showing up.
1061 * OTOH there is a risk a merger might view custom data they do not have permission to.
1062 * Hence for now only making this really explicit and making it reflect perms in
1063 * an api call.
1064 *
1065 * @todo review permissions issue!
6a488035 1066 *
77b97be7 1067 * @return array|bool|int
1e3e0eed
J
1068 *
1069 * rows => An array of arrays, each is row of merge information for the table
1070 * Format: move_fieldname, eg: move_contact_type
1071 * main => Value associated with the main contact
1072 * other => Value associated with the other contact
1073 * title => The title of the field to display in the merge table
1074 *
1075 * elements => An array of form elements for the merge UI
1076 *
1077 * rel_table_elements => An array of form elements for the merge UI for
1078 * entities related to the contact (eg: checkbox to move 'mailings')
1079 *
1e3e0eed
J
1080 * rel_tables => Stores the tables that have related entities for the contact
1081 * for example mailings, groups
1082 *
1083 * main_details => An array of core contact field values, eg: first_name, etc.
1084 * location_blocks => An array of location block data for the main contact
1085 * stored as the 'result' of an API call.
1086 * eg: main_details['location_blocks']['address'][0]['id']
1087 * eg: main_details['location_blocks']['email'][1]['id']
1088 *
1089 * other_details => As above, but for the 'other' contact
1090 *
1091 * migration_info => Stores the 'default' merge actions for each field which
1092 * is used when programatically merging contacts. It contains instructions
1093 * to move all fields from the 'other' contact to the 'main' contact, as
1094 * though the form had been submitted with those options.
1095 *
3058f4d9 1096 * @throws \CRM_Core_Exception
1097 * @throws \CiviCRM_API3_Exception
1098 * @throws \Exception
6a488035 1099 */
201057c0 1100 public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissions = TRUE) {
6a488035 1101 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
74a6069d 1102 $fields = self::getMergeFieldsMetadata();
6a488035 1103
fcc3d8ee 1104 $main = self::getMergeContactDetails($mainId);
1105 $other = self::getMergeContactDetails($otherId);
6a488035 1106
4eea8606 1107 $compareFields = self::retrieveFields($main, $other);
6a488035 1108
2c16165a 1109 $rows = $elements = $relTableElements = $migrationInfo = [];
6a488035 1110
4eea8606 1111 foreach ($compareFields['contact'] as $field) {
723c5a81 1112 if ($field === 'contact_sub_type') {
4d5f18cc 1113 // CRM-15681 don't display sub-types in UI
1114 continue;
1115 }
1ce87307 1116 $rows["move_$field"] = [
1117 'main' => self::getFieldValueAndLabel($field, $main)['label'],
1118 'other' => self::getFieldValueAndLabel($field, $other)['label'],
1119 'title' => $fields[$field]['title'],
1120 ];
2fd72602 1121
bdc6e6ee 1122 $value = self::getFieldValueAndLabel($field, $other)['value'];
1123 //CRM-14334
1124 if ($value === NULL || $value == '') {
1125 $value = 'null';
1126 }
1127 if ($value === 0 or $value === '0') {
1128 $value = $qfZeroBug;
1129 }
1130 if (is_array($value) && empty($value[1])) {
1131 $value[1] = NULL;
1132 }
13919cf8 1133
bdc6e6ee 1134 // Display a checkbox to migrate, only if the values are different
1135 if ($value != $main[$field]) {
1136 $elements[] = [
3d1d395a 1137 0 => 'advcheckbox',
1138 1 => "move_$field",
1139 2 => NULL,
1140 3 => NULL,
1141 4 => NULL,
1142 5 => $value,
1143 'is_checked' => (!isset($main[$field]) || $main[$field] === ''),
bdc6e6ee 1144 ];
1145 }
13919cf8 1146
bdc6e6ee 1147 $migrationInfo["move_$field"] = $value;
6a488035
TO
1148 }
1149
eb61dc07
J
1150 // Handle location blocks.
1151 // @todo OpenID not in API yet, so is not supported here.
65a35632 1152
087f00ec 1153 // Set up useful information about the location blocks
34917198 1154 $locationBlocks = self::getLocationBlockInfo();
087f00ec 1155
1a90ac89 1156 $locations = ['main' => [], 'other' => []];
6a488035 1157
087f00ec 1158 foreach ($locationBlocks as $blockName => $blockInfo) {
18226102 1159 list($locations, $rows, $elements, $migrationInfo) = self::addLocationFieldInfo($mainId, $otherId, $blockInfo, $blockName, $locations, $rows, $elements, $migrationInfo);
34917198 1160 } // End loop through each location block entity
6a488035
TO
1161
1162 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
9287a0b7 1163 $mergeHandler = new CRM_Dedupe_MergeHandler((int) $mainId, (int) $otherId);
1164 $relTables = $mergeHandler->getTablesRelatedToTheMergePair();
6a488035 1165 foreach ($relTables as $name => $null) {
2c16165a 1166 $relTableElements[] = ['checkbox', "move_$name"];
6a488035
TO
1167 $migrationInfo["move_$name"] = 1;
1168
1169 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1170 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
8372e605 1171 if ($name === 'rel_table_users') {
1172 // @todo - this user url stuff is only needed for the form layer - move to CRM_Contact_Form_Merge
1173 $relTables[$name]['main_url'] = str_replace('%ufid', CRM_Core_BAO_UFMatch::getUFId($otherId), $relTables[$name]['url']);
1174 $relTables[$name]['other_url'] = str_replace('%ufid', CRM_Core_BAO_UFMatch::getUFId($otherId), $relTables[$name]['url']);
6a488035 1175 }
723c5a81 1176 if ($name === 'rel_table_memberships') {
7d84a47d
JP
1177 //Enable 'add new' checkbox if main contact does not contain any membership similar to duplicate contact.
1178 $attributes = ['checked' => 'checked'];
1179 $otherContactMemberships = CRM_Member_BAO_Membership::getAllContactMembership($otherId);
1180 foreach ($otherContactMemberships as $membership) {
1181 $mainMembership = CRM_Member_BAO_Membership::getContactMembership($mainId, $membership['membership_type_id'], FALSE);
1182 if ($mainMembership) {
1183 $attributes = [];
1184 }
1185 }
2c16165a 1186 $elements[] = [
1187 'checkbox',
1188 "operation[move_{$name}][add]",
1189 NULL,
1190 ts('add new'),
1191 $attributes,
1192 ];
6a488035
TO
1193 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1194 }
1195 }
1196 foreach ($relTables as $name => $null) {
1197 $relTables["move_$name"] = $relTables[$name];
1198 unset($relTables[$name]);
1199 }
1200
1201 // handle custom fields
201057c0 1202 $mainTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], NULL, $mainId, -1,
1203 CRM_Utils_Array::value('contact_sub_type', $main), NULL, TRUE, NULL, TRUE, $checkPermissions
6a488035 1204 );
0b330e6d 1205 $otherTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], NULL, $otherId, -1,
201057c0 1206 CRM_Utils_Array::value('contact_sub_type', $other), NULL, TRUE, NULL, TRUE, $checkPermissions
6a488035 1207 );
6a488035
TO
1208
1209 foreach ($otherTree as $gid => $group) {
6a488035
TO
1210 if (!isset($group['fields'])) {
1211 continue;
1212 }
1213
1214 foreach ($group['fields'] as $fid => $field) {
b1ff97eb 1215 $mainContactValue = $mainTree[$gid]['fields'][$fid]['customValue'] ?? NULL;
1216 $otherContactValue = $otherTree[$gid]['fields'][$fid]['customValue'] ?? NULL;
4eea8606 1217 if (in_array($fid, $compareFields['custom'])) {
b1ff97eb 1218 $rows["custom_group_$gid"]['title'] = $rows["custom_group_$gid"]['title'] ?? $group['title'];
1219
1220 if ($mainContactValue) {
1221 foreach ($mainContactValue as $valueId => $values) {
51a3717f 1222 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid);
6a488035
TO
1223 }
1224 }
b1ff97eb 1225 $value = 'null';
1226 if ($otherContactValue) {
1227 foreach ($otherContactValue as $valueId => $values) {
51a3717f 1228 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid);
6a488035
TO
1229 if ($values['data'] === 0 || $values['data'] === '0') {
1230 $values['data'] = $qfZeroBug;
d58a19a1 1231 }
6a488035 1232 $value = ($values['data']) ? $values['data'] : $value;
d58a19a1 1233 }
6a488035
TO
1234 }
1235 $rows["move_custom_$fid"]['title'] = $field['label'];
1236
2c16165a 1237 $elements[] = [
97be1890 1238 0 => 'advcheckbox',
1239 1 => "move_custom_$fid",
1240 2 => NULL,
1241 3 => NULL,
1242 4 => NULL,
1243 5 => $value,
1244 'is_checked' => (!isset($rows["move_custom_$fid"]['main']) || $rows["move_custom_$fid"]['main'] === ''),
2c16165a 1245 ];
6a488035
TO
1246 $migrationInfo["move_custom_$fid"] = $value;
1247 }
1248 }
1249 }
abb422f9 1250
2c16165a 1251 $result = [
6a488035
TO
1252 'rows' => $rows,
1253 'elements' => $elements,
1254 'rel_table_elements' => $relTableElements,
6a488035
TO
1255 'rel_tables' => $relTables,
1256 'main_details' => $main,
1257 'other_details' => $other,
1258 'migration_info' => $migrationInfo,
2c16165a 1259 ];
6a488035 1260
34917198
J
1261 $result['main_details']['location_blocks'] = $locations['main'];
1262 $result['other_details']['location_blocks'] = $locations['other'];
6a488035
TO
1263
1264 return $result;
1265 }
1266
1267 /**
1268 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1269 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1270 * A superset of moveContactBelongings() function.
1271 *
98997235
TO
1272 * @param int $mainId
1273 * Main contact with whom merge has to happen.
1274 * @param int $otherId
1275 * Duplicate contact which would be deleted after merge operation.
77b97be7 1276 *
1600a9c0 1277 * @param array $migrationInfo
6a488035 1278 *
3058f4d9 1279 * @param bool $checkPermissions
1280 * Respect logged in user permissions.
1281 *
77b97be7 1282 * @return bool
fe3b8caf 1283 *
1284 * @throws \API_Exception
1285 * @throws \CRM_Core_Exception
1600a9c0 1286 * @throws \CiviCRM_API3_Exception
fe3b8caf 1287 * @throws \Civi\API\Exception\UnauthorizedException
6a488035 1288 */
3058f4d9 1289 public static function moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions = TRUE) {
6a488035
TO
1290 if (empty($migrationInfo)) {
1291 return FALSE;
1292 }
119664d6 1293 // Encapsulate in a transaction to avoid half-merges.
1294 $transaction = new CRM_Core_Transaction();
6a488035 1295
1acd98ec 1296 $contactType = $migrationInfo['main_details']['contact_type'];
6a488035 1297 $relTables = CRM_Dedupe_Merger::relTables();
35e0e03e 1298 $submittedCustomFields = $moveTables = $tableOperations = $removeTables = [];
ae2346d4 1299
54ed517e 1300 self::swapOutFieldsAffectedByQFZeroBug($migrationInfo);
6a488035 1301 foreach ($migrationInfo as $key => $value) {
08b00099 1302
723c5a81 1303 if (substr($key, 0, 12) === 'move_custom_' && $value != NULL) {
6a488035 1304 $submitted[substr($key, 5)] = $value;
ae2346d4 1305 $submittedCustomFields[] = substr($key, 12);
6a488035 1306 }
08b00099 1307 elseif (in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) && $value != NULL) {
6a488035
TO
1308 $submitted[substr($key, 5)] = $value;
1309 }
723c5a81 1310 elseif (substr($key, 0, 15) === 'move_rel_table_' and $value == '1') {
6a488035
TO
1311 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1312 if (array_key_exists('operation', $migrationInfo)) {
1313 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1314 if (array_key_exists($key, $migrationInfo['operation'])) {
1315 $tableOperations[$table] = $migrationInfo['operation'][$key];
1316 }
1317 }
1318 }
1319 }
723c5a81 1320 elseif (substr($key, 0, 15) === 'move_rel_table_' and $value == '0') {
4099a9c5
AP
1321 $removeTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1322 }
6a488035 1323 }
35e0e03e 1324 self::mergeLocations($mainId, $otherId, $migrationInfo);
6a488035 1325
6a488035 1326 // **** Do contact related migrations
1600a9c0 1327 // @todo - move all custom field processing to the move class & eventually have an
1328 // overridable DAO class for it.
1329 $customFieldBAO = new CRM_Core_BAO_CustomField();
1330 $customFieldBAO->move($otherId, $mainId, $submittedCustomFields);
eca28463 1331 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1332 $mergeHandler = new CRM_Dedupe_MergeHandler((int) $mainId, (int) $otherId);
1333 CRM_Dedupe_Merger::moveContactBelongings($mergeHandler, $moveTables, $tableOperations);
0556db5d 1334 unset($moveTables, $tableOperations);
6a488035 1335
4099a9c5
AP
1336 // **** Do table related removals
1337 if (!empty($removeTables)) {
1338 // **** CRM-20421
1339 CRM_Dedupe_Merger::removeContactBelongings($otherId, $removeTables);
2c16165a 1340 $removeTables = [];
4099a9c5
AP
1341 }
1342
6a488035 1343 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
2c16165a 1344 $names['gender'] = ['newName' => 'gender_id', 'groupName' => 'gender'];
1345 $names['individual_prefix'] = [
1346 'newName' => 'prefix_id',
1347 'groupName' => 'individual_prefix',
1348 ];
1349 $names['individual_suffix'] = [
1350 'newName' => 'suffix_id',
1351 'groupName' => 'individual_suffix',
1352 ];
1353 $names['communication_style'] = [
1354 'newName' => 'communication_style_id',
1355 'groupName' => 'communication_style',
1356 ];
1357 $names['addressee'] = [
1358 'newName' => 'addressee_id',
1359 'groupName' => 'addressee',
1360 ];
1361 $names['email_greeting'] = [
1362 'newName' => 'email_greeting_id',
1363 'groupName' => 'email_greeting',
1364 ];
1365 $names['postal_greeting'] = [
1366 'newName' => 'postal_greeting_id',
1367 'groupName' => 'postal_greeting',
1368 ];
6a488035 1369 CRM_Core_OptionGroup::lookupValues($submitted, $names, TRUE);
6a488035 1370 // fix custom fields so they're edible by createProfileContact()
f941d73a 1371 $cFields = self::getCustomFieldMetadata($contactType);
6a488035
TO
1372
1373 if (!isset($submitted)) {
2c16165a 1374 $submitted = [];
6a488035
TO
1375 }
1376 foreach ($submitted as $key => $value) {
1600a9c0 1377 list($cFields, $submitted) = self::processCustomFields($mainId, $key, $cFields, $submitted, $value);
6a488035
TO
1378 }
1379
6a488035 1380 // move view only custom fields CRM-5362
2c16165a 1381 $viewOnlyCustomFields = [];
6a488035 1382 foreach ($submitted as $key => $value) {
ca38a45b 1383 $fid = CRM_Core_BAO_CustomField::getKeyID($key);
1384 if ($fid && array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])
1385 ) {
6a488035
TO
1386 $viewOnlyCustomFields[$key] = $value;
1387 }
1388 }
6a488035
TO
1389 // special case to set values for view only, CRM-5362
1390 if (!empty($viewOnlyCustomFields)) {
1391 $viewOnlyCustomFields['entityID'] = $mainId;
1392 CRM_Core_BAO_CustomValueTable::setValues($viewOnlyCustomFields);
1393 }
1394
1f0138dd
SL
1395 // dev/core#996 Ensure that the earliest created date is stored against the kept contact id
1396 $mainCreatedDate = civicrm_api3('Contact', 'getsingle', [
1397 'id' => $mainId,
1398 'return' => ['created_date'],
1399 ])['created_date'];
1400 $otherCreatedDate = civicrm_api3('Contact', 'getsingle', [
1401 'id' => $otherId,
1402 'return' => ['created_date'],
1403 ])['created_date'];
978b982d 1404 if ($otherCreatedDate < $mainCreatedDate && !empty($otherCreatedDate)) {
1f0138dd
SL
1405 CRM_Core_DAO::executeQuery("UPDATE civicrm_contact SET created_date = %1 WHERE id = %2", [
1406 1 => [$otherCreatedDate, 'String'],
1407 2 => [$mainId, 'Positive'],
1408 ]);
1409 }
1410
3058f4d9 1411 if (!$checkPermissions || (CRM_Core_Permission::check('merge duplicate contacts') &&
2c16165a 1412 CRM_Core_Permission::check('delete contacts'))
6a488035
TO
1413 ) {
1414 // if ext id is submitted then set it null for contact to be deleted
a7488080 1415 if (!empty($submitted['external_identifier'])) {
6a488035
TO
1416 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1417 CRM_Core_DAO::executeQuery($query);
1418 }
2c16165a 1419 civicrm_api3('contact', 'delete', ['id' => $otherId]);
6a488035 1420 }
6a488035 1421
4d5f18cc 1422 // CRM-15681 merge sub_types
35522279
J
1423 if ($other_sub_types = CRM_Utils_Array::value('contact_sub_type', $migrationInfo['other_details'])) {
1424 if ($main_sub_types = CRM_Utils_Array::value('contact_sub_type', $migrationInfo['main_details'])) {
481a74f4 1425 $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types));
0db6c3e1
TO
1426 }
1427 else {
4d5f18cc 1428 $submitted['contact_sub_type'] = $other_sub_types;
1429 }
1430 }
1431
6a488035
TO
1432 // **** Update contact related info for the main contact
1433 if (!empty($submitted)) {
1434 $submitted['contact_id'] = $mainId;
1435
1436 //update current employer field
1437 if ($currentEmloyerId = CRM_Utils_Array::value('current_employer_id', $submitted)) {
1438 if (!CRM_Utils_System::isNull($currentEmloyerId)) {
1439 $submitted['current_employer'] = $submitted['current_employer_id'];
0db6c3e1
TO
1440 }
1441 else {
6a488035
TO
1442 $submitted['current_employer'] = '';
1443 }
1444 unset($submitted['current_employer_id']);
1445 }
1446
00f3da2e 1447 //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
481a74f4 1448 if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) {
00f3da2e
BS
1449 $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
1450 }
481a74f4 1451 if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) {
00f3da2e
BS
1452 $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
1453 }
9b0e7e51 1454 $null = [];
1455 CRM_Contact_BAO_Contact::createProfileContact($submitted, $null, $mainId);
6a488035 1456 }
119664d6 1457 $transaction->commit();
1273d77c 1458 CRM_Utils_Hook::post('merge', 'Contact', $mainId);
f00283b5 1459 self::createMergeActivities($mainId, $otherId);
5ea06a7b 1460
6a488035
TO
1461 return TRUE;
1462 }
16254ae1
ARW
1463
1464 /**
f00283b5 1465 * Get fields in the contact table suitable for merging.
1466 *
a6c01b45 1467 * @return array
f00283b5 1468 * Array of field names to be potentially merged.
16254ae1 1469 */
00be9182 1470 public static function getContactFields() {
16254ae1 1471 $contactFields = CRM_Contact_DAO_Contact::fields();
2c16165a 1472 $invalidFields = [
353ffa53 1473 'api_key',
353ffa53
TO
1474 'created_date',
1475 'display_name',
1476 'hash',
1477 'id',
1478 'modified_date',
1479 'primary_contact_id',
1480 'sort_name',
c301f76e 1481 'user_unique_id',
2c16165a 1482 ];
bdd7870e
RN
1483 foreach ($contactFields as $field => $value) {
1484 if (in_array($field, $invalidFields)) {
1485 unset($contactFields[$field]);
1486 }
1487 }
16254ae1
ARW
1488 return array_keys($contactFields);
1489 }
ada104d5
AW
1490
1491 /**
1492 * Added for CRM-12695
c301f76e 1493 * Based on the contactID provided
ada104d5
AW
1494 * add/update membership(s) to related contacts
1495 *
c301f76e 1496 * @param int $contactID
723c5a81 1497 *
1498 * @throws \CRM_Core_Exception
1499 * @throws \CiviCRM_API3_Exception
ada104d5 1500 */
00be9182 1501 public static function addMembershipToRealtedContacts($contactID) {
ada104d5
AW
1502 $dao = new CRM_Member_DAO_Membership();
1503 $dao->contact_id = $contactID;
1504 $dao->is_test = 0;
1505 $dao->find();
1506
1507 //checks membership of contact itself
1508 while ($dao->fetch()) {
1509 $relationshipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id, 'relationship_type_id', 'id');
1510 if ($relationshipTypeId) {
2c16165a 1511 $membershipParams = [
ada104d5
AW
1512 'id' => $dao->id,
1513 'contact_id' => $dao->contact_id,
1514 'membership_type_id' => $dao->membership_type_id,
1515 'join_date' => CRM_Utils_Date::isoToMysql($dao->join_date),
1516 'start_date' => CRM_Utils_Date::isoToMysql($dao->start_date),
1517 'end_date' => CRM_Utils_Date::isoToMysql($dao->end_date),
1518 'source' => $dao->source,
21dfd5f5 1519 'status_id' => $dao->status_id,
2c16165a 1520 ];
ada104d5
AW
1521 // create/update membership(s) for related contact(s)
1522 CRM_Member_BAO_Membership::createRelatedMemberships($membershipParams, $dao);
1523 } // end of if relationshipTypeId
1524 }
1525 }
96025800 1526
f00283b5 1527 /**
1528 * Create activities tracking the merge on affected contacts.
1529 *
1530 * @param int $mainId
1531 * @param int $otherId
1532 *
1533 * @throws \CiviCRM_API3_Exception
1534 */
1535 public static function createMergeActivities($mainId, $otherId) {
2c16165a 1536 $params = [
f00283b5 1537 1 => $otherId,
1538 2 => $mainId,
2c16165a 1539 ];
1540 $activity = civicrm_api3('activity', 'create', [
dc33398e 1541 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() :
518fa0ee 1542 $mainId,
f00283b5 1543 'subject' => ts('Contact ID %1 has been merged and deleted.', $params),
1544 'target_contact_id' => $mainId,
1545 'activity_type_id' => 'Contact Merged',
1546 'status_id' => 'Completed',
2c16165a 1547 ]);
1548 if (civicrm_api3('Setting', 'getvalue', [
1549 'name' => 'contact_undelete',
1550 'group' => 'CiviCRM Preferences',
1551 ])) {
1552 civicrm_api3('activity', 'create', [
dc33398e 1553 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() :
518fa0ee 1554 $otherId,
4d834a99 1555 'subject' => ts('Contact ID %1 has been merged into Contact ID %2 and deleted.', $params),
1556 'target_contact_id' => $otherId,
1557 'activity_type_id' => 'Contact Deleted by Merge',
1558 'parent_id' => $activity['id'],
1559 'status_id' => 'Completed',
2c16165a 1560 ]);
4d834a99 1561 }
f00283b5 1562 }
1563
2988f5c7 1564 /**
1565 * Get Duplicate Pairs based on a rule for a group.
1566 *
1567 * @param int $rule_group_id
1568 * @param int $group_id
1569 * @param bool $reloadCacheIfEmpty
917acf6f 1570 * Should the cache be reloaded if empty - this must be false when in a dedupe action!
2988f5c7 1571 * @param int $batchLimit
1572 * @param bool $isSelected
5721d85e 1573 * Limit to selected pairs.
66eceb0b 1574 * @param bool $includeConflicts
e23e26ec 1575 * @param array $criteria
1576 * Additional criteria to narrow down the merge group.
2988f5c7 1577 *
3058f4d9 1578 * @param bool $checkPermissions
1579 * Respect logged in user permissions.
1580 *
21a95d83 1581 * @param int $searchLimit
1582 * Limit to searching for matches against this many contacts.
1583 *
c41f68a5 1584 * @param int $isForceNewSearch
1585 * Should a new search be forced, bypassing any cache retrieval.
1586 *
2988f5c7 1587 * @return array
518fa0ee 1588 * Array of matches meeting the criteria.
9c5fe572 1589 *
1590 * @throws \CRM_Core_Exception
1591 * @throws \CiviCRM_API3_Exception
2988f5c7 1592 */
c41f68a5 1593 public static function getDuplicatePairs($rule_group_id, $group_id, $reloadCacheIfEmpty, $batchLimit, $isSelected, $includeConflicts = TRUE, $criteria = [], $checkPermissions = TRUE, $searchLimit = 0, $isForceNewSearch = 0) {
1594 $dupePairs = $isForceNewSearch ? [] : self::getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, $includeConflicts, $criteria, $checkPermissions, $searchLimit);
2988f5c7 1595 if (empty($dupePairs) && $reloadCacheIfEmpty) {
1596 // If we haven't found any dupes, probably cache is empty.
66eceb0b 1597 // Try filling cache and give another try. We don't need to specify include conflicts here are there will not be any
1598 // until we have done some processing.
e1e24a57 1599 CRM_Core_BAO_PrevNextCache::refillCache($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit);
997a03fe 1600 return self::getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, FALSE, $criteria, $checkPermissions, $searchLimit);
2988f5c7 1601 }
1602 return $dupePairs;
1603 }
1604
2ae26001 1605 /**
1606 * Get the cache key string for the merge action.
1607 *
1608 * @param int $rule_group_id
1609 * @param int $group_id
e23e26ec 1610 * @param array $criteria
1611 * Additional criteria to narrow down the merge group.
1612 * Currently we are only supporting the key 'contact' within it.
3058f4d9 1613 * @param bool $checkPermissions
1614 * Respect the users permissions.
997a03fe 1615 * @param int $searchLimit
1616 * Number of contacts to seek dupes for (we need this because if
1617 * we change it the results won't be refreshed otherwise. Changing the limit
1618 * from 100 to 1000 SHOULD result in a new dedupe search).
3058f4d9 1619 *
2ae26001 1620 * @return string
1621 */
997a03fe 1622 public static function getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit) {
2ae26001 1623 $contactType = CRM_Dedupe_BAO_RuleGroup::getContactTypeForRuleGroup($rule_group_id);
9d2f6d53 1624 $cacheKeyString = "merge_{$contactType}";
2ae26001 1625 $cacheKeyString .= $rule_group_id ? "_{$rule_group_id}" : '_0';
1626 $cacheKeyString .= $group_id ? "_{$group_id}" : '_0';
997a03fe 1627 $cacheKeyString .= '_' . (int) $searchLimit;
629dd4f3 1628 $cacheKeyString .= !empty($criteria) ? md5(serialize($criteria)) : '_0';
3058f4d9 1629 if ($checkPermissions) {
1630 $contactID = CRM_Core_Session::getLoggedInContactID();
1631 if (!$contactID) {
1632 // Distinguish between no permission check & no logged in user.
1633 $contactID = 'null';
1634 }
1635 $cacheKeyString .= '_' . $contactID;
1636 }
1637 else {
1638 $cacheKeyString .= '_0';
1639 }
2ae26001 1640 return $cacheKeyString;
1641 }
1642
74a6069d 1643 /**
1644 * Get the metadata for the merge fields.
1645 *
1646 * This is basically the contact metadata, augmented with fields to
1647 * represent email greeting, postal greeting & addressee.
1648 *
1649 * @return array
1650 */
1651 public static function getMergeFieldsMetadata() {
1652 if (isset(\Civi::$statics[__CLASS__]) && isset(\Civi::$statics[__CLASS__]['merge_fields_metadata'])) {
1653 return \Civi::$statics[__CLASS__]['merge_fields_metadata'];
1654 }
1655 $fields = CRM_Contact_DAO_Contact::fields();
2c16165a 1656 static $optionValueFields = [];
74a6069d 1657 if (empty($optionValueFields)) {
1658 $optionValueFields = CRM_Core_OptionValue::getFields();
1659 }
1660 foreach ($optionValueFields as $field => $params) {
1661 $fields[$field]['title'] = $params['title'];
1662 }
1663 \Civi::$statics[__CLASS__]['merge_fields_metadata'] = $fields;
1664 return \Civi::$statics[__CLASS__]['merge_fields_metadata'];
1665 }
1666
1667 /**
1668 * Get the details of the contact to be merged.
1669 *
1670 * @param int $contact_id
74a6069d 1671 *
1672 * @return array
1673 *
1674 * @throws CRM_Core_Exception
1675 */
fcc3d8ee 1676 public static function getMergeContactDetails($contact_id) {
2c16165a 1677 $params = [
74a6069d 1678 'contact_id' => $contact_id,
1679 'version' => 3,
2c16165a 1680 'return' => array_merge(['display_name'], self::getContactFields()),
1681 ];
74a6069d 1682 $result = civicrm_api('contact', 'get', $params);
1683
1684 // CRM-18480: Cancel the process if the contact is already deleted
1685 if (isset($result['values'][$contact_id]['contact_is_deleted']) && !empty($result['values'][$contact_id]['contact_is_deleted'])) {
2c16165a 1686 throw new CRM_Core_Exception(ts('Cannot merge because one contact (ID %1) has been deleted.', [
fcc3d8ee 1687 1 => $contact_id,
2c16165a 1688 ]));
74a6069d 1689 }
1690
1691 return $result['values'][$contact_id];
1692 }
1693
92a77772 1694 /**
1695 * Merge location.
1696 *
1697 * Based on the data in the $locationMigrationInfo merge the locations for 2 contacts.
1698 *
1699 * The data is in the format received from the merge form (which is a fairly confusing format).
1700 *
1701 * It is converted into an array of DAOs which is passed to the alterLocationMergeData hook
1702 * before saving or deleting the DAOs. A new hook is added to allow these to be altered after they have
1703 * been calculated and before saving because
1704 * - the existing format & hook combo is so confusing it is hard for developers to change & inherently fragile
1705 * - passing to a hook right before save means calculations only have to be done once
1706 * - the existing pattern of passing dissimilar data to the same (merge) hook with a different 'type' is just
1707 * ugly.
1708 *
1709 * The use of the new hook is tested, including the fact it is called before contributions are merged, as this
16d4e0b7 1710 * is likely to be significant data in merge hooks.
92a77772 1711 *
1712 * @param int $mainId
1713 * @param int $otherId
92a77772 1714 *
1715 * @param array $migrationInfo
1716 * Migration info for the merge. This is passed to the hook as informational only.
1717 */
35e0e03e 1718 public static function mergeLocations($mainId, $otherId, $migrationInfo) {
1719 foreach ($migrationInfo as $key => $value) {
723c5a81 1720 $isLocationField = (substr($key, 0, 14) === 'move_location_' and $value != NULL);
35e0e03e 1721 if (!$isLocationField) {
1722 continue;
1723 }
92a77772 1724 $locField = explode('_', $key);
1725 $fieldName = $locField[2];
1726 $fieldCount = $locField[3];
1727
1728 // Set up the operation type (add/overwrite)
1729 // Ignore operation for websites
1730 // @todo Tidy this up
1731 $operation = 0;
723c5a81 1732 if ($fieldName !== 'website') {
9c1bc317 1733 $operation = $migrationInfo['location_blocks'][$fieldName][$fieldCount]['operation'] ?? NULL;
92a77772 1734 }
1735 // default operation is overwrite.
1736 if (!$operation) {
1737 $operation = 2;
1738 }
1739 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
1740 }
2c16165a 1741 $blocksDAO = [];
92a77772 1742
1743 // @todo Handle OpenID (not currently in API).
1744 if (!empty($locBlocks)) {
1745 $locationBlocks = self::getLocationBlockInfo();
1746
2c16165a 1747 $primaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, ['is_primary' => 1]);
1748 $billingBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, ['is_billing' => 1]);
92a77772 1749
1750 foreach ($locBlocks as $name => $block) {
2c16165a 1751 $blocksDAO[$name] = ['delete' => [], 'update' => []];
92a77772 1752 if (!is_array($block) || CRM_Utils_System::isNull($block)) {
1753 continue;
1754 }
1755 $daoName = 'CRM_Core_DAO_' . $locationBlocks[$name]['label'];
abd0b852 1756 $changePrimary = FALSE;
92a77772 1757 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ? array_pop($primaryBlockIds[$name]) : NULL;
1758 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ? array_pop($billingBlockIds[$name]) : NULL;
1759
1760 foreach ($block as $blkCount => $values) {
9c1bc317 1761 $otherBlockId = $migrationInfo['other_details']['location_blocks'][$name][$blkCount]['id'] ?? NULL;
92a77772 1762 $mainBlockId = CRM_Utils_Array::value('mainContactBlockId', $migrationInfo['location_blocks'][$name][$blkCount], 0);
1763 if (!$otherBlockId) {
1764 continue;
1765 }
1766
1767 // For the block which belongs to other-contact, link the location block to main-contact
1768 $otherBlockDAO = new $daoName();
1769 $otherBlockDAO->contact_id = $mainId;
1770
1771 // Get the ID of this block on the 'other' contact, otherwise skip
1772 $otherBlockDAO->id = $otherBlockId;
1773
1774 // Add/update location and type information from the form, if applicable
1775 if ($locationBlocks[$name]['hasLocation']) {
9c1bc317 1776 $locTypeId = $migrationInfo['location_blocks'][$name][$blkCount]['locTypeId'] ?? NULL;
92a77772 1777 $otherBlockDAO->location_type_id = $locTypeId;
1778 }
1779 if ($locationBlocks[$name]['hasType']) {
9c1bc317 1780 $typeTypeId = $migrationInfo['location_blocks'][$name][$blkCount]['typeTypeId'] ?? NULL;
92a77772 1781 $otherBlockDAO->{$locationBlocks[$name]['hasType']} = $typeTypeId;
1782 }
1783
abd0b852
J
1784 // If we're deliberately setting this as primary then add the flag
1785 // and remove it from the current primary location (if there is one).
1786 // But only once for each entity.
9c1bc317 1787 $set_primary = $migrationInfo['location_blocks'][$name][$blkCount]['set_other_primary'] ?? NULL;
9e848fc4 1788 if (!$changePrimary && $set_primary == "1") {
abd0b852
J
1789 $otherBlockDAO->is_primary = 1;
1790 if ($primaryDAOId) {
1791 $removePrimaryDAO = new $daoName();
1792 $removePrimaryDAO->id = $primaryDAOId;
1793 $removePrimaryDAO->is_primary = 0;
1794 $blocksDAO[$name]['update'][$primaryDAOId] = $removePrimaryDAO;
1795 }
1796 $changePrimary = TRUE;
1797 }
1798 // Otherwise, if main contact already has primary, set it to 0.
1799 elseif ($primaryDAOId) {
92a77772 1800 $otherBlockDAO->is_primary = 0;
1801 }
abd0b852
J
1802
1803 // If the main contact already has a billing location, set this to 0.
92a77772 1804 if ($billingDAOId) {
1805 $otherBlockDAO->is_billing = 0;
1806 }
1807
1808 $operation = CRM_Utils_Array::value('operation', $values, 2);
1809 // overwrite - need to delete block which belongs to main-contact.
1810 if (!empty($mainBlockId) && ($operation == 2)) {
1811 $deleteDAO = new $daoName();
1812 $deleteDAO->id = $mainBlockId;
1813 $deleteDAO->find(TRUE);
1814
1815 // if we about to delete a primary / billing block, set the flags for new block
1816 // that we going to assign to main-contact
1817 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id)) {
1818 $otherBlockDAO->is_primary = 1;
1819 }
1820 if ($billingDAOId && ($billingDAOId == $deleteDAO->id)) {
1821 $otherBlockDAO->is_billing = 1;
1822 }
1823 $blocksDAO[$name]['delete'][$deleteDAO->id] = $deleteDAO;
1824 }
1825 $blocksDAO[$name]['update'][$otherBlockDAO->id] = $otherBlockDAO;
1826 }
1827 }
1828 }
1829
1830 CRM_Utils_Hook::alterLocationMergeData($blocksDAO, $mainId, $otherId, $migrationInfo);
1831 foreach ($blocksDAO as $blockDAOs) {
1832 if (!empty($blockDAOs['update'])) {
1833 foreach ($blockDAOs['update'] as $blockDAO) {
1834 $blockDAO->save();
1835 }
1836 }
1837 if (!empty($blockDAOs['delete'])) {
1838 foreach ($blockDAOs['delete'] as $blockDAO) {
1839 $blockDAO->delete();
1840 }
1841 }
1842 }
1843 }
1844
e4e1db4b 1845 /**
1846 * Dedupe a pair of contacts.
1847 *
a6b7cfc6 1848 * @param int $mainId Id of contact to keep.
1849 * @param int $otherId Id of contact to delete.
e4e1db4b 1850 * @param string $mode
1851 * @param bool $checkPermissions
e4e1db4b 1852 * @param string $cacheKeyString
37cd9336 1853 *
b068bfde 1854 * @return bool|array
a6b7cfc6 1855 * @throws \API_Exception
37cd9336 1856 * @throws \CRM_Core_Exception
a6b7cfc6 1857 * @throws \CRM_Core_Exception_ResourceConflictException
37cd9336 1858 * @throws \CiviCRM_API3_Exception
a6b7cfc6 1859 * @throws \Civi\API\Exception\UnauthorizedException
e4e1db4b 1860 */
a6b7cfc6 1861 protected static function dedupePair(int $mainId, int $otherId, $mode = 'safe', $checkPermissions = TRUE, $cacheKeyString = NULL) {
b068bfde 1862 $resultStats = [];
1863
aefc291e 1864 $migrationInfo = [];
2c16165a 1865 $conflicts = [];
c9f05fb3 1866 // Try to lock the contacts before we load the data as we don't want it changing under us.
1867 // https://lab.civicrm.org/dev/core/issues/1355
1868 $locks = self::getLocksOnContacts([$mainId, $otherId]);
e4e1db4b 1869 if (!CRM_Dedupe_Merger::skipMerge($mainId, $otherId, $migrationInfo, $mode, $conflicts)) {
1870 CRM_Dedupe_Merger::moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions);
2c16165a 1871 $resultStats['merged'][] = [
e4e1db4b 1872 'main_id' => $mainId,
1873 'other_id' => $otherId,
2c16165a 1874 ];
e4e1db4b 1875 }
1876 else {
2c16165a 1877 $resultStats['skipped'][] = [
e4e1db4b 1878 'main_id' => $mainId,
1879 'other_id' => $otherId,
2c16165a 1880 ];
e4e1db4b 1881 }
1882
1883 // store any conflicts
1884 if (!empty($conflicts)) {
ffa59d18 1885 CRM_Core_BAO_PrevNextCache::markConflict($mainId, $otherId, $cacheKeyString, $conflicts, $mode);
e4e1db4b 1886 }
1887 else {
c131d228 1888 CRM_Core_BAO_PrevNextCache::deletePair($mainId, $otherId, $cacheKeyString);
e4e1db4b 1889 }
c9f05fb3 1890 self::releaseLocks($locks);
b068bfde 1891 return $resultStats;
e4e1db4b 1892 }
1893
54ed517e 1894 /**
1895 * Replace the pseudo QFKey with zero if it is present.
1896 *
1897 * @todo - on the slim chance this is still relevant it should be moved to the form layer.
1898 *
1899 * Details about this bug are somewhat obscured by the move from svn but perhaps JIRA
1900 * can still help.
1901 *
1902 * @param array $migrationInfo
1903 */
1904 protected static function swapOutFieldsAffectedByQFZeroBug(&$migrationInfo) {
1905 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1906 foreach ($migrationInfo as $key => &$value) {
723c5a81 1907 if ($value === $qfZeroBug) {
54ed517e 1908 $value = '0';
1909 }
1910 }
1911 }
1912
830ee2be 1913 /**
1914 * Honestly - what DOES this do - hopefully some refactoring will reveal it's purpose.
1915 *
1600a9c0 1916 * Update this function formats fields in preparation for them to be submitted to the
1917 * 'ProfileContactCreate action. This is a lot of code to do this & for
1918 * - for some fields it fails - e.g Country - per testMergeCustomFields.
1919 *
1920 * Goal is to move all custom field handling into 'move' functions on the various BAO
1921 * with an underlying DAO function. For custom fields it has been started on the BAO.
1922 *
723c5a81 1923 * @param int $mainId
1924 * @param string $key
1925 * @param array $cFields
1926 * @param array $submitted
1927 * @param mixed $value
830ee2be 1928 *
1929 * @return array
9a248526 1930 * @throws \CRM_Core_Exception
830ee2be 1931 */
1600a9c0 1932 protected static function processCustomFields($mainId, $key, $cFields, $submitted, $value) {
723c5a81 1933 if (substr($key, 0, 7) === 'custom_') {
830ee2be 1934 $fid = (int) substr($key, 7);
1935 if (empty($cFields[$fid])) {
1600a9c0 1936 return [$cFields, $submitted];
830ee2be 1937 }
1938 $htmlType = $cFields[$fid]['attributes']['html_type'];
7f348139 1939 $isSerialized = CRM_Core_BAO_CustomField::isSerialized($cFields[$fid]['attributes']);
830ee2be 1940
7f348139
CW
1941 if ($htmlType === 'File') {
1942 // Handled in CustomField->move(). Tested in testMergeCustomFields.
1943 unset($submitted["custom_$fid"]);
1944 }
1945 elseif (!$isSerialized && ($htmlType === 'Select Country' || $htmlType === 'Select State/Province')) {
1946 // @todo Test in testMergeCustomFields disabled as this does not work, Handle in CustomField->move().
1947 $submitted[$key] = CRM_Core_BAO_CustomField::displayValue($value, $fid);
1948 }
1949 elseif ($htmlType === 'Select Date') {
1950 if ($cFields[$fid]['attributes']['is_view']) {
1951 $submitted[$key] = date('YmdHis', strtotime($submitted[$key]));
1952 }
1953 }
1954 elseif ($isSerialized) {
1955 // Merge values from both contacts for multivalue fields, CRM-4385
1956 // get the existing custom values from db.
1957 $customParams = ['entityID' => $mainId, $key => TRUE];
1958 $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams);
1959 if (!empty($customfieldValues[$key])) {
1960 $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]);
1961 if (is_array($existingValue) && !empty($existingValue)) {
1962 $mergeValue = $submittedCustomFields = [];
723c5a81 1963 if ($value === 'null') {
7f348139
CW
1964 // CRM-19074 if someone has deliberately chosen to overwrite with 'null', respect it.
1965 $submitted[$key] = $value;
1966 }
1967 else {
1968 if ($value) {
1969 $submittedCustomFields = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
830ee2be 1970 }
830ee2be 1971
7f348139
CW
1972 // CRM-19653: overwrite or add the existing custom field value with dupicate contact's
1973 // custom field value stored at $submittedCustomValue.
1974 foreach ($submittedCustomFields as $k => $v) {
1975 if ($v != '' && !in_array($v, $mergeValue)) {
1976 $mergeValue[] = $v;
830ee2be 1977 }
7f348139 1978 }
830ee2be 1979
7f348139
CW
1980 //keep state and country as array format.
1981 //for checkbox and m-select format w/ VALUE_SEPARATOR
1982 if (in_array($htmlType, ['CheckBox', 'Select'])) {
1983 $submitted[$key] = CRM_Utils_Array::implodePadded($mergeValue);
1984 }
1985 else {
1986 $submitted[$key] = $mergeValue;
830ee2be 1987 }
1988 }
1989 }
7f348139
CW
1990 }
1991 elseif (in_array($htmlType, ['Select Country', 'Select State/Province'])) {
1992 //we require submitted values should be in array format
1993 if ($value) {
1994 $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1995 //hack to remove null values from array.
1996 $mergeValue = [];
1997 foreach ($mergeValueArray as $k => $v) {
1998 if ($v != '') {
1999 $mergeValue[] = $v;
830ee2be 2000 }
830ee2be 2001 }
7f348139 2002 $submitted[$key] = $mergeValue;
830ee2be 2003 }
7f348139 2004 }
830ee2be 2005 }
2006 }
1600a9c0 2007 return [$cFields, $submitted];
830ee2be 2008 }
2009
f941d73a 2010 /**
2011 * Get metadata for the custom fields for the merge.
2012 *
2013 * @param string $contactType
2014 *
2015 * @return array
9a248526 2016 * @throws \CRM_Core_Exception
f941d73a 2017 */
2018 protected static function getCustomFieldMetadata($contactType) {
2019 $treeCache = [];
2020 if (!array_key_exists($contactType, $treeCache)) {
2021 $treeCache[$contactType] = CRM_Core_BAO_CustomGroup::getTree(
2022 $contactType,
2023 NULL,
2024 NULL,
2025 -1,
2026 [],
2027 NULL,
2028 TRUE,
2029 NULL,
2030 FALSE,
2031 FALSE
2032 );
2033 }
2034
2035 $cFields = [];
2036 foreach ($treeCache[$contactType] as $key => $group) {
2037 if (!isset($group['fields'])) {
2038 continue;
2039 }
2040 foreach ($group['fields'] as $fid => $field) {
2041 $cFields[$fid]['attributes'] = $field;
2042 }
2043 }
2044 return $cFields;
2045 }
2046
a2abc387 2047 /**
2048 * Get conflicts for proposed merge pair.
2049 *
2050 * @param array $migrationInfo
2051 * This is primarily to inform hooks. The can also modify it which feels
2052 * pretty fragile to do it here - but it is historical.
2053 * @param int $mainId
2054 * Main contact with whom merge has to happen.
2055 * @param int $otherId
2056 * Duplicate contact which would be deleted after merge operation.
2057 * @param string $mode
2058 * Helps decide how to behave when there are conflicts.
2059 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
2060 * - Does a force merge otherwise (aggressive mode).
2061 *
2062 * @return array
aefc291e 2063 *
2064 * @throws \CRM_Core_Exception
2065 * @throws \CiviCRM_API3_Exception
a2abc387 2066 */
2067 public static function getConflicts(&$migrationInfo, $mainId, $otherId, $mode) {
2068 $conflicts = [];
aefc291e 2069 // Generate var $migrationInfo. The variable structure is exactly same as
2070 // $formValues submitted during a UI merge for a pair of contacts.
2071 $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($mainId, $otherId, FALSE);
2072 // add additional details that we might need to resolve conflicts
2073 $migrationInfo = $rowsElementsAndInfo['migration_info'];
2074 $migrationInfo['main_details'] = &$rowsElementsAndInfo['main_details'];
2075 $migrationInfo['other_details'] = &$rowsElementsAndInfo['other_details'];
2076 $migrationInfo['rows'] = &$rowsElementsAndInfo['rows'];
2077 // go ahead with merge if there is no conflict
a2abc387 2078 $originalMigrationInfo = $migrationInfo;
2079 foreach ($migrationInfo as $key => $val) {
2080 if ($val === "null") {
2081 // Rule: Never overwrite with an empty value (in any mode)
2082 unset($migrationInfo[$key]);
2083 continue;
2084 }
2085 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) or
723c5a81 2086 substr($key, 0, 12) === 'move_custom_'
a2abc387 2087 ) and $val != NULL
2088 ) {
2089 // Rule: If both main-contact, and other-contact have a field with a
2090 // different value, then let $mode decide if to merge it or not
2091 if (
2092 (!empty($migrationInfo['rows'][$key]['main'])
2093 // For custom fields a 0 (e.g in an int field) could be a true conflict. This
2094 // is probably true for other fields too - e.g. 'do_not_email' but
2095 // leaving that investigation as a @todo - until tests can be written.
2096 // Note the handling of this has test coverage - although the data-typing
2097 // of '0' feels flakey we have insurance.
723c5a81 2098 || ($migrationInfo['rows'][$key]['main'] === '0' && substr($key, 0, 12) === 'move_custom_')
a2abc387 2099 )
2100 && $migrationInfo['rows'][$key]['main'] != $migrationInfo['rows'][$key]['other']
2101 ) {
2102
2103 // note it down & lets wait for response from the hook.
2104 // For no response $mode will decide if to skip this merge
2105 $conflicts[$key] = NULL;
2106 }
2107 }
723c5a81 2108 elseif (substr($key, 0, 14) === 'move_location_' and $val != NULL) {
a2abc387 2109 $locField = explode('_', $key);
2110 $fieldName = $locField[2];
2111 $fieldCount = $locField[3];
2112
2113 // Rule: Catch address conflicts (same address type on both contacts)
2114 if (
2115 isset($migrationInfo['main_details']['location_blocks'][$fieldName]) &&
2116 !empty($migrationInfo['main_details']['location_blocks'][$fieldName])
2117 ) {
2118
2119 // Load the address we're inspecting from the 'other' contact
2120 $addressRecord = $migrationInfo['other_details']['location_blocks'][$fieldName][$fieldCount];
9c1bc317 2121 $addressRecordLocTypeId = $addressRecord['location_type_id'] ?? NULL;
a2abc387 2122
2123 // If it exists on the 'main' contact already, skip it. Otherwise
2124 // if the location type exists already, log a conflict.
2125 foreach ($migrationInfo['main_details']['location_blocks'][$fieldName] as $mainAddressKey => $mainAddressRecord) {
2126 if (self::locationIsSame($addressRecord, $mainAddressRecord)) {
2127 unset($migrationInfo[$key]);
2128 break;
2129 }
2130 elseif ($addressRecordLocTypeId == $mainAddressRecord['location_type_id']) {
2131 $conflicts[$key] = NULL;
2132 break;
2133 }
2134 }
2135 }
2136
2137 // For other locations, don't merge/add if the values are the same
2138 elseif (CRM_Utils_Array::value('main', $migrationInfo['rows'][$key]) == $migrationInfo['rows'][$key]['other']) {
2139 unset($migrationInfo[$key]);
2140 }
2141 }
2142 }
2143
2144 // A hook to implement other algorithms for choosing which contact to bias to when
2145 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
2146 // merge happens with new values filled in here. For a particular field / row not to be merged
2147 // field should be unset from fields_in_conflict.
2148 $migrationData = [
2149 'old_migration_info' => $originalMigrationInfo,
2150 'mode' => $mode,
2151 'fields_in_conflict' => $conflicts,
2152 'merge_mode' => $mode,
2153 'migration_info' => $migrationInfo,
2154 ];
2155 CRM_Utils_Hook::merge('batch', $migrationData, $mainId, $otherId);
2156 $conflicts = $migrationData['fields_in_conflict'];
2157 // allow hook to override / manipulate migrationInfo as well
2158 $migrationInfo = $migrationData['migration_info'];
ffa59d18 2159 foreach ($conflicts as $key => $val) {
403400d9 2160 // Copy over the resolved values. If we are in aggressive mode we update to null
2161 // so as not to copy over. Why it's different to safe mode is a bit murky.
2162 // Working theory is it doesn't matter what we do in safe mode here if $val is NULL.
2163 // as the merge is not gonna happen if $val == NULL
2164 $migrationInfo[$key] = $val ?? ($mode === 'safe' ? $migrationInfo[$key] : NULL);
ffa59d18 2165 }
403400d9 2166 return self::formatConflictArray($conflicts, $migrationInfo['rows'], $migrationInfo['main_details']['location_blocks'], $migrationInfo['other_details']['location_blocks'], $mainId, $otherId, $mode);
ffa59d18 2167 }
2168
2169 /**
2170 * @param array $conflicts
2171 * @param array $migrationInfo
2172 * @param $toKeepContactLocationBlocks
2173 * @param $toRemoveContactLocationBlocks
2174 * @param $toKeepID
2175 * @param $toRemoveID
403400d9 2176 * @param string $mode
ffa59d18 2177 *
2178 * @return mixed
2179 * @throws \CRM_Core_Exception
2180 */
403400d9 2181 protected static function formatConflictArray($conflicts, $migrationInfo, $toKeepContactLocationBlocks, $toRemoveContactLocationBlocks, $toKeepID, $toRemoveID, $mode) {
ffa59d18 2182 $return = [];
403400d9 2183 $resolved = [];
2184 foreach ($conflicts as $key => $val) {
2185 if ($val !== NULL) {
2186 // copy over the resolved values
2187 $resolved[$key] = $val;
2188 unset($conflicts[$key]);
2189 }
2190 elseif ($mode === 'aggressive') {
2191 unset($conflicts[$key]);
2192 if (strpos($key, 'move_location_') !== 0) {
2193 // @todo - just handling plain contact fields for now because I think I need a bigger refactor
2194 // of the below to handle locations & will do as a follow up.
2195 $resolved['contact'][substr($key, 5)] = $migrationInfo[$key]['main'];
2196 }
2197 }
2198 }
ffa59d18 2199 foreach (array_keys($conflicts) as $index) {
2200 if (substr($index, 0, 14) === 'move_location_') {
2201 $parts = explode('_', $index);
2202 $entity = $parts[2];
2203 $blockIndex = $parts[3];
2204 $locationTypeID = $toKeepContactLocationBlocks[$entity][$blockIndex]['location_type_id'];
2205 $entityConflicts = [
2206 'location_type_id' => $locationTypeID,
2207 'title' => $migrationInfo[$index]['title'],
2208 ];
2209 foreach ($toKeepContactLocationBlocks[$entity][$blockIndex] as $fieldName => $fieldValue) {
2210 if (in_array($fieldName, self::ignoredFields())) {
2211 continue;
2212 }
9c1bc317 2213 $toRemoveValue = $toRemoveContactLocationBlocks[$entity][$blockIndex][$fieldName] ?? NULL;
ffa59d18 2214 if ($fieldValue !== $toRemoveValue) {
2215 $entityConflicts[$fieldName] = [
2216 $toKeepID => $fieldValue,
2217 $toRemoveID => $toRemoveValue,
2218 ];
2219 }
2220 }
2221 $return[$entity][] = $entityConflicts;
2222 }
2223 elseif (substr($index, 0, 5) === 'move_') {
2224 $contactFieldsToCompare[] = str_replace('move_', '', $index);
2225 $return['contact'][str_replace('move_', '', $index)] = [
2226 'title' => $migrationInfo[$index]['title'],
2227 $toKeepID => $migrationInfo[$index]['main'],
2228 $toRemoveID => $migrationInfo[$index]['other'],
2229 ];
2230 }
2231 else {
2232 // Can't think of why this would be the case but perhaps it's ensuring it isn't as we
2233 // refactor this.
2234 throw new CRM_Core_Exception(ts('Unknown parameter') . $index);
2235 }
2236 }
403400d9 2237 return ['conflicts' => $return, 'resolved' => $resolved];
a2abc387 2238 }
2239
4107e11e 2240 /**
e1e24a57 2241 * Get any duplicate merge pairs that have been previously cached.
2242 *
2243 * @param int $rule_group_id
2244 * @param int $group_id
2245 * @param int $batchLimit
2246 * @param bool $isSelected
2247 * @param bool $includeConflicts
2248 * @param array $criteria
2249 * @param int $checkPermissions
997a03fe 2250 * @param int $searchLimit
4107e11e 2251 *
2252 * @return array
2253 */
997a03fe 2254 protected static function getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, $includeConflicts, $criteria, $checkPermissions, $searchLimit = 0) {
4107e11e 2255 return CRM_Core_BAO_PrevNextCache::retrieve(
997a03fe 2256 self::getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit),
4107e11e 2257 self::getJoinOnDedupeTable(),
2258 self::getWhereString($isSelected),
2259 0, $batchLimit,
2260 [], '',
2261 $includeConflicts
2262 );
2263 }
2264
ffa59d18 2265 /**
2266 * @return array
2267 */
2268 protected static function ignoredFields(): array {
2269 $keysToIgnore = [
2270 'id',
2271 'is_primary',
2272 'is_billing',
2273 'manual_geo_code',
2274 'contact_id',
2275 'reset_date',
2276 'hold_date',
2277 ];
2278 return $keysToIgnore;
2279 }
2280
6704a926 2281 /**
2282 * Get the field value & label for the given field.
2283 *
2284 * @param $field
2285 * @param $contact
2286 *
2287 * @return array
2288 * @throws \Exception
2289 */
2290 private static function getFieldValueAndLabel($field, $contact): array {
2291 $fields = self::getMergeFieldsMetadata();
9c1bc317 2292 $value = $label = $contact[$field] ?? NULL;
6704a926 2293 $fieldSpec = $fields[$field];
2294 if (!empty($fieldSpec['serialize']) && is_array($value)) {
2295 // In practice this only applies to preferred_communication_method as the sub types are skipped above
2296 // and no others are serialized.
2297 $labels = [];
2298 foreach ($value as $individualValue) {
2299 $labels[] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_BAO_Contact', $field, $individualValue);
2300 }
2301 $label = implode(', ', $labels);
2302 // We serialize this due to historic handling but it's likely that if we just left it as an
2303 // array all would be well & we would have less code.
2304 $value = CRM_Core_DAO::serializeField($value, $fieldSpec['serialize']);
2305 }
2306 elseif (!empty($fieldSpec['type']) && $fieldSpec['type'] == CRM_Utils_Type::T_DATE) {
2307 if ($value) {
2308 $value = str_replace('-', '', $value);
2309 $label = CRM_Utils_Date::customFormat($label);
2310 }
2311 else {
2312 $value = "null";
2313 }
2314 }
2315 elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) {
2316 if ($label === '0') {
2317 $label = ts('[ ]');
2318 }
2319 if ($label === '1') {
2320 $label = ts('[x]');
2321 }
2322 }
2323 elseif (!empty($fieldSpec['pseudoconstant'])) {
2324 $label = CRM_Core_PseudoConstant::getLabel('CRM_Contact_BAO_Contact', $field, $value);
2325 }
2326 elseif ($field == 'current_employer_id' && !empty($value)) {
2327 $label = "$value (" . CRM_Contact_BAO_Contact::displayName($value) . ")";
2328 }
2fd72602 2329 return ['label' => $label, 'value' => $value];
6704a926 2330 }
2331
1a90ac89 2332 /**
2333 * Build up the location block for the contact in dedupe-screen display format.
2334 *
2335 * @param integer $cid
2336 * @param array $blockInfo
2337 * @param string $blockName
2338 *
2339 * @return array
2340 *
2341 * @throws \CiviCRM_API3_Exception
2342 */
2343 private static function buildLocationBlockForContact($cid, $blockInfo, $blockName): array {
2344 $searchParams = [
2345 'contact_id' => $cid,
2346 // CRM-17556 Order by field-specific criteria
2347 'options' => [
2348 'sort' => $blockInfo['sortString'],
2349 ],
2350 ];
2351 $locationBlock = [];
2352 $values = civicrm_api3($blockName, 'get', $searchParams);
2353 if ($values['count']) {
2354 $cnt = 0;
2355 foreach ($values['values'] as $value) {
2356 $locationBlock[$cnt] = $value;
2357 // Fix address display
2358 if ($blockName == 'address') {
2359 // For performance avoid geocoding while merging https://issues.civicrm.org/jira/browse/CRM-21786
2360 // we can expect existing geocode values to be retained.
2361 $value['skip_geocode'] = TRUE;
2362 CRM_Core_BAO_Address::fixAddress($value);
2363 unset($value['skip_geocode']);
2364 $locationBlock[$cnt]['display'] = CRM_Utils_Address::format($value);
2365 }
2366 // Fix email display
2367 elseif ($blockName == 'email') {
2368 $locationBlock[$cnt]['display'] = CRM_Utils_Mail::format($value);
2369 }
2370
2371 $cnt++;
2372 }
2373 }
2374 return $locationBlock;
2375 }
2376
c9f05fb3 2377 /**
2378 * Get a lock on the given contact.
2379 *
2380 * The lock is like a gentleman's agreement between php & mysql. It is reserved at the
2381 * mysql level so it works across php processes but it doesn't actually lock the database.
2382 *
2383 * Instead php can check the lock to see if it has been acquired before taking an action.
2384 *
2385 * In this case we really don't want to attempt to dedupe contacts if another process is
2386 * trying to act on the specific contact as it could result in messy deadlocks & possibly data corruption.
2387 * In most databases this would be a rare event but if multiple dedupe processes are running
2388 * at once (for example) or there is also an import process in play there is potential for them to crash.
2389 * By throwing a specific error the calling process can catch it and determine it is worth trying again later without a lot of
2390 * noise.
2391 *
2392 * As of writing no other processes DO grab contact locks but it would be reasonable to consider
2393 * grabbing them doing contact edits in general as well as imports etc.
2394 *
2395 * @param array $contacts
2396 *
2397 * @return array
2398 *
2399 * @throws \CRM_Core_Exception
2400 * @throws \CRM_Core_Exception_ResourceConflictException
2401 */
2402 protected static function getLocksOnContacts($contacts):array {
2403 $locks = [];
2404 if (!CRM_Utils_SQL::supportsMultipleLocks()) {
2405 return $locks;
2406 }
2407 foreach ($contacts as $contactID) {
2408 $lock = Civi::lockManager()->acquire("data.core.contact.{$contactID}");
2409 if ($lock->isAcquired()) {
2410 $locks[] = $lock;
2411 }
2412 else {
2413 self::releaseLocks($locks);
2414 throw new CRM_Core_Exception_ResourceConflictException(ts('Contact is in Use'), 'contact_lock');
2415 }
2416 }
2417 return $locks;
2418 }
2419
2420 /**
2421 * Release contact locks so another process can alter them if it wants.
2422 *
2423 * @param array $locks
2424 */
2425 protected static function releaseLocks(array $locks) {
2426 foreach ($locks as $lock) {
2427 /* @var Civi\Core\Lock\LockInterface $lock */
2428 $lock->release();
2429 }
2430 }
2431
18226102 2432 /**
2433 * @param $mainId
2434 * @param $otherId
2435 * @param $blockInfo
2436 * @param $blockName
2437 * @param array $locations
2438 * @param array $rows
2439 * @param array $elements
2440 * @param array $migrationInfo
2441 *
2442 * @return array
2443 * @throws \CiviCRM_API3_Exception
2444 */
2445 protected static function addLocationFieldInfo($mainId, $otherId, $blockInfo, $blockName, array $locations, array $rows, array $elements, array $migrationInfo): array {
2446 // Collect existing fields from both 'main' and 'other' contacts first
2447 // This allows us to match up location/types when building the table rows
2448 $locations['main'][$blockName] = self::buildLocationBlockForContact($mainId, $blockInfo, $blockName);
2449 $locations['other'][$blockName] = self::buildLocationBlockForContact($otherId, $blockInfo, $blockName);
2450
2451 // Now, build the table rows appropriately, based off the information on
2452 // the 'other' contact
2453 if (!empty($locations['other']) && !empty($locations['other'][$blockName])) {
2454 foreach ($locations['other'][$blockName] as $count => $value) {
2455
2456 $displayValue = $value[$blockInfo['displayField']];
2457
2458 // Add this value to the table rows
2459 $rows["move_location_{$blockName}_{$count}"]['other'] = $displayValue;
2460
2461 // CRM-17556 Only display 'main' contact value if it's the same location + type
2462 // Look it up from main values...
2463
2464 $lookupLocation = FALSE;
2465 if ($blockInfo['hasLocation']) {
2466 $lookupLocation = $value['location_type_id'];
2467 }
2468
2469 $lookupType = FALSE;
2470 if ($blockInfo['hasType']) {
9c1bc317 2471 $lookupType = $value[$blockInfo['hasType']] ?? NULL;
18226102 2472 }
2473
2474 // Hold ID of main contact's matching block
2475 $mainContactBlockId = 0;
2476
2477 if (!empty($locations['main'][$blockName])) {
2478 foreach ($locations['main'][$blockName] as $mainValueCheck) {
2479 // No location/type, or matching location and type
2480 if (
2481 (empty($lookupLocation) || $lookupLocation == $mainValueCheck['location_type_id'])
2482 && (empty($lookupType) || $lookupType == $mainValueCheck[$blockInfo['hasType']])
2483 ) {
2484 // Set this value as the default against the 'other' contact value
2485 $rows["move_location_{$blockName}_{$count}"]['main'] = $mainValueCheck[$blockInfo['displayField']];
2486 $rows["move_location_{$blockName}_{$count}"]['main_is_primary'] = $mainValueCheck['is_primary'];
2487 $rows["move_location_{$blockName}_{$count}"]['location_entity'] = $blockName;
2488 $mainContactBlockId = $mainValueCheck['id'];
2489 break;
2490 }
2491 }
2492 }
2493
2494 // Add checkbox to migrate data from 'other' to 'main'
2495 $elements[] = ['advcheckbox', "move_location_{$blockName}_{$count}"];
2496
2497 // Add checkbox to set the 'other' location as primary
2498 $elements[] = [
2499 'advcheckbox',
2500 "location_blocks[$blockName][$count][set_other_primary]",
2501 NULL,
2502 ts('Set as primary'),
2503 ];
2504
2505 // Flag up this field to skipMerge function (@todo: do we need to?)
2506 $migrationInfo["move_location_{$blockName}_{$count}"] = 1;
2507
2508 // Add a hidden field to store the ID of the target main contact block
2509 $elements[] = [
2510 'hidden',
2511 "location_blocks[$blockName][$count][mainContactBlockId]",
2512 $mainContactBlockId,
2513 ];
2514
2515 // Setup variables
2516 $thisTypeId = FALSE;
2517 $thisLocId = FALSE;
2518
2519 // Provide a select drop-down for the location's location type
2520 // eg: Home, Work...
2521
2522 if ($blockInfo['hasLocation']) {
2523
2524 // Load the location options for this entity
2525 $locationOptions = civicrm_api3($blockName, 'getoptions', ['field' => 'location_type_id']);
2526
2527 $thisLocId = $value['location_type_id'];
2528
2529 // Put this field's location type at the top of the list
2530 $tmpIdList = $locationOptions['values'];
2531 $defaultLocId = [$thisLocId => $tmpIdList[$thisLocId]];
2532 unset($tmpIdList[$thisLocId]);
2533
2534 // Add the element
2535 $elements[] = [
2536 'select',
2537 "location_blocks[$blockName][$count][locTypeId]",
2538 NULL,
2539 $defaultLocId + $tmpIdList,
2540 ];
2541
2542 // Add the relevant information to the $migrationInfo
2543 // Keep location-type-id same as that of other-contact
2544 // @todo Check this logic out
2545 $migrationInfo['location_blocks'][$blockName][$count]['locTypeId'] = $thisLocId;
2546 if ($blockName != 'address') {
2547 $elements[] = [
2548 'advcheckbox',
2549 "location_blocks[{$blockName}][$count][operation]",
2550 NULL,
2551 ts('Add new'),
2552 ];
2553 // always use add operation
2554 $migrationInfo['location_blocks'][$blockName][$count]['operation'] = 1;
2555 }
2556
2557 }
2558
2559 // Provide a select drop-down for the location's type/provider
2560 // eg websites: Facebook...
2561
2562 if ($blockInfo['hasType']) {
2563
2564 // Load the type options for this entity
2565 $typeOptions = civicrm_api3($blockName, 'getoptions', ['field' => $blockInfo['hasType']]);
2566
9c1bc317 2567 $thisTypeId = $value[$blockInfo['hasType']] ?? NULL;
18226102 2568
2569 // Put this field's location type at the top of the list
2570 $tmpIdList = $typeOptions['values'];
2571 $defaultTypeId = [$thisTypeId => CRM_Utils_Array::value($thisTypeId, $tmpIdList)];
2572 unset($tmpIdList[$thisTypeId]);
2573
2574 // Add the element
2575 $elements[] = [
2576 'select',
2577 "location_blocks[$blockName][$count][typeTypeId]",
2578 NULL,
2579 $defaultTypeId + $tmpIdList,
2580 ];
2581
2582 // Add the information to the migrationInfo
2583 $migrationInfo['location_blocks'][$blockName][$count]['typeTypeId'] = $thisTypeId;
2584
2585 }
2586
2587 // Set the label for this row
2588 $rowTitle = $blockInfo['label'] . ' ' . ($count + 1);
2589 if (!empty($thisLocId)) {
2590 $rowTitle .= ' (' . $locationOptions['values'][$thisLocId] . ')';
2591 }
2592 if (!empty($thisTypeId)) {
2593 $rowTitle .= ' (' . $typeOptions['values'][$thisTypeId] . ')';
2594 }
2595 $rows["move_location_{$blockName}_$count"]['title'] = $rowTitle;
2596
2597 } // End loop through 'other' locations of this type
2598
2599 }
2600 return [$locations, $rows, $elements, $migrationInfo];
2601 }
2602
6a488035 2603}