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