-
-
Notifications
You must be signed in to change notification settings - Fork 824
/
Relationship.php
2440 lines (2217 loc) · 90.1 KB
/
Relationship.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 |
+--------------------------------------------------------------------+
*/
/**
* Class CRM_Contact_BAO_Relationship.
*/
class CRM_Contact_BAO_Relationship extends CRM_Contact_DAO_Relationship {
/**
* Various constants to indicate different type of relationships.
*
* @var int
*/
const ALL = 0, PAST = 1, DISABLED = 2, CURRENT = 4, INACTIVE = 8;
/**
* Constants for is_permission fields.
* Note: the slightly non-obvious ordering is due to history...
*/
const NONE = 0, EDIT = 1, VIEW = 2;
/**
* The list of column headers
* @var array
*/
private static $columnHeaders;
/**
* Create function - use the API instead.
*
* Note that the previous create function has been renamed 'legacyCreateMultiple'
* and this is new in 4.6
* All existing calls have been changed to legacyCreateMultiple except the api call - however, it is recommended
* that you call that as the end to end testing here is based on the api & refactoring may still be done.
*
* @param array $params
*
* @return \CRM_Contact_BAO_Relationship
* @throws \CRM_Core_Exception
*/
public static function create(&$params) {
$extendedParams = self::loadExistingRelationshipDetails($params);
// When id is specified we always wan't to update, so we don't need to
// check for duplicate relations.
if (!isset($params['id']) && self::checkDuplicateRelationship($extendedParams, $extendedParams['contact_id_a'], $extendedParams['contact_id_b'], CRM_Utils_Array::value('id', $extendedParams, 0))) {
throw new CRM_Core_Exception('Duplicate Relationship');
}
$params = $extendedParams;
if (self::checkValidRelationship($params, $params, 0)) {
throw new CRM_Core_Exception('Invalid Relationship');
}
$relationship = self::add($params);
if (!empty($params['contact_id_a'])) {
$ids = [
'contactTarget' => $relationship->contact_id_b,
'contact' => $params['contact_id_a'],
];
//CRM-16087 removed additional call to function relatedMemberships which is already called by disableEnableRelationship
//resulting in membership being created twice
if (array_key_exists('is_active', $params) && empty($params['is_active'])) {
$action = CRM_Core_Action::DISABLE;
$active = FALSE;
}
else {
$action = CRM_Core_Action::ENABLE;
$active = TRUE;
}
$id = empty($params['id']) ? $relationship->id : $params['id'];
self::disableEnableRelationship($id, $action, $params, $ids, $active);
}
if (empty($params['skipRecentView'])) {
self::addRecent($params, $relationship);
}
return $relationship;
}
/**
* Create multiple relationships for one contact.
*
* The relationship details are the same for each relationship except the secondary contact
* id can be an array.
*
* @param array $params
* Parameters for creating multiple relationships.
* The parameters are the same as for relationship create function except that the non-primary
* end of the relationship should be an array of one or more contact IDs.
* @param string $primaryContactLetter
* a or b to denote the primary contact for this action. The secondary may be multiple contacts
* and should be an array.
*
* @return array
* @throws \CRM_Core_Exception
*/
public static function createMultiple($params, $primaryContactLetter) {
$secondaryContactLetter = ($primaryContactLetter == 'a') ? 'b' : 'a';
$secondaryContactIDs = $params['contact_id_' . $secondaryContactLetter];
$valid = $invalid = $duplicate = $saved = 0;
$relationshipIDs = [];
foreach ($secondaryContactIDs as $secondaryContactID) {
try {
$params['contact_id_' . $secondaryContactLetter] = $secondaryContactID;
$relationship = civicrm_api3('relationship', 'create', $params);
$relationshipIDs[] = $relationship['id'];
$valid++;
}
catch (CiviCRM_API3_Exception $e) {
switch ($e->getMessage()) {
case 'Duplicate Relationship':
$duplicate++;
break;
case 'Invalid Relationship':
$invalid++;
break;
default:
throw new CRM_Core_Exception('unknown relationship create error ' . $e->getMessage());
}
}
}
return [
'valid' => $valid,
'invalid' => $invalid,
'duplicate' => $duplicate,
'saved' => $saved,
'relationship_ids' => $relationshipIDs,
];
}
/**
* Takes an associative array and creates a relationship object.
*
* @deprecated For single creates use the api instead (it's tested).
* For multiple a new variant of this function needs to be written and migrated to as this is a bit
* nasty
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $ids
* The array that holds all the db ids.
* per http://wiki.civicrm.org/confluence/display/CRM/Database+layer
* "we are moving away from the $ids param "
*
* @return array
* @throws \CRM_Core_Exception
*/
public static function legacyCreateMultiple(&$params, $ids = []) {
$valid = $invalid = $duplicate = $saved = 0;
$relationships = $relationshipIds = [];
$relationshipId = CRM_Utils_Array::value('relationship', $ids, CRM_Utils_Array::value('id', $params));
//CRM-9015 - the hooks are called here & in add (since add doesn't call create)
// but in future should be tidied per ticket
if (empty($relationshipId)) {
$hook = 'create';
}
else {
$hook = 'edit';
}
// @todo pre hook is called from add - remove it from here
CRM_Utils_Hook::pre($hook, 'Relationship', $relationshipId, $params);
if (!$relationshipId) {
// creating a new relationship
$dataExists = self::dataExists($params);
if (!$dataExists) {
return [FALSE, TRUE, FALSE, FALSE, NULL];
}
$relationshipIds = [];
foreach ($params['contact_check'] as $key => $value) {
// check if the relationship is valid between contacts.
// step 1: check if the relationship is valid if not valid skip and keep the count
// step 2: check the if two contacts already have a relationship if yes skip and keep the count
// step 3: if valid relationship then add the relation and keep the count
// step 1
$contactFields = self::setContactABFromIDs($params, $ids, $key);
$errors = self::checkValidRelationship($contactFields, $ids, $key);
if ($errors) {
$invalid++;
continue;
}
//CRM-16978:check duplicate relationship as per case id.
if ($caseId = CRM_Utils_Array::value('case_id', $params)) {
$contactFields['case_id'] = $caseId;
}
if (
self::checkDuplicateRelationship(
$contactFields,
CRM_Utils_Array::value('contact', $ids),
// step 2
$key
)
) {
$duplicate++;
continue;
}
$singleInstanceParams = array_merge($params, $contactFields);
$relationship = self::add($singleInstanceParams);
$relationshipIds[] = $relationship->id;
$relationships[$relationship->id] = $relationship;
$valid++;
}
// editing the relationship
}
else {
// check for duplicate relationship
// @todo this code doesn't cope well with updates - causes e-Notices.
// API has a lot of code to work around
// this but should review this code & remove the extra handling from the api
// it seems doubtful any of this is relevant if the contact fields & relationship
// type fields are not set
if (
self::checkDuplicateRelationship(
$params,
CRM_Utils_Array::value('contact', $ids),
$ids['contactTarget'],
$relationshipId
)
) {
$duplicate++;
return [$valid, $invalid, $duplicate, $saved, NULL];
}
$validContacts = TRUE;
//validate contacts in update mode also.
$contactFields = self::setContactABFromIDs($params, $ids, $ids['contactTarget']);
if (!empty($ids['contact']) && !empty($ids['contactTarget'])) {
if (self::checkValidRelationship($contactFields, $ids, $ids['contactTarget'])) {
$validContacts = FALSE;
$invalid++;
}
}
if ($validContacts) {
// editing an existing relationship
$singleInstanceParams = array_merge($params, $contactFields);
$relationship = self::add($singleInstanceParams, $ids, $ids['contactTarget']);
$relationshipIds[] = $relationship->id;
$relationships[$relationship->id] = $relationship;
$saved++;
}
}
// do not add to recent items for import, CRM-4399
if (!(!empty($params['skipRecentView']) || $invalid || $duplicate)) {
self::addRecent($params, $relationship);
}
return [$valid, $invalid, $duplicate, $saved, $relationshipIds, $relationships];
}
/**
* This is the function that check/add if the relationship created is valid.
*
* @param array $params
* Array of name/value pairs.
* @param array $ids
* The array that holds all the db ids.
* @param int $contactId
* This is contact id for adding relationship.
*
* @return CRM_Contact_BAO_Relationship
*
* @throws \CiviCRM_API3_Exception
*/
public static function add($params, $ids = [], $contactId = NULL) {
$params['id'] = CRM_Utils_Array::value('relationship', $ids, CRM_Utils_Array::value('id', $params));
$hook = 'create';
if ($params['id']) {
$hook = 'edit';
}
CRM_Utils_Hook::pre($hook, 'Relationship', $params['id'], $params);
$relationshipTypes = $params['relationship_type_id'] ?? NULL;
// explode the string with _ to get the relationship type id
// and to know which contact has to be inserted in
// contact_id_a and which one in contact_id_b
list($relationshipTypeID) = explode('_', $relationshipTypes);
$relationship = new CRM_Contact_BAO_Relationship();
if (!empty($params['id'])) {
$relationship->id = $params['id'];
// Only load the relationship if we're missing required params
$requiredParams = ['contact_id_a', 'contact_id_b', 'relationship_type_id'];
foreach ($requiredParams as $requiredKey) {
if (!isset($params[$requiredKey])) {
$relationship->find(TRUE);
break;
}
}
}
$relationship->copyValues($params);
// @todo we could probably set $params['relationship_type_id'] above but it's unclear
// what that would do with the code below this. So for now be conservative and set it manually.
if (!empty($relationshipTypeID)) {
$relationship->relationship_type_id = $relationshipTypeID;
}
$params['contact_id_a'] = $relationship->contact_id_a;
$params['contact_id_b'] = $relationship->contact_id_b;
// check if the relationship type is Head of Household then update the
// household's primary contact with this contact.
try {
$headOfHouseHoldID = civicrm_api3('RelationshipType', 'getvalue', [
'return' => "id",
'name_a_b' => "Head of Household for",
]);
if ($relationshipTypeID == $headOfHouseHoldID) {
CRM_Contact_BAO_Household::updatePrimaryContact($relationship->contact_id_b, $relationship->contact_id_a);
}
}
catch (Exception $e) {
// No "Head of Household" relationship found so we skip specific processing
}
if (!empty($params['id']) && self::isCurrentEmployerNeedingToBeCleared($relationship->toArray(), $params['id'], $relationshipTypeID)) {
CRM_Contact_BAO_Contact_Utils::clearCurrentEmployer($relationship->contact_id_a);
}
$dateFields = ['end_date', 'start_date'];
foreach (self::getdefaults() as $defaultField => $defaultValue) {
if (isset($params[$defaultField])) {
if (in_array($defaultField, $dateFields)) {
$relationship->$defaultField = CRM_Utils_Date::format(CRM_Utils_Array::value($defaultField, $params));
if (!$relationship->$defaultField) {
$relationship->$defaultField = 'NULL';
}
}
else {
$relationship->$defaultField = $params[$defaultField];
}
}
elseif (empty($params['id'])) {
$relationship->$defaultField = $defaultValue;
}
}
$relationship->save();
// is_current_employer is an optional parameter that triggers updating the employer_id field to reflect
// the relationship being updated. As of writing only truthy versions of the parameter are respected.
// https://github.com/civicrm/civicrm-core/pull/13331 attempted to cover both but stalled in QA
// so currently we have a cut down version.
if (!empty($params['is_current_employer'])) {
if (!$relationship->relationship_type_id || !$relationship->contact_id_a || !$relationship->contact_id_b) {
$relationship->fetch();
}
if (self::isRelationshipTypeCurrentEmployer($relationship->relationship_type_id)) {
CRM_Contact_BAO_Contact_Utils::setCurrentEmployer([$relationship->contact_id_a => $relationship->contact_id_b]);
}
}
// add custom field values
if (!empty($params['custom'])) {
CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_relationship', $relationship->id);
}
CRM_Utils_Hook::post($hook, 'Relationship', $relationship->id, $relationship);
return $relationship;
}
/**
* Add relationship to recent links.
*
* @param array $params
* @param CRM_Contact_DAO_Relationship $relationship
*/
public static function addRecent($params, $relationship) {
$url = CRM_Utils_System::url('civicrm/contact/view/rel',
"action=view&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&context=home"
);
$session = CRM_Core_Session::singleton();
$recentOther = [];
if (($session->get('userID') == $relationship->contact_id_a) ||
CRM_Contact_BAO_Contact_Permission::allow($relationship->contact_id_a, CRM_Core_Permission::EDIT)
) {
$rType = substr(CRM_Utils_Array::value('relationship_type_id', $params), -3);
$recentOther = [
'editUrl' => CRM_Utils_System::url('civicrm/contact/view/rel',
"action=update&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
),
'deleteUrl' => CRM_Utils_System::url('civicrm/contact/view/rel',
"action=delete&reset=1&id={$relationship->id}&cid={$relationship->contact_id_a}&rtype={$rType}&context=home"
),
];
}
$title = CRM_Contact_BAO_Contact::displayName($relationship->contact_id_a) . ' (' . CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType',
$relationship->relationship_type_id, 'label_a_b'
) . ' ' . CRM_Contact_BAO_Contact::displayName($relationship->contact_id_b) . ')';
CRM_Utils_Recent::add($title,
$url,
$relationship->id,
'Relationship',
$relationship->contact_id_a,
NULL,
$recentOther
);
}
/**
* Load contact ids and relationship type id when doing a create call if not provided.
*
* There are are various checks done in create which require this information which is optional
* when using id.
*
* @param array $params
* Parameters passed to create call.
*
* @return array
* Parameters with missing fields added if required.
*/
public static function loadExistingRelationshipDetails($params) {
if (!empty($params['contact_id_a'])
&& !empty($params['contact_id_b'])
&& is_numeric($params['relationship_type_id'])) {
return $params;
}
if (empty($params['id'])) {
return $params;
}
$fieldsToFill = ['contact_id_a', 'contact_id_b', 'relationship_type_id'];
$result = CRM_Core_DAO::executeQuery("SELECT " . implode(',', $fieldsToFill) . " FROM civicrm_relationship WHERE id = %1", [
1 => [
$params['id'],
'Integer',
],
]);
while ($result->fetch()) {
foreach ($fieldsToFill as $field) {
$params[$field] = !empty($params[$field]) ? $params[$field] : $result->$field;
}
}
return $params;
}
/**
* Resolve passed in contact IDs to contact_id_a & contact_id_b.
*
* @param array $params
* @param array $ids
* @param null $contactID
*
* @return array
* @throws \CRM_Core_Exception
*/
public static function setContactABFromIDs($params, $ids = [], $contactID = NULL) {
$returnFields = [];
// $ids['contact'] is deprecated but comes from legacyCreateMultiple function.
if (empty($ids['contact'])) {
if (!empty($params['id'])) {
return self::loadExistingRelationshipDetails($params);
}
throw new CRM_Core_Exception('Cannot create relationship, insufficient contact IDs provided');
}
if (isset($params['relationship_type_id']) && !is_numeric($params['relationship_type_id'])) {
$relationshipTypes = $params['relationship_type_id'] ?? NULL;
list($relationshipTypeID, $first) = explode('_', $relationshipTypes);
$returnFields['relationship_type_id'] = $relationshipTypeID;
foreach (['a', 'b'] as $contactLetter) {
if (empty($params['contact_' . $contactLetter])) {
if ($first == $contactLetter) {
$returnFields['contact_id_' . $contactLetter] = $ids['contact'] ?? NULL;
}
else {
$returnFields['contact_id_' . $contactLetter] = $contactID;
}
}
}
}
return $returnFields;
}
/**
* Specify defaults for creating a relationship.
*
* @return array
* array of defaults for creating relationship
*/
public static function getdefaults() {
return [
'is_active' => 1,
'is_permission_a_b' => self::NONE,
'is_permission_b_a' => self::NONE,
'description' => '',
'start_date' => 'NULL',
'case_id' => NULL,
'end_date' => 'NULL',
];
}
/**
* Check if there is data to create the object.
*
* @param array $params
*
* @return bool
*/
public static function dataExists($params) {
return (isset($params['contact_check']) && is_array($params['contact_check']));
}
/**
* Get get list of relationship type based on the contact type.
*
* @param int $contactId
* This is the contact id of the current contact.
* @param null $contactSuffix
* @param string $relationshipId
* The id of the existing relationship if any.
* @param string $contactType
* Contact type.
* @param bool $all
* If true returns relationship types in both the direction.
* @param string $column
* Name/label that going to retrieve from db.
* @param bool $biDirectional
* @param array $contactSubType
* Includes relationship types between this subtype.
* @param bool $onlySubTypeRelationTypes
* If set only subtype which is passed by $contactSubType
* related relationship types get return
*
* @return array
* array reference of all relationship types with context to current contact.
*/
public static function getContactRelationshipType(
$contactId = NULL,
$contactSuffix = NULL,
$relationshipId = NULL,
$contactType = NULL,
$all = FALSE,
$column = 'label',
$biDirectional = TRUE,
$contactSubType = NULL,
$onlySubTypeRelationTypes = FALSE
) {
$relationshipType = [];
$allRelationshipType = CRM_Core_PseudoConstant::relationshipType($column);
$otherContactType = NULL;
if ($relationshipId) {
$relationship = new CRM_Contact_DAO_Relationship();
$relationship->id = $relationshipId;
if ($relationship->find(TRUE)) {
$contact = new CRM_Contact_DAO_Contact();
$contact->id = ($relationship->contact_id_a == $contactId) ? $relationship->contact_id_b : $relationship->contact_id_a;
if ($contact->find(TRUE)) {
$otherContactType = $contact->contact_type;
//CRM-5125 for contact subtype specific relationshiptypes
if ($contact->contact_sub_type) {
$otherContactSubType = $contact->contact_sub_type;
}
}
}
}
$contactSubType = (array) $contactSubType;
if ($contactId) {
$contactType = CRM_Contact_BAO_Contact::getContactType($contactId);
$contactSubType = CRM_Contact_BAO_Contact::getContactSubType($contactId);
}
foreach ($allRelationshipType as $key => $value) {
// the contact type is required or matches
if (((!$value['contact_type_a']) ||
$value['contact_type_a'] == $contactType
) &&
// the other contact type is required or present or matches
((!$value['contact_type_b']) ||
(!$otherContactType) ||
$value['contact_type_b'] == $otherContactType
) &&
(in_array($value['contact_sub_type_a'], $contactSubType) ||
(!$value['contact_sub_type_a'] && !$onlySubTypeRelationTypes)
)
) {
$relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
}
if (((!$value['contact_type_b']) ||
$value['contact_type_b'] == $contactType
) &&
((!$value['contact_type_a']) ||
(!$otherContactType) ||
$value['contact_type_a'] == $otherContactType
) &&
(in_array($value['contact_sub_type_b'], $contactSubType) ||
(!$value['contact_sub_type_b'] && !$onlySubTypeRelationTypes)
)
) {
$relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
}
if ($all) {
$relationshipType[$key . '_a_b'] = $value["{$column}_a_b"];
$relationshipType[$key . '_b_a'] = $value["{$column}_b_a"];
}
}
if ($biDirectional) {
$relationshipType = self::removeRelationshipTypeDuplicates($relationshipType, $contactSuffix);
}
// sort the relationshipType in ascending order CRM-7736
asort($relationshipType);
return $relationshipType;
}
/**
* Given a list of relationship types, return the list with duplicate types
* removed, being careful to retain only the duplicate which matches the given
* 'a_b' or 'b_a' suffix.
*
* @param array $relationshipTypeList A list of relationship types, in the format
* returned by self::getContactRelationshipType().
* @param string $suffix Either 'a_b' or 'b_a'; defaults to 'a_b'
*
* @return array The modified value of $relationshipType
*/
public static function removeRelationshipTypeDuplicates($relationshipTypeList, $suffix = NULL) {
if (empty($suffix)) {
$suffix = 'a_b';
}
// Find those labels which are listed more than once.
$duplicateValues = array_diff_assoc($relationshipTypeList, array_unique($relationshipTypeList));
// For each duplicate label, find its keys, and remove from $relationshipType
// the key which does not match $suffix.
foreach ($duplicateValues as $value) {
$keys = array_keys($relationshipTypeList, $value);
foreach ($keys as $key) {
if (substr($key, -3) != $suffix) {
unset($relationshipTypeList[$key]);
}
}
}
return $relationshipTypeList;
}
/**
* Delete current employer relationship.
*
* @param int $id
* @param int $action
*
* @return CRM_Contact_DAO_Relationship
*/
public static function clearCurrentEmployer($id, $action) {
$relationship = new CRM_Contact_DAO_Relationship();
$relationship->id = $id;
$relationship->find(TRUE);
//to delete relationship between household and individual \
//or between individual and organization
if (($action & CRM_Core_Action::DISABLE) || ($action & CRM_Core_Action::DELETE)) {
$relTypes = CRM_Utils_Array::index(['name_a_b'], CRM_Core_PseudoConstant::relationshipType('name'));
if (
(isset($relTypes['Employee of']) && $relationship->relationship_type_id == $relTypes['Employee of']['id']) ||
(isset($relTypes['Household Member of']) && $relationship->relationship_type_id == $relTypes['Household Member of']['id'])
) {
$sharedContact = new CRM_Contact_DAO_Contact();
$sharedContact->id = $relationship->contact_id_a;
$sharedContact->find(TRUE);
// CRM-15881 UPDATES
// changed FROM "...relationship->relationship_type_id == 4..." TO "...relationship->relationship_type_id == 5..."
// As the system should be looking for type "employer of" (id 5) and not "sibling of" (id 4)
// As suggested by @davecivicrm, the employee relationship type id is fetched using the CRM_Core_DAO::getFieldValue() class and method, since these ids differ from system to system.
$employerRelTypeId = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b');
if ($relationship->relationship_type_id == $employerRelTypeId && $relationship->contact_id_b == $sharedContact->employer_id) {
CRM_Contact_BAO_Contact_Utils::clearCurrentEmployer($relationship->contact_id_a);
}
}
}
return $relationship;
}
/**
* Delete the relationship.
*
* @param int $id
* Relationship id.
*
* @return CRM_Contact_DAO_Relationship
*
* @throws \CRM_Core_Exception
* @throws \CiviCRM_API3_Exception
*/
public static function del($id) {
// delete from relationship table
CRM_Utils_Hook::pre('delete', 'Relationship', $id, CRM_Core_DAO::$_nullArray);
$relationship = self::clearCurrentEmployer($id, CRM_Core_Action::DELETE);
$relationship->delete();
if (CRM_Core_Permission::access('CiviMember')) {
// create $params array which isrequired to delete memberships
// of the related contacts.
$params = [
'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
'contact_check' => [$relationship->contact_id_b => 1],
];
$ids = [];
// calling relatedMemberships to delete the memberships of
// related contacts.
self::relatedMemberships($relationship->contact_id_a,
$params,
$ids,
CRM_Core_Action::DELETE,
FALSE
);
}
CRM_Core_Session::setStatus(ts('Selected relationship has been deleted successfully.'), ts('Record Deleted'), 'success');
CRM_Utils_Hook::post('delete', 'Relationship', $id, $relationship);
// delete the recently created Relationship
$relationshipRecent = [
'id' => $id,
'type' => 'Relationship',
];
CRM_Utils_Recent::del($relationshipRecent);
return $relationship;
}
/**
* Disable/enable the relationship.
*
* @param int $id
* Relationship id.
*
* @param int $action
* @param array $params
* @param array $ids
* @param bool $active
*
* @throws \CRM_Core_Exception
* @throws \CiviCRM_API3_Exception
*/
public static function disableEnableRelationship($id, $action, $params = [], $ids = [], $active = FALSE) {
$relationship = self::clearCurrentEmployer($id, $action);
if ($id) {
// create $params array which is required to delete memberships
// of the related contacts.
if (empty($params)) {
$params = [
'relationship_type_id' => "{$relationship->relationship_type_id}_a_b",
'contact_check' => [$relationship->contact_id_b => 1],
];
}
$contact_id_a = empty($params['contact_id_a']) ? $relationship->contact_id_a : $params['contact_id_a'];
// calling relatedMemberships to delete/add the memberships of
// related contacts.
if ($action & CRM_Core_Action::DISABLE) {
// @todo this could call a subset of the function that just relates to
// cleaning up no-longer-inherited relationships
CRM_Contact_BAO_Relationship::relatedMemberships($contact_id_a,
$params,
$ids,
CRM_Core_Action::DELETE,
$active
);
}
elseif ($action & CRM_Core_Action::ENABLE) {
$ids['contact'] = empty($ids['contact']) ? $contact_id_a : $ids['contact'];
CRM_Contact_BAO_Relationship::relatedMemberships($contact_id_a,
$params,
$ids,
empty($params['id']) ? CRM_Core_Action::ADD : CRM_Core_Action::UPDATE,
$active
);
}
}
}
/**
* Delete the object records that are associated with this contact.
*
* @param int $contactId
* Id of the contact to delete.
*/
public static function deleteContact($contactId) {
$relationship = new CRM_Contact_DAO_Relationship();
$relationship->contact_id_a = $contactId;
$relationship->delete();
$relationship = new CRM_Contact_DAO_Relationship();
$relationship->contact_id_b = $contactId;
$relationship->delete();
CRM_Contact_BAO_Household::updatePrimaryContact(NULL, $contactId);
}
/**
* Get the other contact in a relationship.
*
* @param int $id
* Relationship id.
*
* $returns returns the contact ids in the relationship
*
* @return \CRM_Contact_DAO_Relationship
*/
public static function getRelationshipByID($id) {
$relationship = new CRM_Contact_DAO_Relationship();
$relationship->id = $id;
$relationship->selectAdd();
$relationship->selectAdd('contact_id_a, contact_id_b');
$relationship->find(TRUE);
return $relationship;
}
/**
* Check if the relationship type selected between two contacts is correct.
*
* @param int $contact_a
* 1st contact id.
* @param int $contact_b
* 2nd contact id.
* @param int $relationshipTypeId
* Relationship type id.
*
* @return bool
* true if it is valid relationship else false
*/
public static function checkRelationshipType($contact_a, $contact_b, $relationshipTypeId) {
$relationshipType = new CRM_Contact_DAO_RelationshipType();
$relationshipType->id = $relationshipTypeId;
$relationshipType->selectAdd();
$relationshipType->selectAdd('contact_type_a, contact_type_b, contact_sub_type_a, contact_sub_type_b');
if ($relationshipType->find(TRUE)) {
$contact_type_a = CRM_Contact_BAO_Contact::getContactType($contact_a);
$contact_type_b = CRM_Contact_BAO_Contact::getContactType($contact_b);
$contact_sub_type_a = CRM_Contact_BAO_Contact::getContactSubType($contact_a);
$contact_sub_type_b = CRM_Contact_BAO_Contact::getContactSubType($contact_b);
if (((!$relationshipType->contact_type_a) || ($relationshipType->contact_type_a == $contact_type_a)) &&
((!$relationshipType->contact_type_b) || ($relationshipType->contact_type_b == $contact_type_b)) &&
((!$relationshipType->contact_sub_type_a) || (in_array($relationshipType->contact_sub_type_a,
$contact_sub_type_a
))) &&
((!$relationshipType->contact_sub_type_b) || (in_array($relationshipType->contact_sub_type_b,
$contact_sub_type_b
)))
) {
return TRUE;
}
else {
return FALSE;
}
}
return FALSE;
}
/**
* This function does the validtion for valid relationship.
*
* @param array $params
* This array contains the values there are subitted by the form.
* @param array $ids
* The array that holds all the db ids.
* @param int $contactId
* This is contact id for adding relationship.
*
* @return string
*/
public static function checkValidRelationship($params, $ids, $contactId) {
$errors = '';
// function to check if the relationship selected is correct
// i.e. employer relationship can exit between Individual and Organization (not between Individual and Individual)
if (!CRM_Contact_BAO_Relationship::checkRelationshipType($params['contact_id_a'], $params['contact_id_b'],
$params['relationship_type_id'])) {
$errors = 'Please select valid relationship between these two contacts.';
}
return $errors;
}
/**
* This function checks for duplicate relationship.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param int $id
* This the id of the contact whom we are adding relationship.
* @param int $contactId
* This is contact id for adding relationship.
* @param int $relationshipId
* This is relationship id for the contact.
*
* @return bool
* true if record exists else false
*/
public static function checkDuplicateRelationship(&$params, $id, $contactId = 0, $relationshipId = 0) {
$relationshipTypeId = $params['relationship_type_id'] ?? NULL;
list($type) = explode('_', $relationshipTypeId);
$queryString = "
SELECT id
FROM civicrm_relationship
WHERE relationship_type_id = " . CRM_Utils_Type::escape($type, 'Integer');
/*
* CRM-11792 - date fields from API are in ISO format, but this function
* supports date arrays BAO has increasingly standardised to ISO format
* so I believe this function should support ISO rather than make API
* format it - however, need to support array format for now to avoid breakage
* @ time of writing this function is called from Relationship::legacyCreateMultiple (twice)
* CRM_BAO_Contact_Utils::clearCurrentEmployer (seemingly without dates)
* CRM_Contact_Form_Task_AddToOrganization::postProcess &
* CRM_Contact_Form_Task_AddToHousehold::postProcess
* (I don't think the last 2 support dates but not sure
*/
$dateFields = ['end_date', 'start_date'];
foreach ($dateFields as $dateField) {
if (array_key_exists($dateField, $params)) {
if (empty($params[$dateField]) || $params[$dateField] == 'null') {
//this is most likely coming from an api call & probably loaded
// from the DB to deal with some of the
// other myriad of excessive checks still in place both in
// the api & the create functions
$queryString .= " AND $dateField IS NULL";
continue;
}
elseif (is_array($params[$dateField])) {
$queryString .= " AND $dateField = " .
CRM_Utils_Type::escape(CRM_Utils_Date::format($params[$dateField]), 'Date');
}
else {
$queryString .= " AND $dateField = " .
CRM_Utils_Type::escape($params[$dateField], 'Date');
}
}
}
$queryString .=
" AND ( ( contact_id_a = " . CRM_Utils_Type::escape($id, 'Integer') .
" AND contact_id_b = " . CRM_Utils_Type::escape($contactId, 'Integer') .
" ) OR ( contact_id_a = " . CRM_Utils_Type::escape($contactId, 'Integer') .
" AND contact_id_b = " . CRM_Utils_Type::escape($id, 'Integer') . " ) ) ";
//if caseId is provided, include it duplicate checking.
if ($caseId = CRM_Utils_Array::value('case_id', $params)) {
$queryString .= " AND case_id = " . CRM_Utils_Type::escape($caseId, 'Integer');
}
if ($relationshipId) {
$queryString .= " AND id !=" . CRM_Utils_Type::escape($relationshipId, 'Integer');
}
$relationship = new CRM_Contact_BAO_Relationship();
$relationship->query($queryString);
while ($relationship->fetch()) {
// Check whether the custom field values are identical.
$result = self::checkDuplicateCustomFields($params, $relationship->id);
if ($result) {
return TRUE;
}
}
return FALSE;
}
/**
* this function checks whether the values of the custom fields in $params are
* the same as the values of the custom fields of the relation with given