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