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