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