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