forked from civicrm/civicrm-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMerger.php
executable file
·2304 lines (2099 loc) · 88.2 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
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
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
*/
public static function relTables() {
static $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();
if ($config->userSystem->is_drupal) {
$userRecordUrl = CRM_Utils_System::url('user/%ufid');
$title = ts('%1 User: %2; user id: %3', array(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', array(1 => $config->userFramework, 2 => '$ufname', 3 => '$ufid'));
}
if (!$relTables) {
$relTables = array(
'rel_table_contributions' => array(
'title' => ts('Contributions'),
'tables' => array('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' => array(
'title' => ts('Contribution Pages'),
'tables' => array('civicrm_contribution_page'),
'url' => CRM_Utils_System::url('civicrm/admin/contribute', 'reset=1&cid=$cid'),
),
'rel_table_memberships' => array(
'title' => ts('Memberships'),
'tables' => array('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' => array(
'title' => ts('Participants'),
'tables' => array('civicrm_participant'),
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=participant'),
),
'rel_table_events' => array(
'title' => ts('Events'),
'tables' => array('civicrm_event'),
'url' => CRM_Utils_System::url('civicrm/event/manage', 'reset=1&cid=$cid'),
),
'rel_table_activities' => array(
'title' => ts('Activities'),
'tables' => array('civicrm_activity', 'civicrm_activity_contact'),
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=activity'),
),
'rel_table_relationships' => array(
'title' => ts('Relationships'),
'tables' => array('civicrm_relationship'),
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=rel'),
),
'rel_table_custom_groups' => array(
'title' => ts('Custom Groups'),
'tables' => array('civicrm_custom_group'),
'url' => CRM_Utils_System::url('civicrm/admin/custom/group', 'reset=1'),
),
'rel_table_uf_groups' => array(
'title' => ts('Profiles'),
'tables' => array('civicrm_uf_group'),
'url' => CRM_Utils_System::url('civicrm/admin/uf/group', 'reset=1'),
),
'rel_table_groups' => array(
'title' => ts('Groups'),
'tables' => array('civicrm_group_contact'),
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=group'),
),
'rel_table_notes' => array(
'title' => ts('Notes'),
'tables' => array('civicrm_note'),
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=note'),
),
'rel_table_tags' => array(
'title' => ts('Tags'),
'tables' => array('civicrm_entity_tag'),
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=tag'),
),
'rel_table_mailings' => array(
'title' => ts('Mailings'),
'tables' => array('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' => array(
'title' => ts('Cases'),
'tables' => array('civicrm_case_contact'),
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=case'),
),
'rel_table_grants' => array(
'title' => ts('Grants'),
'tables' => array('civicrm_grant'),
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=grant'),
),
'rel_table_pcp' => array(
'title' => ts('PCPs'),
'tables' => array('civicrm_pcp'),
'url' => CRM_Utils_System::url('civicrm/contribute/pcp/manage', 'reset=1'),
),
'rel_table_pledges' => array(
'title' => ts('Pledges'),
'tables' => array('civicrm_pledge', 'civicrm_pledge_payment'),
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid&selectedChild=pledge'),
),
'rel_table_users' => array(
'title' => $title,
'tables' => array('civicrm_uf_match'),
'url' => $userRecordUrl,
),
);
$relTables += self::getMultiValueCustomSets('relTables');
// Allow hook_civicrm_merge() to adjust $relTables
CRM_Utils_Hook::merge('relTables', $relTables);
}
return $relTables;
}
/**
* Returns the related tables groups for which a contact has any info entered.
*
* @param int $cid
*
* @return array
*/
public static function getActiveRelTables($cid) {
$cid = (int) $cid;
$groups = array();
$relTables = self::relTables();
$cidRefs = self::cidRefs();
$eidRefs = self::eidRefs();
foreach ($relTables as $group => $params) {
$sqls = array();
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 includes core tables, custom group tables, tables added by the merge
* hook and (somewhat randomly) the entity_tag table.
*
* Refer to CRM-17454 for information on the danger of querying the information
* schema to derive this.
*
* This function calls the merge hook but the entityTypes hook is the recommended
* way to add tables to this result.
*/
public static function cidRefs() {
if (isset(\Civi::$statics[__CLASS__]) && isset(\Civi::$statics[__CLASS__]['contact_references'])) {
return \Civi::$statics[__CLASS__]['contact_references'];
}
$contactReferences = array();
$coreReferences = CRM_Core_DAO::getReferencesToTable('civicrm_contact');
foreach ($coreReferences as $coreReference) {
if (!is_a($coreReference, 'CRM_Core_Reference_Dynamic')) {
$contactReferences[$coreReference->getReferenceTable()][] = $coreReference->getReferenceKey();
}
}
self::addCustomTablesExtendingContactsToCidRefs($contactReferences);
// FixME for time being adding below line statically as no Foreign key constraint defined for table 'civicrm_entity_tag'
$contactReferences['civicrm_entity_tag'][] = 'entity_id';
// Allow hook_civicrm_merge() to adjust $cidRefs.
// Note that if entities are registered using the entityTypes hook there
// is no need to use this hook.
CRM_Utils_Hook::merge('cidRefs', $contactReferences);
\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 = array(
'civicrm_acl' => array('entity_table' => 'entity_id'),
'civicrm_acl_entity_role' => array('entity_table' => 'entity_id'),
'civicrm_entity_file' => array('entity_table' => 'entity_id'),
'civicrm_log' => array('entity_table' => 'entity_id'),
'civicrm_mailing_group' => array('entity_table' => 'entity_id'),
'civicrm_note' => array('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 = array('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'.
* @see CRM-13836
*/
public static function getMultiValueCustomSets($request) {
static $data = NULL;
if ($data === NULL) {
$data = array(
'relTables' => array(),
'cidRefs' => array(),
);
$result = civicrm_api3('custom_group', 'get', array(
'is_multiple' => 1,
'extends' => array('IN' => array('Individual', 'Organization', 'Household', 'Contact')),
'return' => array('id', 'title', 'table_name', 'style'),
));
foreach ($result['values'] as $custom) {
$data['cidRefs'][$custom['table_name']] = array('entity_id');
$urlSuffix = $custom['style'] == 'Tab' ? '&selectedChild=custom_' . $custom['id'] : '';
$data['relTables']['rel_table_custom_' . $custom['id']] = array(
'title' => $custom['title'],
'tables' => array($custom['table_name']),
'url' => CRM_Utils_System::url('civicrm/contact/view', 'reset=1&force=1&cid=$cid' . $urlSuffix),
);
}
}
return $data[$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 = array(
'civicrm_case_contact' => array('CRM_Case_BAO_Case' => 'mergeContacts'),
'civicrm_group_contact' => array('CRM_Contact_BAO_GroupContact' => 'mergeGroupContact'),
// Empty array == do nothing - this table is handled by mergeGroupContact
'civicrm_subscription_history' => array(),
'civicrm_relationship' => array('CRM_Contact_BAO_Relationship' => 'mergeRelationships'),
);
}
return $tables;
}
/**
* Return payment related table.
*/
public static function paymentTables() {
static $tables;
if (!$tables) {
$tables = array('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 = array();
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 = array(), $mode = 'add') {
$sqls = array();
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, move the
* belongings of the other contact to the main one.
*
* @param int $mainId
* @param int $otherId
* @param bool $tables
* @param array $tableOperations
* @param array $customTableToCopyFrom
*/
public static function moveContactBelongings($mainId, $otherId, $tables = FALSE, $tableOperations = array(), $customTableToCopyFrom = NULL) {
$cidRefs = self::cidRefs();
$eidRefs = self::eidRefs();
$cpTables = self::cpTables();
$paymentTables = self::paymentTables();
// CRM-12695:
$membershipMerge = FALSE;
// getting all custom tables
$customTables = array();
if ($customTableToCopyFrom !== NULL) {
self::addCustomTablesExtendingContactsToCidRefs($customTables);
$customTables = array_keys($customTables);
}
$affected = array_merge(array_keys($cidRefs), array_keys($eidRefs));
if ($tables !== FALSE) {
// if there are specific tables, sanitize the list
$affected = array_unique(array_intersect($affected, $tables));
}
else {
// 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();
$handled = self::locTables();
foreach ($relTables as $params) {
$handled = array_merge($handled, $params['tables']);
}
$affected = array_diff($affected, $handled);
/**
* CRM-12695
* Set $membershipMerge flag only once
* while doing contact related migration
* to call addMembershipToRealtedContacts()
* function only once.
* Since the current function (moveContactBelongings) is called twice
* with & without parameters $tables & $tableOperations
*/
// retrieve main contact's related table(s)
$activeMainRelTables = CRM_Dedupe_Merger::getActiveRelTables($mainId);
// check if membership table exists in main contact's related table(s)
// set membership flag - CRM-12695
if (in_array('rel_table_memberships', $activeMainRelTables)) {
$membershipMerge = TRUE;
}
}
$mainId = (int) $mainId;
$otherId = (int) $otherId;
$sqls = array();
foreach ($affected as $table) {
// skipping non selected custom table's value migration
if ($customTableToCopyFrom !== NULL && in_array($table, $customTables) && !in_array($table, $customTableToCopyFrom)) {
continue;
}
// Call custom processing function for objects that require it
if (isset($cpTables[$table])) {
foreach ($cpTables[$table] as $className => $fnName) {
$className::$fnName($mainId, $otherId, $sqls);
}
// Skip normal processing
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 ($customTableToCopyFrom !== NULL && in_array($table, $customTableToCopyFrom) && !self::customRecordExists($mainId, $table, $field)) {
$sqls[] = "INSERT INTO $table ($field) VALUES ($mainId)";
}
$sqls[] = "UPDATE IGNORE $table SET $field = $mainId WHERE $field = $otherId";
$sqls[] = "DELETE FROM $table WHERE $field = $otherId";
}
}
if (isset($eidRefs[$table])) {
foreach ($eidRefs[$table] as $entityTable => $entityId) {
$sqls[] = "UPDATE IGNORE $table SET $entityId = $mainId WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
$sqls[] = "DELETE FROM $table WHERE $entityId = $otherId AND $entityTable = 'civicrm_contact'";
}
}
}
// Allow hook_civicrm_merge() to add SQL statements for the merge operation.
CRM_Utils_Hook::merge('sqls', $sqls, $mainId, $otherId, $tables);
// call the SQL queries in one transaction
$transaction = new CRM_Core_Transaction();
foreach ($sqls as $sql) {
CRM_Core_DAO::executeQuery($sql, array(), TRUE, NULL, TRUE);
}
// CRM-12695
if ($membershipMerge) {
// call to function adding membership to related contacts
CRM_Dedupe_Merger::addMembershipToRealtedContacts($mainId);
}
$transaction->commit();
}
/**
* Given a contact ID, will check if a record exists in given table.
*
* @param $contactID
* @param $table
* @param $idField
* Field where the contact's ID is stored in the table
*
* @return bool
* True if a record is found for the given contact ID, false otherwise
*/
private static function customRecordExists($contactID, $table, $idField) {
$sql = "
SELECT COUNT(*) AS count
FROM $table
WHERE $idField = $contactID
";
$dbResult = CRM_Core_DAO::executeQuery($sql);
$dbResult->fetch();
if ($dbResult->count > 0) {
return TRUE;
}
return FALSE;
}
/**
* Load all non-empty fields for the contacts
*
* @param array $main
* Contact details.
* @param array $other
* Contact details.
*
* @return array
*/
public static function retrieveFields($main, $other) {
$result = array(
'contact' => array(),
'custom' => array(),
);
foreach (self::getContactFields() as $validField) {
// CRM-17556 Get all non-empty fields, to make comparison easier
if (!empty($main[$validField]) || !empty($other[$validField])) {
$result['contact'][] = $validField;
}
}
$mainEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($main['id']);
$otherEvs = CRM_Core_BAO_CustomValueTable::getEntityValues($other['id']);
$keys = array_unique(array_merge(array_keys($mainEvs), array_keys($otherEvs)));
foreach ($keys as $key) {
// Exclude multi-value fields CRM-13836
if (strpos($key, '_')) {
continue;
}
$key1 = CRM_Utils_Array::value($key, $mainEvs);
$key2 = CRM_Utils_Array::value($key, $otherEvs);
// CRM-17556 Get all non-empty fields, to make comparison easier
if (!empty($key1) || !empty($key2)) {
$result['custom'][] = $key;
}
}
return $result;
}
/**
* Batch merge a set of contacts based on rule-group and group.
*
* @param int $rgid
* Rule group id.
* @param int $gid
* Group id.
* @param string $mode
* Helps decide how to behave when there are conflicts.
* A 'safe' value skips the merge if there are any un-resolved conflicts, wheras 'aggressive'
* mode does a force merge.
* @param int $batchLimit number of merges to carry out in one batch.
* @param int $isSelected if records with is_selected column needs to be processed.
*
* @param array $criteria
* Criteria to use in the filter.
*
* @param bool $checkPermissions
* Respect logged in user permissions.
*
* @return array|bool
*/
public static function batchMerge($rgid, $gid = NULL, $mode = 'safe', $batchLimit = 1, $isSelected = 2, $criteria = array(), $checkPermissions = TRUE) {
$redirectForPerformance = ($batchLimit > 1) ? TRUE : FALSE;
$reloadCacheIfEmpty = (!$redirectForPerformance && $isSelected == 2);
$dupePairs = self::getDuplicatePairs($rgid, $gid, $reloadCacheIfEmpty, $batchLimit, $isSelected, '', ($mode == 'aggressive'), $criteria, $checkPermissions);
$cacheParams = array(
'cache_key_string' => self::getMergeCacheKeyString($rgid, $gid, $criteria, $checkPermissions),
// @todo stop passing these parameters in & instead calculate them in the merge function based
// on the 'real' params like $isRespectExclusions $batchLimit and $isSelected.
'join' => self::getJoinOnDedupeTable(),
'where' => self::getWhereString($batchLimit, $isSelected),
);
return CRM_Dedupe_Merger::merge($dupePairs, $cacheParams, $mode, $redirectForPerformance, $checkPermissions);
}
/**
* Get the string to join the prevnext cache to the dedupe table.
*
* @return string
* The join string to join prevnext cache on the dedupe table.
*/
public static function getJoinOnDedupeTable() {
return "
LEFT JOIN civicrm_dedupe_exception de
ON (
pn.entity_id1 = de.contact_id1
AND pn.entity_id2 = de.contact_id2 )
";
}
/**
* Get where string for dedupe join.
*
* @param int $batchLimit
* @param bool $isSelected
*
* @return string
*/
protected static function getWhereString($batchLimit, $isSelected) {
$where = "de.id IS NULL";
if ($isSelected === 0 || $isSelected === 1) {
$where .= " AND pn.is_selected = {$isSelected}";
}
// else consider all dupe pairs
// @todo Adding limit to Where??!!
$where .= " LIMIT {$batchLimit}";
return $where;
}
/**
* Update the statistics for the merge set.
*
* @param string $cacheKeyString
* @param array $result
*/
public static function updateMergeStats($cacheKeyString, $result = array()) {
// gather latest stats
$merged = count($result['merged']);
$skipped = count($result['skipped']);
if ($merged <= 0 && $skipped <= 0) {
return;
}
// get previous stats
$previousStats = CRM_Core_BAO_PrevNextCache::retrieve("{$cacheKeyString}_stats");
if (!empty($previousStats)) {
if ($previousStats[0]['merged']) {
$merged = $merged + $previousStats[0]['merged'];
}
if ($previousStats[0]['skipped']) {
$skipped = $skipped + $previousStats[0]['skipped'];
}
}
// delete old stats
CRM_Dedupe_Merger::resetMergeStats($cacheKeyString);
// store the updated stats
$data = array(
'merged' => $merged,
'skipped' => $skipped,
);
$data = CRM_Core_DAO::escapeString(serialize($data));
$values = array();
$values[] = " ( 'civicrm_contact', 0, 0, '{$cacheKeyString}_stats', '$data' ) ";
CRM_Core_BAO_PrevNextCache::setItem($values);
}
/**
* Delete information about merges for the given string.
*
* @param $cacheKeyString
*/
public static function resetMergeStats($cacheKeyString) {
CRM_Core_BAO_PrevNextCache::deleteItem(NULL, "{$cacheKeyString}_stats");
}
/**
* Get merge outcome statistics.
*
* @param string $cacheKeyString
*
* @return array
* Array of how many were merged and how many were skipped.
*/
public static function getMergeStats($cacheKeyString) {
$stats = CRM_Core_BAO_PrevNextCache::retrieve("{$cacheKeyString}_stats");
if (!empty($stats)) {
$stats = $stats[0];
}
return $stats;
}
/**
* Get merge statistics message.
*
* @param string $cacheKeyString
*
* @return string
*/
public static function getMergeStatsMsg($cacheKeyString) {
$msg = '';
$stats = CRM_Dedupe_Merger::getMergeStats($cacheKeyString);
if (!empty($stats['merged'])) {
$msg = "{$stats['merged']} " . ts('Contact(s) were merged.');
}
if (!empty($stats['skipped'])) {
$msg .= $stats['skipped'] . ts(' Contact(s) were skipped.');
}
return $msg;
}
/**
* Merge given set of contacts. Performs core operation.
*
* @param array $dupePairs
* Set of pair of contacts for whom merge is to be done.
* @param array $cacheParams
* Prev-next-cache params based on which next pair of contacts are computed.
* Generally used with batch-merge.
* @param string $mode
* Helps decide how to behave when there are conflicts.
* A 'safe' value skips the merge if there are any un-resolved conflicts.
* Does a force merge otherwise (aggressive mode).
*
* @param bool $redirectForPerformance
* Redirect to a url for batch processing.
*
* @param bool $checkPermissions
* Respect logged in user permissions.
*
* @return array|bool
*/
public static function merge($dupePairs = array(), $cacheParams = array(), $mode = 'safe',
$redirectForPerformance = FALSE, $checkPermissions = TRUE
) {
$cacheKeyString = CRM_Utils_Array::value('cache_key_string', $cacheParams);
$resultStats = array('merged' => array(), 'skipped' => array());
// we don't want dupe caching to get reset after every-merge, and therefore set the
// doNotResetCache flag
$config = CRM_Core_Config::singleton();
$config->doNotResetCache = 1;
$deletedContacts = array();
while (!empty($dupePairs)) {
foreach ($dupePairs as $index => $dupes) {
if (in_array($dupes['dstID'], $deletedContacts) || in_array($dupes['srcID'], $deletedContacts)) {
unset($dupePairs[$index]);
continue;
}
CRM_Utils_Hook::merge('flip', $dupes, $dupes['dstID'], $dupes['srcID']);
$mainId = $dupes['dstID'];
$otherId = $dupes['srcID'];
if (!$mainId || !$otherId) {
// return error
return FALSE;
}
// Generate var $migrationInfo. The variable structure is exactly same as
// $formValues submitted during a UI merge for a pair of contacts.
$rowsElementsAndInfo = CRM_Dedupe_Merger::getRowsElementsAndInfo($mainId, $otherId, $checkPermissions);
// add additional details that we might need to resolve conflicts
$rowsElementsAndInfo['migration_info']['main_details'] = &$rowsElementsAndInfo['main_details'];
$rowsElementsAndInfo['migration_info']['other_details'] = &$rowsElementsAndInfo['other_details'];
$rowsElementsAndInfo['migration_info']['rows'] = &$rowsElementsAndInfo['rows'];
self::dedupePair($rowsElementsAndInfo['migration_info'], $resultStats, $deletedContacts, $mode, $checkPermissions, $mainId, $otherId, $cacheKeyString);
}
if ($cacheKeyString && !$redirectForPerformance) {
// retrieve next pair of dupes
// @todo call getDuplicatePairs.
$dupePairs = CRM_Core_BAO_PrevNextCache::retrieve($cacheKeyString,
$cacheParams['join'],
$cacheParams['where'],
0,
0,
array(),
'',
FALSE
);
}
else {
// do not proceed. Terminate the loop
unset($dupePairs);
}
}
CRM_Dedupe_Merger::updateMergeStats($cacheKeyString, $resultStats);
return $resultStats;
}
/**
* A function which uses various rules / algorithms for choosing which contact to bias to
* when there's a conflict (to handle "gotchas"). Plus the safest route to merge.
*
* @param int $mainId
* Main contact with whom merge has to happen.
* @param int $otherId
* Duplicate contact which would be deleted after merge operation.
* @param array $migrationInfo
* Array of information about which elements to merge.
* @param string $mode
* Helps decide how to behave when there are conflicts.
* - A 'safe' value skips the merge if there are any un-resolved conflicts.
* - Does a force merge otherwise (aggressive mode).
*
* @param array $conflicts
*
* @return bool
*/
public static function skipMerge($mainId, $otherId, &$migrationInfo, $mode = 'safe', &$conflicts = array()) {
$originalMigrationInfo = $migrationInfo;
foreach ($migrationInfo as $key => $val) {
if ($val === "null") {
// Rule: Never overwrite with an empty value (in any mode)
unset($migrationInfo[$key]);
continue;
}
elseif ((in_array(substr($key, 5), CRM_Dedupe_Merger::getContactFields()) or
substr($key, 0, 12) == 'move_custom_'
) and $val != NULL
) {
// Rule: If both main-contact, and other-contact have a field with a
// different value, then let $mode decide if to merge it or not
if (
(!empty($migrationInfo['rows'][$key]['main'])
// For custom fields a 0 (e.g in an int field) could be a true conflict. This
// is probably true for other fields too - e.g. 'do_not_email' but
// leaving that investigation as a @todo - until tests can be written.
// Note the handling of this has test coverage - although the data-typing
// of '0' feels flakey we have insurance.
|| ($migrationInfo['rows'][$key]['main'] === '0' && substr($key, 0, 12) == 'move_custom_')
)
&& $migrationInfo['rows'][$key]['main'] != $migrationInfo['rows'][$key]['other']
) {
// note it down & lets wait for response from the hook.
// For no response $mode will decide if to skip this merge
$conflicts[$key] = NULL;
}
}
elseif (substr($key, 0, 14) == 'move_location_' and $val != NULL) {
$locField = explode('_', $key);
$fieldName = $locField[2];
$fieldCount = $locField[3];
// Rule: Catch address conflicts (same address type on both contacts)
if (
isset($migrationInfo['main_details']['location_blocks'][$fieldName]) &&
!empty($migrationInfo['main_details']['location_blocks'][$fieldName])
) {
// Load the address we're inspecting from the 'other' contact
$addressRecord = $migrationInfo['other_details']['location_blocks'][$fieldName][$fieldCount];
$addressRecordLocTypeId = CRM_Utils_Array::value('location_type_id', $addressRecord);
// If it exists on the 'main' contact already, skip it. Otherwise
// if the location type exists already, log a conflict.
foreach ($migrationInfo['main_details']['location_blocks'][$fieldName] as $mainAddressKey => $mainAddressRecord) {
if (self::locationIsSame($addressRecord, $mainAddressRecord)) {
unset($migrationInfo[$key]);
break;
}
elseif ($addressRecordLocTypeId == $mainAddressRecord['location_type_id']) {
$conflicts[$key] = NULL;
break;
}
}
}
// For other locations, don't merge/add if the values are the same
elseif (CRM_Utils_Array::value('main', $migrationInfo['rows'][$key]) == $migrationInfo['rows'][$key]['other']) {
unset($migrationInfo[$key]);
}
}
}
// A hook to implement other algorithms for choosing which contact to bias to when
// there's a conflict (to handle "gotchas"). fields_in_conflict could be modified here
// merge happens with new values filled in here. For a particular field / row not to be merged
// field should be unset from fields_in_conflict.
$migrationData = array(
'old_migration_info' => $originalMigrationInfo,
'mode' => $mode,
'fields_in_conflict' => $conflicts,
'merge_mode' => $mode,
'migration_info' => $migrationInfo,
);
CRM_Utils_Hook::merge('batch', $migrationData, $mainId, $otherId);
$conflicts = $migrationData['fields_in_conflict'];
// allow hook to override / manipulate migrationInfo as well
$migrationInfo = $migrationData['migration_info'];
if (!empty($conflicts)) {
foreach ($conflicts as $key => $val) {
if ($val === NULL and $mode == 'safe') {
// un-resolved conflicts still present. Lets skip this merge after saving the conflict / reason.
return TRUE;
}
else {
// copy over the resolved values
$migrationInfo[$key] = $val;
}
}
// if there are conflicts and mode is aggressive, allow hooks to decide if to skip merges
if (array_key_exists('skip_merge', $migrationData)) {
return (bool) $migrationData['skip_merge'];
}
}
return FALSE;
}
/**
* Compare 2 addresses to see if they are the same.
*
* @param array $mainAddress
* @param array $comparisonAddress
*
* @return bool
*/
static public function locationIsSame($mainAddress, $comparisonAddress) {
$keysToIgnore = array('id', 'is_primary', 'is_billing', 'manual_geo_code', 'contact_id', 'reset_date', 'hold_date');
foreach ($comparisonAddress as $field => $value) {
if (in_array($field, $keysToIgnore)) {
continue;
}
if ((!empty($value) || $value === '0') && isset($mainAddress[$field]) && $mainAddress[$field] != $value) {
return FALSE;
}