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