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