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