[REF] Update fetchAll function signature to match parent function
[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 // A hook could have set skip_merge in order to alter merge behaviour.
938 // This is a something we might ideally deprecate since they really 'should'
939 // mess with the conflicts array instead.
940 return (bool) ($migrationData['skip_merge'] ?? !empty($conflicts));
941 }
942
943 /**
944 * Compare 2 addresses to see if they are the same.
945 *
946 * @param array $mainAddress
947 * @param array $comparisonAddress
948 *
949 * @return bool
950 */
951 public static function locationIsSame($mainAddress, $comparisonAddress) {
952 $keysToIgnore = self::ignoredFields();
953 foreach ($comparisonAddress as $field => $value) {
954 if (in_array($field, $keysToIgnore)) {
955 continue;
956 }
957 if ((!empty($value) || $value === '0') && isset($mainAddress[$field]) && $mainAddress[$field] != $value) {
958 return FALSE;
959 }
960 }
961 return TRUE;
962 }
963
964 /**
965 * A function to build an array of information about location blocks that is
966 * required when merging location fields
967 *
968 * @return array
969 */
970 public static function getLocationBlockInfo() {
971 $locationBlocks = [
972 'address' => [
973 'label' => 'Address',
974 'displayField' => 'display',
975 'sortString' => 'location_type_id',
976 'hasLocation' => TRUE,
977 'hasType' => FALSE,
978 ],
979 'email' => [
980 'label' => 'Email',
981 'displayField' => 'display',
982 'sortString' => 'location_type_id',
983 'hasLocation' => TRUE,
984 'hasType' => FALSE,
985 ],
986 'im' => [
987 'label' => 'IM',
988 'displayField' => 'name',
989 'sortString' => 'location_type_id,provider_id',
990 'hasLocation' => TRUE,
991 'hasType' => 'provider_id',
992 ],
993 'phone' => [
994 'label' => 'Phone',
995 'displayField' => 'phone',
996 'sortString' => 'location_type_id,phone_type_id',
997 'hasLocation' => TRUE,
998 'hasType' => 'phone_type_id',
999 ],
1000 'website' => [
1001 'label' => 'Website',
1002 'displayField' => 'url',
1003 'sortString' => 'website_type_id',
1004 'hasLocation' => FALSE,
1005 'hasType' => 'website_type_id',
1006 ],
1007 ];
1008 return $locationBlocks;
1009 }
1010
1011 /**
1012 * A function to build an array of information required by merge function and the merge UI.
1013 *
1014 * @param int $mainId
1015 * Main contact with whom merge has to happen.
1016 * @param int $otherId
1017 * Duplicate contact which would be deleted after merge operation.
1018 * @param bool $checkPermissions
1019 * Should the logged in user's permissions be ignore. Setting this to false is
1020 * highly risky as it could cause data to be lost due to conflicts not showing up.
1021 * OTOH there is a risk a merger might view custom data they do not have permission to.
1022 * Hence for now only making this really explicit and making it reflect perms in
1023 * an api call.
1024 *
1025 * @todo review permissions issue!
1026 *
1027 * @return array|bool|int
1028 *
1029 * rows => An array of arrays, each is row of merge information for the table
1030 * Format: move_fieldname, eg: move_contact_type
1031 * main => Value associated with the main contact
1032 * other => Value associated with the other contact
1033 * title => The title of the field to display in the merge table
1034 *
1035 * elements => An array of form elements for the merge UI
1036 *
1037 * rel_table_elements => An array of form elements for the merge UI for
1038 * entities related to the contact (eg: checkbox to move 'mailings')
1039 *
1040 * rel_tables => Stores the tables that have related entities for the contact
1041 * for example mailings, groups
1042 *
1043 * main_details => An array of core contact field values, eg: first_name, etc.
1044 * location_blocks => An array of location block data for the main contact
1045 * stored as the 'result' of an API call.
1046 * eg: main_details['location_blocks']['address'][0]['id']
1047 * eg: main_details['location_blocks']['email'][1]['id']
1048 *
1049 * other_details => As above, but for the 'other' contact
1050 *
1051 * migration_info => Stores the 'default' merge actions for each field which
1052 * is used when programatically merging contacts. It contains instructions
1053 * to move all fields from the 'other' contact to the 'main' contact, as
1054 * though the form had been submitted with those options.
1055 *
1056 * @throws \CRM_Core_Exception
1057 * @throws \CiviCRM_API3_Exception
1058 * @throws \Exception
1059 */
1060 public static function getRowsElementsAndInfo($mainId, $otherId, $checkPermissions = TRUE) {
1061 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
1062 $fields = self::getMergeFieldsMetadata();
1063
1064 $main = self::getMergeContactDetails($mainId);
1065 $other = self::getMergeContactDetails($otherId);
1066
1067 $compareFields = self::retrieveFields($main, $other);
1068
1069 $rows = $elements = $relTableElements = $migrationInfo = [];
1070
1071 foreach ($compareFields['contact'] as $field) {
1072 if ($field == 'contact_sub_type') {
1073 // CRM-15681 don't display sub-types in UI
1074 continue;
1075 }
1076 $rows["move_$field"] = [
1077 'main' => self::getFieldValueAndLabel($field, $main)['label'],
1078 'other' => self::getFieldValueAndLabel($field, $other)['label'],
1079 'title' => $fields[$field]['title'],
1080 ];
1081
1082 $value = self::getFieldValueAndLabel($field, $other)['value'];
1083 //CRM-14334
1084 if ($value === NULL || $value == '') {
1085 $value = 'null';
1086 }
1087 if ($value === 0 or $value === '0') {
1088 $value = $qfZeroBug;
1089 }
1090 if (is_array($value) && empty($value[1])) {
1091 $value[1] = NULL;
1092 }
1093
1094 // Display a checkbox to migrate, only if the values are different
1095 if ($value != $main[$field]) {
1096 $elements[] = [
1097 0 => 'advcheckbox',
1098 1 => "move_$field",
1099 2 => NULL,
1100 3 => NULL,
1101 4 => NULL,
1102 5 => $value,
1103 'is_checked' => (!isset($main[$field]) || $main[$field] === ''),
1104 ];
1105 }
1106
1107 $migrationInfo["move_$field"] = $value;
1108 }
1109
1110 // Handle location blocks.
1111 // @todo OpenID not in API yet, so is not supported here.
1112
1113 // Set up useful information about the location blocks
1114 $locationBlocks = self::getLocationBlockInfo();
1115
1116 $locations = ['main' => [], 'other' => []];
1117
1118 foreach ($locationBlocks as $blockName => $blockInfo) {
1119
1120 // Collect existing fields from both 'main' and 'other' contacts first
1121 // This allows us to match up location/types when building the table rows
1122 $locations['main'][$blockName] = self::buildLocationBlockForContact($mainId, $blockInfo, $blockName);
1123 $locations['other'][$blockName] = self::buildLocationBlockForContact($otherId, $blockInfo, $blockName);
1124
1125 // Now, build the table rows appropriately, based off the information on
1126 // the 'other' contact
1127 if (!empty($locations['other']) && !empty($locations['other'][$blockName])) {
1128 foreach ($locations['other'][$blockName] as $count => $value) {
1129
1130 $displayValue = $value[$blockInfo['displayField']];
1131
1132 // Add this value to the table rows
1133 $rows["move_location_{$blockName}_{$count}"]['other'] = $displayValue;
1134
1135 // CRM-17556 Only display 'main' contact value if it's the same location + type
1136 // Look it up from main values...
1137
1138 $lookupLocation = FALSE;
1139 if ($blockInfo['hasLocation']) {
1140 $lookupLocation = $value['location_type_id'];
1141 }
1142
1143 $lookupType = FALSE;
1144 if ($blockInfo['hasType']) {
1145 $lookupType = CRM_Utils_Array::value($blockInfo['hasType'], $value);
1146 }
1147
1148 // Hold ID of main contact's matching block
1149 $mainContactBlockId = 0;
1150
1151 if (!empty($locations['main'][$blockName])) {
1152 foreach ($locations['main'][$blockName] as $mainValueCheck) {
1153 // No location/type, or matching location and type
1154 if (
1155 (empty($lookupLocation) || $lookupLocation == $mainValueCheck['location_type_id'])
1156 && (empty($lookupType) || $lookupType == $mainValueCheck[$blockInfo['hasType']])
1157 ) {
1158 // Set this value as the default against the 'other' contact value
1159 $rows["move_location_{$blockName}_{$count}"]['main'] = $mainValueCheck[$blockInfo['displayField']];
1160 $rows["move_location_{$blockName}_{$count}"]['main_is_primary'] = $mainValueCheck['is_primary'];
1161 $rows["move_location_{$blockName}_{$count}"]['location_entity'] = $blockName;
1162 $mainContactBlockId = $mainValueCheck['id'];
1163 break;
1164 }
1165 }
1166 }
1167
1168 // Add checkbox to migrate data from 'other' to 'main'
1169 $elements[] = ['advcheckbox', "move_location_{$blockName}_{$count}"];
1170
1171 // Add checkbox to set the 'other' location as primary
1172 $elements[] = [
1173 'advcheckbox',
1174 "location_blocks[$blockName][$count][set_other_primary]",
1175 NULL,
1176 ts('Set as primary'),
1177 ];
1178
1179 // Flag up this field to skipMerge function (@todo: do we need to?)
1180 $migrationInfo["move_location_{$blockName}_{$count}"] = 1;
1181
1182 // Add a hidden field to store the ID of the target main contact block
1183 $elements[] = [
1184 'hidden',
1185 "location_blocks[$blockName][$count][mainContactBlockId]",
1186 $mainContactBlockId,
1187 ];
1188
1189 // Setup variables
1190 $thisTypeId = FALSE;
1191 $thisLocId = FALSE;
1192
1193 // Provide a select drop-down for the location's location type
1194 // eg: Home, Work...
1195
1196 if ($blockInfo['hasLocation']) {
1197
1198 // Load the location options for this entity
1199 $locationOptions = civicrm_api3($blockName, 'getoptions', ['field' => 'location_type_id']);
1200
1201 $thisLocId = $value['location_type_id'];
1202
1203 // Put this field's location type at the top of the list
1204 $tmpIdList = $locationOptions['values'];
1205 $defaultLocId = [$thisLocId => $tmpIdList[$thisLocId]];
1206 unset($tmpIdList[$thisLocId]);
1207
1208 // Add the element
1209 $elements[] = [
1210 'select',
1211 "location_blocks[$blockName][$count][locTypeId]",
1212 NULL,
1213 $defaultLocId + $tmpIdList,
1214 ];
1215
1216 // Add the relevant information to the $migrationInfo
1217 // Keep location-type-id same as that of other-contact
1218 // @todo Check this logic out
1219 $migrationInfo['location_blocks'][$blockName][$count]['locTypeId'] = $thisLocId;
1220 if ($blockName != 'address') {
1221 $elements[] = [
1222 'advcheckbox',
1223 "location_blocks[{$blockName}][$count][operation]",
1224 NULL,
1225 ts('Add new'),
1226 ];
1227 // always use add operation
1228 $migrationInfo['location_blocks'][$blockName][$count]['operation'] = 1;
1229 }
1230
1231 }
1232
1233 // Provide a select drop-down for the location's type/provider
1234 // eg websites: Facebook...
1235
1236 if ($blockInfo['hasType']) {
1237
1238 // Load the type options for this entity
1239 $typeOptions = civicrm_api3($blockName, 'getoptions', ['field' => $blockInfo['hasType']]);
1240
1241 $thisTypeId = CRM_Utils_Array::value($blockInfo['hasType'], $value);
1242
1243 // Put this field's location type at the top of the list
1244 $tmpIdList = $typeOptions['values'];
1245 $defaultTypeId = [$thisTypeId => CRM_Utils_Array::value($thisTypeId, $tmpIdList)];
1246 unset($tmpIdList[$thisTypeId]);
1247
1248 // Add the element
1249 $elements[] = [
1250 'select',
1251 "location_blocks[$blockName][$count][typeTypeId]",
1252 NULL,
1253 $defaultTypeId + $tmpIdList,
1254 ];
1255
1256 // Add the information to the migrationInfo
1257 $migrationInfo['location_blocks'][$blockName][$count]['typeTypeId'] = $thisTypeId;
1258
1259 }
1260
1261 // Set the label for this row
1262 $rowTitle = $blockInfo['label'] . ' ' . ($count + 1);
1263 if (!empty($thisLocId)) {
1264 $rowTitle .= ' (' . $locationOptions['values'][$thisLocId] . ')';
1265 }
1266 if (!empty($thisTypeId)) {
1267 $rowTitle .= ' (' . $typeOptions['values'][$thisTypeId] . ')';
1268 }
1269 $rows["move_location_{$blockName}_$count"]['title'] = $rowTitle;
1270
1271 } // End loop through 'other' locations of this type
1272
1273 } // End if 'other' location for this type exists
1274
1275 } // End loop through each location block entity
1276
1277 // add the related tables and unset the ones that don't sport any of the duplicate contact's info
1278 $config = CRM_Core_Config::singleton();
1279 $mainUfId = CRM_Core_BAO_UFMatch::getUFId($mainId);
1280 $mainUser = NULL;
1281 if ($mainUfId) {
1282 // d6 compatible
1283 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1284 $mainUser = user_load($mainUfId);
1285 }
1286 elseif ($config->userFramework == 'Joomla') {
1287 $mainUser = JFactory::getUser($mainUfId);
1288 }
1289 }
1290 $otherUfId = CRM_Core_BAO_UFMatch::getUFId($otherId);
1291 $otherUser = NULL;
1292 if ($otherUfId) {
1293 // d6 compatible
1294 if ($config->userSystem->is_drupal == '1' && function_exists($mainUser)) {
1295 $otherUser = user_load($otherUfId);
1296 }
1297 elseif ($config->userFramework == 'Joomla') {
1298 $otherUser = JFactory::getUser($otherUfId);
1299 }
1300 }
1301
1302 $mergeHandler = new CRM_Dedupe_MergeHandler((int) $mainId, (int) $otherId);
1303 $relTables = $mergeHandler->getTablesRelatedToTheMergePair();
1304 foreach ($relTables as $name => $null) {
1305 $relTableElements[] = ['checkbox', "move_$name"];
1306 $migrationInfo["move_$name"] = 1;
1307
1308 $relTables[$name]['main_url'] = str_replace('$cid', $mainId, $relTables[$name]['url']);
1309 $relTables[$name]['other_url'] = str_replace('$cid', $otherId, $relTables[$name]['url']);
1310 if ($name == 'rel_table_users') {
1311 $relTables[$name]['main_url'] = str_replace('%ufid', $mainUfId, $relTables[$name]['url']);
1312 $relTables[$name]['other_url'] = str_replace('%ufid', $otherUfId, $relTables[$name]['url']);
1313 $find = ['$ufid', '$ufname'];
1314 if ($mainUser) {
1315 $replace = [$mainUfId, $mainUser->name];
1316 $relTables[$name]['main_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1317 }
1318 if ($otherUser) {
1319 $replace = [$otherUfId, $otherUser->name];
1320 $relTables[$name]['other_title'] = str_replace($find, $replace, $relTables[$name]['title']);
1321 }
1322 }
1323 if ($name == 'rel_table_memberships') {
1324 //Enable 'add new' checkbox if main contact does not contain any membership similar to duplicate contact.
1325 $attributes = ['checked' => 'checked'];
1326 $otherContactMemberships = CRM_Member_BAO_Membership::getAllContactMembership($otherId);
1327 foreach ($otherContactMemberships as $membership) {
1328 $mainMembership = CRM_Member_BAO_Membership::getContactMembership($mainId, $membership['membership_type_id'], FALSE);
1329 if ($mainMembership) {
1330 $attributes = [];
1331 }
1332 }
1333 $elements[] = [
1334 'checkbox',
1335 "operation[move_{$name}][add]",
1336 NULL,
1337 ts('add new'),
1338 $attributes,
1339 ];
1340 $migrationInfo["operation"]["move_{$name}"]['add'] = 1;
1341 }
1342 }
1343 foreach ($relTables as $name => $null) {
1344 $relTables["move_$name"] = $relTables[$name];
1345 unset($relTables[$name]);
1346 }
1347
1348 // handle custom fields
1349 $mainTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], NULL, $mainId, -1,
1350 CRM_Utils_Array::value('contact_sub_type', $main), NULL, TRUE, NULL, TRUE, $checkPermissions
1351 );
1352 $otherTree = CRM_Core_BAO_CustomGroup::getTree($main['contact_type'], NULL, $otherId, -1,
1353 CRM_Utils_Array::value('contact_sub_type', $other), NULL, TRUE, NULL, TRUE, $checkPermissions
1354 );
1355
1356 foreach ($otherTree as $gid => $group) {
1357 $foundField = FALSE;
1358 if (!isset($group['fields'])) {
1359 continue;
1360 }
1361
1362 foreach ($group['fields'] as $fid => $field) {
1363 if (in_array($fid, $compareFields['custom'])) {
1364 if (!$foundField) {
1365 $rows["custom_group_$gid"]['title'] = $group['title'];
1366 $foundField = TRUE;
1367 }
1368 if (!empty($mainTree[$gid]['fields'][$fid]['customValue'])) {
1369 foreach ($mainTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1370 $rows["move_custom_$fid"]['main'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid);
1371 }
1372 }
1373 $value = "null";
1374 if (!empty($otherTree[$gid]['fields'][$fid]['customValue'])) {
1375 foreach ($otherTree[$gid]['fields'][$fid]['customValue'] as $valueId => $values) {
1376 $rows["move_custom_$fid"]['other'] = CRM_Core_BAO_CustomField::displayValue($values['data'], $fid);
1377 if ($values['data'] === 0 || $values['data'] === '0') {
1378 $values['data'] = $qfZeroBug;
1379 }
1380 $value = ($values['data']) ? $values['data'] : $value;
1381 }
1382 }
1383 $rows["move_custom_$fid"]['title'] = $field['label'];
1384
1385 $elements[] = [
1386 'advcheckbox',
1387 "move_custom_$fid",
1388 NULL,
1389 NULL,
1390 NULL,
1391 $value,
1392 ];
1393 $migrationInfo["move_custom_$fid"] = $value;
1394 }
1395 }
1396 }
1397
1398 $result = [
1399 'rows' => $rows,
1400 'elements' => $elements,
1401 'rel_table_elements' => $relTableElements,
1402 'rel_tables' => $relTables,
1403 'main_details' => $main,
1404 'other_details' => $other,
1405 'migration_info' => $migrationInfo,
1406 ];
1407
1408 $result['main_details']['location_blocks'] = $locations['main'];
1409 $result['other_details']['location_blocks'] = $locations['other'];
1410
1411 return $result;
1412 }
1413
1414 /**
1415 * Based on the provided two contact_ids and a set of tables, move the belongings of the
1416 * other contact to the main one - be it Location / CustomFields or Contact .. related info.
1417 * A superset of moveContactBelongings() function.
1418 *
1419 * @param int $mainId
1420 * Main contact with whom merge has to happen.
1421 * @param int $otherId
1422 * Duplicate contact which would be deleted after merge operation.
1423 *
1424 * @param array $migrationInfo
1425 *
1426 * @param bool $checkPermissions
1427 * Respect logged in user permissions.
1428 *
1429 * @return bool
1430 * @throws \CiviCRM_API3_Exception
1431 */
1432 public static function moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions = TRUE) {
1433 if (empty($migrationInfo)) {
1434 return FALSE;
1435 }
1436 // Encapsulate in a transaction to avoid half-merges.
1437 $transaction = new CRM_Core_Transaction();
1438
1439 $contactType = $migrationInfo['main_details']['contact_type'];
1440 $relTables = CRM_Dedupe_Merger::relTables();
1441 $submittedCustomFields = $moveTables = $tableOperations = $removeTables = [];
1442
1443 self::swapOutFieldsAffectedByQFZeroBug($migrationInfo);
1444 foreach ($migrationInfo as $key => $value) {
1445
1446 if (substr($key, 0, 12) == 'move_custom_' && $value != NULL) {
1447 $submitted[substr($key, 5)] = $value;
1448 $submittedCustomFields[] = substr($key, 12);
1449 }
1450 elseif (in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) && $value != NULL) {
1451 $submitted[substr($key, 5)] = $value;
1452 }
1453 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '1') {
1454 $moveTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1455 if (array_key_exists('operation', $migrationInfo)) {
1456 foreach ($relTables[substr($key, 5)]['tables'] as $table) {
1457 if (array_key_exists($key, $migrationInfo['operation'])) {
1458 $tableOperations[$table] = $migrationInfo['operation'][$key];
1459 }
1460 }
1461 }
1462 }
1463 elseif (substr($key, 0, 15) == 'move_rel_table_' and $value == '0') {
1464 $removeTables = array_merge($moveTables, $relTables[substr($key, 5)]['tables']);
1465 }
1466 }
1467 self::mergeLocations($mainId, $otherId, $migrationInfo);
1468
1469 // **** Do contact related migrations
1470 $customTablesToCopyValues = self::getAffectedCustomTables($submittedCustomFields);
1471 // @todo - move all custom field processing to the move class & eventually have an
1472 // overridable DAO class for it.
1473 $customFieldBAO = new CRM_Core_BAO_CustomField();
1474 $customFieldBAO->move($otherId, $mainId, $submittedCustomFields);
1475 CRM_Dedupe_Merger::moveContactBelongings($mainId, $otherId, $moveTables, $tableOperations, $customTablesToCopyValues);
1476 unset($moveTables, $tableOperations);
1477
1478 // **** Do table related removals
1479 if (!empty($removeTables)) {
1480 // **** CRM-20421
1481 CRM_Dedupe_Merger::removeContactBelongings($otherId, $removeTables);
1482 $removeTables = [];
1483 }
1484
1485 // FIXME: fix gender, prefix and postfix, so they're edible by createProfileContact()
1486 $names['gender'] = ['newName' => 'gender_id', 'groupName' => 'gender'];
1487 $names['individual_prefix'] = [
1488 'newName' => 'prefix_id',
1489 'groupName' => 'individual_prefix',
1490 ];
1491 $names['individual_suffix'] = [
1492 'newName' => 'suffix_id',
1493 'groupName' => 'individual_suffix',
1494 ];
1495 $names['communication_style'] = [
1496 'newName' => 'communication_style_id',
1497 'groupName' => 'communication_style',
1498 ];
1499 $names['addressee'] = [
1500 'newName' => 'addressee_id',
1501 'groupName' => 'addressee',
1502 ];
1503 $names['email_greeting'] = [
1504 'newName' => 'email_greeting_id',
1505 'groupName' => 'email_greeting',
1506 ];
1507 $names['postal_greeting'] = [
1508 'newName' => 'postal_greeting_id',
1509 'groupName' => 'postal_greeting',
1510 ];
1511 CRM_Core_OptionGroup::lookupValues($submitted, $names, TRUE);
1512 // fix custom fields so they're edible by createProfileContact()
1513 $cFields = self::getCustomFieldMetadata($contactType);
1514
1515 if (!isset($submitted)) {
1516 $submitted = [];
1517 }
1518 foreach ($submitted as $key => $value) {
1519 list($cFields, $submitted) = self::processCustomFields($mainId, $key, $cFields, $submitted, $value);
1520 }
1521
1522 // move view only custom fields CRM-5362
1523 $viewOnlyCustomFields = [];
1524 foreach ($submitted as $key => $value) {
1525 $fid = CRM_Core_BAO_CustomField::getKeyID($key);
1526 if ($fid && array_key_exists($fid, $cFields) && !empty($cFields[$fid]['attributes']['is_view'])
1527 ) {
1528 $viewOnlyCustomFields[$key] = $value;
1529 }
1530 }
1531 // special case to set values for view only, CRM-5362
1532 if (!empty($viewOnlyCustomFields)) {
1533 $viewOnlyCustomFields['entityID'] = $mainId;
1534 CRM_Core_BAO_CustomValueTable::setValues($viewOnlyCustomFields);
1535 }
1536
1537 // dev/core#996 Ensure that the earliest created date is stored against the kept contact id
1538 $mainCreatedDate = civicrm_api3('Contact', 'getsingle', [
1539 'id' => $mainId,
1540 'return' => ['created_date'],
1541 ])['created_date'];
1542 $otherCreatedDate = civicrm_api3('Contact', 'getsingle', [
1543 'id' => $otherId,
1544 'return' => ['created_date'],
1545 ])['created_date'];
1546 if ($otherCreatedDate < $mainCreatedDate) {
1547 CRM_Core_DAO::executeQuery("UPDATE civicrm_contact SET created_date = %1 WHERE id = %2", [
1548 1 => [$otherCreatedDate, 'String'],
1549 2 => [$mainId, 'Positive'],
1550 ]);
1551 }
1552
1553 if (!$checkPermissions || (CRM_Core_Permission::check('merge duplicate contacts') &&
1554 CRM_Core_Permission::check('delete contacts'))
1555 ) {
1556 // if ext id is submitted then set it null for contact to be deleted
1557 if (!empty($submitted['external_identifier'])) {
1558 $query = "UPDATE civicrm_contact SET external_identifier = null WHERE id = {$otherId}";
1559 CRM_Core_DAO::executeQuery($query);
1560 }
1561 civicrm_api3('contact', 'delete', ['id' => $otherId]);
1562 }
1563
1564 // CRM-15681 merge sub_types
1565 if ($other_sub_types = CRM_Utils_Array::value('contact_sub_type', $migrationInfo['other_details'])) {
1566 if ($main_sub_types = CRM_Utils_Array::value('contact_sub_type', $migrationInfo['main_details'])) {
1567 $submitted['contact_sub_type'] = array_unique(array_merge($main_sub_types, $other_sub_types));
1568 }
1569 else {
1570 $submitted['contact_sub_type'] = $other_sub_types;
1571 }
1572 }
1573
1574 // **** Update contact related info for the main contact
1575 if (!empty($submitted)) {
1576 $submitted['contact_id'] = $mainId;
1577
1578 //update current employer field
1579 if ($currentEmloyerId = CRM_Utils_Array::value('current_employer_id', $submitted)) {
1580 if (!CRM_Utils_System::isNull($currentEmloyerId)) {
1581 $submitted['current_employer'] = $submitted['current_employer_id'];
1582 }
1583 else {
1584 $submitted['current_employer'] = '';
1585 }
1586 unset($submitted['current_employer_id']);
1587 }
1588
1589 //CRM-14312 include prefix/suffix from mainId if not overridden for proper construction of display/sort name
1590 if (!isset($submitted['prefix_id']) && !empty($migrationInfo['main_details']['prefix_id'])) {
1591 $submitted['prefix_id'] = $migrationInfo['main_details']['prefix_id'];
1592 }
1593 if (!isset($submitted['suffix_id']) && !empty($migrationInfo['main_details']['suffix_id'])) {
1594 $submitted['suffix_id'] = $migrationInfo['main_details']['suffix_id'];
1595 }
1596 $null = [];
1597 CRM_Contact_BAO_Contact::createProfileContact($submitted, $null, $mainId);
1598 }
1599 $transaction->commit();
1600 CRM_Utils_Hook::post('merge', 'Contact', $mainId);
1601 self::createMergeActivities($mainId, $otherId);
1602
1603 return TRUE;
1604 }
1605
1606 /**
1607 * Builds an Array of Custom tables for given custom field ID's.
1608 *
1609 * @param $customFieldIDs
1610 *
1611 * @return array
1612 * Array of custom table names
1613 */
1614 private static function getAffectedCustomTables($customFieldIDs) {
1615 $customTableToCopyValues = [];
1616
1617 foreach ($customFieldIDs as $fieldID) {
1618 if (!empty($fieldID)) {
1619 $customField = civicrm_api3('custom_field', 'getsingle', [
1620 'id' => $fieldID,
1621 'is_active' => TRUE,
1622 ]);
1623 if (!civicrm_error($customField) && !empty($customField['custom_group_id'])) {
1624 $customGroup = civicrm_api3('custom_group', 'getsingle', [
1625 'id' => $customField['custom_group_id'],
1626 'is_active' => TRUE,
1627 ]);
1628
1629 if (!civicrm_error($customGroup) && !empty($customGroup['table_name'])) {
1630 $customTableToCopyValues[] = $customGroup['table_name'];
1631 }
1632 }
1633 }
1634 }
1635
1636 return $customTableToCopyValues;
1637 }
1638
1639 /**
1640 * Get fields in the contact table suitable for merging.
1641 *
1642 * @return array
1643 * Array of field names to be potentially merged.
1644 */
1645 public static function getContactFields() {
1646 $contactFields = CRM_Contact_DAO_Contact::fields();
1647 $invalidFields = [
1648 'api_key',
1649 'created_date',
1650 'display_name',
1651 'hash',
1652 'id',
1653 'modified_date',
1654 'primary_contact_id',
1655 'sort_name',
1656 'user_unique_id',
1657 ];
1658 foreach ($contactFields as $field => $value) {
1659 if (in_array($field, $invalidFields)) {
1660 unset($contactFields[$field]);
1661 }
1662 }
1663 return array_keys($contactFields);
1664 }
1665
1666 /**
1667 * Added for CRM-12695
1668 * Based on the contactID provided
1669 * add/update membership(s) to related contacts
1670 *
1671 * @param int $contactID
1672 */
1673 public static function addMembershipToRealtedContacts($contactID) {
1674 $dao = new CRM_Member_DAO_Membership();
1675 $dao->contact_id = $contactID;
1676 $dao->is_test = 0;
1677 $dao->find();
1678
1679 //checks membership of contact itself
1680 while ($dao->fetch()) {
1681 $relationshipTypeId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipType', $dao->membership_type_id, 'relationship_type_id', 'id');
1682 if ($relationshipTypeId) {
1683 $membershipParams = [
1684 'id' => $dao->id,
1685 'contact_id' => $dao->contact_id,
1686 'membership_type_id' => $dao->membership_type_id,
1687 'join_date' => CRM_Utils_Date::isoToMysql($dao->join_date),
1688 'start_date' => CRM_Utils_Date::isoToMysql($dao->start_date),
1689 'end_date' => CRM_Utils_Date::isoToMysql($dao->end_date),
1690 'source' => $dao->source,
1691 'status_id' => $dao->status_id,
1692 ];
1693 // create/update membership(s) for related contact(s)
1694 CRM_Member_BAO_Membership::createRelatedMemberships($membershipParams, $dao);
1695 } // end of if relationshipTypeId
1696 }
1697 }
1698
1699 /**
1700 * Create activities tracking the merge on affected contacts.
1701 *
1702 * @param int $mainId
1703 * @param int $otherId
1704 *
1705 * @throws \CiviCRM_API3_Exception
1706 */
1707 public static function createMergeActivities($mainId, $otherId) {
1708 $params = [
1709 1 => $otherId,
1710 2 => $mainId,
1711 ];
1712 $activity = civicrm_api3('activity', 'create', [
1713 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() :
1714 $mainId,
1715 'subject' => ts('Contact ID %1 has been merged and deleted.', $params),
1716 'target_contact_id' => $mainId,
1717 'activity_type_id' => 'Contact Merged',
1718 'status_id' => 'Completed',
1719 ]);
1720 if (civicrm_api3('Setting', 'getvalue', [
1721 'name' => 'contact_undelete',
1722 'group' => 'CiviCRM Preferences',
1723 ])) {
1724 civicrm_api3('activity', 'create', [
1725 'source_contact_id' => CRM_Core_Session::getLoggedInContactID() ? CRM_Core_Session::getLoggedInContactID() :
1726 $otherId,
1727 'subject' => ts('Contact ID %1 has been merged into Contact ID %2 and deleted.', $params),
1728 'target_contact_id' => $otherId,
1729 'activity_type_id' => 'Contact Deleted by Merge',
1730 'parent_id' => $activity['id'],
1731 'status_id' => 'Completed',
1732 ]);
1733 }
1734 }
1735
1736 /**
1737 * Get Duplicate Pairs based on a rule for a group.
1738 *
1739 * @param int $rule_group_id
1740 * @param int $group_id
1741 * @param bool $reloadCacheIfEmpty
1742 * Should the cache be reloaded if empty - this must be false when in a dedupe action!
1743 * @param int $batchLimit
1744 * @param bool $isSelected
1745 * Limit to selected pairs.
1746 * @param bool $includeConflicts
1747 * @param array $criteria
1748 * Additional criteria to narrow down the merge group.
1749 *
1750 * @param bool $checkPermissions
1751 * Respect logged in user permissions.
1752 *
1753 * @param int $searchLimit
1754 * Limit to searching for matches against this many contacts.
1755 *
1756 * @param int $isForceNewSearch
1757 * Should a new search be forced, bypassing any cache retrieval.
1758 *
1759 * @return array
1760 * Array of matches meeting the criteria.
1761 *
1762 * @throws \CRM_Core_Exception
1763 * @throws \CiviCRM_API3_Exception
1764 */
1765 public static function getDuplicatePairs($rule_group_id, $group_id, $reloadCacheIfEmpty, $batchLimit, $isSelected, $includeConflicts = TRUE, $criteria = [], $checkPermissions = TRUE, $searchLimit = 0, $isForceNewSearch = 0) {
1766 $dupePairs = $isForceNewSearch ? [] : self::getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, $includeConflicts, $criteria, $checkPermissions, $searchLimit);
1767 if (empty($dupePairs) && $reloadCacheIfEmpty) {
1768 // If we haven't found any dupes, probably cache is empty.
1769 // Try filling cache and give another try. We don't need to specify include conflicts here are there will not be any
1770 // until we have done some processing.
1771 CRM_Core_BAO_PrevNextCache::refillCache($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit);
1772 return self::getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, FALSE, $criteria, $checkPermissions, $searchLimit);
1773 }
1774 return $dupePairs;
1775 }
1776
1777 /**
1778 * Get the cache key string for the merge action.
1779 *
1780 * @param int $rule_group_id
1781 * @param int $group_id
1782 * @param array $criteria
1783 * Additional criteria to narrow down the merge group.
1784 * Currently we are only supporting the key 'contact' within it.
1785 * @param bool $checkPermissions
1786 * Respect the users permissions.
1787 * @param int $searchLimit
1788 * Number of contacts to seek dupes for (we need this because if
1789 * we change it the results won't be refreshed otherwise. Changing the limit
1790 * from 100 to 1000 SHOULD result in a new dedupe search).
1791 *
1792 * @return string
1793 */
1794 public static function getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit) {
1795 $contactType = CRM_Dedupe_BAO_RuleGroup::getContactTypeForRuleGroup($rule_group_id);
1796 $cacheKeyString = "merge_{$contactType}";
1797 $cacheKeyString .= $rule_group_id ? "_{$rule_group_id}" : '_0';
1798 $cacheKeyString .= $group_id ? "_{$group_id}" : '_0';
1799 $cacheKeyString .= '_' . (int) $searchLimit;
1800 $cacheKeyString .= !empty($criteria) ? md5(serialize($criteria)) : '_0';
1801 if ($checkPermissions) {
1802 $contactID = CRM_Core_Session::getLoggedInContactID();
1803 if (!$contactID) {
1804 // Distinguish between no permission check & no logged in user.
1805 $contactID = 'null';
1806 }
1807 $cacheKeyString .= '_' . $contactID;
1808 }
1809 else {
1810 $cacheKeyString .= '_0';
1811 }
1812 return $cacheKeyString;
1813 }
1814
1815 /**
1816 * Get the metadata for the merge fields.
1817 *
1818 * This is basically the contact metadata, augmented with fields to
1819 * represent email greeting, postal greeting & addressee.
1820 *
1821 * @return array
1822 */
1823 public static function getMergeFieldsMetadata() {
1824 if (isset(\Civi::$statics[__CLASS__]) && isset(\Civi::$statics[__CLASS__]['merge_fields_metadata'])) {
1825 return \Civi::$statics[__CLASS__]['merge_fields_metadata'];
1826 }
1827 $fields = CRM_Contact_DAO_Contact::fields();
1828 static $optionValueFields = [];
1829 if (empty($optionValueFields)) {
1830 $optionValueFields = CRM_Core_OptionValue::getFields();
1831 }
1832 foreach ($optionValueFields as $field => $params) {
1833 $fields[$field]['title'] = $params['title'];
1834 }
1835 \Civi::$statics[__CLASS__]['merge_fields_metadata'] = $fields;
1836 return \Civi::$statics[__CLASS__]['merge_fields_metadata'];
1837 }
1838
1839 /**
1840 * Get the details of the contact to be merged.
1841 *
1842 * @param int $contact_id
1843 *
1844 * @return array
1845 *
1846 * @throws CRM_Core_Exception
1847 */
1848 public static function getMergeContactDetails($contact_id) {
1849 $params = [
1850 'contact_id' => $contact_id,
1851 'version' => 3,
1852 'return' => array_merge(['display_name'], self::getContactFields()),
1853 ];
1854 $result = civicrm_api('contact', 'get', $params);
1855
1856 // CRM-18480: Cancel the process if the contact is already deleted
1857 if (isset($result['values'][$contact_id]['contact_is_deleted']) && !empty($result['values'][$contact_id]['contact_is_deleted'])) {
1858 throw new CRM_Core_Exception(ts('Cannot merge because one contact (ID %1) has been deleted.', [
1859 1 => $contact_id,
1860 ]));
1861 }
1862
1863 return $result['values'][$contact_id];
1864 }
1865
1866 /**
1867 * Merge location.
1868 *
1869 * Based on the data in the $locationMigrationInfo merge the locations for 2 contacts.
1870 *
1871 * The data is in the format received from the merge form (which is a fairly confusing format).
1872 *
1873 * It is converted into an array of DAOs which is passed to the alterLocationMergeData hook
1874 * before saving or deleting the DAOs. A new hook is added to allow these to be altered after they have
1875 * been calculated and before saving because
1876 * - the existing format & hook combo is so confusing it is hard for developers to change & inherently fragile
1877 * - passing to a hook right before save means calculations only have to be done once
1878 * - the existing pattern of passing dissimilar data to the same (merge) hook with a different 'type' is just
1879 * ugly.
1880 *
1881 * The use of the new hook is tested, including the fact it is called before contributions are merged, as this
1882 * is likely to be significant data in merge hooks.
1883 *
1884 * @param int $mainId
1885 * @param int $otherId
1886 *
1887 * @param array $migrationInfo
1888 * Migration info for the merge. This is passed to the hook as informational only.
1889 */
1890 public static function mergeLocations($mainId, $otherId, $migrationInfo) {
1891 foreach ($migrationInfo as $key => $value) {
1892 $isLocationField = (substr($key, 0, 14) == 'move_location_' and $value != NULL);
1893 if (!$isLocationField) {
1894 continue;
1895 }
1896 $locField = explode('_', $key);
1897 $fieldName = $locField[2];
1898 $fieldCount = $locField[3];
1899
1900 // Set up the operation type (add/overwrite)
1901 // Ignore operation for websites
1902 // @todo Tidy this up
1903 $operation = 0;
1904 if ($fieldName != 'website') {
1905 $operation = CRM_Utils_Array::value('operation', $migrationInfo['location_blocks'][$fieldName][$fieldCount]);
1906 }
1907 // default operation is overwrite.
1908 if (!$operation) {
1909 $operation = 2;
1910 }
1911 $locBlocks[$fieldName][$fieldCount]['operation'] = $operation;
1912 }
1913 $blocksDAO = [];
1914
1915 // @todo Handle OpenID (not currently in API).
1916 if (!empty($locBlocks)) {
1917 $locationBlocks = self::getLocationBlockInfo();
1918
1919 $primaryBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, ['is_primary' => 1]);
1920 $billingBlockIds = CRM_Contact_BAO_Contact::getLocBlockIds($mainId, ['is_billing' => 1]);
1921
1922 foreach ($locBlocks as $name => $block) {
1923 $blocksDAO[$name] = ['delete' => [], 'update' => []];
1924 if (!is_array($block) || CRM_Utils_System::isNull($block)) {
1925 continue;
1926 }
1927 $daoName = 'CRM_Core_DAO_' . $locationBlocks[$name]['label'];
1928 $changePrimary = FALSE;
1929 $primaryDAOId = (array_key_exists($name, $primaryBlockIds)) ? array_pop($primaryBlockIds[$name]) : NULL;
1930 $billingDAOId = (array_key_exists($name, $billingBlockIds)) ? array_pop($billingBlockIds[$name]) : NULL;
1931
1932 foreach ($block as $blkCount => $values) {
1933 $otherBlockId = CRM_Utils_Array::value('id', $migrationInfo['other_details']['location_blocks'][$name][$blkCount]);
1934 $mainBlockId = CRM_Utils_Array::value('mainContactBlockId', $migrationInfo['location_blocks'][$name][$blkCount], 0);
1935 if (!$otherBlockId) {
1936 continue;
1937 }
1938
1939 // For the block which belongs to other-contact, link the location block to main-contact
1940 $otherBlockDAO = new $daoName();
1941 $otherBlockDAO->contact_id = $mainId;
1942
1943 // Get the ID of this block on the 'other' contact, otherwise skip
1944 $otherBlockDAO->id = $otherBlockId;
1945
1946 // Add/update location and type information from the form, if applicable
1947 if ($locationBlocks[$name]['hasLocation']) {
1948 $locTypeId = CRM_Utils_Array::value('locTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
1949 $otherBlockDAO->location_type_id = $locTypeId;
1950 }
1951 if ($locationBlocks[$name]['hasType']) {
1952 $typeTypeId = CRM_Utils_Array::value('typeTypeId', $migrationInfo['location_blocks'][$name][$blkCount]);
1953 $otherBlockDAO->{$locationBlocks[$name]['hasType']} = $typeTypeId;
1954 }
1955
1956 // If we're deliberately setting this as primary then add the flag
1957 // and remove it from the current primary location (if there is one).
1958 // But only once for each entity.
1959 $set_primary = CRM_Utils_Array::value('set_other_primary', $migrationInfo['location_blocks'][$name][$blkCount]);
1960 if (!$changePrimary && $set_primary == "1") {
1961 $otherBlockDAO->is_primary = 1;
1962 if ($primaryDAOId) {
1963 $removePrimaryDAO = new $daoName();
1964 $removePrimaryDAO->id = $primaryDAOId;
1965 $removePrimaryDAO->is_primary = 0;
1966 $blocksDAO[$name]['update'][$primaryDAOId] = $removePrimaryDAO;
1967 }
1968 $changePrimary = TRUE;
1969 }
1970 // Otherwise, if main contact already has primary, set it to 0.
1971 elseif ($primaryDAOId) {
1972 $otherBlockDAO->is_primary = 0;
1973 }
1974
1975 // If the main contact already has a billing location, set this to 0.
1976 if ($billingDAOId) {
1977 $otherBlockDAO->is_billing = 0;
1978 }
1979
1980 $operation = CRM_Utils_Array::value('operation', $values, 2);
1981 // overwrite - need to delete block which belongs to main-contact.
1982 if (!empty($mainBlockId) && ($operation == 2)) {
1983 $deleteDAO = new $daoName();
1984 $deleteDAO->id = $mainBlockId;
1985 $deleteDAO->find(TRUE);
1986
1987 // if we about to delete a primary / billing block, set the flags for new block
1988 // that we going to assign to main-contact
1989 if ($primaryDAOId && ($primaryDAOId == $deleteDAO->id)) {
1990 $otherBlockDAO->is_primary = 1;
1991 }
1992 if ($billingDAOId && ($billingDAOId == $deleteDAO->id)) {
1993 $otherBlockDAO->is_billing = 1;
1994 }
1995 $blocksDAO[$name]['delete'][$deleteDAO->id] = $deleteDAO;
1996 }
1997 $blocksDAO[$name]['update'][$otherBlockDAO->id] = $otherBlockDAO;
1998 }
1999 }
2000 }
2001
2002 CRM_Utils_Hook::alterLocationMergeData($blocksDAO, $mainId, $otherId, $migrationInfo);
2003 foreach ($blocksDAO as $blockDAOs) {
2004 if (!empty($blockDAOs['update'])) {
2005 foreach ($blockDAOs['update'] as $blockDAO) {
2006 $blockDAO->save();
2007 }
2008 }
2009 if (!empty($blockDAOs['delete'])) {
2010 foreach ($blockDAOs['delete'] as $blockDAO) {
2011 $blockDAO->delete();
2012 }
2013 }
2014 }
2015 }
2016
2017 /**
2018 * Dedupe a pair of contacts.
2019 *
2020 * @param array $dupes
2021 * @param string $mode
2022 * @param bool $checkPermissions
2023 * @param string $cacheKeyString
2024 *
2025 * @return bool|array
2026 * @throws \CRM_Core_Exception
2027 * @throws \CiviCRM_API3_Exception
2028 * @throws \API_Exception
2029 */
2030 protected static function dedupePair($dupes, $mode = 'safe', $checkPermissions = TRUE, $cacheKeyString = NULL) {
2031 CRM_Utils_Hook::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']);
2032 $mainId = $dupes['dstID'];
2033 $otherId = $dupes['srcID'];
2034 $resultStats = [];
2035
2036 if (!$mainId || !$otherId) {
2037 // return error
2038 return FALSE;
2039 }
2040 $migrationInfo = [];
2041 $conflicts = [];
2042 if (!CRM_Dedupe_Merger::skipMerge($mainId, $otherId, $migrationInfo, $mode, $conflicts)) {
2043 CRM_Dedupe_Merger::moveAllBelongings($mainId, $otherId, $migrationInfo, $checkPermissions);
2044 $resultStats['merged'][] = [
2045 'main_id' => $mainId,
2046 'other_id' => $otherId,
2047 ];
2048 }
2049 else {
2050 $resultStats['skipped'][] = [
2051 'main_id' => $mainId,
2052 'other_id' => $otherId,
2053 ];
2054 }
2055
2056 // store any conflicts
2057 if (!empty($conflicts)) {
2058 CRM_Core_BAO_PrevNextCache::markConflict($mainId, $otherId, $cacheKeyString, $conflicts, $mode);
2059 }
2060 else {
2061 CRM_Core_BAO_PrevNextCache::deletePair($mainId, $otherId, $cacheKeyString);
2062 }
2063 return $resultStats;
2064 }
2065
2066 /**
2067 * Replace the pseudo QFKey with zero if it is present.
2068 *
2069 * @todo - on the slim chance this is still relevant it should be moved to the form layer.
2070 *
2071 * Details about this bug are somewhat obscured by the move from svn but perhaps JIRA
2072 * can still help.
2073 *
2074 * @param array $migrationInfo
2075 */
2076 protected static function swapOutFieldsAffectedByQFZeroBug(&$migrationInfo) {
2077 $qfZeroBug = 'e8cddb72-a257-11dc-b9cc-0016d3330ee9';
2078 foreach ($migrationInfo as $key => &$value) {
2079 if ($value == $qfZeroBug) {
2080 $value = '0';
2081 }
2082 }
2083 }
2084
2085 /**
2086 * Honestly - what DOES this do - hopefully some refactoring will reveal it's purpose.
2087 *
2088 * Update this function formats fields in preparation for them to be submitted to the
2089 * 'ProfileContactCreate action. This is a lot of code to do this & for
2090 * - for some fields it fails - e.g Country - per testMergeCustomFields.
2091 *
2092 * Goal is to move all custom field handling into 'move' functions on the various BAO
2093 * with an underlying DAO function. For custom fields it has been started on the BAO.
2094 *
2095 * @param $mainId
2096 * @param $key
2097 * @param $cFields
2098 * @param $submitted
2099 * @param $value
2100 *
2101 * @return array
2102 * @throws \Exception
2103 */
2104 protected static function processCustomFields($mainId, $key, $cFields, $submitted, $value) {
2105 if (substr($key, 0, 7) == 'custom_') {
2106 $fid = (int) substr($key, 7);
2107 if (empty($cFields[$fid])) {
2108 return [$cFields, $submitted];
2109 }
2110 $htmlType = $cFields[$fid]['attributes']['html_type'];
2111 switch ($htmlType) {
2112 case 'File':
2113 // Handled in CustomField->move(). Tested in testMergeCustomFields.
2114 unset($submitted["custom_$fid"]);
2115 break;
2116
2117 case 'Select Country':
2118 // @todo Test in testMergeCustomFields disabled as this does not work, Handle in CustomField->move().
2119 case 'Select State/Province':
2120 $submitted[$key] = CRM_Core_BAO_CustomField::displayValue($value, $fid);
2121 break;
2122
2123 case 'Select Date':
2124 if ($cFields[$fid]['attributes']['is_view']) {
2125 $submitted[$key] = date('YmdHis', strtotime($submitted[$key]));
2126 }
2127 break;
2128
2129 case 'CheckBox':
2130 case 'Multi-Select':
2131 case 'Multi-Select Country':
2132 case 'Multi-Select State/Province':
2133 // Merge values from both contacts for multivalue fields, CRM-4385
2134 // get the existing custom values from db.
2135 $customParams = ['entityID' => $mainId, $key => TRUE];
2136 $customfieldValues = CRM_Core_BAO_CustomValueTable::getValues($customParams);
2137 if (!empty($customfieldValues[$key])) {
2138 $existingValue = explode(CRM_Core_DAO::VALUE_SEPARATOR, $customfieldValues[$key]);
2139 if (is_array($existingValue) && !empty($existingValue)) {
2140 $mergeValue = $submittedCustomFields = [];
2141 if ($value == 'null') {
2142 // CRM-19074 if someone has deliberately chosen to overwrite with 'null', respect it.
2143 $submitted[$key] = $value;
2144 }
2145 else {
2146 if ($value) {
2147 $submittedCustomFields = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
2148 }
2149
2150 // CRM-19653: overwrite or add the existing custom field value with dupicate contact's
2151 // custom field value stored at $submittedCustomValue.
2152 foreach ($submittedCustomFields as $k => $v) {
2153 if ($v != '' && !in_array($v, $mergeValue)) {
2154 $mergeValue[] = $v;
2155 }
2156 }
2157
2158 //keep state and country as array format.
2159 //for checkbox and m-select format w/ VALUE_SEPARATOR
2160 if (in_array($htmlType, [
2161 'CheckBox',
2162 'Multi-Select',
2163 ])) {
2164 $submitted[$key] = CRM_Core_DAO::VALUE_SEPARATOR . implode(CRM_Core_DAO::VALUE_SEPARATOR,
2165 $mergeValue
2166 ) . CRM_Core_DAO::VALUE_SEPARATOR;
2167 }
2168 else {
2169 $submitted[$key] = $mergeValue;
2170 }
2171 }
2172 }
2173 }
2174 elseif (in_array($htmlType, [
2175 'Multi-Select Country',
2176 'Multi-Select State/Province',
2177 ])) {
2178 //we require submitted values should be in array format
2179 if ($value) {
2180 $mergeValueArray = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
2181 //hack to remove null values from array.
2182 $mergeValue = [];
2183 foreach ($mergeValueArray as $k => $v) {
2184 if ($v != '') {
2185 $mergeValue[] = $v;
2186 }
2187 }
2188 $submitted[$key] = $mergeValue;
2189 }
2190 }
2191 break;
2192
2193 default:
2194 break;
2195 }
2196 }
2197 return [$cFields, $submitted];
2198 }
2199
2200 /**
2201 * Get metadata for the custom fields for the merge.
2202 *
2203 * @param string $contactType
2204 *
2205 * @return array
2206 */
2207 protected static function getCustomFieldMetadata($contactType) {
2208 $treeCache = [];
2209 if (!array_key_exists($contactType, $treeCache)) {
2210 $treeCache[$contactType] = CRM_Core_BAO_CustomGroup::getTree(
2211 $contactType,
2212 NULL,
2213 NULL,
2214 -1,
2215 [],
2216 NULL,
2217 TRUE,
2218 NULL,
2219 FALSE,
2220 FALSE
2221 );
2222 }
2223
2224 $cFields = [];
2225 foreach ($treeCache[$contactType] as $key => $group) {
2226 if (!isset($group['fields'])) {
2227 continue;
2228 }
2229 foreach ($group['fields'] as $fid => $field) {
2230 $cFields[$fid]['attributes'] = $field;
2231 }
2232 }
2233 return $cFields;
2234 }
2235
2236 /**
2237 * Get conflicts for proposed merge pair.
2238 *
2239 * @param array $migrationInfo
2240 * This is primarily to inform hooks. The can also modify it which feels
2241 * pretty fragile to do it here - but it is historical.
2242 * @param int $mainId
2243 * Main contact with whom merge has to happen.
2244 * @param int $otherId
2245 * Duplicate contact which would be deleted after merge operation.
2246 * @param string $mode
2247 * Helps decide how to behave when there are conflicts.
2248 * - A 'safe' value skips the merge if there are any un-resolved conflicts.
2249 * - Does a force merge otherwise (aggressive mode).
2250 *
2251 * @return array
2252 *
2253 * @throws \CRM_Core_Exception
2254 * @throws \CiviCRM_API3_Exception
2255 */
2256 public static function getConflicts(&$migrationInfo, $mainId, $otherId, $mode) {
2257 $conflicts = [];
2258 // Generate var $migrationInfo. The variable structure is exactly same as
2259 // $formValues submitted during a UI merge for a pair of contacts.
2260 $rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($mainId, $otherId, FALSE);
2261 // add additional details that we might need to resolve conflicts
2262 $migrationInfo = $rowsElementsAndInfo['migration_info'];
2263 $migrationInfo['main_details'] = &$rowsElementsAndInfo['main_details'];
2264 $migrationInfo['other_details'] = &$rowsElementsAndInfo['other_details'];
2265 $migrationInfo['rows'] = &$rowsElementsAndInfo['rows'];
2266 // go ahead with merge if there is no conflict
2267 $originalMigrationInfo = $migrationInfo;
2268 foreach ($migrationInfo as $key => $val) {
2269 if ($val === "null") {
2270 // Rule: Never overwrite with an empty value (in any mode)
2271 unset($migrationInfo[$key]);
2272 continue;
2273 }
2274 elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) or
2275 substr($key, 0, 12) == 'move_custom_'
2276 ) and $val != NULL
2277 ) {
2278 // Rule: If both main-contact, and other-contact have a field with a
2279 // different value, then let $mode decide if to merge it or not
2280 if (
2281 (!empty($migrationInfo['rows'][$key]['main'])
2282 // For custom fields a 0 (e.g in an int field) could be a true conflict. This
2283 // is probably true for other fields too - e.g. 'do_not_email' but
2284 // leaving that investigation as a @todo - until tests can be written.
2285 // Note the handling of this has test coverage - although the data-typing
2286 // of '0' feels flakey we have insurance.
2287 || ($migrationInfo['rows'][$key]['main'] === '0' && substr($key, 0, 12) == 'move_custom_')
2288 )
2289 && $migrationInfo['rows'][$key]['main'] != $migrationInfo['rows'][$key]['other']
2290 ) {
2291
2292 // note it down & lets wait for response from the hook.
2293 // For no response $mode will decide if to skip this merge
2294 $conflicts[$key] = NULL;
2295 }
2296 }
2297 elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
2298 $locField = explode('_', $key);
2299 $fieldName = $locField[2];
2300 $fieldCount = $locField[3];
2301
2302 // Rule: Catch address conflicts (same address type on both contacts)
2303 if (
2304 isset($migrationInfo['main_details']['location_blocks'][$fieldName]) &&
2305 !empty($migrationInfo['main_details']['location_blocks'][$fieldName])
2306 ) {
2307
2308 // Load the address we're inspecting from the 'other' contact
2309 $addressRecord = $migrationInfo['other_details']['location_blocks'][$fieldName][$fieldCount];
2310 $addressRecordLocTypeId = CRM_Utils_Array::value('location_type_id', $addressRecord);
2311
2312 // If it exists on the 'main' contact already, skip it. Otherwise
2313 // if the location type exists already, log a conflict.
2314 foreach ($migrationInfo['main_details']['location_blocks'][$fieldName] as $mainAddressKey => $mainAddressRecord) {
2315 if (self::locationIsSame($addressRecord, $mainAddressRecord)) {
2316 unset($migrationInfo[$key]);
2317 break;
2318 }
2319 elseif ($addressRecordLocTypeId == $mainAddressRecord['location_type_id']) {
2320 $conflicts[$key] = NULL;
2321 break;
2322 }
2323 }
2324 }
2325
2326 // For other locations, don't merge/add if the values are the same
2327 elseif (CRM_Utils_Array::value('main', $migrationInfo['rows'][$key]) == $migrationInfo['rows'][$key]['other']) {
2328 unset($migrationInfo[$key]);
2329 }
2330 }
2331 }
2332
2333 // A hook to implement other algorithms for choosing which contact to bias to when
2334 // there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
2335 // merge happens with new values filled in here. For a particular field / row not to be merged
2336 // field should be unset from fields_in_conflict.
2337 $migrationData = [
2338 'old_migration_info' => $originalMigrationInfo,
2339 'mode' => $mode,
2340 'fields_in_conflict' => $conflicts,
2341 'merge_mode' => $mode,
2342 'migration_info' => $migrationInfo,
2343 ];
2344 CRM_Utils_Hook::merge('batch', $migrationData, $mainId, $otherId);
2345 $conflicts = $migrationData['fields_in_conflict'];
2346 // allow hook to override / manipulate migrationInfo as well
2347 $migrationInfo = $migrationData['migration_info'];
2348 foreach ($conflicts as $key => $val) {
2349 if ($val !== NULL || $mode !== 'safe') {
2350 // copy over the resolved values
2351 $migrationInfo[$key] = $val;
2352 unset($conflicts[$key]);
2353 }
2354 }
2355 return self::formatConflictArray($conflicts, $migrationInfo['rows'], $migrationInfo['main_details']['location_blocks'], $migrationInfo['other_details']['location_blocks'], $mainId, $otherId);
2356 }
2357
2358 /**
2359 * @param array $conflicts
2360 * @param array $migrationInfo
2361 * @param $toKeepContactLocationBlocks
2362 * @param $toRemoveContactLocationBlocks
2363 * @param $toKeepID
2364 * @param $toRemoveID
2365 *
2366 * @return mixed
2367 * @throws \CRM_Core_Exception
2368 */
2369 protected static function formatConflictArray($conflicts, $migrationInfo, $toKeepContactLocationBlocks, $toRemoveContactLocationBlocks, $toKeepID, $toRemoveID) {
2370 $return = [];
2371 foreach (array_keys($conflicts) as $index) {
2372 if (substr($index, 0, 14) === 'move_location_') {
2373 $parts = explode('_', $index);
2374 $entity = $parts[2];
2375 $blockIndex = $parts[3];
2376 $locationTypeID = $toKeepContactLocationBlocks[$entity][$blockIndex]['location_type_id'];
2377 $entityConflicts = [
2378 'location_type_id' => $locationTypeID,
2379 'title' => $migrationInfo[$index]['title'],
2380 ];
2381 foreach ($toKeepContactLocationBlocks[$entity][$blockIndex] as $fieldName => $fieldValue) {
2382 if (in_array($fieldName, self::ignoredFields())) {
2383 continue;
2384 }
2385 $toRemoveValue = CRM_Utils_Array::value($fieldName, $toRemoveContactLocationBlocks[$entity][$blockIndex]);
2386 if ($fieldValue !== $toRemoveValue) {
2387 $entityConflicts[$fieldName] = [
2388 $toKeepID => $fieldValue,
2389 $toRemoveID => $toRemoveValue,
2390 ];
2391 }
2392 }
2393 $return[$entity][] = $entityConflicts;
2394 }
2395 elseif (substr($index, 0, 5) === 'move_') {
2396 $contactFieldsToCompare[] = str_replace('move_', '', $index);
2397 $return['contact'][str_replace('move_', '', $index)] = [
2398 'title' => $migrationInfo[$index]['title'],
2399 $toKeepID => $migrationInfo[$index]['main'],
2400 $toRemoveID => $migrationInfo[$index]['other'],
2401 ];
2402 }
2403 else {
2404 // Can't think of why this would be the case but perhaps it's ensuring it isn't as we
2405 // refactor this.
2406 throw new CRM_Core_Exception(ts('Unknown parameter') . $index);
2407 }
2408 }
2409 return $return;
2410 }
2411
2412 /**
2413 * Get any duplicate merge pairs that have been previously cached.
2414 *
2415 * @param int $rule_group_id
2416 * @param int $group_id
2417 * @param int $batchLimit
2418 * @param bool $isSelected
2419 * @param bool $includeConflicts
2420 * @param array $criteria
2421 * @param int $checkPermissions
2422 * @param int $searchLimit
2423 *
2424 * @return array
2425 */
2426 protected static function getCachedDuplicateMatches($rule_group_id, $group_id, $batchLimit, $isSelected, $includeConflicts, $criteria, $checkPermissions, $searchLimit = 0) {
2427 return CRM_Core_BAO_PrevNextCache::retrieve(
2428 self::getMergeCacheKeyString($rule_group_id, $group_id, $criteria, $checkPermissions, $searchLimit),
2429 self::getJoinOnDedupeTable(),
2430 self::getWhereString($isSelected),
2431 0, $batchLimit,
2432 [], '',
2433 $includeConflicts
2434 );
2435 }
2436
2437 /**
2438 * @return array
2439 */
2440 protected static function ignoredFields(): array {
2441 $keysToIgnore = [
2442 'id',
2443 'is_primary',
2444 'is_billing',
2445 'manual_geo_code',
2446 'contact_id',
2447 'reset_date',
2448 'hold_date',
2449 ];
2450 return $keysToIgnore;
2451 }
2452
2453 /**
2454 * Get the field value & label for the given field.
2455 *
2456 * @param $field
2457 * @param $contact
2458 *
2459 * @return array
2460 * @throws \Exception
2461 */
2462 private static function getFieldValueAndLabel($field, $contact): array {
2463 $fields = self::getMergeFieldsMetadata();
2464 $value = $label = CRM_Utils_Array::value($field, $contact);
2465 $fieldSpec = $fields[$field];
2466 if (!empty($fieldSpec['serialize']) && is_array($value)) {
2467 // In practice this only applies to preferred_communication_method as the sub types are skipped above
2468 // and no others are serialized.
2469 $labels = [];
2470 foreach ($value as $individualValue) {
2471 $labels[] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_BAO_Contact', $field, $individualValue);
2472 }
2473 $label = implode(', ', $labels);
2474 // We serialize this due to historic handling but it's likely that if we just left it as an
2475 // array all would be well & we would have less code.
2476 $value = CRM_Core_DAO::serializeField($value, $fieldSpec['serialize']);
2477 }
2478 elseif (!empty($fieldSpec['type']) && $fieldSpec['type'] == CRM_Utils_Type::T_DATE) {
2479 if ($value) {
2480 $value = str_replace('-', '', $value);
2481 $label = CRM_Utils_Date::customFormat($label);
2482 }
2483 else {
2484 $value = "null";
2485 }
2486 }
2487 elseif (!empty($fields[$field]['type']) && $fields[$field]['type'] == CRM_Utils_Type::T_BOOLEAN) {
2488 if ($label === '0') {
2489 $label = ts('[ ]');
2490 }
2491 if ($label === '1') {
2492 $label = ts('[x]');
2493 }
2494 }
2495 elseif (!empty($fieldSpec['pseudoconstant'])) {
2496 $label = CRM_Core_PseudoConstant::getLabel('CRM_Contact_BAO_Contact', $field, $value);
2497 }
2498 elseif ($field == 'current_employer_id' && !empty($value)) {
2499 $label = "$value (" . CRM_Contact_BAO_Contact::displayName($value) . ")";
2500 }
2501 return ['label' => $label, 'value' => $value];
2502 }
2503
2504 /**
2505 * Build up the location block for the contact in dedupe-screen display format.
2506 *
2507 * @param integer $cid
2508 * @param array $blockInfo
2509 * @param string $blockName
2510 *
2511 * @return array
2512 *
2513 * @throws \CiviCRM_API3_Exception
2514 */
2515 private static function buildLocationBlockForContact($cid, $blockInfo, $blockName): array {
2516 $searchParams = [
2517 'contact_id' => $cid,
2518 // CRM-17556 Order by field-specific criteria
2519 'options' => [
2520 'sort' => $blockInfo['sortString'],
2521 ],
2522 ];
2523 $locationBlock = [];
2524 $values = civicrm_api3($blockName, 'get', $searchParams);
2525 if ($values['count']) {
2526 $cnt = 0;
2527 foreach ($values['values'] as $value) {
2528 $locationBlock[$cnt] = $value;
2529 // Fix address display
2530 if ($blockName == 'address') {
2531 // For performance avoid geocoding while merging https://issues.civicrm.org/jira/browse/CRM-21786
2532 // we can expect existing geocode values to be retained.
2533 $value['skip_geocode'] = TRUE;
2534 CRM_Core_BAO_Address::fixAddress($value);
2535 unset($value['skip_geocode']);
2536 $locationBlock[$cnt]['display'] = CRM_Utils_Address::format($value);
2537 }
2538 // Fix email display
2539 elseif ($blockName == 'email') {
2540 $locationBlock[$cnt]['display'] = CRM_Utils_Mail::format($value);
2541 }
2542
2543 $cnt++;
2544 }
2545 }
2546 return $locationBlock;
2547 }
2548
2549 }