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