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