-
-
Notifications
You must be signed in to change notification settings - Fork 825
/
Copy pathMembership.php
2772 lines (2492 loc) · 99.1 KB
/
Membership.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\API\Exception\UnauthorizedException;
use Civi\Api4\Membership;
use Civi\Api4\MembershipType;
/**
*
* @package CRM
* @copyright CiviCRM LLC https://civicrm.org/licensing
*/
class CRM_Member_BAO_Membership extends CRM_Member_DAO_Membership {
/**
* Static field for all the membership information that we can potentially import.
*
* @var array
*/
public static $_importableFields = NULL;
public static $_renewalActType = NULL;
public static $_signupActType = NULL;
/**
* Takes an associative array and creates a membership object.
*
* the function extracts all the params it needs to initialize the created
* membership object. The params array could contain additional unused name/value
* pairs
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
*
* @return CRM_Member_BAO_Membership
* @throws \CRM_Core_Exception
*/
public static function add(&$params) {
$oldStatus = $oldType = NULL;
if ($params['id']) {
CRM_Utils_Hook::pre('edit', 'Membership', $params['id'], $params);
}
else {
CRM_Utils_Hook::pre('create', 'Membership', NULL, $params);
}
$id = $params['id'];
// we do this after the hooks are called in case it has been altered
if ($id) {
$membershipObj = new CRM_Member_DAO_Membership();
$membershipObj->id = $id;
$membershipObj->find();
while ($membershipObj->fetch()) {
$oldStatus = $membershipObj->status_id;
$oldType = $membershipObj->membership_type_id;
}
}
if (array_key_exists('is_override', $params) && !$params['is_override']) {
$params['is_override'] = 'null';
}
$membership = new CRM_Member_BAO_Membership();
$membership->copyValues($params);
$membership->id = $id;
$membership->save();
if (empty($membership->contact_id) || empty($membership->status_id)) {
// this means we are in renewal mode and are just updating the membership
// record or this is an API update call and all fields are not present in the update record
// however the hooks don't care and want all data CRM-7784
$tempMembership = new CRM_Member_DAO_Membership();
$tempMembership->id = $membership->id;
$tempMembership->find(TRUE);
$membership = $tempMembership;
}
//get the log start date.
//it is set during renewal of membership.
$logStartDate = $params['log_start_date'] ?? NULL;
$logStartDate = ($logStartDate) ? CRM_Utils_Date::isoToMysql($logStartDate) : CRM_Utils_Date::isoToMysql($membership->start_date);
$values = self::getStatusANDTypeValues($membership->id);
$membershipLog = [
'membership_id' => $membership->id,
'status_id' => $membership->status_id,
'start_date' => $logStartDate,
'end_date' => CRM_Utils_Date::isoToMysql($membership->end_date),
'modified_date' => CRM_Utils_Time::date('Ymd'),
'membership_type_id' => $values[$membership->id]['membership_type_id'],
'max_related' => $membership->max_related,
];
if (!empty($params['modified_id'])) {
$membershipLog['modified_id'] = $params['modified_id'];
}
// If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
elseif (CRM_Core_Session::singleton()->get('userID')) {
$membershipLog['modified_id'] = CRM_Core_Session::singleton()->get('userID');
}
else {
$membershipLog['modified_id'] = $membership->contact_id;
}
CRM_Member_BAO_MembershipLog::add($membershipLog);
// reset the group contact cache since smart groups might be affected due to this
CRM_Contact_BAO_GroupContactCache::opportunisticCacheFlush();
$allStatus = CRM_Member_BAO_Membership::buildOptions('status_id', 'get');
$activityParams = [
'status_id' => $params['membership_activity_status'] ?? 'Completed',
];
if (in_array($allStatus[$membership->status_id], ['Pending', 'Grace'])) {
$activityParams['status_id'] = 'Scheduled';
}
$activityParams['status_id'] = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', $activityParams['status_id']);
$targetContactID = $membership->contact_id;
if (!empty($params['is_for_organization'])) {
// @todo - deprecate is_for_organization, require modified_id
$targetContactID = $params['modified_id'] ?? NULL;
}
// add custom field values
if (!empty($params['custom']) && is_array($params['custom'])
) {
CRM_Core_BAO_CustomValueTable::store($params['custom'], 'civicrm_membership', $membership->id);
}
if ($id) {
if ($membership->status_id != $oldStatus) {
CRM_Activity_BAO_Activity::addActivity($membership,
'Change Membership Status',
NULL,
[
'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
'source_contact_id' => $membershipLog['modified_id'],
'priority_id' => 'Normal',
]
);
}
if (isset($membership->membership_type_id) && $membership->membership_type_id != $oldType) {
$membershipTypes = CRM_Member_BAO_Membership::buildOptions('membership_type_id', 'get');
CRM_Activity_BAO_Activity::addActivity($membership,
'Change Membership Type',
NULL,
[
'subject' => "Type changed from {$membershipTypes[$oldType]} to {$membershipTypes[$membership->membership_type_id]}",
'source_contact_id' => $membershipLog['modified_id'],
'priority_id' => 'Normal',
]
);
}
foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
$activityParams['id'] = civicrm_api3('Activity', 'Get', [
'source_record_id' => $membership->id,
'activity_type_id' => $activityType,
'status_id' => 'Scheduled',
])['id'] ?? NULL;
// 1. Update Schedule Membership Signup/Renwal activity to completed on successful payment of pending membership
// 2. OR Create renewal activity scheduled if its membership renewal will be paid later
if (!empty($params['membership_activity_status']) && (!empty($activityParams['id']) || $activityType == 'Membership Renewal')) {
CRM_Activity_BAO_Activity::addActivity($membership, $activityType, $targetContactID, $activityParams);
break;
}
}
CRM_Utils_Hook::post('edit', 'Membership', $membership->id, $membership);
}
else {
CRM_Activity_BAO_Activity::addActivity($membership, 'Membership Signup', $targetContactID, $activityParams);
CRM_Utils_Hook::post('create', 'Membership', $membership->id, $membership);
}
return $membership;
}
/**
* Fetch the object and store the values in the values array.
*
* @param array $params
* Input parameters to find object.
* @param array $values
* Output values of the object.
* @param bool $active
* Return only memberships with an 'is_current_member' status.
*
* @return CRM_Member_BAO_Membership[]|null
*/
public static function getValues($params, &$values, $active = FALSE) {
if (empty($params)) {
return NULL;
}
$membership = new CRM_Member_BAO_Membership();
$membership->copyValues($params);
$membership->find();
$memberships = [];
while ($membership->fetch()) {
if ($active &&
(!CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus',
$membership->status_id,
'is_current_member'
))
) {
continue;
}
CRM_Core_DAO::storeValues($membership, $values[$membership->id]);
$memberships[$membership->id] = $membership;
}
return $memberships;
}
/**
* Takes an associative array and creates a membership object.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $ids
* Deprecated parameter The array that holds all the db ids.
*
* @return CRM_Member_BAO_Membership|CRM_Core_Error
* @throws \CRM_Core_Exception
*
* @throws CRM_Core_Exception
*/
public static function create(&$params, $ids = []) {
$isLifeTime = FALSE;
if (!empty($params['membership_type_id'])) {
$memTypeDetails = CRM_Member_BAO_MembershipType::getMembershipType($params['membership_type_id']);
$isLifeTime = $memTypeDetails['duration_unit'] === 'lifetime' ? TRUE : FALSE;
}
// always calculate status if is_override/skipStatusCal is not true.
// giving respect to is_override during import. CRM-4012
// To skip status calculation we should use 'skipStatusCal'.
// eg pay later membership, membership update cron CRM-3984
if (empty($params['skipStatusCal'])) {
$fieldsToLoad = [];
foreach (['start_date', 'end_date', 'join_date'] as $dateField) {
if (!empty($params[$dateField]) && $params[$dateField] !== 'null' && strpos($params[$dateField], date('Ymd', CRM_Utils_Time::strtotime(trim($params[$dateField])))) !== 0) {
$params[$dateField] = date('Ymd', CRM_Utils_Time::strtotime(trim($params[$dateField])));
// @todo enable this once core is using the api.
// CRM_Core_Error::deprecatedWarning('Relying on the BAO to clean up dates is deprecated. Call membership create via the api');
}
if (!empty($params['id']) && empty($params[$dateField]) && !($isLifeTime && $dateField == 'end_date')) {
$fieldsToLoad[] = $dateField;
}
}
if (!empty($fieldsToLoad)) {
$membership = civicrm_api3('Membership', 'getsingle', ['id' => $params['id'], 'return' => $fieldsToLoad]);
foreach ($fieldsToLoad as $fieldToLoad) {
$params[$fieldToLoad] = $membership[$fieldToLoad];
}
}
if (empty($params['id'])
&& (empty($params['start_date']) || empty($params['join_date']) || (empty($params['end_date']) && !$isLifeTime))) {
// This is a new membership, calculate the membership dates.
$calcDates = CRM_Member_BAO_MembershipType::getDatesForMembershipType(
$params['membership_type_id'],
$params['join_date'] ?? NULL,
$params['start_date'] ?? NULL,
$params['end_date'] ?? NULL,
$params['num_terms'] ?? 1
);
}
else {
$calcDates = [];
}
$params['start_date'] = empty($params['start_date']) ? ($calcDates['start_date'] ?? 'null') : $params['start_date'];
$params['end_date'] = empty($params['end_date']) ? ($calcDates['end_date'] ?? 'null') : $params['end_date'];
$params['join_date'] = empty($params['join_date']) ? ($calcDates['join_date'] ?? 'null') : $params['join_date'];
//fix for CRM-3570, during import exclude the statuses those having is_admin = 1
$excludeIsAdmin = $params['exclude_is_admin'] ?? FALSE;
//CRM-3724 always skip is_admin if is_override != true.
if (!$excludeIsAdmin && empty($params['is_override'])) {
$excludeIsAdmin = TRUE;
}
if (empty($params['status_id']) && empty($params['is_override'])) {
$calcStatus = CRM_Member_BAO_MembershipStatus::getMembershipStatusByDate($params['start_date'], $params['end_date'], $params['join_date'],
'now', $excludeIsAdmin, $params['membership_type_id'] ?? NULL, $params
);
if (empty($calcStatus)) {
throw new CRM_Core_Exception(ts("The membership cannot be saved because the status cannot be calculated for start_date: {$params['start_date']} end_date {$params['end_date']} join_date {$params['join_date']} as at " . CRM_Utils_Time::date('Y-m-d H:i:s')));
}
$params['status_id'] = $calcStatus['id'];
}
}
// data cleanup only: all verifications on number of related memberships are done upstream in:
// CRM_Member_BAO_Membership::createRelatedMemberships()
// CRM_Contact_BAO_Relationship::relatedMemberships()
if (!empty($params['owner_membership_id'])) {
unset($params['max_related']);
}
else {
// if membership allows related, default max_related to value in membership_type
if (!array_key_exists('max_related', $params) && !empty($params['membership_type_id'])) {
$membershipType = CRM_Member_BAO_MembershipType::getMembershipType($params['membership_type_id']);
if (isset($membershipType['relationship_type_id'])) {
$params['max_related'] = $membershipType['max_related'] ?? NULL;
}
}
}
$transaction = new CRM_Core_Transaction();
$params['id'] = $params['id'] ?? $ids['membership'] ?? NULL;
$membership = self::add($params);
if (is_a($membership, 'CRM_Core_Error')) {
$transaction->rollback();
return $membership;
}
$params['membership_id'] = $membership->id;
// For api v4 we skip all of this stuff. There is an expectation that v4 users either use
// the order api, or handle any financial / related processing themselves.
// Note that the processing below is fairly intertwined with core usage and in some places
// problematic or to be removed.
// Note the choice of 'version' as a parameter is to make it
// unavailable through apiv3.
// once we are rid of direct calls to the BAO::create from core
// we will deprecate this stuff into the v3 api.
if (($params['version'] ?? 0) !== 4) {
// @todo further cleanup required to remove use of $ids['contribution'] from here
if (isset($ids['membership'])) {
$contributionID = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipPayment',
$membership->id,
'contribution_id',
'membership_id'
);
// @todo this is a temporary step to removing $ids['contribution'] completely
if (empty($params['contribution_id']) && !empty($contributionID)) {
$params['contribution_id'] = $contributionID;
}
}
// This code ensures a line item is created but it is recommended you pass in 'skipLineItem' or 'line_item'
if (empty($params['line_item']) && !empty($params['membership_type_id']) && empty($params['skipLineItem'])) {
CRM_Price_BAO_LineItem::getLineItemArray($params, NULL, 'membership', $params['membership_type_id']);
}
$params['skipLineItem'] = TRUE;
// Record contribution for this membership and create a MembershipPayment
// @todo deprecate this.
if (!empty($params['contribution_status_id'])) {
$memInfo = array_merge($params, ['membership_id' => $membership->id]);
$params['contribution'] = self::recordMembershipContribution($memInfo);
}
// If the membership has no associated contribution then we ensure
// the line items are 'correct' here. This is a lazy legacy
// hack whereby they are deleted and recreated
if (empty($contributionID)) {
if (!empty($params['lineItems'])) {
$params['line_item'] = $params['lineItems'];
}
// do cleanup line items if membership edit the Membership type.
if (!empty($ids['membership'])) {
CRM_Price_BAO_LineItem::deleteLineItems($ids['membership'], 'civicrm_membership');
}
// @todo - we should ONLY do the below if a contribution is created. Let's
// get some deprecation notices in here & see where it's hit & work to eliminate.
// This could happen if there is no contribution or we are in one of many
// weird and wonderful flows. This is scary code. Keep adding tests.
if (!empty($params['line_item']) && empty($params['contribution_id'])) {
foreach ($params['line_item'] as $priceSetId => $lineItems) {
foreach ($lineItems as $lineIndex => $lineItem) {
$lineMembershipType = $lineItem['membership_type_id'] ?? NULL;
if (!empty($params['contribution'])) {
$params['line_item'][$priceSetId][$lineIndex]['contribution_id'] = $params['contribution']->id;
}
if ($lineMembershipType && $lineMembershipType == ($params['membership_type_id'] ?? NULL)) {
$params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $membership->id;
$params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_membership';
}
elseif (!$lineMembershipType && !empty($params['contribution'])) {
$params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $params['contribution']->id;
$params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_contribution';
}
}
}
CRM_Price_BAO_LineItem::processPriceSet(
$membership->id,
$params['line_item'],
$params['contribution'] ?? NULL
);
}
}
}
$transaction->commit();
self::createRelatedMemberships($params, $membership);
if (empty($params['skipRecentView'])) {
self::addToRecentItems($membership);
}
return $membership;
}
/**
* @param \CRM_Member_DAO_Membership $membership
*/
private static function addToRecentItems($membership) {
$url = CRM_Utils_System::url('civicrm/contact/view/membership',
"action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
);
if (empty($membership->membership_type_id)) {
// ie in an update situation.
$membership->find(TRUE);
}
$title = CRM_Contact_BAO_Contact::displayName($membership->contact_id) . ' - ' . ts('Membership Type:')
. ' ' . CRM_Core_PseudoConstant::getLabel('CRM_Member_BAO_Membership', 'membership_type_id', $membership->membership_type_id);
$recentOther = [];
if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::UPDATE)) {
$recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership',
"action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
);
}
if (CRM_Core_Permission::checkActionPermission('CiviMember', CRM_Core_Action::DELETE)) {
$recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/membership',
"action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
);
}
// add the recently created Membership
CRM_Utils_Recent::add($title,
$url,
$membership->id,
'Membership',
$membership->contact_id,
NULL,
$recentOther
);
}
/**
* Check the membership extended through relationship.
*
* @param int $membershipTypeID
* Membership type id.
* @param int $contactId
* Contact id.
*
* @param int $action
*
* @return array
* array of contact_id of all related contacts.
*
* @throws \CRM_Core_Exception
*/
public static function checkMembershipRelationship($membershipTypeID, $contactId, $action = CRM_Core_Action::ADD) {
$contacts = [];
$membershipType = CRM_Member_BAO_MembershipType::getMembershipType($membershipTypeID);
$relationships = [];
if (isset($membershipType['relationship_type_id'])) {
$relationships = CRM_Contact_BAO_Relationship::getRelationship($contactId,
CRM_Contact_BAO_Relationship::CURRENT
);
if ($action & CRM_Core_Action::UPDATE) {
$pastRelationships = CRM_Contact_BAO_Relationship::getRelationship($contactId,
CRM_Contact_BAO_Relationship::PAST
);
$relationships = array_merge($relationships, $pastRelationships);
}
}
if (!empty($relationships)) {
// check for each contact relationships
foreach ($relationships as $values) {
//get details of the relationship type
$relType = ['id' => $values['civicrm_relationship_type_id']];
$relValues = [];
CRM_Contact_BAO_RelationshipType::retrieve($relType, $relValues);
// Check if contact's relationship type exists in membership type
$relTypeDirs = [];
$bidirectional = FALSE;
foreach ($membershipType['relationship_type_id'] as $key => $value) {
$relTypeDirs[] = $value . '_' . $membershipType['relationship_direction'][$key];
if (in_array($value, $relType) &&
$relValues['name_a_b'] == $relValues['name_b_a']
) {
$bidirectional = TRUE;
break;
}
}
$relTypeDir = $values['civicrm_relationship_type_id'] . '_' . $values['rtype'];
if ($bidirectional || in_array($relTypeDir, $relTypeDirs)) {
// $values['status'] is going to have value for
// current or past relationships.
$contacts[$values['cid']] = $values['status'];
}
}
}
// Sort by contact_id ascending
ksort($contacts);
return $contacts;
}
/**
* Retrieve DB object based on input parameters.
*
* It also stores all the retrieved values in the default array.
*
* @param array $params
* (reference ) an assoc array of name/value pairs.
* @param array $defaults
* (reference ) an assoc array to hold the name / value pairs.
* in a hierarchical manner
*
* @return CRM_Member_BAO_Membership
*/
public static function retrieve(&$params, &$defaults) {
$membership = new CRM_Member_DAO_Membership();
$membership->copyValues($params);
if ($membership->find(TRUE)) {
CRM_Core_DAO::storeValues($membership, $defaults);
//get the membership status and type values.
$statusANDType = self::getStatusANDTypeValues($membership->id);
foreach (['status', 'membership_type'] as $fld) {
$defaults[$fld] = $statusANDType[$membership->id][$fld] ?? NULL;
}
if (!empty($statusANDType[$membership->id]['is_current_member'])) {
$defaults['active'] = TRUE;
}
return $membership;
}
return NULL;
}
/**
* Get membership status and membership type values.
*
* @param int $membershipId
* Membership id of values to return.
*
* @return array
* Array of key value pairs
*/
public static function getStatusANDTypeValues($membershipId) {
$values = [];
if (!$membershipId) {
return $values;
}
$sql = '
SELECT membership.id as id,
status.id as status_id,
status.label as status,
status.is_current_member as is_current_member,
type.id as membership_type_id,
type.name as membership_type,
type.relationship_type_id as relationship_type_id
FROM civicrm_membership membership
INNER JOIN civicrm_membership_status status ON ( status.id = membership.status_id )
INNER JOIN civicrm_membership_type type ON ( type.id = membership.membership_type_id )
WHERE membership.id = %1';
$dao = CRM_Core_DAO::executeQuery($sql, [1 => [$membershipId, 'Positive']]);
$properties = [
'status',
'status_id',
'membership_type',
'membership_type_id',
'is_current_member',
'relationship_type_id',
];
while ($dao->fetch()) {
foreach ($properties as $property) {
$values[$dao->id][$property] = $dao->$property;
}
}
return $values;
}
/**
* Delete membership.
*
* Wrapper for most delete calls. Use this unless you JUST want to delete related memberships w/o deleting the parent.
*
* @param int $membershipId
* Membership id that needs to be deleted.
* @param bool $preserveContrib
*
* @return int
* Id of deleted Membership on success, false otherwise.
*/
public static function del($membershipId, $preserveContrib = FALSE) {
//delete related first and then delete parent.
self::deleteRelatedMemberships($membershipId);
return self::deleteMembership($membershipId, $preserveContrib);
}
/**
* Delete membership.
*
* @param int $membershipId
* Membership id that needs to be deleted.
* @param bool $preserveContrib
*
* @return int
* Id of deleted Membership on success, false otherwise.
*/
public static function deleteMembership($membershipId, $preserveContrib = FALSE) {
// CRM-12147, retrieve membership data before we delete it for hooks
$params = ['id' => $membershipId];
$memValues = [];
$memberships = self::getValues($params, $memValues);
$membership = $memberships[$membershipId];
CRM_Utils_Hook::pre('delete', 'Membership', $membershipId, $memValues);
$transaction = new CRM_Core_Transaction();
//delete activity record
$activityTypes = CRM_Core_PseudoConstant::activityType(TRUE, FALSE, FALSE, 'name');
$params = [];
$deleteActivity = FALSE;
$membershipActivities = [
'Membership Signup',
'Membership Renewal',
'Change Membership Status',
'Change Membership Type',
'Membership Renewal Reminder',
];
foreach ($membershipActivities as $membershipActivity) {
$activityId = array_search($membershipActivity, $activityTypes);
if ($activityId) {
$params['activity_type_id'][] = $activityId;
$deleteActivity = TRUE;
}
}
if ($deleteActivity) {
$params['source_record_id'] = $membershipId;
CRM_Activity_BAO_Activity::deleteActivity($params);
}
self::deleteMembershipPayment($membershipId, $preserveContrib);
CRM_Price_BAO_LineItem::deleteLineItems($membershipId, 'civicrm_membership');
$results = $membership->delete();
$transaction->commit();
CRM_Utils_Hook::post('delete', 'Membership', $membership->id, $membership);
return $results;
}
/**
* Delete related memberships.
*
* @param int $ownerMembershipId
* @param int $contactId
*
* @return void
*/
public static function deleteRelatedMemberships($ownerMembershipId, $contactId = NULL) {
if (!$ownerMembershipId && !$contactId) {
return;
}
$membership = new CRM_Member_DAO_Membership();
$membership->owner_membership_id = $ownerMembershipId;
if ($contactId) {
$membership->contact_id = $contactId;
}
$membership->find();
while ($membership->fetch()) {
//delete related first and then delete parent.
self::deleteRelatedMemberships($membership->id);
self::deleteMembership($membership->id);
}
}
/**
* Obtain active/inactive memberships from the list of memberships passed to it.
*
* @param array $memberships
* Membership records.
* @param string $status
* Active or inactive.
*
* @return array|null
* array of memberships based on status
*/
public static function activeMembers($memberships, $status = 'active') {
$actives = [];
if ($status == 'active') {
foreach ($memberships as $f => $v) {
if (!empty($v['active'])) {
$actives[$f] = $v;
}
}
return $actives;
}
elseif ($status == 'inactive') {
foreach ($memberships as $f => $v) {
if (empty($v['active'])) {
$actives[$f] = $v;
}
}
return $actives;
}
return NULL;
}
/**
* Return Membership Block info in Contribution Pages.
*
* @param int $pageID
* Contribution page id.
*
* @return array|null
*/
public static function getMembershipBlock($pageID) {
$membershipBlock = [];
$dao = new CRM_Member_DAO_MembershipBlock();
$dao->entity_table = 'civicrm_contribution_page';
$dao->entity_id = $pageID;
$dao->is_active = 1;
if ($dao->find(TRUE)) {
CRM_Core_DAO::storeValues($dao, $membershipBlock);
if (!empty($membershipBlock['membership_types'])) {
$membershipTypes = CRM_Utils_String::unserialize($membershipBlock['membership_types']);
if (!is_array($membershipTypes)) {
return $membershipBlock;
}
$memTypes = [];
foreach ($membershipTypes as $key => $value) {
$membershipBlock['auto_renew'][$key] = $value;
$memTypes[$key] = $key;
}
$membershipBlock['membership_types'] = implode(',', $memTypes);
}
}
else {
return NULL;
}
return $membershipBlock;
}
/**
* Return a current membership of given contact.
*
* NB: if more than one membership meets criteria, a randomly selected one is returned.
*
* @param int $contactID
* Contact id.
* @param int $memType
* Membership type, null to retrieve all types.
* @param int $isTest
* @param int $membershipId
* If provided, then determine if it is current.
* @param bool $onlySameParentOrg
* True if only Memberships with same parent org as the $memType wanted, false otherwise.
*
* @return array|bool
* @throws \CRM_Core_Exception
*/
public static function getContactMembership($contactID, $memType, $isTest, $membershipId = NULL, $onlySameParentOrg = FALSE) {
//check for owner membership id, if it exists update that membership instead: CRM-15992
if ($membershipId) {
$ownerMemberId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
$membershipId,
'owner_membership_id', 'id'
);
if ($ownerMemberId) {
$membershipId = $ownerMemberId;
$contactID = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
$membershipId,
'contact_id', 'id'
);
}
}
$dao = new CRM_Member_DAO_Membership();
if ($membershipId) {
$dao->id = $membershipId;
}
$dao->contact_id = $contactID;
$dao->membership_type_id = $memType;
//fetch proper membership record.
if ($isTest) {
$dao->is_test = $isTest;
}
else {
$dao->whereAdd('is_test IS NULL OR is_test = 0');
}
//avoid pending membership as current membership: CRM-3027
$statusIds = [array_search('Pending', CRM_Member_PseudoConstant::membershipStatus())];
if (!$membershipId) {
// CRM-15475
$statusIds[] = array_search(
'Cancelled',
CRM_Member_PseudoConstant::membershipStatus(
NULL,
" name = 'Cancelled' ",
'name',
FALSE,
TRUE
)
);
}
$dao->whereAdd('status_id NOT IN ( ' . implode(',', $statusIds) . ')');
// order by start date to find most recent membership first, CRM-4545
$dao->orderBy('start_date DESC');
// CRM-8141
if ($onlySameParentOrg && $memType) {
// require the same parent org as the $memType
$params = ['id' => $memType];
$membershipType = [];
if (CRM_Member_BAO_MembershipType::retrieve($params, $membershipType)) {
$memberTypesSameParentOrg = civicrm_api3('MembershipType', 'get', [
'member_of_contact_id' => $membershipType['member_of_contact_id'],
'options' => [
'limit' => 0,
],
]);
$memberTypesSameParentOrgList = implode(',', array_keys($memberTypesSameParentOrg['values'] ?? []));
$dao->whereAdd('membership_type_id IN (' . $memberTypesSameParentOrgList . ')');
}
}
if ($dao->find(TRUE)) {
$membership = [];
CRM_Core_DAO::storeValues($dao, $membership);
$membership['is_current_member'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus',
$membership['status_id'],
'is_current_member', 'id'
);
$ownerMemberId = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
$membership['id'],
'owner_membership_id', 'id'
);
if ($ownerMemberId) {
$membership['id'] = $membership['membership_id'] = $ownerMemberId;
$membership['membership_contact_id'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_Membership',
$membership['id'],
'contact_id', 'id'
);
}
return $membership;
}
// CRM-8141
if ($onlySameParentOrg && $memType) {
// see if there is a membership that has same parent as $memType but different parent than $membershipID
if ($dao->id && CRM_Core_Permission::check('edit memberships')) {
// CRM-10016, This is probably a backend renewal, and make sure we return the same membership thats being renewed.
$dao->whereAdd();
}
else {
unset($dao->id);
}
unset($dao->membership_type_id);
if ($dao->find(TRUE)) {
$membership = [];
CRM_Core_DAO::storeValues($dao, $membership);
$membership['is_current_member'] = CRM_Core_DAO::getFieldValue('CRM_Member_DAO_MembershipStatus',
$membership['status_id'],
'is_current_member', 'id'
);
return $membership;
}
}
return FALSE;
}
/**
* Combine all the importable fields from the lower levels object.
*
* @param string $contactType
* Contact type.
* @param bool $status
*
* @return array
* array of importable Fields
* @throws \CRM_Core_Exception
*
* @deprecated
*/
public static function importableFields($contactType = 'Individual', $status = TRUE) {
CRM_Core_Error::deprecatedFunctionWarning('api');
$fields = Civi::cache('fields')->get('membership_importable_fields' . $contactType . $status);
if (!$fields) {
if (!$status) {
$fields = ['' => ['title' => '- ' . ts('do not import') . ' -']];
}
else {
$fields = ['' => ['title' => '- ' . ts('Membership Fields') . ' -']];
}
$tmpFields = CRM_Member_DAO_Membership::import();
$contactFields = CRM_Contact_BAO_Contact::importableFields($contactType, NULL);
// Using new Dedupe rule.
$ruleParams = [
'contact_type' => $contactType,
'used' => 'Unsupervised',
];
$fieldsArray = CRM_Dedupe_BAO_DedupeRule::dedupeRuleFields($ruleParams);
$tmpContactField = [];
if (is_array($fieldsArray)) {
foreach ($fieldsArray as $value) {
$customFieldId = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField',
$value,
'id',
'column_name'
);
$value = $customFieldId ? 'custom_' . $customFieldId : $value;
$tmpContactField[trim($value)] = $contactFields[trim($value)] ?? NULL;
if (!$status) {
$title = $tmpContactField[trim($value)]['title'] . " " . ts('(match to contact)');
}
else {
$title = $tmpContactField[trim($value)]['title'];
}
$tmpContactField[trim($value)]['title'] = $title;
}
}
$tmpContactField['external_identifier'] = $contactFields['external_identifier'];
$tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
$tmpFields['membership_contact_id']['title'] .= ' ' . ts('(match to contact)');
$fields = array_merge($fields, $tmpContactField);
$fields = array_merge($fields, $tmpFields);
$fields = array_merge($fields, CRM_Core_BAO_CustomField::getFieldsForImport('Membership'));
Civi::cache('fields')->set('membership_importable_fields' . $contactType . $status, $fields);
}
return $fields;
}
/**
* Get all exportable fields.
*
* @return array return array of all exportable fields
*/
public static function &exportableFields() {
$expFieldMembership = CRM_Member_DAO_Membership::export();
$expFieldsMemType = CRM_Member_DAO_MembershipType::export();
$fields = array_merge($expFieldMembership, $expFieldsMemType);
$fields = array_merge($fields, $expFieldMembership);
$membershipStatus = [
'membership_status' => [
'title' => ts('Membership Status'),
'name' => 'membership_status',
'type' => CRM_Utils_Type::T_STRING,
'where' => 'civicrm_membership_status.name',
],
];
//CRM-6161 fix for customdata export
$fields = array_merge($fields, $membershipStatus, CRM_Core_BAO_CustomField::getFieldsForImport('Membership'));
$fields['membership_status_id'] = $membershipStatus['membership_status'];
return $fields;
}
/**
* Get membership joins/renewals for a specified membership type.