3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
12 use Civi\API\Exception\UnauthorizedException
;
13 use Civi\Api4\MembershipType
;
18 * @copyright CiviCRM LLC https://civicrm.org/licensing
20 class CRM_Member_BAO_Membership
extends CRM_Member_DAO_Membership
{
23 * Static field for all the membership information that we can potentially import.
27 public static $_importableFields = NULL;
29 public static $_renewalActType = NULL;
31 public static $_signupActType = NULL;
34 * Takes an associative array and creates a membership object.
36 * the function extracts all the params it needs to initialize the created
37 * membership object. The params array could contain additional unused name/value
40 * @param array $params
41 * (reference ) an assoc array of name/value pairs.
43 * @return CRM_Member_BAO_Membership
44 * @throws \CiviCRM_API3_Exception
46 public static function add(&$params) {
47 $oldStatus = $oldType = NULL;
49 CRM_Utils_Hook
::pre('edit', 'Membership', $params['id'], $params);
52 CRM_Utils_Hook
::pre('create', 'Membership', NULL, $params);
55 // we do this after the hooks are called in case it has been altered
57 $membershipObj = new CRM_Member_DAO_Membership();
58 $membershipObj->id
= $id;
59 $membershipObj->find();
60 while ($membershipObj->fetch()) {
61 $oldStatus = $membershipObj->status_id
;
62 $oldType = $membershipObj->membership_type_id
;
66 if (array_key_exists('is_override', $params) && !$params['is_override']) {
67 $params['is_override'] = 'null';
70 $membership = new CRM_Member_BAO_Membership();
71 $membership->copyValues($params);
72 $membership->id
= $id;
76 if (empty($membership->contact_id
) ||
empty($membership->status_id
)) {
77 // this means we are in renewal mode and are just updating the membership
78 // record or this is an API update call and all fields are not present in the update record
79 // however the hooks don't care and want all data CRM-7784
80 $tempMembership = new CRM_Member_DAO_Membership();
81 $tempMembership->id
= $membership->id
;
82 $tempMembership->find(TRUE);
83 $membership = $tempMembership;
86 //get the log start date.
87 //it is set during renewal of membership.
88 $logStartDate = $params['log_start_date'] ??
NULL;
89 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : CRM_Utils_Date
::isoToMysql($membership->start_date
);
90 $values = self
::getStatusANDTypeValues($membership->id
);
93 'membership_id' => $membership->id
,
94 'status_id' => $membership->status_id
,
95 'start_date' => $logStartDate,
96 'end_date' => CRM_Utils_Date
::isoToMysql($membership->end_date
),
97 'modified_date' => CRM_Utils_Time
::date('Ymd'),
98 'membership_type_id' => $values[$membership->id
]['membership_type_id'],
99 'max_related' => $membership->max_related
,
102 if (!empty($params['modified_id'])) {
103 $membershipLog['modified_id'] = $params['modified_id'];
105 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
106 elseif (CRM_Core_Session
::singleton()->get('userID')) {
107 $membershipLog['modified_id'] = CRM_Core_Session
::singleton()->get('userID');
110 $membershipLog['modified_id'] = $membership->contact_id
;
113 CRM_Member_BAO_MembershipLog
::add($membershipLog);
115 // reset the group contact cache since smart groups might be affected due to this
116 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
118 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
120 'status_id' => $params['membership_activity_status'] ??
'Completed',
122 if (in_array($allStatus[$membership->status_id
], ['Pending', 'Grace'])) {
123 $activityParams['status_id'] = 'Scheduled';
125 $activityParams['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', $activityParams['status_id']);
127 $targetContactID = $membership->contact_id
;
128 if (!empty($params['is_for_organization'])) {
129 // @todo - deprecate is_for_organization, require modified_id
130 $targetContactID = $params['modified_id'] ??
NULL;
133 // add custom field values
134 if (!empty($params['custom']) && is_array($params['custom'])
136 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_membership', $membership->id
);
140 if ($membership->status_id
!= $oldStatus) {
141 CRM_Activity_BAO_Activity
::addActivity($membership,
142 'Change Membership Status',
145 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
146 'source_contact_id' => $membershipLog['modified_id'],
147 'priority_id' => 'Normal',
151 if (isset($membership->membership_type_id
) && $membership->membership_type_id
!= $oldType) {
152 $membershipTypes = CRM_Member_BAO_Membership
::buildOptions('membership_type_id', 'get');
153 CRM_Activity_BAO_Activity
::addActivity($membership,
154 'Change Membership Type',
157 'subject' => "Type changed from {$membershipTypes[$oldType]} to {$membershipTypes[$membership->membership_type_id]}",
158 'source_contact_id' => $membershipLog['modified_id'],
159 'priority_id' => 'Normal',
164 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
165 $activityParams['id'] = civicrm_api3('Activity', 'Get', [
166 'source_record_id' => $membership->id
,
167 'activity_type_id' => $activityType,
168 'status_id' => 'Scheduled',
170 // 1. Update Schedule Membership Signup/Renwal activity to completed on successful payment of pending membership
171 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
172 if (!empty($params['membership_activity_status']) && (!empty($activityParams['id']) ||
$activityType == 'Membership Renewal')) {
173 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $targetContactID, $activityParams);
178 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
181 CRM_Activity_BAO_Activity
::addActivity($membership, 'Membership Signup', $targetContactID, $activityParams);
182 CRM_Utils_Hook
::post('create', 'Membership', $membership->id
, $membership);
189 * Fetch the object and store the values in the values array.
191 * @param array $params
192 * Input parameters to find object.
193 * @param array $values
194 * Output values of the object.
195 * @param bool $active
196 * Do you want only active memberships to.
199 * @return CRM_Member_BAO_Membership|null
200 * The found object or null
202 public static function &getValues(&$params, &$values, $active = FALSE) {
203 if (empty($params)) {
206 $membership = new CRM_Member_BAO_Membership();
208 $membership->copyValues($params);
211 while ($membership->fetch()) {
213 (!CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
214 $membership->status_id
,
221 CRM_Core_DAO
::storeValues($membership, $values[$membership->id
]);
222 $memberships[$membership->id
] = $membership;
229 * Takes an associative array and creates a membership object.
231 * @param array $params
232 * (reference ) an assoc array of name/value pairs.
234 * Deprecated parameter The array that holds all the db ids.
236 * @return CRM_Member_BAO_Membership|CRM_Core_Error
237 * @throws \CiviCRM_API3_Exception
239 * @throws CRM_Core_Exception
241 public static function create(&$params, $ids = []) {
243 if (!empty($params['membership_type_id'])) {
244 $memTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipType($params['membership_type_id']);
245 $isLifeTime = $memTypeDetails['duration_unit'] === 'lifetime' ?
TRUE : FALSE;
247 // always calculate status if is_override/skipStatusCal is not true.
248 // giving respect to is_override during import. CRM-4012
250 // To skip status calculation we should use 'skipStatusCal'.
251 // eg pay later membership, membership update cron CRM-3984
253 if (empty($params['skipStatusCal'])) {
255 foreach (['start_date', 'end_date', 'join_date'] as $dateField) {
256 if (!empty($params[$dateField]) && $params[$dateField] !== 'null' && strpos($params[$dateField], date('Ymd', CRM_Utils_Time
::strtotime(trim($params[$dateField])))) !== 0) {
257 $params[$dateField] = date('Ymd', CRM_Utils_Time
::strtotime(trim($params[$dateField])));
258 // @todo enable this once core is using the api.
259 // CRM_Core_Error::deprecatedWarning('Relying on the BAO to clean up dates is deprecated. Call membership create via the api');
261 if (!empty($params['id']) && empty($params[$dateField]) && !($isLifeTime && $dateField == 'end_date')) {
262 $fieldsToLoad[] = $dateField;
265 if (!empty($fieldsToLoad)) {
266 $membership = civicrm_api3('Membership', 'getsingle', ['id' => $params['id'], 'return' => $fieldsToLoad]);
267 foreach ($fieldsToLoad as $fieldToLoad) {
268 $params[$fieldToLoad] = $membership[$fieldToLoad];
271 if (empty($params['id'])
272 && (empty($params['start_date']) ||
empty($params['join_date']) ||
(empty($params['end_date']) && !$isLifeTime))) {
273 // This is a new membership, calculate the membership dates.
274 $calcDates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType(
275 $params['membership_type_id'],
276 $params['join_date'] ??
NULL,
277 $params['start_date'] ??
NULL,
278 $params['end_date'] ??
NULL,
279 $params['num_terms'] ??
1
285 $params['start_date'] = empty($params['start_date']) ?
($calcDates['start_date'] ??
'null') : $params['start_date'];
286 $params['end_date'] = empty($params['end_date']) ?
($calcDates['end_date'] ??
'null') : $params['end_date'];
287 $params['join_date'] = empty($params['join_date']) ?
($calcDates['join_date'] ??
'null') : $params['join_date'];
289 //fix for CRM-3570, during import exclude the statuses those having is_admin = 1
290 $excludeIsAdmin = $params['exclude_is_admin'] ??
FALSE;
292 //CRM-3724 always skip is_admin if is_override != true.
293 if (!$excludeIsAdmin && empty($params['is_override'])) {
294 $excludeIsAdmin = TRUE;
297 if (empty($params['status_id']) && empty($params['is_override'])) {
298 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($params['start_date'], $params['end_date'], $params['join_date'],
299 'now', $excludeIsAdmin, $params['membership_type_id'] ??
NULL, $params
301 if (empty($calcStatus)) {
302 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')));
304 $params['status_id'] = $calcStatus['id'];
308 // data cleanup only: all verifications on number of related memberships are done upstream in:
309 // CRM_Member_BAO_Membership::createRelatedMemberships()
310 // CRM_Contact_BAO_Relationship::relatedMemberships()
311 if (!empty($params['owner_membership_id'])) {
312 unset($params['max_related']);
315 // if membership allows related, default max_related to value in membership_type
316 if (!array_key_exists('max_related', $params) && !empty($params['membership_type_id'])) {
317 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipType($params['membership_type_id']);
318 if (isset($membershipType['relationship_type_id'])) {
319 $params['max_related'] = $membershipType['max_related'] ??
NULL;
324 $transaction = new CRM_Core_Transaction();
326 $params['id'] = $params['id'] ??
$ids['membership'] ??
NULL;
327 $membership = self
::add($params);
329 if (is_a($membership, 'CRM_Core_Error')) {
330 $transaction->rollback();
334 $params['membership_id'] = $membership->id
;
335 // For api v4 we skip all of this stuff. There is an expectation that v4 users either use
336 // the order api, or handle any financial / related processing themselves.
337 // Note that the processing below is fairly intertwined with core usage and in some places
338 // problematic or to be removed.
339 // Note the choice of 'version' as a parameter is to make it
340 // unavailable through apiv3.
341 // once we are rid of direct calls to the BAO::create from core
342 // we will deprecate this stuff into the v3 api.
343 if (($params['version'] ??
0) !== 4) {
344 // @todo further cleanup required to remove use of $ids['contribution'] from here
345 if (isset($ids['membership'])) {
346 $contributionID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment',
351 // @todo this is a temporary step to removing $ids['contribution'] completely
352 if (empty($params['contribution_id']) && !empty($contributionID)) {
353 $params['contribution_id'] = $contributionID;
357 // This code ensures a line item is created but it is recommended you pass in 'skipLineItem' or 'line_item'
358 if (empty($params['line_item']) && !empty($params['membership_type_id']) && empty($params['skipLineItem'])) {
359 CRM_Price_BAO_LineItem
::getLineItemArray($params, NULL, 'membership', $params['membership_type_id']);
361 $params['skipLineItem'] = TRUE;
363 // Record contribution for this membership and create a MembershipPayment
364 // @todo deprecate this.
365 if (!empty($params['contribution_status_id'])) {
366 $memInfo = array_merge($params, ['membership_id' => $membership->id
]);
367 $params['contribution'] = self
::recordMembershipContribution($memInfo);
370 // If the membership has no associated contribution then we ensure
371 // the line items are 'correct' here. This is a lazy legacy
372 // hack whereby they are deleted and recreated
373 if (empty($contributionID)) {
374 if (!empty($params['lineItems'])) {
375 $params['line_item'] = $params['lineItems'];
377 // do cleanup line items if membership edit the Membership type.
378 if (!empty($ids['membership'])) {
379 CRM_Price_BAO_LineItem
::deleteLineItems($ids['membership'], 'civicrm_membership');
381 // @todo - we should ONLY do the below if a contribution is created. Let's
382 // get some deprecation notices in here & see where it's hit & work to eliminate.
383 // This could happen if there is no contribution or we are in one of many
384 // weird and wonderful flows. This is scary code. Keep adding tests.
385 if (!empty($params['line_item']) && empty($params['contribution_id'])) {
387 foreach ($params['line_item'] as $priceSetId => $lineItems) {
388 foreach ($lineItems as $lineIndex => $lineItem) {
389 $lineMembershipType = $lineItem['membership_type_id'] ??
NULL;
390 if (!empty($params['contribution'])) {
391 $params['line_item'][$priceSetId][$lineIndex]['contribution_id'] = $params['contribution']->id
;
393 if ($lineMembershipType && $lineMembershipType == ($params['membership_type_id'] ??
NULL)) {
394 $params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $membership->id
;
395 $params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_membership';
397 elseif (!$lineMembershipType && !empty($params['contribution'])) {
398 $params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $params['contribution']->id
;
399 $params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_contribution';
403 CRM_Price_BAO_LineItem
::processPriceSet(
405 $params['line_item'],
406 $params['contribution'] ??
NULL
412 $transaction->commit();
414 self
::createRelatedMemberships($params, $membership);
416 if (empty($params['skipRecentView'])) {
417 self
::addToRecentItems($membership);
424 * @param \CRM_Member_DAO_Membership $membership
426 private static function addToRecentItems($membership) {
427 $url = CRM_Utils_System
::url('civicrm/contact/view/membership',
428 "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
430 if (empty($membership->membership_type_id
)) {
431 // ie in an update situation.
432 $membership->find(TRUE);
434 $title = CRM_Contact_BAO_Contact
::displayName($membership->contact_id
) . ' - ' . ts('Membership Type:')
435 . ' ' . CRM_Core_PseudoConstant
::getLabel('CRM_Member_BAO_Membership', 'membership_type_id', $membership->membership_type_id
);
438 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::UPDATE
)) {
439 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
440 "action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
443 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::DELETE
)) {
444 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
445 "action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
449 // add the recently created Membership
450 CRM_Utils_Recent
::add($title,
454 $membership->contact_id
,
461 * Check the membership extended through relationship.
463 * @param int $membershipTypeID
464 * Membership type id.
465 * @param int $contactId
471 * array of contact_id of all related contacts.
473 * @throws \CRM_Core_Exception
474 * @throws \CiviCRM_API3_Exception
476 public static function checkMembershipRelationship($membershipTypeID, $contactId, $action = CRM_Core_Action
::ADD
) {
479 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipType($membershipTypeID);
482 if (isset($membershipType['relationship_type_id'])) {
483 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
484 CRM_Contact_BAO_Relationship
::CURRENT
486 if ($action & CRM_Core_Action
::UPDATE
) {
487 $pastRelationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
488 CRM_Contact_BAO_Relationship
::PAST
490 $relationships = array_merge($relationships, $pastRelationships);
494 if (!empty($relationships)) {
495 // check for each contact relationships
496 foreach ($relationships as $values) {
497 //get details of the relationship type
498 $relType = ['id' => $values['civicrm_relationship_type_id']];
500 CRM_Contact_BAO_RelationshipType
::retrieve($relType, $relValues);
501 // Check if contact's relationship type exists in membership type
503 $bidirectional = FALSE;
504 foreach ($membershipType['relationship_type_id'] as $key => $value) {
505 $relTypeDirs[] = $value . '_' . $membershipType['relationship_direction'][$key];
506 if (in_array($value, $relType) &&
507 $relValues['name_a_b'] == $relValues['name_b_a']
509 $bidirectional = TRUE;
513 $relTypeDir = $values['civicrm_relationship_type_id'] . '_' . $values['rtype'];
514 if ($bidirectional ||
in_array($relTypeDir, $relTypeDirs)) {
515 // $values['status'] is going to have value for
516 // current or past relationships.
517 $contacts[$values['cid']] = $values['status'];
522 // Sort by contact_id ascending
528 * Retrieve DB object based on input parameters.
530 * It also stores all the retrieved values in the default array.
532 * @param array $params
533 * (reference ) an assoc array of name/value pairs.
534 * @param array $defaults
535 * (reference ) an assoc array to hold the name / value pairs.
536 * in a hierarchical manner
538 * @return CRM_Member_BAO_Membership
540 public static function retrieve(&$params, &$defaults) {
541 $membership = new CRM_Member_DAO_Membership();
543 $membership->copyValues($params);
545 if ($membership->find(TRUE)) {
546 CRM_Core_DAO
::storeValues($membership, $defaults);
548 //get the membership status and type values.
549 $statusANDType = self
::getStatusANDTypeValues($membership->id
);
550 foreach (['status', 'membership_type'] as $fld) {
551 $defaults[$fld] = $statusANDType[$membership->id
][$fld] ??
NULL;
553 if (!empty($statusANDType[$membership->id
]['is_current_member'])) {
554 $defaults['active'] = TRUE;
564 * Get membership status and membership type values.
566 * @param int $membershipId
567 * Membership id of values to return.
570 * Array of key value pairs
572 public static function getStatusANDTypeValues($membershipId) {
574 if (!$membershipId) {
578 SELECT membership.id as id,
579 status.id as status_id,
580 status.label as status,
581 status.is_current_member as is_current_member,
582 type.id as membership_type_id,
583 type.name as membership_type,
584 type.relationship_type_id as relationship_type_id
585 FROM civicrm_membership membership
586 INNER JOIN civicrm_membership_status status ON ( status.id = membership.status_id )
587 INNER JOIN civicrm_membership_type type ON ( type.id = membership.membership_type_id )
588 WHERE membership.id = %1';
589 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$membershipId, 'Positive']]);
594 'membership_type_id',
596 'relationship_type_id',
598 while ($dao->fetch()) {
599 foreach ($properties as $property) {
600 $values[$dao->id
][$property] = $dao->$property;
610 * Wrapper for most delete calls. Use this unless you JUST want to delete related memberships w/o deleting the parent.
612 * @param int $membershipId
613 * Membership id that needs to be deleted.
614 * @param bool $preserveContrib
617 * Id of deleted Membership on success, false otherwise.
619 public static function del($membershipId, $preserveContrib = FALSE) {
620 //delete related first and then delete parent.
621 self
::deleteRelatedMemberships($membershipId);
622 return self
::deleteMembership($membershipId, $preserveContrib);
628 * @param int $membershipId
629 * Membership id that needs to be deleted.
630 * @param bool $preserveContrib
633 * Id of deleted Membership on success, false otherwise.
635 public static function deleteMembership($membershipId, $preserveContrib = FALSE) {
636 // CRM-12147, retrieve membership data before we delete it for hooks
637 $params = ['id' => $membershipId];
639 $memberships = self
::getValues($params, $memValues);
641 $membership = $memberships[$membershipId];
643 CRM_Utils_Hook
::pre('delete', 'Membership', $membershipId, $memValues);
645 $transaction = new CRM_Core_Transaction();
648 //delete activity record
649 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
652 $deleteActivity = FALSE;
653 $membershipActivities = [
655 'Membership Renewal',
656 'Change Membership Status',
657 'Change Membership Type',
658 'Membership Renewal Reminder',
660 foreach ($membershipActivities as $membershipActivity) {
661 $activityId = array_search($membershipActivity, $activityTypes);
663 $params['activity_type_id'][] = $activityId;
664 $deleteActivity = TRUE;
667 if ($deleteActivity) {
668 $params['source_record_id'] = $membershipId;
669 CRM_Activity_BAO_Activity
::deleteActivity($params);
671 self
::deleteMembershipPayment($membershipId, $preserveContrib);
672 CRM_Price_BAO_LineItem
::deleteLineItems($membershipId, 'civicrm_membership');
674 $results = $membership->delete();
675 $transaction->commit();
677 CRM_Utils_Hook
::post('delete', 'Membership', $membership->id
, $membership);
683 * Delete related memberships.
685 * @param int $ownerMembershipId
686 * @param int $contactId
690 public static function deleteRelatedMemberships($ownerMembershipId, $contactId = NULL) {
691 if (!$ownerMembershipId && !$contactId) {
695 $membership = new CRM_Member_DAO_Membership();
696 $membership->owner_membership_id
= $ownerMembershipId;
699 $membership->contact_id
= $contactId;
703 while ($membership->fetch()) {
704 //delete related first and then delete parent.
705 self
::deleteRelatedMemberships($membership->id
);
706 self
::deleteMembership($membership->id
);
711 * Obtain active/inactive memberships from the list of memberships passed to it.
713 * @param array $memberships
714 * Membership records.
715 * @param string $status
716 * Active or inactive.
719 * array of memberships based on status
721 public static function activeMembers($memberships, $status = 'active') {
723 if ($status == 'active') {
724 foreach ($memberships as $f => $v) {
725 if (!empty($v['active'])) {
731 elseif ($status == 'inactive') {
732 foreach ($memberships as $f => $v) {
733 if (empty($v['active'])) {
743 * Return Membership Block info in Contribution Pages.
746 * Contribution page id.
750 public static function getMembershipBlock($pageID) {
751 $membershipBlock = [];
752 $dao = new CRM_Member_DAO_MembershipBlock();
753 $dao->entity_table
= 'civicrm_contribution_page';
755 $dao->entity_id
= $pageID;
757 if ($dao->find(TRUE)) {
758 CRM_Core_DAO
::storeValues($dao, $membershipBlock);
759 if (!empty($membershipBlock['membership_types'])) {
760 $membershipTypes = CRM_Utils_String
::unserialize($membershipBlock['membership_types']);
761 if (!is_array($membershipTypes)) {
762 return $membershipBlock;
765 foreach ($membershipTypes as $key => $value) {
766 $membershipBlock['auto_renew'][$key] = $value;
767 $memTypes[$key] = $key;
769 $membershipBlock['membership_types'] = implode(',', $memTypes);
776 return $membershipBlock;
780 * Return a current membership of given contact.
782 * NB: if more than one membership meets criteria, a randomly selected one is returned.
784 * @param int $contactID
786 * @param int $memType
787 * Membership type, null to retrieve all types.
789 * @param int $membershipId
790 * If provided, then determine if it is current.
791 * @param bool $onlySameParentOrg
792 * True if only Memberships with same parent org as the $memType wanted, false otherwise.
795 * @throws \CiviCRM_API3_Exception
797 public static function getContactMembership($contactID, $memType, $isTest, $membershipId = NULL, $onlySameParentOrg = FALSE) {
798 //check for owner membership id, if it exists update that membership instead: CRM-15992
800 $ownerMemberId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
802 'owner_membership_id', 'id'
804 if ($ownerMemberId) {
805 $membershipId = $ownerMemberId;
806 $contactID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
813 $dao = new CRM_Member_DAO_Membership();
815 $dao->id
= $membershipId;
817 $dao->contact_id
= $contactID;
818 $dao->membership_type_id
= $memType;
820 //fetch proper membership record.
822 $dao->is_test
= $isTest;
825 $dao->whereAdd('is_test IS NULL OR is_test = 0');
828 //avoid pending membership as current membership: CRM-3027
829 $statusIds = [array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus())];
830 if (!$membershipId) {
832 $statusIds[] = array_search(
834 CRM_Member_PseudoConstant
::membershipStatus(
836 " name = 'Cancelled' ",
843 $dao->whereAdd('status_id NOT IN ( ' . implode(',', $statusIds) . ')');
845 // order by start date to find most recent membership first, CRM-4545
846 $dao->orderBy('start_date DESC');
849 if ($onlySameParentOrg && $memType) {
850 // require the same parent org as the $memType
851 $params = ['id' => $memType];
852 $membershipType = [];
853 if (CRM_Member_BAO_MembershipType
::retrieve($params, $membershipType)) {
854 $memberTypesSameParentOrg = civicrm_api3('MembershipType', 'get', [
855 'member_of_contact_id' => $membershipType['member_of_contact_id'],
860 $memberTypesSameParentOrgList = implode(',', array_keys($memberTypesSameParentOrg['values'] ??
[]));
861 $dao->whereAdd('membership_type_id IN (' . $memberTypesSameParentOrgList . ')');
865 if ($dao->find(TRUE)) {
867 CRM_Core_DAO
::storeValues($dao, $membership);
868 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
869 $membership['status_id'],
870 'is_current_member', 'id'
872 $ownerMemberId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
874 'owner_membership_id', 'id'
876 if ($ownerMemberId) {
877 $membership['id'] = $membership['membership_id'] = $ownerMemberId;
878 $membership['membership_contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
887 if ($onlySameParentOrg && $memType) {
888 // see if there is a membership that has same parent as $memType but different parent than $membershipID
889 if ($dao->id
&& CRM_Core_Permission
::check('edit memberships')) {
890 // CRM-10016, This is probably a backend renewal, and make sure we return the same membership thats being renewed.
897 unset($dao->membership_type_id
);
898 if ($dao->find(TRUE)) {
900 CRM_Core_DAO
::storeValues($dao, $membership);
901 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
902 $membership['status_id'],
903 'is_current_member', 'id'
912 * Combine all the importable fields from the lower levels object.
914 * @param string $contactType
916 * @param bool $status
919 * array of importable Fields
920 * @throws \CRM_Core_Exception
922 public static function importableFields($contactType = 'Individual', $status = TRUE) {
923 $fields = Civi
::cache('fields')->get('membership_importable_fields' . $contactType . $status);
926 $fields = ['' => ['title' => '- ' . ts('do not import') . ' -']];
929 $fields = ['' => ['title' => '- ' . ts('Membership Fields') . ' -']];
932 $tmpFields = CRM_Member_DAO_Membership
::import();
933 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
935 // Using new Dedupe rule.
937 'contact_type' => $contactType,
938 'used' => 'Unsupervised',
940 $fieldsArray = CRM_Dedupe_BAO_DedupeRule
::dedupeRuleFields($ruleParams);
942 $tmpContactField = [];
943 if (is_array($fieldsArray)) {
944 foreach ($fieldsArray as $value) {
945 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
950 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
951 $tmpContactField[trim($value)] = $contactFields[trim($value)] ??
NULL;
953 $title = $tmpContactField[trim($value)]['title'] . " " . ts('(match to contact)');
956 $title = $tmpContactField[trim($value)]['title'];
958 $tmpContactField[trim($value)]['title'] = $title;
961 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
962 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
964 $tmpFields['membership_contact_id']['title'] .= ' ' . ts('(match to contact)');
966 $fields = array_merge($fields, $tmpContactField);
967 $fields = array_merge($fields, $tmpFields);
968 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
969 Civi
::cache('fields')->set('membership_importable_fields' . $contactType . $status, $fields);
975 * Get all exportable fields.
977 * @return array return array of all exportable fields
979 public static function &exportableFields() {
980 $expFieldMembership = CRM_Member_DAO_Membership
::export();
982 $expFieldsMemType = CRM_Member_DAO_MembershipType
::export();
983 $fields = array_merge($expFieldMembership, $expFieldsMemType);
984 $fields = array_merge($fields, $expFieldMembership);
985 $membershipStatus = [
986 'membership_status' => [
987 'title' => ts('Membership Status'),
988 'name' => 'membership_status',
989 'type' => CRM_Utils_Type
::T_STRING
,
990 'where' => 'civicrm_membership_status.name',
993 //CRM-6161 fix for customdata export
994 $fields = array_merge($fields, $membershipStatus, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
995 $fields['membership_status_id'] = $membershipStatus['membership_status'];
1000 * Get membership joins/renewals for a specified membership type.
1002 * Specifically, retrieves a count of memberships whose "Membership
1003 * Signup" or "Membership Renewal" activity falls in the given date range.
1004 * Dates match the pattern "yyyy-mm-dd".
1006 * @param int $membershipTypeId
1007 * Membership type id.
1008 * @param int $startDate
1009 * Date on which to start counting.
1010 * @param int $endDate
1011 * Date on which to end counting.
1012 * @param bool|int $isTest if true, membership is for a test site
1013 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1016 * the number of members of type $membershipTypeId whose
1017 * start_date is between $startDate and $endDate
1019 public static function getMembershipStarts($membershipTypeId, $startDate, $endDate, $isTest = 0, $isOwner = 0) {
1020 // Ensure that the dates that are passed to the query are in the format of yyyy-mm-dd
1021 $dates = ['startDate', 'endDate'];
1022 foreach ($dates as $date) {
1023 if (strlen($
$date) === 8) {
1024 $
$date = date('Y-m-d', CRM_Utils_Time
::strtotime($
$date));
1028 $testClause = 'membership.is_test = 1';
1030 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1033 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1034 self
::_getActTypes();
1037 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1042 SELECT COUNT(DISTINCT membership.id) as member_count
1043 FROM civicrm_membership membership
1044 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id in (%1, %2))
1045 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1046 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1047 WHERE membership.membership_type_id = %3
1048 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1051 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1054 1 => [self
::$_signupActType, 'Integer'],
1055 2 => [self
::$_renewalActType, 'Integer'],
1056 3 => [$membershipTypeId, 'Integer'],
1059 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1060 return (int) $memberCount;
1064 * Get a count of membership for a specified membership type, optionally for a specified date.
1066 * The date must have the form yyyy-mm-dd.
1068 * If $date is omitted, this function counts as a member anyone whose
1069 * membership status_id indicates they're a current member.
1070 * If $date is given, this function counts as a member anyone who:
1071 * -- Has a start_date before $date and end_date after $date, or
1072 * -- Has a start_date before $date and is currently a member, as indicated
1073 * by the the membership's status_id.
1074 * The second condition takes care of records that have no end_date. These
1075 * are assumed to be lifetime memberships.
1077 * @param int $membershipTypeId
1078 * Membership type id.
1079 * @param string $date
1080 * The date for which to retrieve the count.
1081 * @param bool|int $isTest if true, membership is for a test site
1082 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1085 * the number of members of type $membershipTypeId as of $date.
1087 public static function getMembershipCount($membershipTypeId, $date = NULL, $isTest = 0, $isOwner = 0) {
1088 if (!CRM_Utils_Rule
::date($date)) {
1089 throw new CRM_Core_Exception(ts('Invalid date "%1" (must have form yyyy-mm-dd).', [1 => $date]));
1093 1 => [$membershipTypeId, 'Integer'],
1094 2 => [$isTest, 'Boolean'],
1096 $query = "SELECT count(civicrm_membership.id ) as member_count
1097 FROM civicrm_membership left join civicrm_membership_status on ( civicrm_membership.status_id = civicrm_membership_status.id )
1098 WHERE civicrm_membership.membership_type_id = %1
1099 AND civicrm_membership.contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)
1100 AND civicrm_membership.is_test = %2";
1102 $query .= " AND civicrm_membership_status.is_current_member = 1";
1105 $query .= " AND civicrm_membership.start_date <= '$date' AND civicrm_membership_status.is_current_member = 1";
1108 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1109 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1110 return (int) $memberCount;
1114 * Function check the status of the membership before adding membership for a contact.
1118 public static function statusAvailabilty() {
1119 $membership = new CRM_Member_DAO_MembershipStatus();
1120 $membership->whereAdd('is_active=1');
1121 return $membership->count();
1125 * @deprecated This is not used anywhere and should be removed soon!
1126 * Function for updating a membership record's contribution_recur_id.
1128 * @param CRM_Member_DAO_Membership $membership
1129 * @param \CRM_Contribute_BAO_Contribution|\CRM_Contribute_DAO_Contribution $contribution
1131 public static function updateRecurMembership(CRM_Member_DAO_Membership
$membership, CRM_Contribute_BAO_Contribution
$contribution) {
1132 CRM_Core_Error
::deprecatedFunctionWarning('Use the API instead');
1134 if (empty($contribution->contribution_recur_id
)) {
1139 1 => [$contribution->contribution_recur_id
, 'Integer'],
1140 2 => [$membership->id
, 'Integer'],
1143 $sql = "UPDATE civicrm_membership SET contribution_recur_id = %1 WHERE id = %2";
1144 CRM_Core_DAO
::executeQuery($sql, $params);
1148 * Method to fix membership status of stale membership.
1150 * This method first checks if the membership is stale. If it is,
1151 * then status will be updated based on existing start and end
1152 * dates and log will be added for the status change.
1154 * @param array $currentMembership
1155 * Reference to the array.
1156 * containing all values of
1157 * the current membership
1158 * @param string|null $changeToday
1159 * In case today needs
1160 * to be customised, null otherwise
1162 * @throws \CRM_Core_Exception
1164 public static function fixMembershipStatusBeforeRenew(&$currentMembership, $changeToday = NULL) {
1167 $today = CRM_Utils_Date
::processDate($changeToday, NULL, FALSE, 'Y-m-d');
1170 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
1171 $currentMembership['start_date'] ??
NULL,
1172 $currentMembership['end_date'] ??
NULL,
1173 $currentMembership['join_date'] ??
NULL,
1176 $currentMembership['membership_type_id'],
1180 if (empty($status) ||
empty($status['id'])) {
1181 throw new CRM_Core_Exception(ts('Oops, it looks like there is no valid membership status corresponding to the membership start and end dates for this membership. Contact the site administrator for assistance.'));
1184 if ($status['id'] !== $currentMembership['status_id']) {
1185 $oldStatus = $currentMembership['status_id'];
1186 $memberDAO = new CRM_Member_DAO_Membership();
1187 $memberDAO->id
= $currentMembership['id'];
1188 $memberDAO->find(TRUE);
1190 $memberDAO->status_id
= $status['id'];
1192 CRM_Core_DAO
::storeValues($memberDAO, $currentMembership);
1194 $currentMembership['is_current_member'] = CRM_Core_DAO
::getFieldValue(
1195 'CRM_Member_DAO_MembershipStatus',
1196 $currentMembership['status_id'],
1202 'membership_id' => $currentMembership['id'],
1203 'status_id' => $status['id'],
1204 'start_date' => CRM_Utils_Date
::customFormat(
1205 $currentMembership['start_date'],
1208 'end_date' => CRM_Utils_Date
::customFormat(
1209 $currentMembership['end_date'],
1212 'modified_date' => date('Y-m-d H:i:s', CRM_Utils_Time
::strtotime($today)),
1213 'membership_type_id' => $currentMembership['membership_type_id'],
1214 'max_related' => $currentMembership['max_related'] ??
0,
1217 $session = CRM_Core_Session
::singleton();
1218 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
1219 if ($session->get('userID')) {
1220 $logParams['modified_id'] = $session->get('userID');
1223 $logParams['modified_id'] = $currentMembership['contact_id'];
1226 //Create activity for status change.
1227 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
1228 CRM_Activity_BAO_Activity
::addActivity($memberDAO,
1229 'Change Membership Status',
1232 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$status['id']]}",
1233 'source_contact_id' => $logParams['modified_id'],
1234 'priority_id' => 'Normal',
1238 CRM_Member_BAO_MembershipLog
::add($logParams);
1243 * Get the contribution page id from the membership record.
1245 * @param int $membershipID
1248 * contribution page id
1250 public static function getContributionPageId($membershipID) {
1252 SELECT c.contribution_page_id as pageID
1253 FROM civicrm_membership_payment mp, civicrm_contribution c
1254 WHERE mp.contribution_id = c.id
1255 AND c.contribution_page_id IS NOT NULL
1256 AND mp.membership_id = " . CRM_Utils_Type
::escape($membershipID, 'Integer')
1257 . " ORDER BY mp.id DESC";
1259 return CRM_Core_DAO
::singleValueQuery($query);
1263 * Updated related memberships.
1265 * @param int $ownerMembershipId
1266 * Owner Membership Id.
1267 * @param array $params
1268 * Formatted array of key => value.
1270 public static function updateRelatedMemberships($ownerMembershipId, $params) {
1271 $membership = new CRM_Member_DAO_Membership();
1272 $membership->owner_membership_id
= $ownerMembershipId;
1273 $membership->find();
1275 while ($membership->fetch()) {
1276 $relatedMembership = new CRM_Member_DAO_Membership();
1277 $relatedMembership->id
= $membership->id
;
1278 $relatedMembership->copyValues($params);
1279 $relatedMembership->save();
1285 * Get list of membership fields for profile.
1287 * For now we only allow custom membership fields to be in
1291 * FIXME: This param is ignored
1294 * the list of membership fields
1296 public static function getMembershipFields($mode = NULL) {
1297 $fields = CRM_Member_DAO_Membership
::export();
1299 unset($fields['membership_contact_id']);
1300 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1302 $membershipType = CRM_Member_DAO_MembershipType
::export();
1304 $membershipStatus = CRM_Member_DAO_MembershipStatus
::export();
1306 $fields = array_merge($fields, $membershipType, $membershipStatus);
1312 * Get the sort name of a contact for a particular membership.
1315 * Id of the membership.
1317 * @return null|string
1318 * sort name of the contact if found
1320 public static function sortName($id) {
1321 $id = CRM_Utils_Type
::escape($id, 'Integer');
1324 SELECT civicrm_contact.sort_name
1325 FROM civicrm_membership, civicrm_contact
1326 WHERE civicrm_membership.contact_id = civicrm_contact.id
1327 AND civicrm_membership.id = {$id}
1329 return CRM_Core_DAO
::singleValueQuery($query);
1333 * Create memberships for related contacts, taking into account the maximum related memberships.
1335 * @param array $params
1336 * Array of key - value pairs.
1337 * @param CRM_Core_DAO $dao
1338 * Membership object.
1340 * @throws \CRM_Core_Exception
1341 * @throws \CiviCRM_API3_Exception
1343 public static function createRelatedMemberships($params, $dao) {
1344 unset($params['membership_id']);
1345 $membership = new CRM_Member_DAO_Membership();
1346 $membership->id
= $dao->id
;
1348 // required since create method doesn't return all the
1349 // parameters in the returned membership object
1350 if (!$membership->find(TRUE)) {
1353 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1354 // FIXME : While updating/ renewing the
1355 // membership, if the relationship is PAST then
1356 // the membership of the related contact must be
1358 // For that, getting Membership Status for which
1359 // is_current_member is 0. It works for the
1360 // generated data as there is only one membership
1361 // status having is_current_member = 0.
1362 // But this wont work exactly if there will be
1363 // more than one status having is_current_member = 0.
1364 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
1365 $membershipStatus->is_current_member
= 0;
1366 if ($membershipStatus->find(TRUE)) {
1367 $expiredStatusId = $membershipStatus->id
;
1370 $expiredStatusId = array_search('Expired', CRM_Member_PseudoConstant
::membershipStatus());
1373 $relatedContacts = [];
1374 $allRelatedContacts = CRM_Member_BAO_Membership
::checkMembershipRelationship($membership->membership_type_id
,
1375 $membership->contact_id
,
1376 $params['action'] ??
NULL
1379 // CRM-4213, CRM-19735 check for loops, using static variable to record contacts already processed.
1380 // Remove repeated related contacts, which already inherited membership of this type$relatedContactIds[$membership->contact_id][$membership->membership_type_id] = TRUE;
1381 foreach ($allRelatedContacts as $cid => $status) {
1382 // relatedContactIDs is always empty now - will remove next roud because of whitespace readability.
1383 if (empty($relatedContactIds[$cid]) ||
empty($relatedContactIds[$cid][$membership->membership_type_id
])) {
1384 $relatedContactIds[$cid][$membership->membership_type_id
] = TRUE;
1386 //don't create membership again for owner contact.
1387 $nestedRelationship = FALSE;
1388 if ($membership->owner_membership_id
) {
1389 $nestedRelMembership = new CRM_Member_DAO_Membership();
1390 $nestedRelMembership->id
= $membership->owner_membership_id
;
1391 $nestedRelMembership->contact_id
= $cid;
1392 $nestedRelationship = $nestedRelMembership->find(TRUE);
1394 if (!$nestedRelationship) {
1395 $relatedContacts[$cid] = $status;
1400 //lets cleanup related membership if any.
1401 if (empty($relatedContacts)) {
1402 self
::deleteRelatedMemberships($membership->id
);
1405 // Edit the params array
1406 unset($params['id']);
1407 // Reminder should be sent only to the direct membership
1408 unset($params['reminder_date']);
1409 // unset the custom value ids
1410 if (isset($params['custom']) && is_array($params['custom'])) {
1411 foreach ($params['custom'] as $k => $values) {
1412 foreach ($values as $i => $value) {
1413 unset($params['custom'][$k][$i]['id']);
1417 if (!isset($params['membership_type_id'])) {
1418 $params['membership_type_id'] = $membership->membership_type_id
;
1421 // max_related should be set in the parent membership
1422 unset($params['max_related']);
1423 // Number of inherited memberships available - NULL is interpreted as unlimited, '0' as none
1424 $numRelatedAvailable = ($membership->max_related
== NULL ? PHP_INT_MAX
: $membership->max_related
);
1425 // will be used to queue potential memberships to be created.
1428 foreach ($relatedContacts as $contactId => $relationshipStatus) {
1429 //use existing membership record.
1430 $relMembership = new CRM_Member_DAO_Membership();
1431 $relMembership->contact_id
= $contactId;
1432 $relMembership->owner_membership_id
= $membership->id
;
1434 if ($relMembership->find(TRUE)) {
1435 $params['id'] = $relMembership->id
;
1438 unset($params['id']);
1441 $params['contact_id'] = $contactId;
1442 $params['owner_membership_id'] = $membership->id
;
1444 // set status_id as it might have been changed for
1445 // past relationship
1446 $params['status_id'] = $membership->status_id
;
1448 if ($deceasedStatusId &&
1449 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'is_deceased')
1451 $params['status_id'] = $deceasedStatusId;
1453 elseif ((($params['action'] ??
NULL) & CRM_Core_Action
::UPDATE
) &&
1454 ($relationshipStatus == CRM_Contact_BAO_Relationship
::PAST
)
1456 $params['status_id'] = $expiredStatusId;
1459 //don't calculate status again in create( );
1460 $params['skipStatusCal'] = TRUE;
1462 //do create activity if we changed status.
1463 if ($params['status_id'] != $relMembership->status_id
) {
1464 $params['createActivity'] = TRUE;
1467 //CRM-20707 - include start/end date
1468 $params['start_date'] = $membership->start_date
;
1469 $params['end_date'] = $membership->end_date
;
1471 // we should not created contribution record for related contacts, CRM-3371
1472 unset($params['contribution_status_id']);
1474 //CRM-16857: Do not create multiple line-items for inherited membership through priceset.
1475 unset($params['lineItems']);
1476 unset($params['line_item']);
1478 // CRM-20966: Do not create membership_payment record for inherited membership.
1479 unset($params['relate_contribution_id']);
1481 if (($params['status_id'] == $deceasedStatusId) ||
($params['status_id'] == $expiredStatusId)) {
1482 // related membership is not active so does not count towards maximum
1483 if (!self
::hasExistingInheritedMembership($params)) {
1484 civicrm_api3('Membership', 'create', $params);
1488 // related membership already exists, so this is just an update
1489 if (isset($params['id'])) {
1490 if ($numRelatedAvailable > 0) {
1491 CRM_Member_BAO_Membership
::create($params);
1492 $numRelatedAvailable--;
1495 // we have run out of inherited memberships, so delete extras
1496 self
::deleteMembership($params['id']);
1498 // we need to first check if there will remain inherited memberships, so queue it up
1505 // now go over the queue and create any available related memberships
1506 foreach ($queue as $params) {
1507 if ($numRelatedAvailable <= 0) {
1510 if (!self
::hasExistingInheritedMembership($params)) {
1511 CRM_Member_BAO_Membership
::create($params);
1513 $numRelatedAvailable--;
1519 * Delete the record that are associated with this Membership Payment.
1521 * @param int $membershipId
1522 * @param bool $preserveContrib
1525 * $membershipPayment deleted membership payment object
1527 public static function deleteMembershipPayment($membershipId, $preserveContrib = FALSE) {
1529 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
1530 $membershipPayment->membership_id
= $membershipId;
1531 $membershipPayment->find();
1533 while ($membershipPayment->fetch()) {
1534 if (!$preserveContrib) {
1535 CRM_Contribute_BAO_Contribution
::deleteContribution($membershipPayment->contribution_id
);
1537 CRM_Utils_Hook
::pre('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1538 $membershipPayment->delete();
1539 CRM_Utils_Hook
::post('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1541 return $membershipPayment;
1545 * Build an array of available membership types in the current context.
1547 * While core does not do anything context specific extensions may filter
1548 * or alter amounts based on user details.
1550 * @param CRM_Core_Form $form
1551 * @param array $membershipTypeID
1552 * @param bool $activeOnly
1553 * Do we only want active ones?
1554 * (probably this should default to TRUE but as a newly added parameter we are leaving default b
1555 * behaviour unchanged).
1559 * @throws \CiviCRM_API3_Exception
1561 public static function buildMembershipTypeValues($form, $membershipTypeID = [], $activeOnly = FALSE) {
1562 $membershipTypeIDS = (array) $membershipTypeID;
1563 $membershipTypeValues = CRM_Member_BAO_MembershipType
::getAllMembershipTypes();
1565 // MembershipTypes are already filtered by domain, filter as appropriate by is_active & a passed in list of ids.
1566 foreach ($membershipTypeValues as $id => $type) {
1567 if (($activeOnly && empty($type['is_active']))
1568 ||
(!empty($membershipTypeIDS) && !in_array($id, $membershipTypeIDS, FALSE))
1570 unset($membershipTypeValues[$id]);
1574 CRM_Utils_Hook
::membershipTypeValues($form, $membershipTypeValues);
1575 return $membershipTypeValues;
1579 * Get membership record count for a Contact.
1581 * @param int $contactID
1582 * @param bool $activeOnly
1585 * @throws \API_Exception
1587 public static function getContactMembershipCount(int $contactID, $activeOnly = FALSE): int {
1589 $membershipTypes = MembershipType
::get(TRUE)
1593 $addWhere = " AND membership_type_id IN (0)";
1594 if (!empty($membershipTypes)) {
1595 $addWhere = " AND membership_type_id IN (" . implode(',', array_keys($membershipTypes)) . ")";
1598 $select = "SELECT COUNT(*) FROM civicrm_membership ";
1599 $where = "WHERE civicrm_membership.contact_id = {$contactID} AND civicrm_membership.is_test = 0 ";
1601 // CRM-6627, all status below 3 (active, pending, grace) are considered active
1603 $select .= " INNER JOIN civicrm_membership_status ON civicrm_membership.status_id = civicrm_membership_status.id ";
1604 $where .= " and civicrm_membership_status.is_current_member = 1";
1607 $query = $select . $where . $addWhere;
1608 return (int) CRM_Core_DAO
::singleValueQuery($query);
1610 catch (UnauthorizedException
$e) {
1616 * Check whether payment processor supports cancellation of membership subscription.
1621 * @param bool $isNotCancelled
1625 public static function isCancelSubscriptionSupported($mid, $isNotCancelled = TRUE) {
1626 $cacheKeyString = "$mid";
1627 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
1629 static $supportsCancel = [];
1631 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
1632 $supportsCancel[$cacheKeyString] = FALSE;
1633 $isCancelled = FALSE;
1635 if ($isNotCancelled) {
1636 $isCancelled = self
::isSubscriptionCancelled($mid);
1639 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($mid, 'membership', 'obj');
1640 if (!empty($paymentObject)) {
1641 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
1644 return $supportsCancel[$cacheKeyString];
1648 * Check whether subscription is already cancelled.
1654 * contribution status
1656 public static function isSubscriptionCancelled($mid) {
1658 SELECT cr.contribution_status_id
1659 FROM civicrm_contribution_recur cr
1660 LEFT JOIN civicrm_membership mem ON ( cr.id = mem.contribution_recur_id )
1661 WHERE mem.id = %1 LIMIT 1";
1662 $params = [1 => [$mid, 'Integer']];
1663 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
1664 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
1665 if ($status == 'Cancelled') {
1672 * Get membership joins for a specified membership type.
1674 * Specifically, retrieves a count of still current memberships whose
1675 * join_date and start_date are within a specified date range. Dates match
1676 * the pattern "yyyy-mm-dd".
1678 * @param int $membershipTypeId
1679 * Membership type id.
1680 * @param int $startDate
1681 * Date on which to start counting.
1682 * @param int $endDate
1683 * Date on which to end counting.
1684 * @param bool|int $isTest if true, membership is for a test site
1687 * the number of members of type $membershipTypeId
1688 * whose join_date is between $startDate and $endDate and
1689 * whose start_date is between $startDate and $endDate
1691 public static function getMembershipJoins($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1692 $testClause = 'membership.is_test = 1';
1694 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1696 if (!self
::$_signupActType) {
1697 self
::_getActTypes();
1700 if (!self
::$_signupActType) {
1705 SELECT COUNT(DISTINCT membership.id) as member_count
1706 FROM civicrm_membership membership
1707 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1708 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1709 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1710 WHERE membership.membership_type_id = %2
1711 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1715 1 => [self
::$_signupActType, 'Integer'],
1716 2 => [$membershipTypeId, 'Integer'],
1719 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1721 return (int) $memberCount;
1725 * Get membership renewals for a specified membership type.
1727 * Specifically, retrieves a count of still current memberships
1728 * whose join_date is before and start_date is within a specified date
1729 * range. Dates match the pattern "yyyy-mm-dd".
1731 * @param int $membershipTypeId
1732 * Membership type id.
1733 * @param int $startDate
1734 * Date on which to start counting.
1735 * @param int $endDate
1736 * Date on which to end counting.
1737 * @param bool|int $isTest if true, membership is for a test site
1740 * returns the number of members of type $membershipTypeId
1741 * whose join_date is before $startDate and
1742 * whose start_date is between $startDate and $endDate
1744 public static function getMembershipRenewals($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1745 $testClause = 'membership.is_test = 1';
1747 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1749 if (!self
::$_renewalActType) {
1750 self
::_getActTypes();
1753 if (!self
::$_renewalActType) {
1758 SELECT COUNT(DISTINCT membership.id) as member_count
1759 FROM civicrm_membership membership
1760 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1761 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1762 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1763 WHERE membership.membership_type_id = %2
1764 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1768 1 => [self
::$_renewalActType, 'Integer'],
1769 2 => [$membershipTypeId, 'Integer'],
1771 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1773 return (int) $memberCount;
1779 * @param int $contactID
1780 * @param int $membershipTypeID
1781 * @param bool $is_test
1782 * @param string $changeToday
1783 * @param int $modifiedID
1784 * @param $customFieldsFormatted
1785 * @param $numRenewTerms
1786 * @param int $membershipID
1788 * @param int $contributionRecurID
1789 * @param $membershipSource
1790 * @param $isPayLater
1791 * @param array $memParams
1792 * @param null|CRM_Contribute_BAO_Contribution $contribution
1793 * @param array $lineItems
1796 * @throws \CRM_Core_Exception
1797 * @throws \CiviCRM_API3_Exception
1799 public static function processMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $contributionRecurID, $membershipSource, $isPayLater, $memParams = [], $contribution = NULL, $lineItems = []) {
1800 CRM_Core_Error
::deprecatedFunctionWarning('use the order api, BAO functions should only be called from unit tested core code.');
1801 $renewalMode = $updateStatusId = FALSE;
1802 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1804 $statusFormat = '%Y-%m-%d';
1805 $membershipTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipType($membershipTypeID);
1809 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
1810 // is the same as the parent org of an existing membership of the contact
1811 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($contactID, $membershipTypeID,
1812 $is_test, $membershipID, TRUE
1814 if ($currentMembership) {
1815 $renewalMode = TRUE;
1817 // Do NOT do anything.
1818 //1. membership with status : PENDING/CANCELLED (CRM-2395)
1819 //2. Paylater/IPN renew. CRM-4556.
1820 if ($pending ||
in_array($currentMembership['status_id'], [
1821 array_search('Pending', $allStatus),
1823 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1826 $memParams = array_merge([
1827 'id' => $currentMembership['id'],
1828 'contribution' => $contribution,
1829 'status_id' => $currentMembership['status_id'],
1830 'start_date' => $currentMembership['start_date'],
1831 'end_date' => $currentMembership['end_date'],
1832 'line_item' => $lineItems,
1833 'join_date' => $currentMembership['join_date'],
1834 'membership_type_id' => $membershipTypeID,
1835 'max_related' => !empty($membershipTypeDetails['max_related']) ?
$membershipTypeDetails['max_related'] : NULL,
1836 'membership_activity_status' => ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed',
1838 if ($contributionRecurID) {
1839 $memParams['contribution_recur_id'] = $contributionRecurID;
1842 $membership = self
::create($memParams);
1843 return [$membership, $renewalMode, $dates];
1846 // Check and fix the membership if it is STALE
1847 self
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
1849 // Now Renew the membership
1850 if (!$currentMembership['is_current_member']) {
1851 // membership is not CURRENT
1853 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1854 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($currentMembership['id'],
1860 $currentMembership['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1861 foreach (['start_date', 'end_date'] as $dateType) {
1862 $currentMembership[$dateType] = $dates[$dateType] ??
NULL;
1864 $currentMembership['is_test'] = $is_test;
1866 if (!empty($membershipSource)) {
1867 $currentMembership['source'] = $membershipSource;
1870 if (!empty($currentMembership['id'])) {
1871 $ids['membership'] = $currentMembership['id'];
1873 $memParams = array_merge($currentMembership, $memParams);
1874 $memParams['membership_type_id'] = $membershipTypeID;
1876 //set the log start date.
1877 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1881 // CURRENT Membership
1882 $membership = new CRM_Member_DAO_Membership();
1883 $membership->id
= $currentMembership['id'];
1884 $membership->find(TRUE);
1885 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1886 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
1892 // Insert renewed dates for CURRENT membership
1893 $memParams['join_date'] = CRM_Utils_Date
::isoToMysql($membership->join_date
);
1894 $memParams['start_date'] = CRM_Utils_Date
::isoToMysql($membership->start_date
);
1895 $memParams['end_date'] = $dates['end_date'] ??
NULL;
1896 $memParams['membership_type_id'] = $membershipTypeID;
1898 //set the log start date.
1899 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1902 if (!empty($membershipSource)) {
1903 $memParams['source'] = $membershipSource;
1905 elseif (empty($membership->source
)) {
1906 $memParams['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
1907 $currentMembership['id'],
1912 if (!empty($currentMembership['id'])) {
1913 $ids['membership'] = $currentMembership['id'];
1915 $memParams['membership_activity_status'] = ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed';
1920 $memParams = array_merge([
1921 'contact_id' => $contactID,
1922 'membership_type_id' => $membershipTypeID,
1926 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
1928 foreach (['join_date', 'start_date', 'end_date'] as $dateType) {
1929 $memParams[$dateType] = $dates[$dateType] ??
NULL;
1932 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(CRM_Utils_Date
::customFormat($dates['start_date'],
1935 CRM_Utils_Date
::customFormat($dates['end_date'],
1938 CRM_Utils_Date
::customFormat($dates['join_date'],
1946 $updateStatusId = $status['id'] ??
NULL;
1949 // if IPN/Pay-Later set status to: PENDING
1950 $updateStatusId = array_search('Pending', $allStatus);
1953 if (!empty($membershipSource)) {
1954 $memParams['source'] = $membershipSource;
1956 $memParams['is_test'] = $is_test;
1957 $memParams['is_pay_later'] = $isPayLater;
1959 // Putting this in an IF is precautionary as it seems likely that it would be ignored if empty, but
1960 // perhaps shouldn't be?
1961 if ($contributionRecurID) {
1962 $memParams['contribution_recur_id'] = $contributionRecurID;
1965 //if we decided status here and want to skip status
1966 //calculation in create( ); then need to pass 'skipStatusCal'.
1967 if ($updateStatusId) {
1968 $memParams['status_id'] = $updateStatusId;
1969 $memParams['skipStatusCal'] = TRUE;
1972 //since we are renewing,
1973 //make status override false.
1974 $memParams['is_override'] = FALSE;
1976 //CRM-4027, create log w/ individual contact.
1978 // @todo this param is likely unused now.
1979 $memParams['is_for_organization'] = TRUE;
1981 $params['modified_id'] = $modifiedID ??
$contactID;
1983 $memParams['contribution'] = $contribution;
1984 $memParams['custom'] = $customFieldsFormatted;
1985 // Load all line items & process all in membership. Don't do in contribution.
1986 // Relevant tests in api_v3_ContributionPageTest.
1987 $memParams['line_item'] = $lineItems;
1988 // @todo stop passing $ids (membership and userId may be set by this point)
1989 $membership = self
::create($memParams, $ids);
1991 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
1992 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
1993 $membership->find(TRUE);
1995 return [$membership, $renewalMode, $dates];
1999 * Get line items representing the default price set.
2001 * @param int $membershipOrg
2002 * @param int $membershipTypeID
2003 * @param float $total_amount
2004 * @param int $priceSetId
2008 public static function setQuickConfigMembershipParameters($membershipOrg, $membershipTypeID, $total_amount, $priceSetId) {
2009 $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
2011 // The name of the price field corresponds to the membership_type organization contact.
2013 'price_set_id' => $priceSetId,
2014 'name' => $membershipOrg,
2017 CRM_Price_BAO_PriceField
::retrieve($params, $results);
2019 if (!empty($results)) {
2020 $fields[$results['id']] = $priceSets['fields'][$results['id']];
2021 $fid = $results['id'];
2022 $editedFieldParams = [
2023 'price_field_id' => $results['id'],
2024 'membership_type_id' => $membershipTypeID,
2027 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $results);
2028 $fields[$fid]['options'][$results['id']] = $priceSets['fields'][$fid]['options'][$results['id']];
2029 if (!empty($total_amount)) {
2030 $fields[$fid]['options'][$results['id']]['amount'] = $total_amount;
2034 $fieldID = key($fields);
2036 'price_set_id' => $priceSetId,
2037 'price_sets' => $priceSets,
2038 'fields' => $fields,
2040 'price_' . $fieldID => $results['id'] ??
NULL,
2043 return $returnParams;
2047 * Update the status of all deceased members to deceased.
2050 * Count of updated contacts.
2052 * @throws \CiviCRM_API3_Exception
2053 * @throws \CRM_Core_Exception
2055 protected static function updateDeceasedMembersStatuses() {
2058 $deceasedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Deceased');
2060 // 'create' context for buildOptions returns only if enabled.
2061 $allStatus = self
::buildOptions('status_id', 'create');
2062 if (array_key_exists($deceasedStatusId, $allStatus) === FALSE) {
2063 // Deceased status is an admin status & is required. We want to fail early if
2064 // it is not present or active.
2065 // We could make the case 'some databases just don't use deceased so we will check
2066 // for the presence of a deceased contact in the DB before rejecting.
2067 if (CRM_Core_DAO
::singleValueQuery('
2068 SELECT count(*) FROM civicrm_contact WHERE is_deceased = 0'
2070 throw new CRM_Core_Exception(
2071 ts("Deceased Membership status is missing or not active. <a href='%1'>Click here to check</a>.",
2072 [1 => CRM_Utils_System
::url('civicrm/admin/member/membershipStatus', 'reset=1')]
2076 $deceasedDAO = CRM_Core_DAO
::executeQuery(
2078 SELECT membership.id as membership_id
2079 FROM civicrm_membership membership
2080 INNER JOIN civicrm_contact ON membership.contact_id = civicrm_contact.id
2081 INNER JOIN civicrm_membership_type ON membership.membership_type_id = civicrm_membership_type.id
2082 AND civicrm_membership_type.is_active = 1
2083 WHERE membership.is_test = 0
2084 AND civicrm_contact.is_deceased = 1
2085 AND membership.status_id <> %1
2087 [1 => [$deceasedStatusId, 'Integer']]
2089 while ($deceasedDAO->fetch()) {
2090 civicrm_api3('membership', 'create', [
2091 'id' => $deceasedDAO->membership_id
,
2092 'status_id' => $deceasedStatusId,
2093 'createActivity' => TRUE,
2094 'skipStatusCal' => TRUE,
2095 'skipRecentView' => TRUE,
2103 * Does the existing membership match the required membership.
2105 * Check before updating that the params are not a match - this is part of avoiding
2106 * a loop if we have already updated.
2108 * https://issues.civicrm.org/jira/browse/CRM-4213
2109 * @param array $params
2111 * @param array $membership
2115 protected static function matchesRequiredMembership($params, $membership) {
2116 foreach (['start_date', 'end_date'] as $date) {
2117 if (CRM_Utils_Time
::strtotime($params[$date]) !== CRM_Utils_Time
::strtotime($membership[$date])) {
2120 if ((int) $params['status_id'] !== (int) $membership['status_id']) {
2123 if ((int) $params['membership_type_id'] !== (int) $membership['membership_type_id']) {
2131 * Params of new membership.
2133 * @param array $params
2136 * @throws \CiviCRM_API3_Exception
2138 protected static function hasExistingInheritedMembership($params) {
2139 foreach (civicrm_api3('Membership', 'get', ['contact_id' => $params['contact_id']])['values'] as $membership) {
2140 if (!empty($membership['owner_membership_id'])
2141 && $membership['membership_type_id'] === $params['membership_type_id']
2142 && (int) $params['owner_membership_id'] !== (int) $membership['owner_membership_id']
2144 // Inheriting it from another contact, don't update here.
2147 if (self
::matchesRequiredMembership($params, $membership)) {
2155 * Process price set and line items.
2157 * @param int $membershipId
2158 * @param array $lineItem
2160 * @throws \CiviCRM_API3_Exception
2162 public function processPriceSet($membershipId, $lineItem) {
2163 //FIXME : need to move this too
2164 if (!$membershipId ||
!is_array($lineItem)
2165 || CRM_Utils_System
::isNull($lineItem)
2170 foreach ($lineItem as $priceSetId => $values) {
2174 foreach ($values as $line) {
2175 $line['entity_table'] = 'civicrm_membership';
2176 $line['entity_id'] = $membershipId;
2177 CRM_Price_BAO_LineItem
::create($line);
2183 * Retrieve the contribution id for the associated Membership id.
2184 * @todo we should get this off the line item
2186 * @param int $membershipId
2189 * if more than one payment associated with membership id need to be returned.
2193 * @todo we should get this off the line item
2196 public static function getMembershipContributionId($membershipId, $all = FALSE) {
2198 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
2199 $membershipPayment->membership_id
= $membershipId;
2200 if ($all && $membershipPayment->find()) {
2201 $contributionIds = [];
2202 while ($membershipPayment->fetch()) {
2203 $contributionIds[] = $membershipPayment->contribution_id
;
2205 return $contributionIds;
2208 if ($membershipPayment->find(TRUE)) {
2209 return $membershipPayment->contribution_id
;
2215 * The function checks and updates the status of all membership records for a given domain using the
2216 * calc_membership_status and update_contact_membership APIs.
2219 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
2221 * @param array $params
2222 * only_active_membership_types, exclude_test_memberships, exclude_membership_status_ids
2226 * @throws \CiviCRM_API3_Exception
2227 * @throws \CRM_Core_Exception
2229 public static function updateAllMembershipStatus($params = []) {
2230 // We want all of the statuses as id => name, even the disabled ones (cf.
2231 // CRM-15475), to identify which are Pending, Deceased, Cancelled, and
2233 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'validate');
2234 if (empty($params['exclude_membership_status_ids'])) {
2235 $params['exclude_membership_status_ids'] = [
2236 array_search('Pending', $allStatus),
2237 array_search('Cancelled', $allStatus),
2238 array_search('Expired', $allStatus) ?
: 0,
2239 array_search('Deceased', $allStatus),
2242 // Deceased is *always* excluded because it is has very specific processing below.
2243 elseif (!in_array(array_search('Deceased', $allStatus), $params['exclude_membership_status_ids'])) {
2244 $params['exclude_membership_status_ids'][] = array_search('Deceased', $allStatus);
2247 for ($index = 0; $index < count($params['exclude_membership_status_ids']); $index++
) {
2248 $queryParams[$index] = [$params['exclude_membership_status_ids'][$index], 'Integer'];
2250 $membershipStatusClause = 'civicrm_membership.status_id NOT IN (%' . implode(', %', array_keys($queryParams)) . ')';
2252 // Tests for this function are in api_v3_JobTest. Please add tests for all updates.
2254 $updateCount = $processCount = self
::updateDeceasedMembersStatuses();
2256 $whereClauses[] = 'civicrm_contact.is_deceased = 0';
2257 if ($params['exclude_test_memberships']) {
2258 $whereClauses[] = 'civicrm_membership.is_test = 0';
2260 $whereClause = implode(' AND ', $whereClauses);
2261 $activeMembershipClause = '';
2262 if ($params['only_active_membership_types']) {
2263 $activeMembershipClause = ' AND civicrm_membership_type.is_active = 1';
2266 // This query retrieves ALL memberships of active types.
2268 SELECT civicrm_membership.id as membership_id,
2269 civicrm_membership.is_override as is_override,
2270 civicrm_membership.status_override_end_date as status_override_end_date,
2271 civicrm_membership.membership_type_id as membership_type_id,
2272 civicrm_membership.status_id as status_id,
2273 civicrm_membership.join_date as join_date,
2274 civicrm_membership.start_date as start_date,
2275 civicrm_membership.end_date as end_date,
2276 civicrm_membership.source as source,
2277 civicrm_contact.id as contact_id,
2278 civicrm_membership.owner_membership_id as owner_membership_id,
2279 civicrm_membership.contribution_recur_id as recur_id
2280 FROM civicrm_membership
2281 INNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )
2282 INNER JOIN civicrm_membership_type ON
2283 (civicrm_membership.membership_type_id = civicrm_membership_type.id {$activeMembershipClause})
2284 WHERE {$whereClause}";
2286 $query = $baseQuery . " AND civicrm_membership.is_override IS NOT NULL AND civicrm_membership.status_override_end_date IS NOT NULL";
2287 $dao1 = CRM_Core_DAO
::executeQuery($query);
2288 while ($dao1->fetch()) {
2289 self
::processOverriddenUntilDateMembership($dao1);
2292 $query = $baseQuery . " AND (civicrm_membership.is_override = 0 OR civicrm_membership.is_override IS NULL)
2293 AND {$membershipStatusClause}
2294 AND civicrm_membership.owner_membership_id IS NULL ";
2296 $allMembershipTypes = CRM_Member_BAO_MembershipType
::getAllMembershipTypes();
2298 $dao2 = CRM_Core_DAO
::executeQuery($query, $queryParams);
2300 while ($dao2->fetch()) {
2303 // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses
2304 //get the membership status as per id.
2305 $newStatus = civicrm_api3('membership_status', 'calc',
2307 'membership_id' => $dao2->membership_id
,
2308 'ignore_admin_only' => TRUE,
2311 $statusId = $newStatus['id'] ??
NULL;
2313 //process only when status change.
2315 $statusId != $dao2->status_id
2318 'id' => $dao2->membership_id
,
2319 'skipStatusCal' => TRUE,
2320 'skipRecentView' => TRUE,
2321 'status_id' => $statusId,
2322 'createActivity' => TRUE,
2325 //process member record.
2326 civicrm_api3('membership', 'create', $memberParams);
2330 $result['is_error'] = 0;
2331 $result['messages'] = ts('Processed %1 membership records. Updated %2 records.', [
2339 * Set is_override for the 'overridden until date' membership to
2340 * False and clears the 'until date' field in case the 'until date'
2341 * is equal or after today date.
2343 * @param CRM_Core_DAO $membership
2344 * The membership to be processed
2346 * @throws \CiviCRM_API3_Exception
2348 private static function processOverriddenUntilDateMembership($membership) {
2349 $isOverriddenUntilDate = !empty($membership->is_override
) && !empty($membership->status_override_end_date
);
2350 if (!$isOverriddenUntilDate) {
2354 $todayDate = new DateTime();
2355 $todayDate->setTime(0, 0);
2357 $overrideEndDate = new DateTime($membership->status_override_end_date
);
2358 $overrideEndDate->setTime(0, 0);
2360 $datesDifference = $todayDate->diff($overrideEndDate);
2361 $daysDifference = (int) $datesDifference->format('%R%a');
2362 if ($daysDifference <= 0) {
2364 'id' => $membership->membership_id
,
2365 'is_override' => FALSE,
2366 'status_override_end_date' => 'null',
2368 civicrm_api3('membership', 'create', $params);
2373 * Returns the membership types for a particular contact
2374 * who has lifetime membership without end date.
2376 * @param int $contactID
2377 * @param bool $isTest
2378 * @param bool $onlyLifeTime
2382 public static function getAllContactMembership($contactID, $isTest = FALSE, $onlyLifeTime = FALSE) {
2383 $contactMembershipType = [];
2385 return $contactMembershipType;
2388 $dao = new CRM_Member_DAO_Membership();
2389 $dao->contact_id
= $contactID;
2390 $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
2391 $dao->whereAdd("status_id != $pendingStatusId");
2394 $dao->is_test
= $isTest;
2397 $dao->whereAdd('is_test IS NULL OR is_test = 0');
2400 if ($onlyLifeTime) {
2401 $dao->whereAdd('end_date IS NULL');
2405 while ($dao->fetch()) {
2407 CRM_Core_DAO
::storeValues($dao, $membership);
2408 $contactMembershipType[$dao->membership_type_id
] = $membership;
2410 return $contactMembershipType;
2414 * Record contribution record associated with membership.
2415 * This will update an existing contribution if $params['contribution_id'] is passed in.
2416 * This will create a MembershipPayment to link the contribution and membership
2418 * @param array $params
2419 * Array of submitted params.
2421 * @return CRM_Contribute_BAO_Contribution
2422 * @throws \CRM_Core_Exception
2423 * @throws \CiviCRM_API3_Exception
2425 public static function recordMembershipContribution(&$params) {
2426 $contributionParams = [];
2427 $config = CRM_Core_Config
::singleton();
2428 $contributionParams['currency'] = $config->defaultCurrency
;
2429 $contributionParams['receipt_date'] = !empty($params['receipt_date']) ?
$params['receipt_date'] : 'null';
2430 $contributionParams['source'] = $params['contribution_source'] ??
NULL;
2431 $contributionParams['non_deductible_amount'] = 'null';
2432 $contributionParams['skipCleanMoney'] = TRUE;
2433 $contributionParams['payment_processor'] = $params['payment_processor_id'] ??
NULL;
2434 $contributionSoftParams = $params['soft_credit'] ??
NULL;
2435 $recordContribution = [
2440 'financial_type_id',
2441 'payment_instrument_id',
2445 'contribution_status_id',
2452 'contribution_recur_id',
2456 foreach ($recordContribution as $f) {
2457 $contributionParams[$f] = $params[$f] ??
NULL;
2460 if (!empty($params['contribution_id'])) {
2461 $contributionParams['id'] = $params['contribution_id'];
2463 // make entry in batch entity batch table
2464 if (!empty($params['batch_id'])) {
2465 $contributionParams['batch_id'] = $params['batch_id'];
2468 if (!empty($params['contribution_contact_id'])) {
2469 // deal with possibility of a different person paying for contribution
2470 $contributionParams['contact_id'] = $params['contribution_contact_id'];
2473 if (!empty($params['processPriceSet']) &&
2474 !empty($params['lineItems'])
2476 $contributionParams['line_item'] = $params['lineItems'] ??
NULL;
2479 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams);
2481 //CRM-13981, create new soft-credit record as to record payment from different person for this membership
2482 if (!empty($contributionSoftParams)) {
2483 if (!empty($params['batch_id'])) {
2484 foreach ($contributionSoftParams as $contributionSoft) {
2485 $contributionSoft['contribution_id'] = $contribution->id
;
2486 $contributionSoft['currency'] = $contribution->currency
;
2487 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoft);
2491 $contributionSoftParams['contribution_id'] = $contribution->id
;
2492 $contributionSoftParams['currency'] = $contribution->currency
;
2493 $contributionSoftParams['amount'] = $contribution->total_amount
;
2494 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoftParams);
2498 // store contribution id
2499 $params['contribution_id'] = $contribution->id
;
2501 // Create membership payment if it does not already exist
2502 $membershipPayment = civicrm_api3('MembershipPayment', 'get', [
2503 'contribution_id' => $contribution->id
,
2505 if (empty($membershipPayment['count'])) {
2506 civicrm_api3('MembershipPayment', 'create', [
2507 'membership_id' => $params['membership_id'],
2508 'contribution_id' => $contribution->id
,
2512 return $contribution;
2516 * @todo document me - I seem a bit out of date....
2518 public static function _getActTypes() {
2519 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2520 self
::$_renewalActType = CRM_Utils_Array
::key('Membership Renewal', $activityTypes);
2521 self
::$_signupActType = CRM_Utils_Array
::key('Membership Signup', $activityTypes);
2525 * Get all Cancelled Membership(s) for a contact
2527 * @param int $contactID
2529 * @param bool $isTest
2533 * Array of membership type
2535 public static function getContactsCancelledMembership($contactID, $isTest = FALSE) {
2539 $query = 'SELECT membership_type_id FROM civicrm_membership WHERE contact_id = %1 AND status_id = %2 AND is_test = %3';
2541 1 => [$contactID, 'Integer'],
2546 CRM_Member_PseudoConstant
::membershipStatus(
2548 " name = 'Cancelled' ",
2556 3 => [$isTest, 'Boolean'],
2559 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
2560 $cancelledMembershipIds = [];
2561 while ($dao->fetch()) {
2562 $cancelledMembershipIds[] = $dao->membership_type_id
;
2564 return $cancelledMembershipIds;
2568 * Merges the memberships from otherContactID to mainContactID.
2570 * General idea is to merge memberships in regards to their type. We
2571 * move the other contact’s contributions to the main contact’s
2572 * membership which has the same type (if any) and then we update
2573 * membership to avoid loosing `join_date`, `end_date`, and
2574 * `status_id`. In this function, we don’t touch the contributions
2575 * directly (CRM_Dedupe_Merger::moveContactBelongings() takes care
2578 * This function adds new SQL queries to the $sqlQueries parameter.
2580 * @param int $mainContactID
2581 * Contact id of main contact record.
2582 * @param int $otherContactID
2583 * Contact id of record which is going to merge.
2584 * @param array $sqlQueries
2585 * (reference) array of SQL queries to be executed.
2586 * @param array $tables
2587 * List of tables that have to be merged.
2588 * @param array $tableOperations
2589 * Special options/params for some tables to be merged.
2591 * @see CRM_Dedupe_Merger::cpTables()
2593 public static function mergeMemberships($mainContactID, $otherContactID, &$sqlQueries, $tables, $tableOperations) {
2595 * If the user requests not to merge memberships but to add them,
2596 * just attribute the `civicrm_membership` to the
2597 * `$mainContactID`. We have to do this here since the general
2598 * merge process is bypassed by this function.
2600 if (array_key_exists("civicrm_membership", $tableOperations) && $tableOperations['civicrm_membership']['add']) {
2601 $sqlQueries[] = "UPDATE IGNORE civicrm_membership SET contact_id = $mainContactID WHERE contact_id = $otherContactID";
2606 * Retrieve all memberships that belongs to each contacts and
2607 * keep track of each membership type.
2609 $mainContactMemberships = [];
2610 $otherContactMemberships = [];
2612 $sql = "SELECT id, membership_type_id FROM civicrm_membership membership WHERE contact_id = %1";
2613 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$mainContactID, "Integer"]]);
2614 while ($dao->fetch()) {
2615 $mainContactMemberships[$dao->id
] = $dao->membership_type_id
;
2618 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$otherContactID, "Integer"]]);
2619 while ($dao->fetch()) {
2620 $otherContactMemberships[$dao->id
] = $dao->membership_type_id
;
2624 * For each membership, move related contributions to the main
2625 * contact’s membership (by updating `membership_payments`). Then,
2626 * update membership’s `join_date` (if the other membership’s
2627 * join_date is older) and `end_date` (if the other membership’s
2628 * `end_date` is newer) and `status_id` (if the newly calculated
2629 * status is different).
2631 * FIXME: what should we do if we have multiple memberships with
2632 * the same type (currently we only take the first one)?
2635 foreach ($otherContactMemberships as $otherMembershipId => $otherMembershipTypeId) {
2636 if ($newMembershipId = array_search($otherMembershipTypeId, $mainContactMemberships)) {
2639 * Move other membership’s contributions to the main one only
2640 * if user requested to merge contributions.
2642 if (!empty($tables) && in_array('civicrm_contribution', $tables)) {
2643 $newSql[] = "UPDATE civicrm_membership_payment SET membership_id=$newMembershipId WHERE membership_id=$otherMembershipId";
2646 $sql = "SELECT * FROM civicrm_membership membership WHERE id = %1";
2648 $newMembership = CRM_Member_DAO_Membership
::findById($newMembershipId);
2649 $otherMembership = CRM_Member_DAO_Membership
::findById($otherMembershipId);
2652 if (new DateTime($otherMembership->join_date
) < new DateTime($newMembership->join_date
)) {
2653 $updates["join_date"] = $otherMembership->join_date
;
2656 if (new DateTime($otherMembership->end_date
) > new DateTime($newMembership->end_date
)) {
2657 $updates["end_date"] = $otherMembership->end_date
;
2660 if (count($updates)) {
2665 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
2666 $updates["start_date"] ??
$newMembership->start_date
,
2667 $updates["end_date"] ??
$newMembership->end_date
,
2668 $updates["join_date"] ??
$newMembership->join_date
,
2675 if (!empty($status['id']) and $status['id'] != $newMembership->status_id
) {
2676 $updates['status_id'] = $status['id'];
2680 foreach ($updates as $k => $v) {
2681 $updates_sql[] = "$k = '{$v}'";
2684 $newSql[] = sprintf("UPDATE civicrm_membership SET %s WHERE id=%s", implode(", ", $updates_sql), $newMembershipId);
2685 $newSql[] = sprintf("DELETE FROM civicrm_membership WHERE id=%s", $otherMembershipId);
2691 $sqlQueries = array_merge($sqlQueries, $newSql);
2695 * Update membership status to deceased.
2696 * function return the status message for updated membership.
2698 * @param array $deceasedParams
2703 * @param string $contactType
2705 * @return null|string
2706 * $updateMembershipMsg string status message for updated membership.
2708 public static function updateMembershipStatus($deceasedParams, $contactType) {
2709 $updateMembershipMsg = NULL;
2710 $contactId = $deceasedParams['contact_id'];
2711 $deceasedDate = $deceasedParams['deceased_date'];
2713 // process to set membership status to deceased for both active/inactive membership
2715 $contactType === 'Individual' &&
2716 !empty($deceasedParams['is_deceased'])
2719 $userId = CRM_Core_Session
::getLoggedInContactID() ?
: $contactId;
2721 // get deceased status id
2722 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2723 $deceasedStatusId = array_search('Deceased', $allStatus);
2724 if (!$deceasedStatusId) {
2725 return $updateMembershipMsg;
2728 $today = CRM_Utils_Time
::time();
2729 if ($deceasedDate && CRM_Utils_Time
::strtotime($deceasedDate) > $today) {
2730 return $updateMembershipMsg;
2733 // get non deceased membership
2734 $dao = new CRM_Member_DAO_Membership();
2735 $dao->contact_id
= $contactId;
2736 $dao->whereAdd("status_id != $deceasedStatusId");
2738 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2739 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2741 while ($dao->fetch()) {
2742 // update status to deceased (for both active/inactive membership )
2743 CRM_Core_DAO
::setFieldValue('CRM_Member_DAO_Membership', $dao->id
,
2744 'status_id', $deceasedStatusId
2747 // add membership log
2749 'membership_id' => $dao->id
,
2750 'status_id' => $deceasedStatusId,
2751 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
2752 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
2753 'modified_id' => $userId,
2754 'modified_date' => CRM_Utils_Time
::date('Ymd'),
2755 'membership_type_id' => $dao->membership_type_id
,
2756 'max_related' => $dao->max_related
,
2759 CRM_Member_BAO_MembershipLog
::add($membershipLog);
2761 //create activity when membership status is changed
2763 'subject' => "Status changed from {$allStatus[$dao->status_id]} to {$allStatus[$deceasedStatusId]}",
2764 'source_contact_id' => $userId,
2765 'target_contact_id' => $dao->contact_id
,
2766 'source_record_id' => $dao->id
,
2767 'activity_type_id' => array_search('Change Membership Status', $activityTypes),
2771 'activity_date_time' => CRM_Utils_Time
::date('Y-m-d H:i:s'),
2773 'is_current_revision' => 1,
2776 civicrm_api('activity', 'create', $activityParam);
2783 CRM_Core_Session
::setStatus(ts("%1 Current membership(s) for this contact have been set to 'Deceased' status.",
2788 return $updateMembershipMsg;