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