-
-
Notifications
You must be signed in to change notification settings - Fork 825
/
Copy pathMerger.php
3105 lines (2860 loc) · 114 KB
/
Merger.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC. All rights reserved. |
| |
| This work is published under the GNU AGPLv3 license with some |
| permitted exceptions and without any warranty. For full license |
| and copyright information, see https://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
use Civi\Api4\CustomGroup;
/**
*
* @package CRM
* @copyright CiviCRM LLC https://civicrm.org/licensing
*/
class CRM_Dedupe_Merger {
/**
* FIXME: consider creating a common structure with cidRefs() and eidRefs()
* FIXME: the sub-pages references by the URLs should
* be loaded dynamically on the merge form instead
*
* @return array
* @throws \CRM_Core_Exception
*/
public static function relTables() {
if (!isset(Civi::$statics[__CLASS__]['relTables'])) {
// Setting these merely prevents enotices - but it may be more appropriate not to add the user table below
// if the url can't be retrieved. A more standardised way to retrieve them is.
// CRM_Core_Config::singleton()->userSystem->getUserRecordUrl() - however that function takes a contact_id &
// we may need a different function when it is not known.
$title = $userRecordUrl = '';
$config = CRM_Core_Config::singleton();
// @todo - this user url stuff is only needed for the form layer - move to CRM_Contact_Form_Merge
if ($config->userSystem->is_drupal) {
$userRecordUrl = CRM_Utils_System::url('user/%ufid');
$title = ts('%1 User: %2; user id: %3', [
1 => $config->userFramework,
2 => '$ufname',
3 => '$ufid',
]);
}
elseif ($config->userFramework === 'Joomla') {
$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';
$title = ts('%1 User: %2; user id: %3', [
1 => $config->userFramework,
2 => '$ufname',
3 => '$ufid',
]);
}
$relTables = [
'rel_table_contributions' => [
'title' => ts('Contributions'),
'tables' => [
'civicrm_contribution',
'civicrm_contribution_recur',
'civicrm_contribution_soft',
],
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=contribute'),
],
'rel_table_contribution_page' => [
'title' => ts('Contribution Pages'),
'tables' => ['civicrm_contribution_page'],
'url' => CRM_Utils_System::url('civicrm/admin/contribute', 'reset=1&cid=$cid'),
],
'rel_table_memberships' => [
'title' => ts('Memberships'),
'tables' => [
'civicrm_membership',
'civicrm_membership_log',
'civicrm_membership_type',
],
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=member'),
],
'rel_table_participants' => [
'title' => ts('Participants'),
'tables' => ['civicrm_participant'],
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=participant'),
],
'rel_table_events' => [
'title' => ts('Events'),
'tables' => ['civicrm_event'],
'url' => CRM_Utils_System::url('civicrm/event/manage', 'reset=1&cid=$cid'),
],
'rel_table_activities' => [
'title' => ts('Activities'),
'tables' => ['civicrm_activity', 'civicrm_activity_contact'],
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=activity'),
],
'rel_table_relationships' => [
'title' => ts('Relationships'),
'tables' => ['civicrm_relationship'],
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=rel'),
],
'rel_table_custom_groups' => [
'title' => ts('Custom Groups'),
'tables' => ['civicrm_custom_group'],
'url' => CRM_Utils_System::url('civicrm/admin/custom/group'),
],
'rel_table_uf_groups' => [
'title' => ts('Profiles'),
'tables' => ['civicrm_uf_group'],
'url' => CRM_Utils_System::url('civicrm/admin/uf/group', 'reset=1'),
],
'rel_table_groups' => [
'title' => ts('Groups'),
'tables' => ['civicrm_group_contact'],
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=group'),
],
'rel_table_notes' => [
'title' => ts('Notes'),
'tables' => ['civicrm_note'],
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=note'),
],
'rel_table_tags' => [
'title' => ts('Tags'),
'tables' => ['civicrm_entity_tag'],
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=tag'),
],
'rel_table_mailings' => [
'title' => ts('Mailings'),
'tables' => [
'civicrm_mailing',
'civicrm_mailing_event_queue',
'civicrm_mailing_event_subscribe',
],
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=mailing'),
],
'rel_table_cases' => [
'title' => ts('Cases'),
'tables' => ['civicrm_case_contact'],
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=case'),
],
'rel_table_grants' => [
'title' => ts('Grants'),
'tables' => ['civicrm_grant'],
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=grant'),
],
'rel_table_pcp' => [
'title' => ts('PCPs'),
'tables' => ['civicrm_pcp'],
'url' => CRM_Utils_System::url('civicrm/contribute/pcp/manage', 'reset=1'),
],
'rel_table_pledges' => [
'title' => ts('Pledges'),
'tables' => ['civicrm_pledge', 'civicrm_pledge_payment'],
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=pledge'),
],
'rel_table_users' => [
'title' => $title,
'tables' => ['civicrm_uf_match'],
'url' => $userRecordUrl,
],
];
$relTables += self::getMultiValueCustomSets('relTables');
// Allow hook_civicrm_merge() to adjust $relTables
CRM_Utils_Hook::merge('relTables', $relTables);
// Cache the results in a static variable
Civi::$statics[__CLASS__]['relTables'] = $relTables;
}
return Civi::$statics[__CLASS__]['relTables'];
}
/**
* Returns the related tables groups for which a contact has any info entered.
*
* @param int $cid
*
* @return array
* @throws \CRM_Core_Exception
*/
public static function getActiveRelTables($cid) {
$cid = (int) $cid;
$groups = [];
$relTables = self::relTables();
$cidRefs = self::cidRefs();
$eidRefs = self::eidRefs();
foreach ($relTables as $group => $params) {
$sqls = [];
foreach ($params['tables'] as $table) {
if (isset($cidRefs[$table])) {
foreach ($cidRefs[$table] as $field) {
$sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $field = $cid";
}
}
if (isset($eidRefs[$table])) {
foreach ($eidRefs[$table] as $entityTable => $entityId) {
$sqls[] = "SELECT COUNT(*) AS count FROM $table WHERE $entityId = $cid AND $entityTable = 'civicrm_contact'";
}
}
foreach ($sqls as $sql) {
if (CRM_Core_DAO::singleValueQuery($sql) > 0) {
$groups[] = $group;
}
}
}
}
return array_unique($groups);
}
/**
* Get array tables and fields that reference civicrm_contact.id.
*
* This function calls the merge hook and only exists to wrap the DAO function to support that deprecated call.
* The entityTypes hook is the recommended way to add tables to this result.
*
* I thought about adding another hook to alter tableReferences but decided it was unclear if there
* are use cases not covered by entityTables and instead we should wait & see.
*/
public static function cidRefs() {
if (isset(\Civi::$statics[__CLASS__]) && isset(\Civi::$statics[__CLASS__]['contact_references'])) {
return \Civi::$statics[__CLASS__]['contact_references'];
}
$contactReferences = $coreReferences = CRM_Core_DAO::getReferencesToContactTable();
foreach (['civicrm_group_contact_cache', 'civicrm_acl_cache', 'civicrm_acl_contact_cache'] as $tableName) {
// Don't merge cache tables. These should be otherwise cleared at some point in the dedupe
// but they are prone to locking to let's not touch during the dedupe.
unset($contactReferences[$tableName], $coreReferences[$tableName]);
}
CRM_Utils_Hook::merge('cidRefs', $contactReferences);
if ($contactReferences !== $coreReferences) {
CRM_Core_Error::deprecatedWarning("Deprecated hook ::merge in context of 'cidRefs. Use entityTypes instead.");
}
\Civi::$statics[__CLASS__]['contact_references'] = $contactReferences;
return \Civi::$statics[__CLASS__]['contact_references'];
}
/**
* Return tables and their fields referencing civicrm_contact.contact_id with entity_id
*/
public static function eidRefs() {
static $eidRefs;
if (!$eidRefs) {
// FIXME: this should be generated dynamically from the schema
// tables that reference contacts with entity_{id,table}
$eidRefs = [
'civicrm_acl' => ['entity_table' => 'entity_id'],
'civicrm_acl_entity_role' => ['entity_table' => 'entity_id'],
'civicrm_entity_file' => ['entity_table' => 'entity_id'],
'civicrm_log' => ['entity_table' => 'entity_id'],
'civicrm_mailing_group' => ['entity_table' => 'entity_id'],
'civicrm_note' => ['entity_table' => 'entity_id'],
];
// Allow hook_civicrm_merge() to adjust $eidRefs
CRM_Utils_Hook::merge('eidRefs', $eidRefs);
}
return $eidRefs;
}
/**
* Return tables using locations.
*/
public static function locTables() {
static $locTables;
if (!$locTables) {
$locTables = ['civicrm_email', 'civicrm_address', 'civicrm_phone'];
// Allow hook_civicrm_merge() to adjust $locTables
CRM_Utils_Hook::merge('locTables', $locTables);
}
return $locTables;
}
/**
* We treat multi-valued custom sets as "related tables" similar to activities, contributions, etc.
*
* @param string $request
* 'relTables' or 'cidRefs'.
*
* @return array
* @throws \CRM_Core_Exception
* @see CRM-13836
*/
public static function getMultiValueCustomSets($request) {
if (!isset(Civi::$statics[__CLASS__]['multiValueCustomSets'])) {
$data = [
'relTables' => [],
'cidRefs' => [],
];
$result = civicrm_api3('custom_group', 'get', [
'is_multiple' => 1,
'extends' => [
'IN' => [
'Individual',
'Organization',
'Household',
'Contact',
],
],
'return' => ['id', 'title', 'table_name', 'style'],
]);
foreach ($result['values'] as $custom) {
$data['cidRefs'][$custom['table_name']] = ['entity_id'];
$urlSuffix = $custom['style'] === 'Tab' ? '&selectedChild=custom_' . $custom['id'] : '';
$data['relTables']['rel_table_custom_' . $custom['id']] = [
'title' => $custom['title'],
'tables' => [$custom['table_name']],
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid' . $urlSuffix),
];
}
// Store the result in a static variable cache
Civi::$statics[__CLASS__]['multiValueCustomSets'] = $data;
}
return Civi::$statics[__CLASS__]['multiValueCustomSets'][$request];
}
/**
* Tables which require custom processing should declare functions to call here.
* Doing so will override normal processing.
*/
public static function cpTables() {
static $tables;
if (!$tables) {
$tables = [
'civicrm_case_contact' => ['CRM_Case_BAO_Case' => 'mergeContacts'],
'civicrm_group_contact' => ['CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'],
// Empty array == do nothing - this table is handled by mergeGroupContact
'civicrm_subscription_history' => [],
'civicrm_relationship' => ['CRM_Contact_BAO_Relationship' => 'mergeRelationships'],
'civicrm_membership' => ['CRM_Member_BAO_Membership' => 'mergeMemberships'],
];
}
return $tables;
}
/**
* Return payment related table.
*/
public static function paymentTables() {
static $tables;
if (!$tables) {
$tables = ['civicrm_pledge', 'civicrm_membership', 'civicrm_participant'];
}
return $tables;
}
/**
* Return payment update Query.
*
* @param string $tableName
* @param int $mainContactId
* @param int $otherContactId
*
* @return array
*/
public static function paymentSql($tableName, $mainContactId, $otherContactId) {
$sqls = [];
if (!$tableName || !$mainContactId || !$otherContactId) {
return $sqls;
}
$paymentTables = self::paymentTables();
if (!in_array($tableName, $paymentTables)) {
return $sqls;
}
switch ($tableName) {
case 'civicrm_pledge':
$sqls[] = "
UPDATE IGNORE civicrm_contribution contribution
INNER JOIN civicrm_pledge_payment payment ON ( payment.contribution_id = contribution.id )
INNER JOIN civicrm_pledge pledge ON ( pledge.id = payment.pledge_id )
SET contribution.contact_id = $mainContactId
WHERE pledge.contact_id = $otherContactId";
break;
case 'civicrm_membership':
$sqls[] = "
UPDATE IGNORE civicrm_contribution contribution
INNER JOIN civicrm_membership_payment payment ON ( payment.contribution_id = contribution.id )
INNER JOIN civicrm_membership membership ON ( membership.id = payment.membership_id )
SET contribution.contact_id = $mainContactId
WHERE membership.contact_id = $otherContactId";
break;
case 'civicrm_participant':
$sqls[] = "
UPDATE IGNORE civicrm_contribution contribution
INNER JOIN civicrm_participant_payment payment ON ( payment.contribution_id = contribution.id )
INNER JOIN civicrm_participant participant ON ( participant.id = payment.participant_id )
SET contribution.contact_id = $mainContactId
WHERE participant.contact_id = $otherContactId";
break;
}
return $sqls;
}
/**
* @param int $mainId
* @param int $otherId
* @param string $tableName
* @param array $tableOperations
* @param string $mode
*
* @return array
*/
public static function operationSql($mainId, $otherId, $tableName, $tableOperations = [], $mode = 'add') {
$sqls = [];
if (!$tableName || !$mainId || !$otherId) {
return $sqls;
}
switch ($tableName) {
case 'civicrm_membership':
if (array_key_exists($tableName, $tableOperations) && $tableOperations[$tableName]['add']) {
break;
}
if ($mode === 'add') {
$sqls[] = "
DELETE membership1.* FROM civicrm_membership membership1
INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
AND membership1.contact_id = {$mainId}
AND membership2.contact_id = {$otherId} ";
}
if ($mode === 'payment') {
$sqls[] = "
DELETE contribution.* FROM civicrm_contribution contribution
INNER JOIN civicrm_membership_payment payment ON payment.contribution_id = contribution.id
INNER JOIN civicrm_membership membership1 ON membership1.id = payment.membership_id
AND membership1.contact_id = {$mainId}
INNER JOIN civicrm_membership membership2 ON membership1.membership_type_id = membership2.membership_type_id
AND membership2.contact_id = {$otherId}";
}
break;
case 'civicrm_uf_match':
// normal queries won't work for uf_match since that will lead to violation of unique constraint,
// failing to meet intended result. Therefore we introduce this additional query:
$sqls[] = "DELETE FROM civicrm_uf_match WHERE contact_id = {$mainId}";
break;
}
return $sqls;
}
/**
* Based on the provided two contact_ids and a set of tables, remove the
* belongings of the other contact and of their relations.
*
* @param int $otherID
* @param array $tables
*
* @throws \CRM_Core_Exception
*/
public static function removeContactBelongings($otherID, $tables) {
// CRM-20421: Removing Inherited memberships when memberships of parent are not migrated to new contact.
if (in_array('civicrm_membership', $tables, TRUE)) {
$membershipIDs = CRM_Utils_Array::collect('id',
CRM_Utils_Array::value('values',
civicrm_api3('Membership', "get", [
'contact_id' => $otherID,
'return' => 'id',
])
)
);
if (!empty($membershipIDs)) {
civicrm_api3('Membership', 'get', [
'owner_membership_id' => ['IN' => $membershipIDs],
'api.Membership.delete' => ['id' => '$value.id'],
]);
}
}
}
/**
* Based on the provided two contact_ids and a set of tables, move the
* belongings of the other contact to the main one.
*
* @param CRM_Dedupe_MergeHandler $mergeHandler
* @param array $tables
* @param array $tableOperations
*
* @throws \CRM_Core_Exception
* @throws \Civi\API\Exception\UnauthorizedException
*/
public static function moveContactBelongings($mergeHandler, $tables, $tableOperations) {
$mainId = $mergeHandler->getToKeepID();
$otherId = $mergeHandler->getToRemoveID();
$cidRefs = self::cidRefs();
$eidRefs = $mergeHandler->getTablesDynamicallyRelatedToContactTable();
$dynamicRefs = CRM_Core_DAO::getDynamicReferencesToTable('civicrm_contact');
$cpTables = self::cpTables();
$paymentTables = self::paymentTables();
self::filterRowBasedCustomDataFromCustomTables($cidRefs);
$multiValueCidRefs = self::getMultiValueCidRefs();
$affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
// if there aren't any specific tables, don't affect the ones handled by relTables()
// also don't affect tables in locTables() CRM-15658
$relTables = self::relTables();
// These arrays don't make a lot of sense. For now ensure the tested handling of tags works...
// it is moved over further down....
unset($relTables['rel_table_tags']);
$handled = self::locTables();
foreach ($relTables as $params) {
$handled = array_merge($handled, $params['tables']);
}
$affected = array_diff($affected, $handled);
$affected = array_unique(array_merge($affected, $tables));
$mainId = (int) $mainId;
$otherId = (int) $otherId;
$sqls = [];
foreach ($affected as $table) {
// Call custom processing function for objects that require it
if (isset($cpTables[$table])) {
foreach ($cpTables[$table] as $className => $fnName) {
$className::$fnName($mainId, $otherId, $sqls, $tables, $tableOperations);
}
// Skip normal processing
continue;
}
if ($table === 'civicrm_activity_contact') {
$sqls[] = "UPDATE IGNORE civicrm_activity_contact SET contact_id = $mainId WHERE contact_id = $otherId";
$sqls[] = "DELETE FROM civicrm_activity_contact WHERE contact_id = $otherId";
continue;
}
if ($table === 'civicrm_dashboard_contact') {
$sqls[] = "UPDATE IGNORE civicrm_dashboard_contact SET contact_id = $mainId WHERE contact_id = $otherId";
$sqls[] = "DELETE FROM civicrm_dashboard_contact WHERE contact_id = $otherId";
continue;
}
if ($table === 'civicrm_dedupe_exception') {
$sqls[] = "UPDATE IGNORE civicrm_dedupe_exception SET contact_id1 = $mainId WHERE contact_id1 = $otherId";
$sqls[] = "UPDATE IGNORE civicrm_dedupe_exception SET contact_id2 = $mainId WHERE contact_id2 = $otherId";
$sqls[] = "DELETE FROM civicrm_dedupe_exception WHERE contact_id1 = $otherId OR contact_id2 = $otherId";
continue;
}
if ($table === 'civicrm_setting') {
// Per https://lab.civicrm.org/dev/core/-/issues/1934
// Note this line is not unit tested as yet as a quick-fix for a regression
// but it would be better to do a SELECT request & only update if needed (as a general rule
// more selects & less UPDATES will result in less deadlocks while de-duping.
// Note the delete is not important here - it can stay with the deleted contact on the
// off chance they get restored.
$sqls[] = "UPDATE IGNORE civicrm_setting SET contact_id = $mainId WHERE contact_id = $otherId";
continue;
}
// use UPDATE IGNORE + DELETE query pair to skip on situations when
// there's a UNIQUE restriction on ($field, some_other_field) pair
if (isset($cidRefs[$table])) {
foreach ($cidRefs[$table] as $field) {
// carry related contributions CRM-5359
if (in_array($table, $paymentTables)) {
$paymentSqls = self::paymentSql($table, $mainId, $otherId);
$sqls = array_merge($sqls, $paymentSqls);
if (!empty($tables) && !in_array('civicrm_contribution', $tables)) {
$payOprSqls = self::operationSql($mainId, $otherId, $table, $tableOperations, 'payment');
$sqls = array_merge($sqls, $payOprSqls);
}
}
$preOperationSqls = self::operationSql($mainId, $otherId, $table, $tableOperations);
$sqls = array_merge($sqls, $preOperationSqls);
if (!empty($multiValueCidRefs[$table][$field])) {
$sep = CRM_Core_DAO::VALUE_SEPARATOR;
$sqls[] = "UPDATE $table SET $field = REPLACE($field, '$sep$otherId$sep', '$sep$mainId$sep') WHERE $field LIKE '%$sep$otherId$sep%'";
}
else {
$sqls[] = "UPDATE $table SET $field = $mainId WHERE $field = $otherId";
}
}
}
if (isset($eidRefs[$table])) {
foreach ($dynamicRefs[$table] as $dynamicRef) {
$sqls[] = "UPDATE IGNORE $table SET {$dynamicRef[0]}= $mainId WHERE {$dynamicRef[0]} = $otherId AND {$dynamicRef[1]} = 'civicrm_contact'";
$sqls[] = "DELETE FROM $table WHERE {$dynamicRef[0]} = $otherId AND {$dynamicRef[1]} = 'civicrm_contact'";
}
}
}
// Allow hook_civicrm_merge() to add SQL statements for the merge operation.
CRM_Utils_Hook::merge('sqls', $sqls, $mainId, $otherId, $tables);
foreach ($sqls as $sql) {
CRM_Core_DAO::executeQuery($sql, [], TRUE, NULL, TRUE);
}
CRM_Dedupe_Merger::addMembershipToRelatedContacts($mainId);
}
/**
* Filter out custom tables from cidRefs unless they are there due to a contact reference or are a multiple set.
*
* The only fields where we want to move the data by sql is where entity reference fields
* on another contact refer to the contact being merged, or it is a multiple record set.
* The transference of custom data from one contact to another is done in 2 other places in the dedupe process but should
* not be done in moveAllContactData.
*
* Note it's a bit silly the way we build & then cull cidRefs - however, poor hook placement means that
* until we fully deprecate calling the hook from cidRefs we are stuck.
*
* It was deprecated in code (via deprecation notices if people altered it) in Mar 2019 but in docs only in Apri 2020.
*
* @param array $cidRefs
*
* @throws \CRM_Core_Exception
* @throws \Civi\API\Exception\UnauthorizedException
*/
protected static function filterRowBasedCustomDataFromCustomTables(array &$cidRefs) {
$customTables = (array) CustomGroup::get(FALSE)
->setSelect(['table_name'])
->addWhere('is_multiple', '=', 0)
->addWhere('extends', 'IN', array_merge(['Contact'], CRM_Contact_BAO_ContactType::contactTypes()))
->execute()
->indexBy('table_name');
foreach (array_intersect_key($cidRefs, $customTables) as $tableName => $cidSpec) {
if (in_array('entity_id', $cidSpec, TRUE)) {
unset($cidRefs[$tableName][array_search('entity_id', $cidSpec, TRUE)]);
}
if (empty($cidRefs[$tableName])) {
unset($cidRefs[$tableName]);
}
}
}
/**
* Return an array of tables & fields which hold serialized arrays of contact ids
*
* Return format is ['table_name' => ['field_name' => SERIALIZE_METHOD]]
*
* For now, only custom fields can be serialized and the only
* method used is CRM_Core_DAO::SERIALIZE_SEPARATOR_BOOKEND.
*/
protected static function getMultiValueCidRefs() {
$fields = \Civi\Api4\CustomField::get(FALSE)
->addSelect('custom_group_id.table_name', 'column_name', 'serialize')
->addWhere('data_type', '=', 'ContactReference')
->addWhere('serialize', 'IS NOT EMPTY')
->execute();
$map = [];
foreach ($fields as $field) {
$map[$field['custom_group_id.table_name']][$field['column_name']] = $field['serialize'];
}
return $map;
}
/**
* Update the contact with the new parameters.
*
* This function is intended as an interim function, with the intent being
* an apiv4 call.
*
* The function was calling the rather-terrifying createProfileContact. I copied all
* that code into this function and then removed all the parts that have no effect in this scenario.
*
* @param int $contactID
* @param array $params
*
* @throws \CRM_Core_Exception
* @throws \Civi\API\Exception\UnauthorizedException
*/
protected static function updateContact(int $contactID, $params): void {
// This parameter causes blank fields to be be emptied out.
// We can probably remove.
$params['updateBlankLocInfo'] = TRUE;
$data = self::formatProfileContactParams($params, $contactID);
CRM_Contact_BAO_Contact::create($data);
}
/**
* Format profile contact parameters.
*
* Note this function has been duplicated from CRM_Contact_BAO_Contact
* in order to allow us to unravel all the work this class
* does to prepare to call this & create some sanity. Also start to
* eliminate a toxic function.
*
* @param array $params
* @param int $contactID
*
* @return array
*/
private static function formatProfileContactParams(
$params,
int $contactID
) {
$data = $contactDetails = [];
// get the contact details (hier)
$details = CRM_Contact_BAO_Contact::getHierContactDetails($contactID, []);
$contactDetails = $details[$contactID];
$data['contact_type'] = $contactDetails['contact_type'] ?? NULL;
$data['contact_sub_type'] = $contactDetails['contact_sub_type'] ?? NULL;
//fix contact sub type CRM-5125
if (array_key_exists('contact_sub_type', $params) &&
!empty($params['contact_sub_type'])
) {
$data['contact_sub_type'] = CRM_Utils_Array::implodePadded($params['contact_sub_type']);
}
elseif (array_key_exists('contact_sub_type_hidden', $params) &&
!empty($params['contact_sub_type_hidden'])
) {
// if profile was used, and had any subtype, we obtain it from there
//CRM-13596 - add to existing contact types, rather than overwriting
if (empty($data['contact_sub_type'])) {
// If we don't have a contact ID the $data['contact_sub_type'] will not be defined...
$data['contact_sub_type'] = CRM_Utils_Array::implodePadded($params['contact_sub_type_hidden']);
}
else {
$data_contact_sub_type_arr = CRM_Utils_Array::explodePadded($data['contact_sub_type']);
if (!in_array($params['contact_sub_type_hidden'], $data_contact_sub_type_arr)) {
//CRM-20517 - make sure contact_sub_type gets the correct delimiters
$data['contact_sub_type'] = trim($data['contact_sub_type'], CRM_Core_DAO::VALUE_SEPARATOR);
$data['contact_sub_type'] = CRM_Core_DAO::VALUE_SEPARATOR . $data['contact_sub_type'] . CRM_Utils_Array::implodePadded($params['contact_sub_type_hidden']);
}
}
}
$locationType = [];
$count = 1;
//add contact id
$data['contact_id'] = $contactID;
$primaryLocationType = CRM_Contact_BAO_Contact::getPrimaryLocationType($contactID);
$billingLocationTypeId = CRM_Core_BAO_LocationType::getBilling();
$blocks = ['email', 'phone', 'im', 'openid'];
$multiplFields = ['url'];
// prevent overwritten of formatted array, reset all block from
// params if it is not in valid format (since import pass valid format)
foreach ($blocks as $blk) {
if (array_key_exists($blk, $params) &&
!is_array($params[$blk])
) {
unset($params[$blk]);
}
}
$primaryPhoneLoc = NULL;
$session = CRM_Core_Session::singleton();
foreach ($params as $key => $value) {
[$fieldName, $locTypeId, $typeId] = CRM_Utils_System::explode('-', $key, 3);
if ($locTypeId == 'Primary') {
if (in_array($fieldName, $blocks)) {
$locTypeId = CRM_Contact_BAO_Contact::getPrimaryLocationType($contactID, FALSE, $fieldName);
}
else {
$locTypeId = CRM_Contact_BAO_Contact::getPrimaryLocationType($contactID, FALSE, 'address');
}
$primaryLocationType = $locTypeId;
}
if (is_numeric($locTypeId) &&
!in_array($fieldName, $multiplFields) &&
substr($fieldName, 0, 7) != 'custom_'
) {
$index = $locTypeId;
if (is_numeric($typeId)) {
$index .= '-' . $typeId;
}
if (!in_array($index, $locationType)) {
$locationType[$count] = $index;
$count++;
}
$loc = CRM_Utils_Array::key($index, $locationType);
$blockName = self::getLocationEntityForKey($fieldName);
$data[$blockName][$loc]['location_type_id'] = $locTypeId;
//set is_billing true, for location type "Billing"
if ($locTypeId == $billingLocationTypeId) {
$data[$blockName][$loc]['is_billing'] = 1;
}
if ($contactID) {
//get the primary location type
if ($locTypeId == $primaryLocationType) {
$data[$blockName][$loc]['is_primary'] = 1;
}
}
elseif ($locTypeId == $defaultLocationId) {
$data[$blockName][$loc]['is_primary'] = 1;
}
if (in_array($fieldName, ['phone'])) {
if ($typeId) {
$data['phone'][$loc]['phone_type_id'] = $typeId;
}
else {
$data['phone'][$loc]['phone_type_id'] = '';
}
$data['phone'][$loc]['phone'] = $value;
//special case to handle primary phone with different phone types
// in this case we make first phone type as primary
if (isset($data['phone'][$loc]['is_primary']) && !$primaryPhoneLoc) {
$primaryPhoneLoc = $loc;
}
if ($loc != $primaryPhoneLoc) {
unset($data['phone'][$loc]['is_primary']);
}
}
elseif ($fieldName == 'email') {
$data['email'][$loc]['email'] = $value;
if (empty($contactID)) {
$data['email'][$loc]['is_primary'] = 1;
}
}
elseif ($fieldName == 'im') {
if (isset($params[$key . '-provider_id'])) {
$data['im'][$loc]['provider_id'] = $params[$key . '-provider_id'];
}
if (strpos($key, '-provider_id') !== FALSE) {
$data['im'][$loc]['provider_id'] = $params[$key];
}
else {
$data['im'][$loc]['name'] = $value;
}
}
elseif ($fieldName == 'openid') {
$data['openid'][$loc]['openid'] = $value;
}
else {
if ($fieldName === 'state_province') {
// CRM-3393
if (is_numeric($value) && ((int ) $value) >= 1000) {
$data['address'][$loc]['state_province_id'] = $value;
}
elseif (empty($value)) {
$data['address'][$loc]['state_province_id'] = '';
}
else {
$data['address'][$loc]['state_province'] = $value;
}
}
elseif ($fieldName === 'country') {
// CRM-3393
if (is_numeric($value) && ((int ) $value) >= 1000
) {
$data['address'][$loc]['country_id'] = $value;
}
elseif (empty($value)) {
$data['address'][$loc]['country_id'] = '';
}
else {
$data['address'][$loc]['country'] = $value;
}
}
elseif ($fieldName === 'county') {
$data['address'][$loc]['county_id'] = $value;
}
elseif ($fieldName == 'address_name') {
$data['address'][$loc]['name'] = $value;
}
elseif (substr($fieldName, 0, 14) === 'address_custom') {
$data['address'][$loc][substr($fieldName, 8)] = $value;
}
else {
$data[$blockName][$loc][$fieldName] = $value;
}
}
}
else {
if (substr($key, 0, 4) === 'url-') {
$websiteField = explode('-', $key);
$data['website'][$websiteField[1]]['website_type_id'] = $websiteField[1];
$data['website'][$websiteField[1]]['url'] = $value;
}
elseif (in_array($key, CRM_Contact_BAO_Contact::$_greetingTypes, TRUE)) {
//save email/postal greeting and addressee values if any, CRM-4575
$data[$key . '_id'] = $value;
}
elseif (($customFieldId = CRM_Core_BAO_CustomField::getKeyID($key))) {
// for autocomplete transfer hidden value instead of label
if ($params[$key] && isset($params[$key . '_id'])) {
$value = $params[$key . '_id'];
}
// we need to append time with date
if ($params[$key] && isset($params[$key . '_time'])) {
$value .= ' ' . $params[$key . '_time'];
}
// if auth source is not checksum / login && $value is blank, do not proceed - CRM-10128
if (($session->get('authSrc') & (CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN)) == 0 &&
($value == '' || !isset($value))
) {
continue;
}
$valueId = NULL;
if (!empty($params['customRecordValues'])) {
if (is_array($params['customRecordValues']) && !empty($params['customRecordValues'])) {
foreach ($params['customRecordValues'] as $recId => $customFields) {
if (is_array($customFields) && !empty($customFields)) {
foreach ($customFields as $customFieldName) {
if ($customFieldName == $key) {
$valueId = $recId;
break;
}
}
}
}
}
}
//CRM-13596 - check for contact_sub_type_hidden first
if (array_key_exists('contact_sub_type_hidden', $params)) {
$type = $params['contact_sub_type_hidden'];
}
else {
$type = $data['contact_type'];
if (!empty($data['contact_sub_type'])) {
$type = CRM_Utils_Array::explodePadded($data['contact_sub_type']);
}
}
CRM_Core_BAO_CustomField::formatCustomField($customFieldId,
$data['custom'],
$value,
$type,
$valueId,
$contactID,
FALSE,
FALSE
);
}
elseif ($key === 'edit') {
continue;
}
else {
if ($key === 'location') {
foreach ($value as $locationTypeId => $field) {
foreach ($field as $block => $val) {
if ($block === 'address' && array_key_exists('address_name', $val)) {
$value[$locationTypeId][$block]['name'] = $value[$locationTypeId][$block]['address_name'];
}
}
}
}
if ($key === 'phone' && isset($params['phone_ext'])) {
$data[$key] = $value;
foreach ($value as $cnt => $phoneBlock) {
if ($params[$key][$cnt]['location_type_id'] == $params['phone_ext'][$cnt]['location_type_id']) {
$data[$key][$cnt]['phone_ext'] = CRM_Utils_Array::retrieveValueRecursive($params['phone_ext'][$cnt], 'phone_ext');
}
}
}
elseif (in_array($key, ['nick_name', 'job_title', 'middle_name', 'birth_date', 'gender_id', 'current_employer', 'prefix_id', 'suffix_id'])
&& ($value == '' || !isset($value)) &&
($session->get('authSrc') & (CRM_Core_Permission::AUTH_SRC_CHECKSUM + CRM_Core_Permission::AUTH_SRC_LOGIN)) == 0 ||
($key === 'current_employer' && empty($params['current_employer']))) {
// CRM-10128: if auth source is not checksum / login && $value is blank, do not fill $data with empty value
// to avoid update with empty values
continue;
}
else {
$data[$key] = $value;
}
}
}
}
if (!isset($data['contact_type'])) {
$data['contact_type'] = 'Individual';
}
return $data;