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