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