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