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;
36 public function __construct() {
37 parent
::__construct();
41 * Takes an associative array and creates a membership object.
43 * the function extracts all the params it needs to initialize the created
44 * membership object. The params array could contain additional unused name/value
47 * @param array $params
48 * (reference ) an assoc array of name/value pairs.
50 * @return CRM_Member_BAO_Membership
51 * @throws \CiviCRM_API3_Exception
53 public static function add(&$params) {
54 $oldStatus = $oldType = NULL;
56 CRM_Utils_Hook
::pre('edit', 'Membership', $params['id'], $params);
59 CRM_Utils_Hook
::pre('create', 'Membership', NULL, $params);
62 // we do this after the hooks are called in case it has been altered
64 $membershipObj = new CRM_Member_DAO_Membership();
65 $membershipObj->id
= $id;
66 $membershipObj->find();
67 while ($membershipObj->fetch()) {
68 $oldStatus = $membershipObj->status_id
;
69 $oldType = $membershipObj->membership_type_id
;
73 if (array_key_exists('is_override', $params) && !$params['is_override']) {
74 $params['is_override'] = 'null';
77 $membership = new CRM_Member_BAO_Membership();
78 $membership->copyValues($params);
79 $membership->id
= $id;
83 if (empty($membership->contact_id
) ||
empty($membership->status_id
)) {
84 // this means we are in renewal mode and are just updating the membership
85 // record or this is an API update call and all fields are not present in the update record
86 // however the hooks don't care and want all data CRM-7784
87 $tempMembership = new CRM_Member_DAO_Membership();
88 $tempMembership->id
= $membership->id
;
89 $tempMembership->find(TRUE);
90 $membership = $tempMembership;
93 //get the log start date.
94 //it is set during renewal of membership.
95 $logStartDate = $params['log_start_date'] ??
NULL;
96 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : CRM_Utils_Date
::isoToMysql($membership->start_date
);
97 $values = self
::getStatusANDTypeValues($membership->id
);
100 'membership_id' => $membership->id
,
101 'status_id' => $membership->status_id
,
102 'start_date' => $logStartDate,
103 'end_date' => CRM_Utils_Date
::isoToMysql($membership->end_date
),
104 'modified_date' => CRM_Utils_Time
::date('Ymd'),
105 'membership_type_id' => $values[$membership->id
]['membership_type_id'],
106 'max_related' => $membership->max_related
,
109 if (!empty($params['modified_id'])) {
110 $membershipLog['modified_id'] = $params['modified_id'];
112 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
113 elseif (CRM_Core_Session
::singleton()->get('userID')) {
114 $membershipLog['modified_id'] = CRM_Core_Session
::singleton()->get('userID');
117 $membershipLog['modified_id'] = $membership->contact_id
;
120 CRM_Member_BAO_MembershipLog
::add($membershipLog);
122 // reset the group contact cache since smart groups might be affected due to this
123 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
125 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
127 'status_id' => $params['membership_activity_status'] ??
'Completed',
129 if (in_array($allStatus[$membership->status_id
], ['Pending', 'Grace'])) {
130 $activityParams['status_id'] = 'Scheduled';
132 $activityParams['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', $activityParams['status_id']);
134 $targetContactID = $membership->contact_id
;
135 if (!empty($params['is_for_organization'])) {
136 // @todo - deprecate is_for_organization, require modified_id
137 $targetContactID = $params['modified_id'] ??
NULL;
140 // add custom field values
141 if (!empty($params['custom']) && is_array($params['custom'])
143 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_membership', $membership->id
);
147 if ($membership->status_id
!= $oldStatus) {
148 CRM_Activity_BAO_Activity
::addActivity($membership,
149 'Change Membership Status',
152 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
153 'source_contact_id' => $membershipLog['modified_id'],
154 'priority_id' => 'Normal',
158 if (isset($membership->membership_type_id
) && $membership->membership_type_id
!= $oldType) {
159 $membershipTypes = CRM_Member_BAO_Membership
::buildOptions('membership_type_id', 'get');
160 CRM_Activity_BAO_Activity
::addActivity($membership,
161 'Change Membership Type',
164 'subject' => "Type changed from {$membershipTypes[$oldType]} to {$membershipTypes[$membership->membership_type_id]}",
165 'source_contact_id' => $membershipLog['modified_id'],
166 'priority_id' => 'Normal',
171 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
172 $activityParams['id'] = civicrm_api3('Activity', 'Get', [
173 'source_record_id' => $membership->id
,
174 'activity_type_id' => $activityType,
175 'status_id' => 'Scheduled',
177 // 1. Update Schedule Membership Signup/Renwal activity to completed on successful payment of pending membership
178 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
179 if (!empty($params['membership_activity_status']) && (!empty($activityParams['id']) ||
$activityType == 'Membership Renewal')) {
180 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $targetContactID, $activityParams);
185 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
188 CRM_Activity_BAO_Activity
::addActivity($membership, 'Membership Signup', $targetContactID, $activityParams);
189 CRM_Utils_Hook
::post('create', 'Membership', $membership->id
, $membership);
196 * Fetch the object and store the values in the values array.
198 * @param array $params
199 * Input parameters to find object.
200 * @param array $values
201 * Output values of the object.
202 * @param bool $active
203 * Do you want only active memberships to.
206 * @return CRM_Member_BAO_Membership|null
207 * The found object or null
209 public static function &getValues(&$params, &$values, $active = FALSE) {
210 if (empty($params)) {
213 $membership = new CRM_Member_BAO_Membership();
215 $membership->copyValues($params);
218 while ($membership->fetch()) {
220 (!CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
221 $membership->status_id
,
228 CRM_Core_DAO
::storeValues($membership, $values[$membership->id
]);
229 $memberships[$membership->id
] = $membership;
236 * Takes an associative array and creates a membership object.
238 * @param array $params
239 * (reference ) an assoc array of name/value pairs.
241 * Deprecated parameter The array that holds all the db ids.
243 * @return CRM_Member_BAO_Membership|CRM_Core_Error
244 * @throws \CiviCRM_API3_Exception
246 * @throws CRM_Core_Exception
248 public static function create(&$params, $ids = []) {
250 if (!empty($params['membership_type_id'])) {
251 $memTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipType($params['membership_type_id']);
252 $isLifeTime = $memTypeDetails['duration_unit'] === 'lifetime' ?
TRUE : FALSE;
254 // always calculate status if is_override/skipStatusCal is not true.
255 // giving respect to is_override during import. CRM-4012
257 // To skip status calculation we should use 'skipStatusCal'.
258 // eg pay later membership, membership update cron CRM-3984
260 if (empty($params['skipStatusCal'])) {
262 foreach (['start_date', 'end_date', 'join_date'] as $dateField) {
263 if (!empty($params[$dateField]) && $params[$dateField] !== 'null' && strpos($params[$dateField], date('Ymd', CRM_Utils_Time
::strtotime(trim($params[$dateField])))) !== 0) {
264 $params[$dateField] = date('Ymd', CRM_Utils_Time
::strtotime(trim($params[$dateField])));
265 // @todo enable this once core is using the api.
266 // CRM_Core_Error::deprecatedWarning('Relying on the BAO to clean up dates is deprecated. Call membership create via the api');
268 if (!empty($params['id']) && empty($params[$dateField]) && !($isLifeTime && $dateField == 'end_date')) {
269 $fieldsToLoad[] = $dateField;
272 if (!empty($fieldsToLoad)) {
273 $membership = civicrm_api3('Membership', 'getsingle', ['id' => $params['id'], 'return' => $fieldsToLoad]);
274 foreach ($fieldsToLoad as $fieldToLoad) {
275 $params[$fieldToLoad] = $membership[$fieldToLoad];
278 if (empty($params['id'])
279 && (empty($params['start_date']) ||
empty($params['join_date']) ||
(empty($params['end_date']) && !$isLifeTime))) {
280 // This is a new membership, calculate the membership dates.
281 $calcDates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType(
282 $params['membership_type_id'],
283 $params['join_date'] ??
NULL,
284 $params['start_date'] ??
NULL,
285 $params['end_date'] ??
NULL,
286 $params['num_terms'] ??
1
292 $params['start_date'] = $params['start_date'] ??
($calcDates['start_date'] ??
'null');
293 $params['end_date'] = $params['end_date'] ??
($calcDates['end_date'] ??
'null');
294 $params['join_date'] = $params['join_date'] ??
($calcDates['join_date'] ??
'null');
296 //fix for CRM-3570, during import exclude the statuses those having is_admin = 1
297 $excludeIsAdmin = $params['exclude_is_admin'] ??
FALSE;
299 //CRM-3724 always skip is_admin if is_override != true.
300 if (!$excludeIsAdmin && empty($params['is_override'])) {
301 $excludeIsAdmin = TRUE;
304 if (empty($params['status_id']) && empty($params['is_override'])) {
305 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($params['start_date'], $params['end_date'], $params['join_date'],
306 'now', $excludeIsAdmin, $params['membership_type_id'] ??
NULL, $params
308 if (empty($calcStatus)) {
309 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')));
311 $params['status_id'] = $calcStatus['id'];
315 // data cleanup only: all verifications on number of related memberships are done upstream in:
316 // CRM_Member_BAO_Membership::createRelatedMemberships()
317 // CRM_Contact_BAO_Relationship::relatedMemberships()
318 if (!empty($params['owner_membership_id'])) {
319 unset($params['max_related']);
322 // if membership allows related, default max_related to value in membership_type
323 if (!array_key_exists('max_related', $params) && !empty($params['membership_type_id'])) {
324 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipType($params['membership_type_id']);
325 if (isset($membershipType['relationship_type_id'])) {
326 $params['max_related'] = $membershipType['max_related'] ??
NULL;
331 $transaction = new CRM_Core_Transaction();
333 $params['id'] = $params['id'] ??
$ids['membership'] ??
NULL;
334 $membership = self
::add($params);
336 if (is_a($membership, 'CRM_Core_Error')) {
337 $transaction->rollback();
341 $params['membership_id'] = $membership->id
;
342 // @todo further cleanup required to remove use of $ids['contribution'] from here
343 if (isset($ids['membership'])) {
344 $contributionID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment',
349 // @todo this is a temporary step to removing $ids['contribution'] completely
350 if (empty($params['contribution_id']) && !empty($contributionID)) {
351 $params['contribution_id'] = $contributionID;
355 // This code ensures a line item is created but it is recommended you pass in 'skipLineItem' or 'line_item'
356 if (empty($params['line_item']) && !empty($params['membership_type_id']) && empty($params['skipLineItem'])) {
357 CRM_Price_BAO_LineItem
::getLineItemArray($params, NULL, 'membership', $params['membership_type_id']);
359 $params['skipLineItem'] = TRUE;
361 // Record contribution for this membership and create a MembershipPayment
362 // @todo deprecate this.
363 if (!empty($params['contribution_status_id'])) {
364 $memInfo = array_merge($params, ['membership_id' => $membership->id
]);
365 $params['contribution'] = self
::recordMembershipContribution($memInfo);
368 // If the membership has no associated contribution then we ensure
369 // the line items are 'correct' here. This is a lazy legacy
370 // hack whereby they are deleted and recreated
371 if (empty($contributionID)) {
372 if (!empty($params['lineItems'])) {
373 $params['line_item'] = $params['lineItems'];
375 // do cleanup line items if membership edit the Membership type.
376 if (!empty($ids['membership'])) {
377 CRM_Price_BAO_LineItem
::deleteLineItems($ids['membership'], 'civicrm_membership');
379 // @todo - we should ONLY do the below if a contribution is created. Let's
380 // get some deprecation notices in here & see where it's hit & work to eliminate.
381 // This could happen if there is no contribution or we are in one of many
382 // weird and wonderful flows. This is scary code. Keep adding tests.
383 if (!empty($params['line_item']) && empty($params['contribution_id'])) {
385 foreach ($params['line_item'] as $priceSetId => $lineItems) {
386 foreach ($lineItems as $lineIndex => $lineItem) {
387 $lineMembershipType = $lineItem['membership_type_id'] ??
NULL;
388 if (!empty($params['contribution'])) {
389 $params['line_item'][$priceSetId][$lineIndex]['contribution_id'] = $params['contribution']->id
;
391 if ($lineMembershipType && $lineMembershipType == ($params['membership_type_id'] ??
NULL)) {
392 $params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $membership->id
;
393 $params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_membership';
395 elseif (!$lineMembershipType && !empty($params['contribution'])) {
396 $params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $params['contribution']->id
;
397 $params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_contribution';
401 CRM_Price_BAO_LineItem
::processPriceSet(
403 $params['line_item'],
404 $params['contribution'] ??
NULL
409 $transaction->commit();
411 self
::createRelatedMemberships($params, $membership);
413 if (empty($params['skipRecentView'])) {
414 self
::addToRecentItems($membership);
421 * @param \CRM_Member_DAO_Membership $membership
423 private static function addToRecentItems($membership) {
424 $url = CRM_Utils_System
::url('civicrm/contact/view/membership',
425 "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
427 if (empty($membership->membership_type_id
)) {
428 // ie in an update situation.
429 $membership->find(TRUE);
431 $title = CRM_Contact_BAO_Contact
::displayName($membership->contact_id
) . ' - ' . ts('Membership Type:')
432 . ' ' . CRM_Core_PseudoConstant
::getLabel('CRM_Member_BAO_Membership', 'membership_type_id', $membership->membership_type_id
);
435 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::UPDATE
)) {
436 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
437 "action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
440 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::DELETE
)) {
441 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
442 "action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
446 // add the recently created Membership
447 CRM_Utils_Recent
::add($title,
451 $membership->contact_id
,
458 * Check the membership extended through relationship.
460 * @param int $membershipTypeID
461 * Membership type id.
462 * @param int $contactId
468 * array of contact_id of all related contacts.
470 * @throws \CRM_Core_Exception
471 * @throws \CiviCRM_API3_Exception
473 public static function checkMembershipRelationship($membershipTypeID, $contactId, $action = CRM_Core_Action
::ADD
) {
476 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipType($membershipTypeID);
479 if (isset($membershipType['relationship_type_id'])) {
480 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
481 CRM_Contact_BAO_Relationship
::CURRENT
483 if ($action & CRM_Core_Action
::UPDATE
) {
484 $pastRelationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
485 CRM_Contact_BAO_Relationship
::PAST
487 $relationships = array_merge($relationships, $pastRelationships);
491 if (!empty($relationships)) {
492 // check for each contact relationships
493 foreach ($relationships as $values) {
494 //get details of the relationship type
495 $relType = ['id' => $values['civicrm_relationship_type_id']];
497 CRM_Contact_BAO_RelationshipType
::retrieve($relType, $relValues);
498 // Check if contact's relationship type exists in membership type
500 $bidirectional = FALSE;
501 foreach ($membershipType['relationship_type_id'] as $key => $value) {
502 $relTypeDirs[] = $value . '_' . $membershipType['relationship_direction'][$key];
503 if (in_array($value, $relType) &&
504 $relValues['name_a_b'] == $relValues['name_b_a']
506 $bidirectional = TRUE;
510 $relTypeDir = $values['civicrm_relationship_type_id'] . '_' . $values['rtype'];
511 if ($bidirectional ||
in_array($relTypeDir, $relTypeDirs)) {
512 // $values['status'] is going to have value for
513 // current or past relationships.
514 $contacts[$values['cid']] = $values['status'];
519 // Sort by contact_id ascending
525 * Retrieve DB object based on input parameters.
527 * It also stores all the retrieved values in the default array.
529 * @param array $params
530 * (reference ) an assoc array of name/value pairs.
531 * @param array $defaults
532 * (reference ) an assoc array to hold the name / value pairs.
533 * in a hierarchical manner
535 * @return CRM_Member_BAO_Membership
537 public static function retrieve(&$params, &$defaults) {
538 $membership = new CRM_Member_DAO_Membership();
540 $membership->copyValues($params);
542 if ($membership->find(TRUE)) {
543 CRM_Core_DAO
::storeValues($membership, $defaults);
545 //get the membership status and type values.
546 $statusANDType = self
::getStatusANDTypeValues($membership->id
);
547 foreach (['status', 'membership_type'] as $fld) {
548 $defaults[$fld] = $statusANDType[$membership->id
][$fld] ??
NULL;
550 if (!empty($statusANDType[$membership->id
]['is_current_member'])) {
551 $defaults['active'] = TRUE;
561 * Get membership status and membership type values.
563 * @param int $membershipId
564 * Membership id of values to return.
567 * Array of key value pairs
569 public static function getStatusANDTypeValues($membershipId) {
571 if (!$membershipId) {
575 SELECT membership.id as id,
576 status.id as status_id,
577 status.label as status,
578 status.is_current_member as is_current_member,
579 type.id as membership_type_id,
580 type.name as membership_type,
581 type.relationship_type_id as relationship_type_id
582 FROM civicrm_membership membership
583 INNER JOIN civicrm_membership_status status ON ( status.id = membership.status_id )
584 INNER JOIN civicrm_membership_type type ON ( type.id = membership.membership_type_id )
585 WHERE membership.id = %1';
586 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$membershipId, 'Positive']]);
591 'membership_type_id',
593 'relationship_type_id',
595 while ($dao->fetch()) {
596 foreach ($properties as $property) {
597 $values[$dao->id
][$property] = $dao->$property;
607 * Wrapper for most delete calls. Use this unless you JUST want to delete related memberships w/o deleting the parent.
609 * @param int $membershipId
610 * Membership id that needs to be deleted.
611 * @param bool $preserveContrib
614 * Id of deleted Membership on success, false otherwise.
616 public static function del($membershipId, $preserveContrib = FALSE) {
617 //delete related first and then delete parent.
618 self
::deleteRelatedMemberships($membershipId);
619 return self
::deleteMembership($membershipId, $preserveContrib);
625 * @param int $membershipId
626 * Membership id that needs to be deleted.
627 * @param bool $preserveContrib
630 * Id of deleted Membership on success, false otherwise.
632 public static function deleteMembership($membershipId, $preserveContrib = FALSE) {
633 // CRM-12147, retrieve membership data before we delete it for hooks
634 $params = ['id' => $membershipId];
636 $memberships = self
::getValues($params, $memValues);
638 $membership = $memberships[$membershipId];
640 CRM_Utils_Hook
::pre('delete', 'Membership', $membershipId, $memValues);
642 $transaction = new CRM_Core_Transaction();
645 //delete activity record
646 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
649 $deleteActivity = FALSE;
650 $membershipActivities = [
652 'Membership Renewal',
653 'Change Membership Status',
654 'Change Membership Type',
655 'Membership Renewal Reminder',
657 foreach ($membershipActivities as $membershipActivity) {
658 $activityId = array_search($membershipActivity, $activityTypes);
660 $params['activity_type_id'][] = $activityId;
661 $deleteActivity = TRUE;
664 if ($deleteActivity) {
665 $params['source_record_id'] = $membershipId;
666 CRM_Activity_BAO_Activity
::deleteActivity($params);
668 self
::deleteMembershipPayment($membershipId, $preserveContrib);
669 CRM_Price_BAO_LineItem
::deleteLineItems($membershipId, 'civicrm_membership');
671 $results = $membership->delete();
672 $transaction->commit();
674 CRM_Utils_Hook
::post('delete', 'Membership', $membership->id
, $membership);
680 * Delete related memberships.
682 * @param int $ownerMembershipId
683 * @param int $contactId
687 public static function deleteRelatedMemberships($ownerMembershipId, $contactId = NULL) {
688 if (!$ownerMembershipId && !$contactId) {
692 $membership = new CRM_Member_DAO_Membership();
693 $membership->owner_membership_id
= $ownerMembershipId;
696 $membership->contact_id
= $contactId;
700 while ($membership->fetch()) {
701 //delete related first and then delete parent.
702 self
::deleteRelatedMemberships($membership->id
);
703 self
::deleteMembership($membership->id
);
708 * Obtain active/inactive memberships from the list of memberships passed to it.
710 * @param array $memberships
711 * Membership records.
712 * @param string $status
713 * Active or inactive.
716 * array of memberships based on status
718 public static function activeMembers($memberships, $status = 'active') {
720 if ($status == 'active') {
721 foreach ($memberships as $f => $v) {
722 if (!empty($v['active'])) {
728 elseif ($status == 'inactive') {
729 foreach ($memberships as $f => $v) {
730 if (empty($v['active'])) {
740 * Return Membership Block info in Contribution Pages.
743 * Contribution page id.
747 public static function getMembershipBlock($pageID) {
748 $membershipBlock = [];
749 $dao = new CRM_Member_DAO_MembershipBlock();
750 $dao->entity_table
= 'civicrm_contribution_page';
752 $dao->entity_id
= $pageID;
754 if ($dao->find(TRUE)) {
755 CRM_Core_DAO
::storeValues($dao, $membershipBlock);
756 if (!empty($membershipBlock['membership_types'])) {
757 $membershipTypes = CRM_Utils_String
::unserialize($membershipBlock['membership_types']);
758 if (!is_array($membershipTypes)) {
759 return $membershipBlock;
762 foreach ($membershipTypes as $key => $value) {
763 $membershipBlock['auto_renew'][$key] = $value;
764 $memTypes[$key] = $key;
766 $membershipBlock['membership_types'] = implode(',', $memTypes);
773 return $membershipBlock;
777 * Return a current membership of given contact.
779 * NB: if more than one membership meets criteria, a randomly selected one is returned.
781 * @param int $contactID
783 * @param int $memType
784 * Membership type, null to retrieve all types.
786 * @param int $membershipId
787 * If provided, then determine if it is current.
788 * @param bool $onlySameParentOrg
789 * True if only Memberships with same parent org as the $memType wanted, false otherwise.
792 * @throws \CiviCRM_API3_Exception
794 public static function getContactMembership($contactID, $memType, $isTest, $membershipId = NULL, $onlySameParentOrg = FALSE) {
795 //check for owner membership id, if it exists update that membership instead: CRM-15992
797 $ownerMemberId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
799 'owner_membership_id', 'id'
801 if ($ownerMemberId) {
802 $membershipId = $ownerMemberId;
803 $contactID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
810 $dao = new CRM_Member_DAO_Membership();
812 $dao->id
= $membershipId;
814 $dao->contact_id
= $contactID;
815 $dao->membership_type_id
= $memType;
817 //fetch proper membership record.
819 $dao->is_test
= $isTest;
822 $dao->whereAdd('is_test IS NULL OR is_test = 0');
825 //avoid pending membership as current membership: CRM-3027
826 $statusIds = [array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus())];
827 if (!$membershipId) {
829 $statusIds[] = array_search(
831 CRM_Member_PseudoConstant
::membershipStatus(
833 " name = 'Cancelled' ",
840 $dao->whereAdd('status_id NOT IN ( ' . implode(',', $statusIds) . ')');
842 // order by start date to find most recent membership first, CRM-4545
843 $dao->orderBy('start_date DESC');
846 if ($onlySameParentOrg && $memType) {
847 // require the same parent org as the $memType
848 $params = ['id' => $memType];
849 $membershipType = [];
850 if (CRM_Member_BAO_MembershipType
::retrieve($params, $membershipType)) {
851 $memberTypesSameParentOrg = civicrm_api3('MembershipType', 'get', [
852 'member_of_contact_id' => $membershipType['member_of_contact_id'],
857 $memberTypesSameParentOrgList = implode(',', array_keys($memberTypesSameParentOrg['values'] ??
[]));
858 $dao->whereAdd('membership_type_id IN (' . $memberTypesSameParentOrgList . ')');
862 if ($dao->find(TRUE)) {
864 CRM_Core_DAO
::storeValues($dao, $membership);
865 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
866 $membership['status_id'],
867 'is_current_member', 'id'
869 $ownerMemberId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
871 'owner_membership_id', 'id'
873 if ($ownerMemberId) {
874 $membership['id'] = $membership['membership_id'] = $ownerMemberId;
875 $membership['membership_contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
884 if ($onlySameParentOrg && $memType) {
885 // see if there is a membership that has same parent as $memType but different parent than $membershipID
886 if ($dao->id
&& CRM_Core_Permission
::check('edit memberships')) {
887 // CRM-10016, This is probably a backend renewal, and make sure we return the same membership thats being renewed.
894 unset($dao->membership_type_id
);
895 if ($dao->find(TRUE)) {
897 CRM_Core_DAO
::storeValues($dao, $membership);
898 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
899 $membership['status_id'],
900 'is_current_member', 'id'
909 * Combine all the importable fields from the lower levels object.
911 * @param string $contactType
913 * @param bool $status
916 * array of importable Fields
917 * @throws \CRM_Core_Exception
919 public static function importableFields($contactType = 'Individual', $status = TRUE) {
920 $fields = Civi
::cache('fields')->get('membership_importable_fields' . $contactType . $status);
923 $fields = ['' => ['title' => '- ' . ts('do not import') . ' -']];
926 $fields = ['' => ['title' => '- ' . ts('Membership Fields') . ' -']];
929 $tmpFields = CRM_Member_DAO_Membership
::import();
930 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
932 // Using new Dedupe rule.
934 'contact_type' => $contactType,
935 'used' => 'Unsupervised',
937 $fieldsArray = CRM_Dedupe_BAO_DedupeRule
::dedupeRuleFields($ruleParams);
939 $tmpContactField = [];
940 if (is_array($fieldsArray)) {
941 foreach ($fieldsArray as $value) {
942 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
947 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
948 $tmpContactField[trim($value)] = $contactFields[trim($value)] ??
NULL;
950 $title = $tmpContactField[trim($value)]['title'] . " " . ts('(match to contact)');
953 $title = $tmpContactField[trim($value)]['title'];
955 $tmpContactField[trim($value)]['title'] = $title;
958 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
959 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
961 $tmpFields['membership_contact_id']['title'] .= ' ' . ts('(match to contact)');
963 $fields = array_merge($fields, $tmpContactField);
964 $fields = array_merge($fields, $tmpFields);
965 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
966 Civi
::cache('fields')->set('membership_importable_fields' . $contactType . $status, $fields);
972 * Get all exportable fields.
974 * @return array return array of all exportable fields
976 public static function &exportableFields() {
977 $expFieldMembership = CRM_Member_DAO_Membership
::export();
979 $expFieldsMemType = CRM_Member_DAO_MembershipType
::export();
980 $fields = array_merge($expFieldMembership, $expFieldsMemType);
981 $fields = array_merge($fields, $expFieldMembership);
982 $membershipStatus = [
983 'membership_status' => [
984 'title' => ts('Membership Status'),
985 'name' => 'membership_status',
986 'type' => CRM_Utils_Type
::T_STRING
,
987 'where' => 'civicrm_membership_status.name',
990 //CRM-6161 fix for customdata export
991 $fields = array_merge($fields, $membershipStatus, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
992 $fields['membership_status_id'] = $membershipStatus['membership_status'];
997 * Get membership joins/renewals for a specified membership type.
999 * Specifically, retrieves a count of memberships whose "Membership
1000 * Signup" or "Membership Renewal" activity falls in the given date range.
1001 * Dates match the pattern "yyyy-mm-dd".
1003 * @param int $membershipTypeId
1004 * Membership type id.
1005 * @param int $startDate
1006 * Date on which to start counting.
1007 * @param int $endDate
1008 * Date on which to end counting.
1009 * @param bool|int $isTest if true, membership is for a test site
1010 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1013 * the number of members of type $membershipTypeId whose
1014 * start_date is between $startDate and $endDate
1016 public static function getMembershipStarts($membershipTypeId, $startDate, $endDate, $isTest = 0, $isOwner = 0) {
1017 // Ensure that the dates that are passed to the query are in the format of yyyy-mm-dd
1018 $dates = ['startDate', 'endDate'];
1019 foreach ($dates as $date) {
1020 if (strlen($
$date) === 8) {
1021 $
$date = date('Y-m-d', CRM_Utils_Time
::strtotime($
$date));
1025 $testClause = 'membership.is_test = 1';
1027 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1030 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1031 self
::_getActTypes();
1034 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1039 SELECT COUNT(DISTINCT membership.id) as member_count
1040 FROM civicrm_membership membership
1041 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id in (%1, %2))
1042 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1043 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1044 WHERE membership.membership_type_id = %3
1045 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1048 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1051 1 => [self
::$_signupActType, 'Integer'],
1052 2 => [self
::$_renewalActType, 'Integer'],
1053 3 => [$membershipTypeId, 'Integer'],
1056 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1057 return (int) $memberCount;
1061 * Get a count of membership for a specified membership type, optionally for a specified date.
1063 * The date must have the form yyyy-mm-dd.
1065 * If $date is omitted, this function counts as a member anyone whose
1066 * membership status_id indicates they're a current member.
1067 * If $date is given, this function counts as a member anyone who:
1068 * -- Has a start_date before $date and end_date after $date, or
1069 * -- Has a start_date before $date and is currently a member, as indicated
1070 * by the the membership's status_id.
1071 * The second condition takes care of records that have no end_date. These
1072 * are assumed to be lifetime memberships.
1074 * @param int $membershipTypeId
1075 * Membership type id.
1076 * @param string $date
1077 * The date for which to retrieve the count.
1078 * @param bool|int $isTest if true, membership is for a test site
1079 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1082 * the number of members of type $membershipTypeId as of $date.
1084 public static function getMembershipCount($membershipTypeId, $date = NULL, $isTest = 0, $isOwner = 0) {
1085 if (!CRM_Utils_Rule
::date($date)) {
1086 throw new CRM_Core_Exception(ts('Invalid date "%1" (must have form yyyy-mm-dd).', [1 => $date]));
1090 1 => [$membershipTypeId, 'Integer'],
1091 2 => [$isTest, 'Boolean'],
1093 $query = "SELECT count(civicrm_membership.id ) as member_count
1094 FROM civicrm_membership left join civicrm_membership_status on ( civicrm_membership.status_id = civicrm_membership_status.id )
1095 WHERE civicrm_membership.membership_type_id = %1
1096 AND civicrm_membership.contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)
1097 AND civicrm_membership.is_test = %2";
1099 $query .= " AND civicrm_membership_status.is_current_member = 1";
1102 $query .= " AND civicrm_membership.start_date <= '$date' AND civicrm_membership_status.is_current_member = 1";
1105 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1106 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1107 return (int) $memberCount;
1111 * Function check the status of the membership before adding membership for a contact.
1115 public static function statusAvailabilty() {
1116 $membership = new CRM_Member_DAO_MembershipStatus();
1117 $membership->whereAdd('is_active=1');
1118 return $membership->count();
1122 * @deprecated This is not used anywhere and should be removed soon!
1123 * Function for updating a membership record's contribution_recur_id.
1125 * @param CRM_Member_DAO_Membership $membership
1126 * @param \CRM_Contribute_BAO_Contribution|\CRM_Contribute_DAO_Contribution $contribution
1128 public static function updateRecurMembership(CRM_Member_DAO_Membership
$membership, CRM_Contribute_BAO_Contribution
$contribution) {
1129 CRM_Core_Error
::deprecatedFunctionWarning('Use the API instead');
1131 if (empty($contribution->contribution_recur_id
)) {
1136 1 => [$contribution->contribution_recur_id
, 'Integer'],
1137 2 => [$membership->id
, 'Integer'],
1140 $sql = "UPDATE civicrm_membership SET contribution_recur_id = %1 WHERE id = %2";
1141 CRM_Core_DAO
::executeQuery($sql, $params);
1145 * Method to fix membership status of stale membership.
1147 * This method first checks if the membership is stale. If it is,
1148 * then status will be updated based on existing start and end
1149 * dates and log will be added for the status change.
1151 * @param array $currentMembership
1152 * Reference to the array.
1153 * containing all values of
1154 * the current membership
1155 * @param string|null $changeToday
1156 * In case today needs
1157 * to be customised, null otherwise
1159 * @throws \CRM_Core_Exception
1161 public static function fixMembershipStatusBeforeRenew(&$currentMembership, $changeToday = NULL) {
1164 $today = CRM_Utils_Date
::processDate($changeToday, NULL, FALSE, 'Y-m-d');
1167 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
1168 $currentMembership['start_date'] ??
NULL,
1169 $currentMembership['end_date'] ??
NULL,
1170 $currentMembership['join_date'] ??
NULL,
1173 $currentMembership['membership_type_id'],
1177 if (empty($status) ||
empty($status['id'])) {
1178 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.'));
1181 if ($status['id'] !== $currentMembership['status_id']) {
1182 $oldStatus = $currentMembership['status_id'];
1183 $memberDAO = new CRM_Member_DAO_Membership();
1184 $memberDAO->id
= $currentMembership['id'];
1185 $memberDAO->find(TRUE);
1187 $memberDAO->status_id
= $status['id'];
1189 CRM_Core_DAO
::storeValues($memberDAO, $currentMembership);
1191 $currentMembership['is_current_member'] = CRM_Core_DAO
::getFieldValue(
1192 'CRM_Member_DAO_MembershipStatus',
1193 $currentMembership['status_id'],
1199 'membership_id' => $currentMembership['id'],
1200 'status_id' => $status['id'],
1201 'start_date' => CRM_Utils_Date
::customFormat(
1202 $currentMembership['start_date'],
1205 'end_date' => CRM_Utils_Date
::customFormat(
1206 $currentMembership['end_date'],
1209 'modified_date' => date('Y-m-d H:i:s', CRM_Utils_Time
::strtotime($today)),
1210 'membership_type_id' => $currentMembership['membership_type_id'],
1211 'max_related' => $currentMembership['max_related'] ??
0,
1214 $session = CRM_Core_Session
::singleton();
1215 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
1216 if ($session->get('userID')) {
1217 $logParams['modified_id'] = $session->get('userID');
1220 $logParams['modified_id'] = $currentMembership['contact_id'];
1223 //Create activity for status change.
1224 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
1225 CRM_Activity_BAO_Activity
::addActivity($memberDAO,
1226 'Change Membership Status',
1229 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$status['id']]}",
1230 'source_contact_id' => $logParams['modified_id'],
1231 'priority_id' => 'Normal',
1235 CRM_Member_BAO_MembershipLog
::add($logParams);
1240 * Get the contribution page id from the membership record.
1242 * @param int $membershipID
1245 * contribution page id
1247 public static function getContributionPageId($membershipID) {
1249 SELECT c.contribution_page_id as pageID
1250 FROM civicrm_membership_payment mp, civicrm_contribution c
1251 WHERE mp.contribution_id = c.id
1252 AND c.contribution_page_id IS NOT NULL
1253 AND mp.membership_id = " . CRM_Utils_Type
::escape($membershipID, 'Integer')
1254 . " ORDER BY mp.id DESC";
1256 return CRM_Core_DAO
::singleValueQuery($query);
1260 * Updated related memberships.
1262 * @param int $ownerMembershipId
1263 * Owner Membership Id.
1264 * @param array $params
1265 * Formatted array of key => value.
1267 public static function updateRelatedMemberships($ownerMembershipId, $params) {
1268 $membership = new CRM_Member_DAO_Membership();
1269 $membership->owner_membership_id
= $ownerMembershipId;
1270 $membership->find();
1272 while ($membership->fetch()) {
1273 $relatedMembership = new CRM_Member_DAO_Membership();
1274 $relatedMembership->id
= $membership->id
;
1275 $relatedMembership->copyValues($params);
1276 $relatedMembership->save();
1282 * Get list of membership fields for profile.
1284 * For now we only allow custom membership fields to be in
1288 * FIXME: This param is ignored
1291 * the list of membership fields
1293 public static function getMembershipFields($mode = NULL) {
1294 $fields = CRM_Member_DAO_Membership
::export();
1296 unset($fields['membership_contact_id']);
1297 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1299 $membershipType = CRM_Member_DAO_MembershipType
::export();
1301 $membershipStatus = CRM_Member_DAO_MembershipStatus
::export();
1303 $fields = array_merge($fields, $membershipType, $membershipStatus);
1309 * Get the sort name of a contact for a particular membership.
1312 * Id of the membership.
1314 * @return null|string
1315 * sort name of the contact if found
1317 public static function sortName($id) {
1318 $id = CRM_Utils_Type
::escape($id, 'Integer');
1321 SELECT civicrm_contact.sort_name
1322 FROM civicrm_membership, civicrm_contact
1323 WHERE civicrm_membership.contact_id = civicrm_contact.id
1324 AND civicrm_membership.id = {$id}
1326 return CRM_Core_DAO
::singleValueQuery($query);
1330 * Create memberships for related contacts, taking into account the maximum related memberships.
1332 * @param array $params
1333 * Array of key - value pairs.
1334 * @param CRM_Core_DAO $dao
1335 * Membership object.
1337 * @throws \CRM_Core_Exception
1338 * @throws \CiviCRM_API3_Exception
1340 public static function createRelatedMemberships($params, $dao) {
1341 unset($params['membership_id']);
1342 $membership = new CRM_Member_DAO_Membership();
1343 $membership->id
= $dao->id
;
1345 // required since create method doesn't return all the
1346 // parameters in the returned membership object
1347 if (!$membership->find(TRUE)) {
1350 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1351 // FIXME : While updating/ renewing the
1352 // membership, if the relationship is PAST then
1353 // the membership of the related contact must be
1355 // For that, getting Membership Status for which
1356 // is_current_member is 0. It works for the
1357 // generated data as there is only one membership
1358 // status having is_current_member = 0.
1359 // But this wont work exactly if there will be
1360 // more than one status having is_current_member = 0.
1361 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
1362 $membershipStatus->is_current_member
= 0;
1363 if ($membershipStatus->find(TRUE)) {
1364 $expiredStatusId = $membershipStatus->id
;
1367 $expiredStatusId = array_search('Expired', CRM_Member_PseudoConstant
::membershipStatus());
1370 $relatedContacts = [];
1371 $allRelatedContacts = CRM_Member_BAO_Membership
::checkMembershipRelationship($membership->membership_type_id
,
1372 $membership->contact_id
,
1373 $params['action'] ??
NULL
1376 // CRM-4213, CRM-19735 check for loops, using static variable to record contacts already processed.
1377 // Remove repeated related contacts, which already inherited membership of this type$relatedContactIds[$membership->contact_id][$membership->membership_type_id] = TRUE;
1378 foreach ($allRelatedContacts as $cid => $status) {
1379 // relatedContactIDs is always empty now - will remove next roud because of whitespace readability.
1380 if (empty($relatedContactIds[$cid]) ||
empty($relatedContactIds[$cid][$membership->membership_type_id
])) {
1381 $relatedContactIds[$cid][$membership->membership_type_id
] = TRUE;
1383 //don't create membership again for owner contact.
1384 $nestedRelationship = FALSE;
1385 if ($membership->owner_membership_id
) {
1386 $nestedRelMembership = new CRM_Member_DAO_Membership();
1387 $nestedRelMembership->id
= $membership->owner_membership_id
;
1388 $nestedRelMembership->contact_id
= $cid;
1389 $nestedRelationship = $nestedRelMembership->find(TRUE);
1391 if (!$nestedRelationship) {
1392 $relatedContacts[$cid] = $status;
1397 //lets cleanup related membership if any.
1398 if (empty($relatedContacts)) {
1399 self
::deleteRelatedMemberships($membership->id
);
1402 // Edit the params array
1403 unset($params['id']);
1404 // Reminder should be sent only to the direct membership
1405 unset($params['reminder_date']);
1406 // unset the custom value ids
1407 if (isset($params['custom']) && is_array($params['custom'])) {
1408 foreach ($params['custom'] as $k => $values) {
1409 foreach ($values as $i => $value) {
1410 unset($params['custom'][$k][$i]['id']);
1414 if (!isset($params['membership_type_id'])) {
1415 $params['membership_type_id'] = $membership->membership_type_id
;
1418 // max_related should be set in the parent membership
1419 unset($params['max_related']);
1420 // Number of inherited memberships available - NULL is interpreted as unlimited, '0' as none
1421 $numRelatedAvailable = ($membership->max_related
== NULL ? PHP_INT_MAX
: $membership->max_related
);
1422 // will be used to queue potential memberships to be created.
1425 foreach ($relatedContacts as $contactId => $relationshipStatus) {
1426 //use existing membership record.
1427 $relMembership = new CRM_Member_DAO_Membership();
1428 $relMembership->contact_id
= $contactId;
1429 $relMembership->owner_membership_id
= $membership->id
;
1431 if ($relMembership->find(TRUE)) {
1432 $params['id'] = $relMembership->id
;
1435 unset($params['id']);
1438 $params['contact_id'] = $contactId;
1439 $params['owner_membership_id'] = $membership->id
;
1441 // set status_id as it might have been changed for
1442 // past relationship
1443 $params['status_id'] = $membership->status_id
;
1445 if ($deceasedStatusId &&
1446 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'is_deceased')
1448 $params['status_id'] = $deceasedStatusId;
1450 elseif ((($params['action'] ??
NULL) & CRM_Core_Action
::UPDATE
) &&
1451 ($relationshipStatus == CRM_Contact_BAO_Relationship
::PAST
)
1453 $params['status_id'] = $expiredStatusId;
1456 //don't calculate status again in create( );
1457 $params['skipStatusCal'] = TRUE;
1459 //do create activity if we changed status.
1460 if ($params['status_id'] != $relMembership->status_id
) {
1461 $params['createActivity'] = TRUE;
1464 //CRM-20707 - include start/end date
1465 $params['start_date'] = $membership->start_date
;
1466 $params['end_date'] = $membership->end_date
;
1468 // we should not created contribution record for related contacts, CRM-3371
1469 unset($params['contribution_status_id']);
1471 //CRM-16857: Do not create multiple line-items for inherited membership through priceset.
1472 unset($params['lineItems']);
1473 unset($params['line_item']);
1475 // CRM-20966: Do not create membership_payment record for inherited membership.
1476 unset($params['relate_contribution_id']);
1478 if (($params['status_id'] == $deceasedStatusId) ||
($params['status_id'] == $expiredStatusId)) {
1479 // related membership is not active so does not count towards maximum
1480 if (!self
::hasExistingInheritedMembership($params)) {
1481 civicrm_api3('Membership', 'create', $params);
1485 // related membership already exists, so this is just an update
1486 if (isset($params['id'])) {
1487 if ($numRelatedAvailable > 0) {
1488 CRM_Member_BAO_Membership
::create($params);
1489 $numRelatedAvailable--;
1492 // we have run out of inherited memberships, so delete extras
1493 self
::deleteMembership($params['id']);
1495 // we need to first check if there will remain inherited memberships, so queue it up
1502 // now go over the queue and create any available related memberships
1503 foreach ($queue as $params) {
1504 if ($numRelatedAvailable <= 0) {
1507 if (!self
::hasExistingInheritedMembership($params)) {
1508 CRM_Member_BAO_Membership
::create($params);
1510 $numRelatedAvailable--;
1516 * Delete the record that are associated with this Membership Payment.
1518 * @param int $membershipId
1519 * @param bool $preserveContrib
1522 * $membershipPayment deleted membership payment object
1524 public static function deleteMembershipPayment($membershipId, $preserveContrib = FALSE) {
1526 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
1527 $membershipPayment->membership_id
= $membershipId;
1528 $membershipPayment->find();
1530 while ($membershipPayment->fetch()) {
1531 if (!$preserveContrib) {
1532 CRM_Contribute_BAO_Contribution
::deleteContribution($membershipPayment->contribution_id
);
1534 CRM_Utils_Hook
::pre('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1535 $membershipPayment->delete();
1536 CRM_Utils_Hook
::post('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1538 return $membershipPayment;
1542 * Build an array of available membership types in the current context.
1544 * While core does not do anything context specific extensions may filter
1545 * or alter amounts based on user details.
1547 * @param CRM_Core_Form $form
1548 * @param array $membershipTypeID
1549 * @param bool $activeOnly
1550 * Do we only want active ones?
1551 * (probably this should default to TRUE but as a newly added parameter we are leaving default b
1552 * behaviour unchanged).
1556 * @throws \CiviCRM_API3_Exception
1558 public static function buildMembershipTypeValues($form, $membershipTypeID = [], $activeOnly = FALSE) {
1559 $membershipTypeIDS = (array) $membershipTypeID;
1560 $membershipTypeValues = CRM_Member_BAO_MembershipType
::getAllMembershipTypes();
1562 // MembershipTypes are already filtered by domain, filter as appropriate by is_active & a passed in list of ids.
1563 foreach ($membershipTypeValues as $id => $type) {
1564 if (($activeOnly && empty($type['is_active']))
1565 ||
(!empty($membershipTypeIDS) && !in_array($id, $membershipTypeIDS, FALSE))
1567 unset($membershipTypeValues[$id]);
1571 CRM_Utils_Hook
::membershipTypeValues($form, $membershipTypeValues);
1572 return $membershipTypeValues;
1576 * Get membership record count for a Contact.
1578 * @param int $contactID
1579 * @param bool $activeOnly
1582 * @throws \API_Exception
1584 public static function getContactMembershipCount(int $contactID, $activeOnly = FALSE): int {
1586 $membershipTypes = MembershipType
::get(TRUE)
1590 $addWhere = " AND membership_type_id IN (0)";
1591 if (!empty($membershipTypes)) {
1592 $addWhere = " AND membership_type_id IN (" . implode(',', array_keys($membershipTypes)) . ")";
1595 $select = "SELECT COUNT(*) FROM civicrm_membership ";
1596 $where = "WHERE civicrm_membership.contact_id = {$contactID} AND civicrm_membership.is_test = 0 ";
1598 // CRM-6627, all status below 3 (active, pending, grace) are considered active
1600 $select .= " INNER JOIN civicrm_membership_status ON civicrm_membership.status_id = civicrm_membership_status.id ";
1601 $where .= " and civicrm_membership_status.is_current_member = 1";
1604 $query = $select . $where . $addWhere;
1605 return (int) CRM_Core_DAO
::singleValueQuery($query);
1607 catch (UnauthorizedException
$e) {
1613 * Check whether payment processor supports cancellation of membership subscription.
1618 * @param bool $isNotCancelled
1622 public static function isCancelSubscriptionSupported($mid, $isNotCancelled = TRUE) {
1623 $cacheKeyString = "$mid";
1624 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
1626 static $supportsCancel = [];
1628 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
1629 $supportsCancel[$cacheKeyString] = FALSE;
1630 $isCancelled = FALSE;
1632 if ($isNotCancelled) {
1633 $isCancelled = self
::isSubscriptionCancelled($mid);
1636 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($mid, 'membership', 'obj');
1637 if (!empty($paymentObject)) {
1638 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
1641 return $supportsCancel[$cacheKeyString];
1645 * Check whether subscription is already cancelled.
1651 * contribution status
1653 public static function isSubscriptionCancelled($mid) {
1655 SELECT cr.contribution_status_id
1656 FROM civicrm_contribution_recur cr
1657 LEFT JOIN civicrm_membership mem ON ( cr.id = mem.contribution_recur_id )
1658 WHERE mem.id = %1 LIMIT 1";
1659 $params = [1 => [$mid, 'Integer']];
1660 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
1661 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
1662 if ($status == 'Cancelled') {
1669 * Get membership joins for a specified membership type.
1671 * Specifically, retrieves a count of still current memberships whose
1672 * join_date and start_date are within a specified date range. Dates match
1673 * the pattern "yyyy-mm-dd".
1675 * @param int $membershipTypeId
1676 * Membership type id.
1677 * @param int $startDate
1678 * Date on which to start counting.
1679 * @param int $endDate
1680 * Date on which to end counting.
1681 * @param bool|int $isTest if true, membership is for a test site
1684 * the number of members of type $membershipTypeId
1685 * whose join_date is between $startDate and $endDate and
1686 * whose start_date is between $startDate and $endDate
1688 public static function getMembershipJoins($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1689 $testClause = 'membership.is_test = 1';
1691 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1693 if (!self
::$_signupActType) {
1694 self
::_getActTypes();
1697 if (!self
::$_signupActType) {
1702 SELECT COUNT(DISTINCT membership.id) as member_count
1703 FROM civicrm_membership membership
1704 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1705 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1706 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1707 WHERE membership.membership_type_id = %2
1708 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1712 1 => [self
::$_signupActType, 'Integer'],
1713 2 => [$membershipTypeId, 'Integer'],
1716 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1718 return (int) $memberCount;
1722 * Get membership renewals for a specified membership type.
1724 * Specifically, retrieves a count of still current memberships
1725 * whose join_date is before and start_date is within a specified date
1726 * range. Dates match the pattern "yyyy-mm-dd".
1728 * @param int $membershipTypeId
1729 * Membership type id.
1730 * @param int $startDate
1731 * Date on which to start counting.
1732 * @param int $endDate
1733 * Date on which to end counting.
1734 * @param bool|int $isTest if true, membership is for a test site
1737 * returns the number of members of type $membershipTypeId
1738 * whose join_date is before $startDate and
1739 * whose start_date is between $startDate and $endDate
1741 public static function getMembershipRenewals($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1742 $testClause = 'membership.is_test = 1';
1744 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1746 if (!self
::$_renewalActType) {
1747 self
::_getActTypes();
1750 if (!self
::$_renewalActType) {
1755 SELECT COUNT(DISTINCT membership.id) as member_count
1756 FROM civicrm_membership membership
1757 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1758 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1759 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1760 WHERE membership.membership_type_id = %2
1761 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1765 1 => [self
::$_renewalActType, 'Integer'],
1766 2 => [$membershipTypeId, 'Integer'],
1768 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1770 return (int) $memberCount;
1776 * @param int $contactID
1777 * @param int $membershipTypeID
1778 * @param bool $is_test
1779 * @param string $changeToday
1780 * @param int $modifiedID
1781 * @param $customFieldsFormatted
1782 * @param $numRenewTerms
1783 * @param int $membershipID
1785 * @param int $contributionRecurID
1786 * @param $membershipSource
1787 * @param $isPayLater
1788 * @param array $memParams
1789 * @param null|CRM_Contribute_BAO_Contribution $contribution
1790 * @param array $lineItems
1793 * @throws \CRM_Core_Exception
1794 * @throws \CiviCRM_API3_Exception
1796 public static function processMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $contributionRecurID, $membershipSource, $isPayLater, $memParams = [], $contribution = NULL, $lineItems = []) {
1797 CRM_Core_Error
::deprecatedFunctionWarning('use the order api, BAO functions should only be called from unit tested core code.');
1798 $renewalMode = $updateStatusId = FALSE;
1799 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1801 $statusFormat = '%Y-%m-%d';
1802 $membershipTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipType($membershipTypeID);
1806 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
1807 // is the same as the parent org of an existing membership of the contact
1808 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($contactID, $membershipTypeID,
1809 $is_test, $membershipID, TRUE
1811 if ($currentMembership) {
1812 $renewalMode = TRUE;
1814 // Do NOT do anything.
1815 //1. membership with status : PENDING/CANCELLED (CRM-2395)
1816 //2. Paylater/IPN renew. CRM-4556.
1817 if ($pending ||
in_array($currentMembership['status_id'], [
1818 array_search('Pending', $allStatus),
1820 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1823 $memParams = array_merge([
1824 'id' => $currentMembership['id'],
1825 'contribution' => $contribution,
1826 'status_id' => $currentMembership['status_id'],
1827 'start_date' => $currentMembership['start_date'],
1828 'end_date' => $currentMembership['end_date'],
1829 'line_item' => $lineItems,
1830 'join_date' => $currentMembership['join_date'],
1831 'membership_type_id' => $membershipTypeID,
1832 'max_related' => !empty($membershipTypeDetails['max_related']) ?
$membershipTypeDetails['max_related'] : NULL,
1833 'membership_activity_status' => ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed',
1835 if ($contributionRecurID) {
1836 $memParams['contribution_recur_id'] = $contributionRecurID;
1839 $membership = self
::create($memParams);
1840 return [$membership, $renewalMode, $dates];
1843 // Check and fix the membership if it is STALE
1844 self
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
1846 // Now Renew the membership
1847 if (!$currentMembership['is_current_member']) {
1848 // membership is not CURRENT
1850 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1851 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($currentMembership['id'],
1857 $currentMembership['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1858 foreach (['start_date', 'end_date'] as $dateType) {
1859 $currentMembership[$dateType] = $dates[$dateType] ??
NULL;
1861 $currentMembership['is_test'] = $is_test;
1863 if (!empty($membershipSource)) {
1864 $currentMembership['source'] = $membershipSource;
1867 if (!empty($currentMembership['id'])) {
1868 $ids['membership'] = $currentMembership['id'];
1870 $memParams = array_merge($currentMembership, $memParams);
1871 $memParams['membership_type_id'] = $membershipTypeID;
1873 //set the log start date.
1874 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1878 // CURRENT Membership
1879 $membership = new CRM_Member_DAO_Membership();
1880 $membership->id
= $currentMembership['id'];
1881 $membership->find(TRUE);
1882 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1883 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
1889 // Insert renewed dates for CURRENT membership
1890 $memParams['join_date'] = CRM_Utils_Date
::isoToMysql($membership->join_date
);
1891 $memParams['start_date'] = CRM_Utils_Date
::isoToMysql($membership->start_date
);
1892 $memParams['end_date'] = $dates['end_date'] ??
NULL;
1893 $memParams['membership_type_id'] = $membershipTypeID;
1895 //set the log start date.
1896 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1899 if (!empty($membershipSource)) {
1900 $memParams['source'] = $membershipSource;
1902 elseif (empty($membership->source
)) {
1903 $memParams['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
1904 $currentMembership['id'],
1909 if (!empty($currentMembership['id'])) {
1910 $ids['membership'] = $currentMembership['id'];
1912 $memParams['membership_activity_status'] = ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed';
1917 $memParams = array_merge([
1918 'contact_id' => $contactID,
1919 'membership_type_id' => $membershipTypeID,
1923 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
1925 foreach (['join_date', 'start_date', 'end_date'] as $dateType) {
1926 $memParams[$dateType] = $dates[$dateType] ??
NULL;
1929 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(CRM_Utils_Date
::customFormat($dates['start_date'],
1932 CRM_Utils_Date
::customFormat($dates['end_date'],
1935 CRM_Utils_Date
::customFormat($dates['join_date'],
1943 $updateStatusId = $status['id'] ??
NULL;
1946 // if IPN/Pay-Later set status to: PENDING
1947 $updateStatusId = array_search('Pending', $allStatus);
1950 if (!empty($membershipSource)) {
1951 $memParams['source'] = $membershipSource;
1953 $memParams['is_test'] = $is_test;
1954 $memParams['is_pay_later'] = $isPayLater;
1956 // Putting this in an IF is precautionary as it seems likely that it would be ignored if empty, but
1957 // perhaps shouldn't be?
1958 if ($contributionRecurID) {
1959 $memParams['contribution_recur_id'] = $contributionRecurID;
1962 //if we decided status here and want to skip status
1963 //calculation in create( ); then need to pass 'skipStatusCal'.
1964 if ($updateStatusId) {
1965 $memParams['status_id'] = $updateStatusId;
1966 $memParams['skipStatusCal'] = TRUE;
1969 //since we are renewing,
1970 //make status override false.
1971 $memParams['is_override'] = FALSE;
1973 //CRM-4027, create log w/ individual contact.
1975 // @todo this param is likely unused now.
1976 $memParams['is_for_organization'] = TRUE;
1978 $params['modified_id'] = $modifiedID ??
$contactID;
1980 $memParams['contribution'] = $contribution;
1981 $memParams['custom'] = $customFieldsFormatted;
1982 // Load all line items & process all in membership. Don't do in contribution.
1983 // Relevant tests in api_v3_ContributionPageTest.
1984 $memParams['line_item'] = $lineItems;
1985 // @todo stop passing $ids (membership and userId may be set by this point)
1986 $membership = self
::create($memParams, $ids);
1988 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
1989 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
1990 $membership->find(TRUE);
1992 return [$membership, $renewalMode, $dates];
1996 * Get line items representing the default price set.
1998 * @param int $membershipOrg
1999 * @param int $membershipTypeID
2000 * @param float $total_amount
2001 * @param int $priceSetId
2005 public static function setQuickConfigMembershipParameters($membershipOrg, $membershipTypeID, $total_amount, $priceSetId) {
2006 $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
2008 // The name of the price field corresponds to the membership_type organization contact.
2010 'price_set_id' => $priceSetId,
2011 'name' => $membershipOrg,
2014 CRM_Price_BAO_PriceField
::retrieve($params, $results);
2016 if (!empty($results)) {
2017 $fields[$results['id']] = $priceSets['fields'][$results['id']];
2018 $fid = $results['id'];
2019 $editedFieldParams = [
2020 'price_field_id' => $results['id'],
2021 'membership_type_id' => $membershipTypeID,
2024 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $results);
2025 $fields[$fid]['options'][$results['id']] = $priceSets['fields'][$fid]['options'][$results['id']];
2026 if (!empty($total_amount)) {
2027 $fields[$fid]['options'][$results['id']]['amount'] = $total_amount;
2031 $fieldID = key($fields);
2033 'price_set_id' => $priceSetId,
2034 'price_sets' => $priceSets,
2035 'fields' => $fields,
2037 'price_' . $fieldID => $results['id'] ??
NULL,
2040 return $returnParams;
2044 * Update the status of all deceased members to deceased.
2047 * Count of updated contacts.
2049 * @throws \CiviCRM_API3_Exception
2050 * @throws \CRM_Core_Exception
2052 protected static function updateDeceasedMembersStatuses() {
2055 $deceasedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Deceased');
2057 // 'create' context for buildOptions returns only if enabled.
2058 $allStatus = self
::buildOptions('status_id', 'create');
2059 if (array_key_exists($deceasedStatusId, $allStatus) === FALSE) {
2060 // Deceased status is an admin status & is required. We want to fail early if
2061 // it is not present or active.
2062 // We could make the case 'some databases just don't use deceased so we will check
2063 // for the presence of a deceased contact in the DB before rejecting.
2064 if (CRM_Core_DAO
::singleValueQuery('
2065 SELECT count(*) FROM civicrm_contact WHERE is_deceased = 0'
2067 throw new CRM_Core_Exception(
2068 ts("Deceased Membership status is missing or not active. <a href='%1'>Click here to check</a>.",
2069 [1 => CRM_Utils_System
::url('civicrm/admin/member/membershipStatus', 'reset=1')]
2073 $deceasedDAO = CRM_Core_DAO
::executeQuery(
2075 SELECT membership.id as membership_id
2076 FROM civicrm_membership membership
2077 INNER JOIN civicrm_contact ON membership.contact_id = civicrm_contact.id
2078 INNER JOIN civicrm_membership_type ON membership.membership_type_id = civicrm_membership_type.id
2079 AND civicrm_membership_type.is_active = 1
2080 WHERE membership.is_test = 0
2081 AND civicrm_contact.is_deceased = 1
2082 AND membership.status_id <> %1
2084 [1 => [$deceasedStatusId, 'Integer']]
2086 while ($deceasedDAO->fetch()) {
2087 civicrm_api3('membership', 'create', [
2088 'id' => $deceasedDAO->membership_id
,
2089 'status_id' => $deceasedStatusId,
2090 'createActivity' => TRUE,
2091 'skipStatusCal' => TRUE,
2092 'skipRecentView' => TRUE,
2100 * Does the existing membership match the required membership.
2102 * Check before updating that the params are not a match - this is part of avoiding
2103 * a loop if we have already updated.
2105 * https://issues.civicrm.org/jira/browse/CRM-4213
2106 * @param array $params
2108 * @param array $membership
2112 protected static function matchesRequiredMembership($params, $membership) {
2113 foreach (['start_date', 'end_date'] as $date) {
2114 if (CRM_Utils_Time
::strtotime($params[$date]) !== CRM_Utils_Time
::strtotime($membership[$date])) {
2117 if ((int) $params['status_id'] !== (int) $membership['status_id']) {
2120 if ((int) $params['membership_type_id'] !== (int) $membership['membership_type_id']) {
2128 * Params of new membership.
2130 * @param array $params
2133 * @throws \CiviCRM_API3_Exception
2135 protected static function hasExistingInheritedMembership($params) {
2136 foreach (civicrm_api3('Membership', 'get', ['contact_id' => $params['contact_id']])['values'] as $membership) {
2137 if (!empty($membership['owner_membership_id'])
2138 && $membership['membership_type_id'] === $params['membership_type_id']
2139 && (int) $params['owner_membership_id'] !== (int) $membership['owner_membership_id']
2141 // Inheriting it from another contact, don't update here.
2144 if (self
::matchesRequiredMembership($params, $membership)) {
2152 * Process price set and line items.
2154 * @param int $membershipId
2155 * @param array $lineItem
2157 * @throws \CiviCRM_API3_Exception
2159 public function processPriceSet($membershipId, $lineItem) {
2160 //FIXME : need to move this too
2161 if (!$membershipId ||
!is_array($lineItem)
2162 || CRM_Utils_System
::isNull($lineItem)
2167 foreach ($lineItem as $priceSetId => $values) {
2171 foreach ($values as $line) {
2172 $line['entity_table'] = 'civicrm_membership';
2173 $line['entity_id'] = $membershipId;
2174 CRM_Price_BAO_LineItem
::create($line);
2180 * Retrieve the contribution id for the associated Membership id.
2181 * @todo we should get this off the line item
2183 * @param int $membershipId
2186 * if more than one payment associated with membership id need to be returned.
2190 * @todo we should get this off the line item
2193 public static function getMembershipContributionId($membershipId, $all = FALSE) {
2195 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
2196 $membershipPayment->membership_id
= $membershipId;
2197 if ($all && $membershipPayment->find()) {
2198 $contributionIds = [];
2199 while ($membershipPayment->fetch()) {
2200 $contributionIds[] = $membershipPayment->contribution_id
;
2202 return $contributionIds;
2205 if ($membershipPayment->find(TRUE)) {
2206 return $membershipPayment->contribution_id
;
2212 * The function checks and updates the status of all membership records for a given domain using the
2213 * calc_membership_status and update_contact_membership APIs.
2216 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
2218 * @param array $params
2219 * only_active_membership_types, exclude_test_memberships, exclude_membership_status_ids
2223 * @throws \CiviCRM_API3_Exception
2224 * @throws \CRM_Core_Exception
2226 public static function updateAllMembershipStatus($params = []) {
2227 // We want all of the statuses as id => name, even the disabled ones (cf.
2228 // CRM-15475), to identify which are Pending, Deceased, Cancelled, and
2230 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'validate');
2231 if (empty($params['exclude_membership_status_ids'])) {
2232 $params['exclude_membership_status_ids'] = [
2233 array_search('Pending', $allStatus),
2234 array_search('Cancelled', $allStatus),
2235 array_search('Expired', $allStatus) ?
: 0,
2236 array_search('Deceased', $allStatus),
2239 // Deceased is *always* excluded because it is has very specific processing below.
2240 elseif (!in_array(array_search('Deceased', $allStatus), $params['exclude_membership_status_ids'])) {
2241 $params['exclude_membership_status_ids'][] = array_search('Deceased', $allStatus);
2244 for ($index = 0; $index < count($params['exclude_membership_status_ids']); $index++
) {
2245 $queryParams[$index] = [$params['exclude_membership_status_ids'][$index], 'Integer'];
2247 $membershipStatusClause = 'civicrm_membership.status_id NOT IN (%' . implode(', %', array_keys($queryParams)) . ')';
2249 // Tests for this function are in api_v3_JobTest. Please add tests for all updates.
2251 $updateCount = $processCount = self
::updateDeceasedMembersStatuses();
2253 $whereClauses[] = 'civicrm_contact.is_deceased = 0';
2254 if ($params['exclude_test_memberships']) {
2255 $whereClauses[] = 'civicrm_membership.is_test = 0';
2257 $whereClause = implode(' AND ', $whereClauses);
2258 $activeMembershipClause = '';
2259 if ($params['only_active_membership_types']) {
2260 $activeMembershipClause = ' AND civicrm_membership_type.is_active = 1';
2263 // This query retrieves ALL memberships of active types.
2265 SELECT civicrm_membership.id as membership_id,
2266 civicrm_membership.is_override as is_override,
2267 civicrm_membership.status_override_end_date as status_override_end_date,
2268 civicrm_membership.membership_type_id as membership_type_id,
2269 civicrm_membership.status_id as status_id,
2270 civicrm_membership.join_date as join_date,
2271 civicrm_membership.start_date as start_date,
2272 civicrm_membership.end_date as end_date,
2273 civicrm_membership.source as source,
2274 civicrm_contact.id as contact_id,
2275 civicrm_membership.owner_membership_id as owner_membership_id,
2276 civicrm_membership.contribution_recur_id as recur_id
2277 FROM civicrm_membership
2278 INNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )
2279 INNER JOIN civicrm_membership_type ON
2280 (civicrm_membership.membership_type_id = civicrm_membership_type.id {$activeMembershipClause})
2281 WHERE {$whereClause}";
2283 $query = $baseQuery . " AND civicrm_membership.is_override IS NOT NULL AND civicrm_membership.status_override_end_date IS NOT NULL";
2284 $dao1 = CRM_Core_DAO
::executeQuery($query);
2285 while ($dao1->fetch()) {
2286 self
::processOverriddenUntilDateMembership($dao1);
2289 $query = $baseQuery . " AND (civicrm_membership.is_override = 0 OR civicrm_membership.is_override IS NULL)
2290 AND {$membershipStatusClause}
2291 AND civicrm_membership.owner_membership_id IS NULL ";
2293 $allMembershipTypes = CRM_Member_BAO_MembershipType
::getAllMembershipTypes();
2295 $dao2 = CRM_Core_DAO
::executeQuery($query, $queryParams);
2297 while ($dao2->fetch()) {
2300 // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses
2301 //get the membership status as per id.
2302 $newStatus = civicrm_api3('membership_status', 'calc',
2304 'membership_id' => $dao2->membership_id
,
2305 'ignore_admin_only' => TRUE,
2308 $statusId = $newStatus['id'] ??
NULL;
2310 //process only when status change.
2312 $statusId != $dao2->status_id
2315 'id' => $dao2->membership_id
,
2316 'skipStatusCal' => TRUE,
2317 'skipRecentView' => TRUE,
2318 'status_id' => $statusId,
2319 'createActivity' => TRUE,
2322 //process member record.
2323 civicrm_api3('membership', 'create', $memberParams);
2327 $result['is_error'] = 0;
2328 $result['messages'] = ts('Processed %1 membership records. Updated %2 records.', [
2336 * Set is_override for the 'overridden until date' membership to
2337 * False and clears the 'until date' field in case the 'until date'
2338 * is equal or after today date.
2340 * @param CRM_Core_DAO $membership
2341 * The membership to be processed
2343 * @throws \CiviCRM_API3_Exception
2345 private static function processOverriddenUntilDateMembership($membership) {
2346 $isOverriddenUntilDate = !empty($membership->is_override
) && !empty($membership->status_override_end_date
);
2347 if (!$isOverriddenUntilDate) {
2351 $todayDate = new DateTime();
2352 $todayDate->setTime(0, 0);
2354 $overrideEndDate = new DateTime($membership->status_override_end_date
);
2355 $overrideEndDate->setTime(0, 0);
2357 $datesDifference = $todayDate->diff($overrideEndDate);
2358 $daysDifference = (int) $datesDifference->format('%R%a');
2359 if ($daysDifference <= 0) {
2361 'id' => $membership->membership_id
,
2362 'is_override' => FALSE,
2363 'status_override_end_date' => 'null',
2365 civicrm_api3('membership', 'create', $params);
2370 * Returns the membership types for a particular contact
2371 * who has lifetime membership without end date.
2373 * @param int $contactID
2374 * @param bool $isTest
2375 * @param bool $onlyLifeTime
2379 public static function getAllContactMembership($contactID, $isTest = FALSE, $onlyLifeTime = FALSE) {
2380 $contactMembershipType = [];
2382 return $contactMembershipType;
2385 $dao = new CRM_Member_DAO_Membership();
2386 $dao->contact_id
= $contactID;
2387 $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
2388 $dao->whereAdd("status_id != $pendingStatusId");
2391 $dao->is_test
= $isTest;
2394 $dao->whereAdd('is_test IS NULL OR is_test = 0');
2397 if ($onlyLifeTime) {
2398 $dao->whereAdd('end_date IS NULL');
2402 while ($dao->fetch()) {
2404 CRM_Core_DAO
::storeValues($dao, $membership);
2405 $contactMembershipType[$dao->membership_type_id
] = $membership;
2407 return $contactMembershipType;
2411 * Record contribution record associated with membership.
2412 * This will update an existing contribution if $params['contribution_id'] is passed in.
2413 * This will create a MembershipPayment to link the contribution and membership
2415 * @param array $params
2416 * Array of submitted params.
2418 * @return CRM_Contribute_BAO_Contribution
2419 * @throws \CRM_Core_Exception
2420 * @throws \CiviCRM_API3_Exception
2422 public static function recordMembershipContribution(&$params) {
2423 $contributionParams = [];
2424 $config = CRM_Core_Config
::singleton();
2425 $contributionParams['currency'] = $config->defaultCurrency
;
2426 $contributionParams['receipt_date'] = !empty($params['receipt_date']) ?
$params['receipt_date'] : 'null';
2427 $contributionParams['source'] = $params['contribution_source'] ??
NULL;
2428 $contributionParams['non_deductible_amount'] = 'null';
2429 $contributionParams['skipCleanMoney'] = TRUE;
2430 $contributionParams['payment_processor'] = $params['payment_processor_id'] ??
NULL;
2431 $contributionSoftParams = $params['soft_credit'] ??
NULL;
2432 $recordContribution = [
2437 'financial_type_id',
2438 'payment_instrument_id',
2442 'contribution_status_id',
2449 'contribution_recur_id',
2453 foreach ($recordContribution as $f) {
2454 $contributionParams[$f] = $params[$f] ??
NULL;
2457 if (!empty($params['contribution_id'])) {
2458 $contributionParams['id'] = $params['contribution_id'];
2460 // make entry in batch entity batch table
2461 if (!empty($params['batch_id'])) {
2462 $contributionParams['batch_id'] = $params['batch_id'];
2465 if (!empty($params['contribution_contact_id'])) {
2466 // deal with possibility of a different person paying for contribution
2467 $contributionParams['contact_id'] = $params['contribution_contact_id'];
2470 if (!empty($params['processPriceSet']) &&
2471 !empty($params['lineItems'])
2473 $contributionParams['line_item'] = $params['lineItems'] ??
NULL;
2476 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams);
2478 //CRM-13981, create new soft-credit record as to record payment from different person for this membership
2479 if (!empty($contributionSoftParams)) {
2480 if (!empty($params['batch_id'])) {
2481 foreach ($contributionSoftParams as $contributionSoft) {
2482 $contributionSoft['contribution_id'] = $contribution->id
;
2483 $contributionSoft['currency'] = $contribution->currency
;
2484 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoft);
2488 $contributionSoftParams['contribution_id'] = $contribution->id
;
2489 $contributionSoftParams['currency'] = $contribution->currency
;
2490 $contributionSoftParams['amount'] = $contribution->total_amount
;
2491 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoftParams);
2495 // store contribution id
2496 $params['contribution_id'] = $contribution->id
;
2498 // Create membership payment if it does not already exist
2499 $membershipPayment = civicrm_api3('MembershipPayment', 'get', [
2500 'contribution_id' => $contribution->id
,
2502 if (empty($membershipPayment['count'])) {
2503 civicrm_api3('MembershipPayment', 'create', [
2504 'membership_id' => $params['membership_id'],
2505 'contribution_id' => $contribution->id
,
2509 return $contribution;
2513 * @todo document me - I seem a bit out of date....
2515 public static function _getActTypes() {
2516 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2517 self
::$_renewalActType = CRM_Utils_Array
::key('Membership Renewal', $activityTypes);
2518 self
::$_signupActType = CRM_Utils_Array
::key('Membership Signup', $activityTypes);
2522 * Get all Cancelled Membership(s) for a contact
2524 * @param int $contactID
2526 * @param bool $isTest
2530 * Array of membership type
2532 public static function getContactsCancelledMembership($contactID, $isTest = FALSE) {
2536 $query = 'SELECT membership_type_id FROM civicrm_membership WHERE contact_id = %1 AND status_id = %2 AND is_test = %3';
2538 1 => [$contactID, 'Integer'],
2543 CRM_Member_PseudoConstant
::membershipStatus(
2545 " name = 'Cancelled' ",
2553 3 => [$isTest, 'Boolean'],
2556 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
2557 $cancelledMembershipIds = [];
2558 while ($dao->fetch()) {
2559 $cancelledMembershipIds[] = $dao->membership_type_id
;
2561 return $cancelledMembershipIds;
2565 * Merges the memberships from otherContactID to mainContactID.
2567 * General idea is to merge memberships in regards to their type. We
2568 * move the other contact’s contributions to the main contact’s
2569 * membership which has the same type (if any) and then we update
2570 * membership to avoid loosing `join_date`, `end_date`, and
2571 * `status_id`. In this function, we don’t touch the contributions
2572 * directly (CRM_Dedupe_Merger::moveContactBelongings() takes care
2575 * This function adds new SQL queries to the $sqlQueries parameter.
2577 * @param int $mainContactID
2578 * Contact id of main contact record.
2579 * @param int $otherContactID
2580 * Contact id of record which is going to merge.
2581 * @param array $sqlQueries
2582 * (reference) array of SQL queries to be executed.
2583 * @param array $tables
2584 * List of tables that have to be merged.
2585 * @param array $tableOperations
2586 * Special options/params for some tables to be merged.
2588 * @see CRM_Dedupe_Merger::cpTables()
2590 public static function mergeMemberships($mainContactID, $otherContactID, &$sqlQueries, $tables, $tableOperations) {
2592 * If the user requests not to merge memberships but to add them,
2593 * just attribute the `civicrm_membership` to the
2594 * `$mainContactID`. We have to do this here since the general
2595 * merge process is bypassed by this function.
2597 if (array_key_exists("civicrm_membership", $tableOperations) && $tableOperations['civicrm_membership']['add']) {
2598 $sqlQueries[] = "UPDATE IGNORE civicrm_membership SET contact_id = $mainContactID WHERE contact_id = $otherContactID";
2603 * Retrieve all memberships that belongs to each contacts and
2604 * keep track of each membership type.
2606 $mainContactMemberships = [];
2607 $otherContactMemberships = [];
2609 $sql = "SELECT id, membership_type_id FROM civicrm_membership membership WHERE contact_id = %1";
2610 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$mainContactID, "Integer"]]);
2611 while ($dao->fetch()) {
2612 $mainContactMemberships[$dao->id
] = $dao->membership_type_id
;
2615 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$otherContactID, "Integer"]]);
2616 while ($dao->fetch()) {
2617 $otherContactMemberships[$dao->id
] = $dao->membership_type_id
;
2621 * For each membership, move related contributions to the main
2622 * contact’s membership (by updating `membership_payments`). Then,
2623 * update membership’s `join_date` (if the other membership’s
2624 * join_date is older) and `end_date` (if the other membership’s
2625 * `end_date` is newer) and `status_id` (if the newly calculated
2626 * status is different).
2628 * FIXME: what should we do if we have multiple memberships with
2629 * the same type (currently we only take the first one)?
2632 foreach ($otherContactMemberships as $otherMembershipId => $otherMembershipTypeId) {
2633 if ($newMembershipId = array_search($otherMembershipTypeId, $mainContactMemberships)) {
2636 * Move other membership’s contributions to the main one only
2637 * if user requested to merge contributions.
2639 if (!empty($tables) && in_array('civicrm_contribution', $tables)) {
2640 $newSql[] = "UPDATE civicrm_membership_payment SET membership_id=$newMembershipId WHERE membership_id=$otherMembershipId";
2643 $sql = "SELECT * FROM civicrm_membership membership WHERE id = %1";
2645 $newMembership = CRM_Member_DAO_Membership
::findById($newMembershipId);
2646 $otherMembership = CRM_Member_DAO_Membership
::findById($otherMembershipId);
2649 if (new DateTime($otherMembership->join_date
) < new DateTime($newMembership->join_date
)) {
2650 $updates["join_date"] = $otherMembership->join_date
;
2653 if (new DateTime($otherMembership->end_date
) > new DateTime($newMembership->end_date
)) {
2654 $updates["end_date"] = $otherMembership->end_date
;
2657 if (count($updates)) {
2662 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
2663 $updates["start_date"] ??
$newMembership->start_date
,
2664 $updates["end_date"] ??
$newMembership->end_date
,
2665 $updates["join_date"] ??
$newMembership->join_date
,
2672 if (!empty($status['id']) and $status['id'] != $newMembership->status_id
) {
2673 $updates['status_id'] = $status['id'];
2677 foreach ($updates as $k => $v) {
2678 $updates_sql[] = "$k = '{$v}'";
2681 $newSql[] = sprintf("UPDATE civicrm_membership SET %s WHERE id=%s", implode(", ", $updates_sql), $newMembershipId);
2682 $newSql[] = sprintf("DELETE FROM civicrm_membership WHERE id=%s", $otherMembershipId);
2688 $sqlQueries = array_merge($sqlQueries, $newSql);
2692 * Update membership status to deceased.
2693 * function return the status message for updated membership.
2695 * @param array $deceasedParams
2700 * @param string $contactType
2702 * @return null|string
2703 * $updateMembershipMsg string status message for updated membership.
2705 public static function updateMembershipStatus($deceasedParams, $contactType) {
2706 $updateMembershipMsg = NULL;
2707 $contactId = $deceasedParams['contact_id'];
2708 $deceasedDate = $deceasedParams['deceased_date'];
2710 // process to set membership status to deceased for both active/inactive membership
2712 $contactType === 'Individual' &&
2713 !empty($deceasedParams['is_deceased'])
2716 $userId = CRM_Core_Session
::getLoggedInContactID() ?
: $contactId;
2718 // get deceased status id
2719 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2720 $deceasedStatusId = array_search('Deceased', $allStatus);
2721 if (!$deceasedStatusId) {
2722 return $updateMembershipMsg;
2725 $today = CRM_Utils_Time
::time();
2726 if ($deceasedDate && CRM_Utils_Time
::strtotime($deceasedDate) > $today) {
2727 return $updateMembershipMsg;
2730 // get non deceased membership
2731 $dao = new CRM_Member_DAO_Membership();
2732 $dao->contact_id
= $contactId;
2733 $dao->whereAdd("status_id != $deceasedStatusId");
2735 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2736 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2738 while ($dao->fetch()) {
2739 // update status to deceased (for both active/inactive membership )
2740 CRM_Core_DAO
::setFieldValue('CRM_Member_DAO_Membership', $dao->id
,
2741 'status_id', $deceasedStatusId
2744 // add membership log
2746 'membership_id' => $dao->id
,
2747 'status_id' => $deceasedStatusId,
2748 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
2749 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
2750 'modified_id' => $userId,
2751 'modified_date' => CRM_Utils_Time
::date('Ymd'),
2752 'membership_type_id' => $dao->membership_type_id
,
2753 'max_related' => $dao->max_related
,
2756 CRM_Member_BAO_MembershipLog
::add($membershipLog);
2758 //create activity when membership status is changed
2760 'subject' => "Status changed from {$allStatus[$dao->status_id]} to {$allStatus[$deceasedStatusId]}",
2761 'source_contact_id' => $userId,
2762 'target_contact_id' => $dao->contact_id
,
2763 'source_record_id' => $dao->id
,
2764 'activity_type_id' => array_search('Change Membership Status', $activityTypes),
2768 'activity_date_time' => CRM_Utils_Time
::date('Y-m-d H:i:s'),
2770 'is_current_revision' => 1,
2773 civicrm_api('activity', 'create', $activityParam);
2780 CRM_Core_Session
::setStatus(ts("%1 Current membership(s) for this contact have been set to 'Deceased' status.",
2785 return $updateMembershipMsg;