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