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