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