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