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['is_override']) && 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 $params['start_date'] = $params['start_date'] ?
: 'null';
279 $params['end_date'] = $params['end_date'] ?
: 'null';
280 $params['join_date'] = $params['join_date'] ?
: 'null';
282 //fix for CRM-3570, during import exclude the statuses those having is_admin = 1
283 $excludeIsAdmin = $params['exclude_is_admin'] ??
FALSE;
285 //CRM-3724 always skip is_admin if is_override != true.
286 if (!$excludeIsAdmin && empty($params['is_override'])) {
287 $excludeIsAdmin = TRUE;
290 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($params['start_date'], $params['end_date'], $params['join_date'],
291 'now', $excludeIsAdmin, $params['membership_type_id'] ??
NULL, $params
293 if (empty($calcStatus)) {
294 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')));
296 $params['status_id'] = $calcStatus['id'];
299 // data cleanup only: all verifications on number of related memberships are done upstream in:
300 // CRM_Member_BAO_Membership::createRelatedMemberships()
301 // CRM_Contact_BAO_Relationship::relatedMemberships()
302 if (!empty($params['owner_membership_id'])) {
303 unset($params['max_related']);
306 // if membership allows related, default max_related to value in membership_type
307 if (!array_key_exists('max_related', $params) && !empty($params['membership_type_id'])) {
308 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipType($params['membership_type_id']);
309 if (isset($membershipType['relationship_type_id'])) {
310 $params['max_related'] = $membershipType['max_related'] ??
NULL;
315 $transaction = new CRM_Core_Transaction();
317 $params['id'] = $params['id'] ??
$ids['membership'] ??
NULL;
318 $membership = self
::add($params);
320 if (is_a($membership, 'CRM_Core_Error')) {
321 $transaction->rollback();
325 $params['membership_id'] = $membership->id
;
326 // @todo further cleanup required to remove use of $ids['contribution'] from here
327 if (isset($ids['membership'])) {
328 $contributionID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment',
333 // @todo this is a temporary step to removing $ids['contribution'] completely
334 if (empty($params['contribution_id']) && !empty($contributionID)) {
335 $params['contribution_id'] = $contributionID;
339 // This code ensures a line item is created but it is recommended you pass in 'skipLineItem' or 'line_item'
340 if (empty($params['line_item']) && !empty($params['membership_type_id']) && empty($params['skipLineItem'])) {
341 CRM_Price_BAO_LineItem
::getLineItemArray($params, NULL, 'membership', $params['membership_type_id']);
343 $params['skipLineItem'] = TRUE;
345 // Record contribution for this membership and create a MembershipPayment
346 // @todo deprecate this.
347 if (!empty($params['contribution_status_id'])) {
348 $memInfo = array_merge($params, ['membership_id' => $membership->id
]);
349 $params['contribution'] = self
::recordMembershipContribution($memInfo);
352 // If the membership has no associated contribution then we ensure
353 // the line items are 'correct' here. This is a lazy legacy
354 // hack whereby they are deleted and recreated
355 if (empty($contributionID)) {
356 if (!empty($params['lineItems'])) {
357 $params['line_item'] = $params['lineItems'];
359 // do cleanup line items if membership edit the Membership type.
360 if (!empty($ids['membership'])) {
361 CRM_Price_BAO_LineItem
::deleteLineItems($ids['membership'], 'civicrm_membership');
363 // @todo - we should ONLY do the below if a contribution is created. Let's
364 // get some deprecation notices in here & see where it's hit & work to eliminate.
365 // This could happen if there is no contribution or we are in one of many
366 // weird and wonderful flows. This is scary code. Keep adding tests.
367 if (!empty($params['line_item']) && empty($params['contribution_id'])) {
369 foreach ($params['line_item'] as $priceSetId => $lineItems) {
370 foreach ($lineItems as $lineIndex => $lineItem) {
371 $lineMembershipType = $lineItem['membership_type_id'] ??
NULL;
372 if (!empty($params['contribution'])) {
373 $params['line_item'][$priceSetId][$lineIndex]['contribution_id'] = $params['contribution']->id
;
375 if ($lineMembershipType && $lineMembershipType == ($params['membership_type_id'] ??
NULL)) {
376 $params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $membership->id
;
377 $params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_membership';
379 elseif (!$lineMembershipType && !empty($params['contribution'])) {
380 $params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $params['contribution']->id
;
381 $params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_contribution';
385 CRM_Price_BAO_LineItem
::processPriceSet(
387 $params['line_item'],
388 $params['contribution'] ??
NULL
393 $transaction->commit();
395 self
::createRelatedMemberships($params, $membership);
397 if (empty($params['skipRecentView'])) {
398 self
::addToRecentItems($membership);
405 * @param \CRM_Member_DAO_Membership $membership
407 private static function addToRecentItems($membership) {
408 $url = CRM_Utils_System
::url('civicrm/contact/view/membership',
409 "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
411 if (empty($membership->membership_type_id
)) {
412 // ie in an update situation.
413 $membership->find(TRUE);
415 $title = CRM_Contact_BAO_Contact
::displayName($membership->contact_id
) . ' - ' . ts('Membership Type:')
416 . ' ' . CRM_Core_PseudoConstant
::getLabel('CRM_Member_BAO_Membership', 'membership_type_id', $membership->membership_type_id
);
419 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::UPDATE
)) {
420 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
421 "action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
424 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::DELETE
)) {
425 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
426 "action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
430 // add the recently created Membership
431 CRM_Utils_Recent
::add($title,
435 $membership->contact_id
,
442 * Check the membership extended through relationship.
444 * @param int $membershipTypeID
445 * Membership type id.
446 * @param int $contactId
452 * array of contact_id of all related contacts.
454 * @throws \CRM_Core_Exception
455 * @throws \CiviCRM_API3_Exception
457 public static function checkMembershipRelationship($membershipTypeID, $contactId, $action = CRM_Core_Action
::ADD
) {
460 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipType($membershipTypeID);
463 if (isset($membershipType['relationship_type_id'])) {
464 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
465 CRM_Contact_BAO_Relationship
::CURRENT
467 if ($action & CRM_Core_Action
::UPDATE
) {
468 $pastRelationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
469 CRM_Contact_BAO_Relationship
::PAST
471 $relationships = array_merge($relationships, $pastRelationships);
475 if (!empty($relationships)) {
476 // check for each contact relationships
477 foreach ($relationships as $values) {
478 //get details of the relationship type
479 $relType = ['id' => $values['civicrm_relationship_type_id']];
481 CRM_Contact_BAO_RelationshipType
::retrieve($relType, $relValues);
482 // Check if contact's relationship type exists in membership type
484 $bidirectional = FALSE;
485 foreach ($membershipType['relationship_type_id'] as $key => $value) {
486 $relTypeDirs[] = $value . '_' . $membershipType['relationship_direction'][$key];
487 if (in_array($value, $relType) &&
488 $relValues['name_a_b'] == $relValues['name_b_a']
490 $bidirectional = TRUE;
494 $relTypeDir = $values['civicrm_relationship_type_id'] . '_' . $values['rtype'];
495 if ($bidirectional ||
in_array($relTypeDir, $relTypeDirs)) {
496 // $values['status'] is going to have value for
497 // current or past relationships.
498 $contacts[$values['cid']] = $values['status'];
503 // Sort by contact_id ascending
509 * Retrieve DB object based on input parameters.
511 * It also stores all the retrieved values in the default array.
513 * @param array $params
514 * (reference ) an assoc array of name/value pairs.
515 * @param array $defaults
516 * (reference ) an assoc array to hold the name / value pairs.
517 * in a hierarchical manner
519 * @return CRM_Member_BAO_Membership
521 public static function retrieve(&$params, &$defaults) {
522 $membership = new CRM_Member_DAO_Membership();
524 $membership->copyValues($params);
526 if ($membership->find(TRUE)) {
527 CRM_Core_DAO
::storeValues($membership, $defaults);
529 //get the membership status and type values.
530 $statusANDType = self
::getStatusANDTypeValues($membership->id
);
531 foreach (['status', 'membership_type'] as $fld) {
532 $defaults[$fld] = $statusANDType[$membership->id
][$fld] ??
NULL;
534 if (!empty($statusANDType[$membership->id
]['is_current_member'])) {
535 $defaults['active'] = TRUE;
545 * Get membership status and membership type values.
547 * @param int $membershipId
548 * Membership id of values to return.
551 * Array of key value pairs
553 public static function getStatusANDTypeValues($membershipId) {
555 if (!$membershipId) {
559 SELECT membership.id as id,
560 status.id as status_id,
561 status.label as status,
562 status.is_current_member as is_current_member,
563 type.id as membership_type_id,
564 type.name as membership_type,
565 type.relationship_type_id as relationship_type_id
566 FROM civicrm_membership membership
567 INNER JOIN civicrm_membership_status status ON ( status.id = membership.status_id )
568 INNER JOIN civicrm_membership_type type ON ( type.id = membership.membership_type_id )
569 WHERE membership.id = %1';
570 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$membershipId, 'Positive']]);
575 'membership_type_id',
577 'relationship_type_id',
579 while ($dao->fetch()) {
580 foreach ($properties as $property) {
581 $values[$dao->id
][$property] = $dao->$property;
591 * Wrapper for most delete calls. Use this unless you JUST want to delete related memberships w/o deleting the parent.
593 * @param int $membershipId
594 * Membership id that needs to be deleted.
595 * @param bool $preserveContrib
598 * Id of deleted Membership on success, false otherwise.
600 public static function del($membershipId, $preserveContrib = FALSE) {
601 //delete related first and then delete parent.
602 self
::deleteRelatedMemberships($membershipId);
603 return self
::deleteMembership($membershipId, $preserveContrib);
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 deleteMembership($membershipId, $preserveContrib = FALSE) {
617 // CRM-12147, retrieve membership data before we delete it for hooks
618 $params = ['id' => $membershipId];
620 $memberships = self
::getValues($params, $memValues);
622 $membership = $memberships[$membershipId];
624 CRM_Utils_Hook
::pre('delete', 'Membership', $membershipId, $memValues);
626 $transaction = new CRM_Core_Transaction();
629 //delete activity record
630 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
633 $deleteActivity = FALSE;
634 $membershipActivities = [
636 'Membership Renewal',
637 'Change Membership Status',
638 'Change Membership Type',
639 'Membership Renewal Reminder',
641 foreach ($membershipActivities as $membershipActivity) {
642 $activityId = array_search($membershipActivity, $activityTypes);
644 $params['activity_type_id'][] = $activityId;
645 $deleteActivity = TRUE;
648 if ($deleteActivity) {
649 $params['source_record_id'] = $membershipId;
650 CRM_Activity_BAO_Activity
::deleteActivity($params);
652 self
::deleteMembershipPayment($membershipId, $preserveContrib);
653 CRM_Price_BAO_LineItem
::deleteLineItems($membershipId, 'civicrm_membership');
655 $results = $membership->delete();
656 $transaction->commit();
658 CRM_Utils_Hook
::post('delete', 'Membership', $membership->id
, $membership);
660 // delete the recently created Membership
661 $membershipRecent = [
662 'id' => $membershipId,
663 'type' => 'Membership',
665 CRM_Utils_Recent
::del($membershipRecent);
671 * Delete related memberships.
673 * @param int $ownerMembershipId
674 * @param int $contactId
678 public static function deleteRelatedMemberships($ownerMembershipId, $contactId = NULL) {
679 if (!$ownerMembershipId && !$contactId) {
683 $membership = new CRM_Member_DAO_Membership();
684 $membership->owner_membership_id
= $ownerMembershipId;
687 $membership->contact_id
= $contactId;
691 while ($membership->fetch()) {
692 //delete related first and then delete parent.
693 self
::deleteRelatedMemberships($membership->id
);
694 self
::deleteMembership($membership->id
);
699 * Obtain active/inactive memberships from the list of memberships passed to it.
701 * @param array $memberships
702 * Membership records.
703 * @param string $status
704 * Active or inactive.
707 * array of memberships based on status
709 public static function activeMembers($memberships, $status = 'active') {
711 if ($status == 'active') {
712 foreach ($memberships as $f => $v) {
713 if (!empty($v['active'])) {
719 elseif ($status == 'inactive') {
720 foreach ($memberships as $f => $v) {
721 if (empty($v['active'])) {
731 * Return Membership Block info in Contribution Pages.
734 * Contribution page id.
738 public static function getMembershipBlock($pageID) {
739 $membershipBlock = [];
740 $dao = new CRM_Member_DAO_MembershipBlock();
741 $dao->entity_table
= 'civicrm_contribution_page';
743 $dao->entity_id
= $pageID;
745 if ($dao->find(TRUE)) {
746 CRM_Core_DAO
::storeValues($dao, $membershipBlock);
747 if (!empty($membershipBlock['membership_types'])) {
748 $membershipTypes = CRM_Utils_String
::unserialize($membershipBlock['membership_types']);
749 if (!is_array($membershipTypes)) {
750 return $membershipBlock;
753 foreach ($membershipTypes as $key => $value) {
754 $membershipBlock['auto_renew'][$key] = $value;
755 $memTypes[$key] = $key;
757 $membershipBlock['membership_types'] = implode(',', $memTypes);
764 return $membershipBlock;
768 * Return a current membership of given contact.
770 * NB: if more than one membership meets criteria, a randomly selected one is returned.
772 * @param int $contactID
774 * @param int $memType
775 * Membership type, null to retrieve all types.
777 * @param int $membershipId
778 * If provided, then determine if it is current.
779 * @param bool $onlySameParentOrg
780 * True if only Memberships with same parent org as the $memType wanted, false otherwise.
783 * @throws \CiviCRM_API3_Exception
785 public static function getContactMembership($contactID, $memType, $isTest, $membershipId = NULL, $onlySameParentOrg = FALSE) {
786 //check for owner membership id, if it exists update that membership instead: CRM-15992
788 $ownerMemberId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
790 'owner_membership_id', 'id'
792 if ($ownerMemberId) {
793 $membershipId = $ownerMemberId;
794 $contactID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
801 $dao = new CRM_Member_DAO_Membership();
803 $dao->id
= $membershipId;
805 $dao->contact_id
= $contactID;
806 $dao->membership_type_id
= $memType;
808 //fetch proper membership record.
810 $dao->is_test
= $isTest;
813 $dao->whereAdd('is_test IS NULL OR is_test = 0');
816 //avoid pending membership as current membership: CRM-3027
817 $statusIds = [array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus())];
818 if (!$membershipId) {
820 $statusIds[] = array_search(
822 CRM_Member_PseudoConstant
::membershipStatus(
824 " name = 'Cancelled' ",
831 $dao->whereAdd('status_id NOT IN ( ' . implode(',', $statusIds) . ')');
833 // order by start date to find most recent membership first, CRM-4545
834 $dao->orderBy('start_date DESC');
837 if ($onlySameParentOrg && $memType) {
838 // require the same parent org as the $memType
839 $params = ['id' => $memType];
840 $membershipType = [];
841 if (CRM_Member_BAO_MembershipType
::retrieve($params, $membershipType)) {
842 $memberTypesSameParentOrg = civicrm_api3('MembershipType', 'get', [
843 'member_of_contact_id' => $membershipType['member_of_contact_id'],
848 $memberTypesSameParentOrgList = implode(',', array_keys($memberTypesSameParentOrg['values'] ??
[]));
849 $dao->whereAdd('membership_type_id IN (' . $memberTypesSameParentOrgList . ')');
853 if ($dao->find(TRUE)) {
855 CRM_Core_DAO
::storeValues($dao, $membership);
856 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
857 $membership['status_id'],
858 'is_current_member', 'id'
860 $ownerMemberId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
862 'owner_membership_id', 'id'
864 if ($ownerMemberId) {
865 $membership['id'] = $membership['membership_id'] = $ownerMemberId;
866 $membership['membership_contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
875 if ($onlySameParentOrg && $memType) {
876 // see if there is a membership that has same parent as $memType but different parent than $membershipID
877 if ($dao->id
&& CRM_Core_Permission
::check('edit memberships')) {
878 // CRM-10016, This is probably a backend renewal, and make sure we return the same membership thats being renewed.
885 unset($dao->membership_type_id
);
886 if ($dao->find(TRUE)) {
888 CRM_Core_DAO
::storeValues($dao, $membership);
889 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
890 $membership['status_id'],
891 'is_current_member', 'id'
900 * Combine all the importable fields from the lower levels object.
902 * @param string $contactType
904 * @param bool $status
907 * array of importable Fields
908 * @throws \CRM_Core_Exception
910 public static function importableFields($contactType = 'Individual', $status = TRUE) {
911 $fields = Civi
::cache('fields')->get('membership_importable_fields' . $contactType . $status);
914 $fields = ['' => ['title' => '- ' . ts('do not import') . ' -']];
917 $fields = ['' => ['title' => '- ' . ts('Membership Fields') . ' -']];
920 $tmpFields = CRM_Member_DAO_Membership
::import();
921 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
923 // Using new Dedupe rule.
925 'contact_type' => $contactType,
926 'used' => 'Unsupervised',
928 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
930 $tmpContactField = [];
931 if (is_array($fieldsArray)) {
932 foreach ($fieldsArray as $value) {
933 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
938 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
939 $tmpContactField[trim($value)] = $contactFields[trim($value)] ??
NULL;
941 $title = $tmpContactField[trim($value)]['title'] . " " . ts('(match to contact)');
944 $title = $tmpContactField[trim($value)]['title'];
946 $tmpContactField[trim($value)]['title'] = $title;
949 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
950 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
952 $tmpFields['membership_contact_id']['title'] .= ' ' . ts('(match to contact)');
954 $fields = array_merge($fields, $tmpContactField);
955 $fields = array_merge($fields, $tmpFields);
956 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
957 Civi
::cache('fields')->set('membership_importable_fields' . $contactType . $status, $fields);
963 * Get all exportable fields.
965 * @return array return array of all exportable fields
967 public static function &exportableFields() {
968 $expFieldMembership = CRM_Member_DAO_Membership
::export();
970 $expFieldsMemType = CRM_Member_DAO_MembershipType
::export();
971 $fields = array_merge($expFieldMembership, $expFieldsMemType);
972 $fields = array_merge($fields, $expFieldMembership);
973 $membershipStatus = [
974 'membership_status' => [
975 'title' => ts('Membership Status'),
976 'name' => 'membership_status',
977 'type' => CRM_Utils_Type
::T_STRING
,
978 'where' => 'civicrm_membership_status.name',
981 //CRM-6161 fix for customdata export
982 $fields = array_merge($fields, $membershipStatus, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
983 $fields['membership_status_id'] = $membershipStatus['membership_status'];
988 * Get membership joins/renewals for a specified membership type.
990 * Specifically, retrieves a count of memberships whose "Membership
991 * Signup" or "Membership Renewal" activity falls in the given date range.
992 * Dates match the pattern "yyyy-mm-dd".
994 * @param int $membershipTypeId
995 * Membership type id.
996 * @param int $startDate
997 * Date on which to start counting.
998 * @param int $endDate
999 * Date on which to end counting.
1000 * @param bool|int $isTest if true, membership is for a test site
1001 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1004 * the number of members of type $membershipTypeId whose
1005 * start_date is between $startDate and $endDate
1007 public static function getMembershipStarts($membershipTypeId, $startDate, $endDate, $isTest = 0, $isOwner = 0) {
1008 // Ensure that the dates that are passed to the query are in the format of yyyy-mm-dd
1009 $dates = ['startDate', 'endDate'];
1010 foreach ($dates as $date) {
1011 if (strlen($
$date) === 8) {
1012 $
$date = date('Y-m-d', CRM_Utils_Time
::strtotime($
$date));
1016 $testClause = 'membership.is_test = 1';
1018 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1021 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1022 self
::_getActTypes();
1025 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1030 SELECT COUNT(DISTINCT membership.id) as member_count
1031 FROM civicrm_membership membership
1032 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id in (%1, %2))
1033 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1034 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1035 WHERE membership.membership_type_id = %3
1036 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1039 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1042 1 => [self
::$_signupActType, 'Integer'],
1043 2 => [self
::$_renewalActType, 'Integer'],
1044 3 => [$membershipTypeId, 'Integer'],
1047 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1048 return (int) $memberCount;
1052 * Get a count of membership for a specified membership type, optionally for a specified date.
1054 * The date must have the form yyyy-mm-dd.
1056 * If $date is omitted, this function counts as a member anyone whose
1057 * membership status_id indicates they're a current member.
1058 * If $date is given, this function counts as a member anyone who:
1059 * -- Has a start_date before $date and end_date after $date, or
1060 * -- Has a start_date before $date and is currently a member, as indicated
1061 * by the the membership's status_id.
1062 * The second condition takes care of records that have no end_date. These
1063 * are assumed to be lifetime memberships.
1065 * @param int $membershipTypeId
1066 * Membership type id.
1067 * @param string $date
1068 * The date for which to retrieve the count.
1069 * @param bool|int $isTest if true, membership is for a test site
1070 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1073 * the number of members of type $membershipTypeId as of $date.
1075 public static function getMembershipCount($membershipTypeId, $date = NULL, $isTest = 0, $isOwner = 0) {
1076 if (!CRM_Utils_Rule
::date($date)) {
1077 throw new CRM_Core_Exception(ts('Invalid date "%1" (must have form yyyy-mm-dd).', [1 => $date]));
1081 1 => [$membershipTypeId, 'Integer'],
1082 2 => [$isTest, 'Boolean'],
1084 $query = "SELECT count(civicrm_membership.id ) as member_count
1085 FROM civicrm_membership left join civicrm_membership_status on ( civicrm_membership.status_id = civicrm_membership_status.id )
1086 WHERE civicrm_membership.membership_type_id = %1
1087 AND civicrm_membership.contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)
1088 AND civicrm_membership.is_test = %2";
1090 $query .= " AND civicrm_membership_status.is_current_member = 1";
1093 $query .= " AND civicrm_membership.start_date <= '$date' AND civicrm_membership_status.is_current_member = 1";
1096 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1097 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1098 return (int) $memberCount;
1102 * Function check the status of the membership before adding membership for a contact.
1106 public static function statusAvailabilty() {
1107 $membership = new CRM_Member_DAO_MembershipStatus();
1108 $membership->whereAdd('is_active=1');
1109 return $membership->count();
1113 * @deprecated This is not used anywhere and should be removed soon!
1114 * Function for updating a membership record's contribution_recur_id.
1116 * @param CRM_Member_DAO_Membership $membership
1117 * @param \CRM_Contribute_BAO_Contribution|\CRM_Contribute_DAO_Contribution $contribution
1119 public static function updateRecurMembership(CRM_Member_DAO_Membership
$membership, CRM_Contribute_BAO_Contribution
$contribution) {
1120 CRM_Core_Error
::deprecatedFunctionWarning('Use the API instead');
1122 if (empty($contribution->contribution_recur_id
)) {
1127 1 => [$contribution->contribution_recur_id
, 'Integer'],
1128 2 => [$membership->id
, 'Integer'],
1131 $sql = "UPDATE civicrm_membership SET contribution_recur_id = %1 WHERE id = %2";
1132 CRM_Core_DAO
::executeQuery($sql, $params);
1136 * Method to fix membership status of stale membership.
1138 * This method first checks if the membership is stale. If it is,
1139 * then status will be updated based on existing start and end
1140 * dates and log will be added for the status change.
1142 * @param array $currentMembership
1143 * Reference to the array.
1144 * containing all values of
1145 * the current membership
1146 * @param string|null $changeToday
1147 * In case today needs
1148 * to be customised, null otherwise
1150 * @throws \CRM_Core_Exception
1152 public static function fixMembershipStatusBeforeRenew(&$currentMembership, $changeToday = NULL) {
1155 $today = CRM_Utils_Date
::processDate($changeToday, NULL, FALSE, 'Y-m-d');
1158 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
1159 $currentMembership['start_date'] ??
NULL,
1160 $currentMembership['end_date'] ??
NULL,
1161 $currentMembership['join_date'] ??
NULL,
1164 $currentMembership['membership_type_id'],
1168 if (empty($status) ||
empty($status['id'])) {
1169 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.'));
1172 if ($status['id'] !== $currentMembership['status_id']) {
1173 $oldStatus = $currentMembership['status_id'];
1174 $memberDAO = new CRM_Member_DAO_Membership();
1175 $memberDAO->id
= $currentMembership['id'];
1176 $memberDAO->find(TRUE);
1178 $memberDAO->status_id
= $status['id'];
1180 CRM_Core_DAO
::storeValues($memberDAO, $currentMembership);
1182 $currentMembership['is_current_member'] = CRM_Core_DAO
::getFieldValue(
1183 'CRM_Member_DAO_MembershipStatus',
1184 $currentMembership['status_id'],
1190 'membership_id' => $currentMembership['id'],
1191 'status_id' => $status['id'],
1192 'start_date' => CRM_Utils_Date
::customFormat(
1193 $currentMembership['start_date'],
1196 'end_date' => CRM_Utils_Date
::customFormat(
1197 $currentMembership['end_date'],
1200 'modified_date' => date('Y-m-d H:i:s', CRM_Utils_Time
::strtotime($today)),
1201 'membership_type_id' => $currentMembership['membership_type_id'],
1202 'max_related' => $currentMembership['max_related'] ??
0,
1205 $session = CRM_Core_Session
::singleton();
1206 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
1207 if ($session->get('userID')) {
1208 $logParams['modified_id'] = $session->get('userID');
1211 $logParams['modified_id'] = $currentMembership['contact_id'];
1214 //Create activity for status change.
1215 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
1216 CRM_Activity_BAO_Activity
::addActivity($memberDAO,
1217 'Change Membership Status',
1220 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$status['id']]}",
1221 'source_contact_id' => $logParams['modified_id'],
1222 'priority_id' => 'Normal',
1226 CRM_Member_BAO_MembershipLog
::add($logParams);
1231 * Get the contribution page id from the membership record.
1233 * @param int $membershipID
1236 * contribution page id
1238 public static function getContributionPageId($membershipID) {
1240 SELECT c.contribution_page_id as pageID
1241 FROM civicrm_membership_payment mp, civicrm_contribution c
1242 WHERE mp.contribution_id = c.id
1243 AND c.contribution_page_id IS NOT NULL
1244 AND mp.membership_id = " . CRM_Utils_Type
::escape($membershipID, 'Integer')
1245 . " ORDER BY mp.id DESC";
1247 return CRM_Core_DAO
::singleValueQuery($query);
1251 * Updated related memberships.
1253 * @param int $ownerMembershipId
1254 * Owner Membership Id.
1255 * @param array $params
1256 * Formatted array of key => value.
1258 public static function updateRelatedMemberships($ownerMembershipId, $params) {
1259 $membership = new CRM_Member_DAO_Membership();
1260 $membership->owner_membership_id
= $ownerMembershipId;
1261 $membership->find();
1263 while ($membership->fetch()) {
1264 $relatedMembership = new CRM_Member_DAO_Membership();
1265 $relatedMembership->id
= $membership->id
;
1266 $relatedMembership->copyValues($params);
1267 $relatedMembership->save();
1273 * Get list of membership fields for profile.
1275 * For now we only allow custom membership fields to be in
1279 * FIXME: This param is ignored
1282 * the list of membership fields
1284 public static function getMembershipFields($mode = NULL) {
1285 $fields = CRM_Member_DAO_Membership
::export();
1287 unset($fields['membership_contact_id']);
1288 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1290 $membershipType = CRM_Member_DAO_MembershipType
::export();
1292 $membershipStatus = CRM_Member_DAO_MembershipStatus
::export();
1294 $fields = array_merge($fields, $membershipType, $membershipStatus);
1300 * Get the sort name of a contact for a particular membership.
1303 * Id of the membership.
1305 * @return null|string
1306 * sort name of the contact if found
1308 public static function sortName($id) {
1309 $id = CRM_Utils_Type
::escape($id, 'Integer');
1312 SELECT civicrm_contact.sort_name
1313 FROM civicrm_membership, civicrm_contact
1314 WHERE civicrm_membership.contact_id = civicrm_contact.id
1315 AND civicrm_membership.id = {$id}
1317 return CRM_Core_DAO
::singleValueQuery($query);
1321 * Create memberships for related contacts, taking into account the maximum related memberships.
1323 * @param array $params
1324 * Array of key - value pairs.
1325 * @param CRM_Core_DAO $dao
1326 * Membership object.
1328 * @throws \CRM_Core_Exception
1329 * @throws \CiviCRM_API3_Exception
1331 public static function createRelatedMemberships($params, $dao) {
1332 unset($params['membership_id']);
1333 $membership = new CRM_Member_DAO_Membership();
1334 $membership->id
= $dao->id
;
1336 // required since create method doesn't return all the
1337 // parameters in the returned membership object
1338 if (!$membership->find(TRUE)) {
1341 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1342 // FIXME : While updating/ renewing the
1343 // membership, if the relationship is PAST then
1344 // the membership of the related contact must be
1346 // For that, getting Membership Status for which
1347 // is_current_member is 0. It works for the
1348 // generated data as there is only one membership
1349 // status having is_current_member = 0.
1350 // But this wont work exactly if there will be
1351 // more than one status having is_current_member = 0.
1352 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
1353 $membershipStatus->is_current_member
= 0;
1354 if ($membershipStatus->find(TRUE)) {
1355 $expiredStatusId = $membershipStatus->id
;
1358 $expiredStatusId = array_search('Expired', CRM_Member_PseudoConstant
::membershipStatus());
1361 $relatedContacts = [];
1362 $allRelatedContacts = CRM_Member_BAO_Membership
::checkMembershipRelationship($membership->membership_type_id
,
1363 $membership->contact_id
,
1364 $params['action'] ??
NULL
1367 // CRM-4213, CRM-19735 check for loops, using static variable to record contacts already processed.
1368 // Remove repeated related contacts, which already inherited membership of this type$relatedContactIds[$membership->contact_id][$membership->membership_type_id] = TRUE;
1369 foreach ($allRelatedContacts as $cid => $status) {
1370 // relatedContactIDs is always empty now - will remove next roud because of whitespace readability.
1371 if (empty($relatedContactIds[$cid]) ||
empty($relatedContactIds[$cid][$membership->membership_type_id
])) {
1372 $relatedContactIds[$cid][$membership->membership_type_id
] = TRUE;
1374 //don't create membership again for owner contact.
1375 $nestedRelationship = FALSE;
1376 if ($membership->owner_membership_id
) {
1377 $nestedRelMembership = new CRM_Member_DAO_Membership();
1378 $nestedRelMembership->id
= $membership->owner_membership_id
;
1379 $nestedRelMembership->contact_id
= $cid;
1380 $nestedRelationship = $nestedRelMembership->find(TRUE);
1382 if (!$nestedRelationship) {
1383 $relatedContacts[$cid] = $status;
1388 //lets cleanup related membership if any.
1389 if (empty($relatedContacts)) {
1390 self
::deleteRelatedMemberships($membership->id
);
1393 // Edit the params array
1394 unset($params['id']);
1395 // Reminder should be sent only to the direct membership
1396 unset($params['reminder_date']);
1397 // unset the custom value ids
1398 if (isset($params['custom']) && is_array($params['custom'])) {
1399 foreach ($params['custom'] as $k => $values) {
1400 foreach ($values as $i => $value) {
1401 unset($params['custom'][$k][$i]['id']);
1405 if (!isset($params['membership_type_id'])) {
1406 $params['membership_type_id'] = $membership->membership_type_id
;
1409 // max_related should be set in the parent membership
1410 unset($params['max_related']);
1411 // Number of inherited memberships available - NULL is interpreted as unlimited, '0' as none
1412 $numRelatedAvailable = ($membership->max_related
== NULL ? PHP_INT_MAX
: $membership->max_related
);
1413 // will be used to queue potential memberships to be created.
1416 foreach ($relatedContacts as $contactId => $relationshipStatus) {
1417 //use existing membership record.
1418 $relMembership = new CRM_Member_DAO_Membership();
1419 $relMembership->contact_id
= $contactId;
1420 $relMembership->owner_membership_id
= $membership->id
;
1422 if ($relMembership->find(TRUE)) {
1423 $params['id'] = $relMembership->id
;
1426 unset($params['id']);
1429 $params['contact_id'] = $contactId;
1430 $params['owner_membership_id'] = $membership->id
;
1432 // set status_id as it might have been changed for
1433 // past relationship
1434 $params['status_id'] = $membership->status_id
;
1436 if ($deceasedStatusId &&
1437 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'is_deceased')
1439 $params['status_id'] = $deceasedStatusId;
1441 elseif ((($params['action'] ??
NULL) & CRM_Core_Action
::UPDATE
) &&
1442 ($relationshipStatus == CRM_Contact_BAO_Relationship
::PAST
)
1444 $params['status_id'] = $expiredStatusId;
1447 //don't calculate status again in create( );
1448 $params['skipStatusCal'] = TRUE;
1450 //do create activity if we changed status.
1451 if ($params['status_id'] != $relMembership->status_id
) {
1452 $params['createActivity'] = TRUE;
1455 //CRM-20707 - include start/end date
1456 $params['start_date'] = $membership->start_date
;
1457 $params['end_date'] = $membership->end_date
;
1459 // we should not created contribution record for related contacts, CRM-3371
1460 unset($params['contribution_status_id']);
1462 //CRM-16857: Do not create multiple line-items for inherited membership through priceset.
1463 unset($params['lineItems']);
1464 unset($params['line_item']);
1466 // CRM-20966: Do not create membership_payment record for inherited membership.
1467 unset($params['relate_contribution_id']);
1469 if (($params['status_id'] == $deceasedStatusId) ||
($params['status_id'] == $expiredStatusId)) {
1470 // related membership is not active so does not count towards maximum
1471 if (!self
::hasExistingInheritedMembership($params)) {
1472 civicrm_api3('Membership', 'create', $params);
1476 // related membership already exists, so this is just an update
1477 if (isset($params['id'])) {
1478 if ($numRelatedAvailable > 0) {
1479 CRM_Member_BAO_Membership
::create($params);
1480 $numRelatedAvailable--;
1483 // we have run out of inherited memberships, so delete extras
1484 self
::deleteMembership($params['id']);
1486 // we need to first check if there will remain inherited memberships, so queue it up
1493 // now go over the queue and create any available related memberships
1494 foreach ($queue as $params) {
1495 if ($numRelatedAvailable <= 0) {
1498 if (!self
::hasExistingInheritedMembership($params)) {
1499 CRM_Member_BAO_Membership
::create($params);
1501 $numRelatedAvailable--;
1507 * Delete the record that are associated with this Membership Payment.
1509 * @param int $membershipId
1510 * @param bool $preserveContrib
1513 * $membershipPayment deleted membership payment object
1515 public static function deleteMembershipPayment($membershipId, $preserveContrib = FALSE) {
1517 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
1518 $membershipPayment->membership_id
= $membershipId;
1519 $membershipPayment->find();
1521 while ($membershipPayment->fetch()) {
1522 if (!$preserveContrib) {
1523 CRM_Contribute_BAO_Contribution
::deleteContribution($membershipPayment->contribution_id
);
1525 CRM_Utils_Hook
::pre('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1526 $membershipPayment->delete();
1527 CRM_Utils_Hook
::post('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1529 return $membershipPayment;
1533 * Build an array of available membership types in the current context.
1535 * While core does not do anything context specific extensions may filter
1536 * or alter amounts based on user details.
1538 * @param CRM_Core_Form $form
1539 * @param array $membershipTypeID
1540 * @param bool $activeOnly
1541 * Do we only want active ones?
1542 * (probably this should default to TRUE but as a newly added parameter we are leaving default b
1543 * behaviour unchanged).
1547 * @throws \CiviCRM_API3_Exception
1549 public static function buildMembershipTypeValues($form, $membershipTypeID = [], $activeOnly = FALSE) {
1550 $membershipTypeIDS = (array) $membershipTypeID;
1551 $membershipTypeValues = CRM_Member_BAO_MembershipType
::getAllMembershipTypes();
1553 // MembershipTypes are already filtered by domain, filter as appropriate by is_active & a passed in list of ids.
1554 foreach ($membershipTypeValues as $id => $type) {
1555 if (($activeOnly && empty($type['is_active']))
1556 ||
(!empty($membershipTypeIDS) && !in_array($id, $membershipTypeIDS, FALSE))
1558 unset($membershipTypeValues[$id]);
1562 CRM_Utils_Hook
::membershipTypeValues($form, $membershipTypeValues);
1563 return $membershipTypeValues;
1567 * Get membership record count for a Contact.
1569 * @param int $contactID
1570 * @param bool $activeOnly
1573 * @throws \API_Exception
1575 public static function getContactMembershipCount(int $contactID, $activeOnly = FALSE): int {
1577 $membershipTypes = MembershipType
::get(TRUE)
1581 $addWhere = " AND membership_type_id IN (0)";
1582 if (!empty($membershipTypes)) {
1583 $addWhere = " AND membership_type_id IN (" . implode(',', array_keys($membershipTypes)) . ")";
1586 $select = "SELECT COUNT(*) FROM civicrm_membership ";
1587 $where = "WHERE civicrm_membership.contact_id = {$contactID} AND civicrm_membership.is_test = 0 ";
1589 // CRM-6627, all status below 3 (active, pending, grace) are considered active
1591 $select .= " INNER JOIN civicrm_membership_status ON civicrm_membership.status_id = civicrm_membership_status.id ";
1592 $where .= " and civicrm_membership_status.is_current_member = 1";
1595 $query = $select . $where . $addWhere;
1596 return (int) CRM_Core_DAO
::singleValueQuery($query);
1598 catch (UnauthorizedException
$e) {
1604 * Check whether payment processor supports cancellation of membership subscription.
1609 * @param bool $isNotCancelled
1613 public static function isCancelSubscriptionSupported($mid, $isNotCancelled = TRUE) {
1614 $cacheKeyString = "$mid";
1615 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
1617 static $supportsCancel = [];
1619 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
1620 $supportsCancel[$cacheKeyString] = FALSE;
1621 $isCancelled = FALSE;
1623 if ($isNotCancelled) {
1624 $isCancelled = self
::isSubscriptionCancelled($mid);
1627 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($mid, 'membership', 'obj');
1628 if (!empty($paymentObject)) {
1629 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
1632 return $supportsCancel[$cacheKeyString];
1636 * Check whether subscription is already cancelled.
1642 * contribution status
1644 public static function isSubscriptionCancelled($mid) {
1646 SELECT cr.contribution_status_id
1647 FROM civicrm_contribution_recur cr
1648 LEFT JOIN civicrm_membership mem ON ( cr.id = mem.contribution_recur_id )
1649 WHERE mem.id = %1 LIMIT 1";
1650 $params = [1 => [$mid, 'Integer']];
1651 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
1652 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
1653 if ($status == 'Cancelled') {
1660 * Get membership joins for a specified membership type.
1662 * Specifically, retrieves a count of still current memberships whose
1663 * join_date and start_date are within a specified date range. Dates match
1664 * the pattern "yyyy-mm-dd".
1666 * @param int $membershipTypeId
1667 * Membership type id.
1668 * @param int $startDate
1669 * Date on which to start counting.
1670 * @param int $endDate
1671 * Date on which to end counting.
1672 * @param bool|int $isTest if true, membership is for a test site
1675 * the number of members of type $membershipTypeId
1676 * whose join_date is between $startDate and $endDate and
1677 * whose start_date is between $startDate and $endDate
1679 public static function getMembershipJoins($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1680 $testClause = 'membership.is_test = 1';
1682 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1684 if (!self
::$_signupActType) {
1685 self
::_getActTypes();
1688 if (!self
::$_signupActType) {
1693 SELECT COUNT(DISTINCT membership.id) as member_count
1694 FROM civicrm_membership membership
1695 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1696 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1697 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1698 WHERE membership.membership_type_id = %2
1699 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1703 1 => [self
::$_signupActType, 'Integer'],
1704 2 => [$membershipTypeId, 'Integer'],
1707 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1709 return (int) $memberCount;
1713 * Get membership renewals for a specified membership type.
1715 * Specifically, retrieves a count of still current memberships
1716 * whose join_date is before and start_date is within a specified date
1717 * range. Dates match the pattern "yyyy-mm-dd".
1719 * @param int $membershipTypeId
1720 * Membership type id.
1721 * @param int $startDate
1722 * Date on which to start counting.
1723 * @param int $endDate
1724 * Date on which to end counting.
1725 * @param bool|int $isTest if true, membership is for a test site
1728 * returns the number of members of type $membershipTypeId
1729 * whose join_date is before $startDate and
1730 * whose start_date is between $startDate and $endDate
1732 public static function getMembershipRenewals($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1733 $testClause = 'membership.is_test = 1';
1735 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1737 if (!self
::$_renewalActType) {
1738 self
::_getActTypes();
1741 if (!self
::$_renewalActType) {
1746 SELECT COUNT(DISTINCT membership.id) as member_count
1747 FROM civicrm_membership membership
1748 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1749 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1750 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1751 WHERE membership.membership_type_id = %2
1752 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1756 1 => [self
::$_renewalActType, 'Integer'],
1757 2 => [$membershipTypeId, 'Integer'],
1759 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1761 return (int) $memberCount;
1767 * @param int $contactID
1768 * @param int $membershipTypeID
1769 * @param bool $is_test
1770 * @param string $changeToday
1771 * @param int $modifiedID
1772 * @param $customFieldsFormatted
1773 * @param $numRenewTerms
1774 * @param int $membershipID
1776 * @param int $contributionRecurID
1777 * @param $membershipSource
1778 * @param $isPayLater
1779 * @param array $memParams
1780 * @param null|CRM_Contribute_BAO_Contribution $contribution
1781 * @param array $lineItems
1784 * @throws \CRM_Core_Exception
1785 * @throws \CiviCRM_API3_Exception
1787 public static function processMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $contributionRecurID, $membershipSource, $isPayLater, $memParams = [], $contribution = NULL, $lineItems = []) {
1788 CRM_Core_Error
::deprecatedFunctionWarning('use the order api, BAO functions should only be called from unit tested core code.');
1789 $renewalMode = $updateStatusId = FALSE;
1790 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1792 $statusFormat = '%Y-%m-%d';
1793 $membershipTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipType($membershipTypeID);
1797 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
1798 // is the same as the parent org of an existing membership of the contact
1799 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($contactID, $membershipTypeID,
1800 $is_test, $membershipID, TRUE
1802 if ($currentMembership) {
1803 $renewalMode = TRUE;
1805 // Do NOT do anything.
1806 //1. membership with status : PENDING/CANCELLED (CRM-2395)
1807 //2. Paylater/IPN renew. CRM-4556.
1808 if ($pending ||
in_array($currentMembership['status_id'], [
1809 array_search('Pending', $allStatus),
1811 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1814 $memParams = array_merge([
1815 'id' => $currentMembership['id'],
1816 'contribution' => $contribution,
1817 'status_id' => $currentMembership['status_id'],
1818 'start_date' => $currentMembership['start_date'],
1819 'end_date' => $currentMembership['end_date'],
1820 'line_item' => $lineItems,
1821 'join_date' => $currentMembership['join_date'],
1822 'membership_type_id' => $membershipTypeID,
1823 'max_related' => !empty($membershipTypeDetails['max_related']) ?
$membershipTypeDetails['max_related'] : NULL,
1824 'membership_activity_status' => ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed',
1826 if ($contributionRecurID) {
1827 $memParams['contribution_recur_id'] = $contributionRecurID;
1830 $membership = self
::create($memParams);
1831 return [$membership, $renewalMode, $dates];
1834 // Check and fix the membership if it is STALE
1835 self
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
1837 // Now Renew the membership
1838 if (!$currentMembership['is_current_member']) {
1839 // membership is not CURRENT
1841 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1842 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($currentMembership['id'],
1848 $currentMembership['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1849 foreach (['start_date', 'end_date'] as $dateType) {
1850 $currentMembership[$dateType] = $dates[$dateType] ??
NULL;
1852 $currentMembership['is_test'] = $is_test;
1854 if (!empty($membershipSource)) {
1855 $currentMembership['source'] = $membershipSource;
1858 if (!empty($currentMembership['id'])) {
1859 $ids['membership'] = $currentMembership['id'];
1861 $memParams = array_merge($currentMembership, $memParams);
1862 $memParams['membership_type_id'] = $membershipTypeID;
1864 //set the log start date.
1865 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1869 // CURRENT Membership
1870 $membership = new CRM_Member_DAO_Membership();
1871 $membership->id
= $currentMembership['id'];
1872 $membership->find(TRUE);
1873 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1874 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
1880 // Insert renewed dates for CURRENT membership
1881 $memParams['join_date'] = CRM_Utils_Date
::isoToMysql($membership->join_date
);
1882 $memParams['start_date'] = CRM_Utils_Date
::isoToMysql($membership->start_date
);
1883 $memParams['end_date'] = $dates['end_date'] ??
NULL;
1884 $memParams['membership_type_id'] = $membershipTypeID;
1886 //set the log start date.
1887 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1890 if (!empty($membershipSource)) {
1891 $memParams['source'] = $membershipSource;
1893 elseif (empty($membership->source
)) {
1894 $memParams['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
1895 $currentMembership['id'],
1900 if (!empty($currentMembership['id'])) {
1901 $ids['membership'] = $currentMembership['id'];
1903 $memParams['membership_activity_status'] = ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed';
1908 $memParams = array_merge([
1909 'contact_id' => $contactID,
1910 'membership_type_id' => $membershipTypeID,
1914 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
1916 foreach (['join_date', 'start_date', 'end_date'] as $dateType) {
1917 $memParams[$dateType] = $dates[$dateType] ??
NULL;
1920 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(CRM_Utils_Date
::customFormat($dates['start_date'],
1923 CRM_Utils_Date
::customFormat($dates['end_date'],
1926 CRM_Utils_Date
::customFormat($dates['join_date'],
1934 $updateStatusId = $status['id'] ??
NULL;
1937 // if IPN/Pay-Later set status to: PENDING
1938 $updateStatusId = array_search('Pending', $allStatus);
1941 if (!empty($membershipSource)) {
1942 $memParams['source'] = $membershipSource;
1944 $memParams['is_test'] = $is_test;
1945 $memParams['is_pay_later'] = $isPayLater;
1947 // Putting this in an IF is precautionary as it seems likely that it would be ignored if empty, but
1948 // perhaps shouldn't be?
1949 if ($contributionRecurID) {
1950 $memParams['contribution_recur_id'] = $contributionRecurID;
1953 //if we decided status here and want to skip status
1954 //calculation in create( ); then need to pass 'skipStatusCal'.
1955 if ($updateStatusId) {
1956 $memParams['status_id'] = $updateStatusId;
1957 $memParams['skipStatusCal'] = TRUE;
1960 //since we are renewing,
1961 //make status override false.
1962 $memParams['is_override'] = FALSE;
1964 //CRM-4027, create log w/ individual contact.
1966 // @todo this param is likely unused now.
1967 $memParams['is_for_organization'] = TRUE;
1969 $params['modified_id'] = $modifiedID ??
$contactID;
1971 $memParams['contribution'] = $contribution;
1972 $memParams['custom'] = $customFieldsFormatted;
1973 // Load all line items & process all in membership. Don't do in contribution.
1974 // Relevant tests in api_v3_ContributionPageTest.
1975 $memParams['line_item'] = $lineItems;
1976 // @todo stop passing $ids (membership and userId may be set by this point)
1977 $membership = self
::create($memParams, $ids);
1979 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
1980 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
1981 $membership->find(TRUE);
1983 return [$membership, $renewalMode, $dates];
1987 * Get line items representing the default price set.
1989 * @param int $membershipOrg
1990 * @param int $membershipTypeID
1991 * @param float $total_amount
1992 * @param int $priceSetId
1996 public static function setQuickConfigMembershipParameters($membershipOrg, $membershipTypeID, $total_amount, $priceSetId) {
1997 $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
1999 // The name of the price field corresponds to the membership_type organization contact.
2001 'price_set_id' => $priceSetId,
2002 'name' => $membershipOrg,
2005 CRM_Price_BAO_PriceField
::retrieve($params, $results);
2007 if (!empty($results)) {
2008 $fields[$results['id']] = $priceSets['fields'][$results['id']];
2009 $fid = $results['id'];
2010 $editedFieldParams = [
2011 'price_field_id' => $results['id'],
2012 'membership_type_id' => $membershipTypeID,
2015 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $results);
2016 $fields[$fid]['options'][$results['id']] = $priceSets['fields'][$fid]['options'][$results['id']];
2017 if (!empty($total_amount)) {
2018 $fields[$fid]['options'][$results['id']]['amount'] = $total_amount;
2022 $fieldID = key($fields);
2024 'price_set_id' => $priceSetId,
2025 'price_sets' => $priceSets,
2026 'fields' => $fields,
2028 'price_' . $fieldID => $results['id'] ??
NULL,
2031 return $returnParams;
2035 * Update the status of all deceased members to deceased.
2038 * Count of updated contacts.
2040 * @throws \CiviCRM_API3_Exception
2041 * @throws \CRM_Core_Exception
2043 protected static function updateDeceasedMembersStatuses() {
2046 $deceasedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Deceased');
2048 // 'create' context for buildOptions returns only if enabled.
2049 $allStatus = self
::buildOptions('status_id', 'create');
2050 if (array_key_exists($deceasedStatusId, $allStatus) === FALSE) {
2051 // Deceased status is an admin status & is required. We want to fail early if
2052 // it is not present or active.
2053 // We could make the case 'some databases just don't use deceased so we will check
2054 // for the presence of a deceased contact in the DB before rejecting.
2055 if (CRM_Core_DAO
::singleValueQuery('
2056 SELECT count(*) FROM civicrm_contact WHERE is_deceased = 0'
2058 throw new CRM_Core_Exception(
2059 ts("Deceased Membership status is missing or not active. <a href='%1'>Click here to check</a>.",
2060 [1 => CRM_Utils_System
::url('civicrm/admin/member/membershipStatus', 'reset=1')]
2064 $deceasedDAO = CRM_Core_DAO
::executeQuery(
2066 SELECT membership.id as membership_id
2067 FROM civicrm_membership membership
2068 INNER JOIN civicrm_contact ON membership.contact_id = civicrm_contact.id
2069 INNER JOIN civicrm_membership_type ON membership.membership_type_id = civicrm_membership_type.id
2070 AND civicrm_membership_type.is_active = 1
2071 WHERE membership.is_test = 0
2072 AND civicrm_contact.is_deceased = 1
2073 AND membership.status_id <> %1
2075 [1 => [$deceasedStatusId, 'Integer']]
2077 while ($deceasedDAO->fetch()) {
2078 civicrm_api3('membership', 'create', [
2079 'id' => $deceasedDAO->membership_id
,
2080 'status_id' => $deceasedStatusId,
2081 'createActivity' => TRUE,
2082 'skipStatusCal' => TRUE,
2083 'skipRecentView' => TRUE,
2091 * Does the existing membership match the required membership.
2093 * Check before updating that the params are not a match - this is part of avoiding
2094 * a loop if we have already updated.
2096 * https://issues.civicrm.org/jira/browse/CRM-4213
2097 * @param array $params
2099 * @param array $membership
2103 protected static function matchesRequiredMembership($params, $membership) {
2104 foreach (['start_date', 'end_date'] as $date) {
2105 if (CRM_Utils_Time
::strtotime($params[$date]) !== CRM_Utils_Time
::strtotime($membership[$date])) {
2108 if ((int) $params['status_id'] !== (int) $membership['status_id']) {
2111 if ((int) $params['membership_type_id'] !== (int) $membership['membership_type_id']) {
2119 * Params of new membership.
2121 * @param array $params
2124 * @throws \CiviCRM_API3_Exception
2126 protected static function hasExistingInheritedMembership($params) {
2127 foreach (civicrm_api3('Membership', 'get', ['contact_id' => $params['contact_id']])['values'] as $membership) {
2128 if (!empty($membership['owner_membership_id'])
2129 && $membership['membership_type_id'] === $params['membership_type_id']
2130 && (int) $params['owner_membership_id'] !== (int) $membership['owner_membership_id']
2132 // Inheriting it from another contact, don't update here.
2135 if (self
::matchesRequiredMembership($params, $membership)) {
2143 * Process price set and line items.
2145 * @param int $membershipId
2146 * @param array $lineItem
2148 * @throws \CiviCRM_API3_Exception
2150 public function processPriceSet($membershipId, $lineItem) {
2151 //FIXME : need to move this too
2152 if (!$membershipId ||
!is_array($lineItem)
2153 || CRM_Utils_System
::isNull($lineItem)
2158 foreach ($lineItem as $priceSetId => $values) {
2162 foreach ($values as $line) {
2163 $line['entity_table'] = 'civicrm_membership';
2164 $line['entity_id'] = $membershipId;
2165 CRM_Price_BAO_LineItem
::create($line);
2171 * Retrieve the contribution id for the associated Membership id.
2172 * @todo we should get this off the line item
2174 * @param int $membershipId
2177 * if more than one payment associated with membership id need to be returned.
2181 * @todo we should get this off the line item
2184 public static function getMembershipContributionId($membershipId, $all = FALSE) {
2186 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
2187 $membershipPayment->membership_id
= $membershipId;
2188 if ($all && $membershipPayment->find()) {
2189 $contributionIds = [];
2190 while ($membershipPayment->fetch()) {
2191 $contributionIds[] = $membershipPayment->contribution_id
;
2193 return $contributionIds;
2196 if ($membershipPayment->find(TRUE)) {
2197 return $membershipPayment->contribution_id
;
2203 * The function checks and updates the status of all membership records for a given domain using the
2204 * calc_membership_status and update_contact_membership APIs.
2207 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
2209 * @param array $params
2210 * only_active_membership_types, exclude_test_memberships, exclude_membership_status_ids
2214 * @throws \CiviCRM_API3_Exception
2215 * @throws \CRM_Core_Exception
2217 public static function updateAllMembershipStatus($params = []) {
2218 // We want all of the statuses as id => name, even the disabled ones (cf.
2219 // CRM-15475), to identify which are Pending, Deceased, Cancelled, and
2221 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'validate');
2222 if (empty($params['exclude_membership_status_ids'])) {
2223 $params['exclude_membership_status_ids'] = [
2224 array_search('Pending', $allStatus),
2225 array_search('Cancelled', $allStatus),
2226 array_search('Expired', $allStatus) ?
: 0,
2227 array_search('Deceased', $allStatus),
2230 // Deceased is *always* excluded because it is has very specific processing below.
2231 elseif (!in_array(array_search('Deceased', $allStatus), $params['exclude_membership_status_ids'])) {
2232 $params['exclude_membership_status_ids'][] = array_search('Deceased', $allStatus);
2235 for ($index = 0; $index < count($params['exclude_membership_status_ids']); $index++
) {
2236 $queryParams[$index] = [$params['exclude_membership_status_ids'][$index], 'Integer'];
2238 $membershipStatusClause = 'civicrm_membership.status_id NOT IN (%' . implode(', %', array_keys($queryParams)) . ')';
2240 // Tests for this function are in api_v3_JobTest. Please add tests for all updates.
2242 $updateCount = $processCount = self
::updateDeceasedMembersStatuses();
2244 $whereClauses[] = 'civicrm_contact.is_deceased = 0';
2245 if ($params['exclude_test_memberships']) {
2246 $whereClauses[] = 'civicrm_membership.is_test = 0';
2248 $whereClause = implode(' AND ', $whereClauses);
2249 $activeMembershipClause = '';
2250 if ($params['only_active_membership_types']) {
2251 $activeMembershipClause = ' AND civicrm_membership_type.is_active = 1';
2254 // This query retrieves ALL memberships of active types.
2256 SELECT civicrm_membership.id as membership_id,
2257 civicrm_membership.is_override as is_override,
2258 civicrm_membership.status_override_end_date as status_override_end_date,
2259 civicrm_membership.membership_type_id as membership_type_id,
2260 civicrm_membership.status_id as status_id,
2261 civicrm_membership.join_date as join_date,
2262 civicrm_membership.start_date as start_date,
2263 civicrm_membership.end_date as end_date,
2264 civicrm_membership.source as source,
2265 civicrm_contact.id as contact_id,
2266 civicrm_membership.owner_membership_id as owner_membership_id,
2267 civicrm_membership.contribution_recur_id as recur_id
2268 FROM civicrm_membership
2269 INNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )
2270 INNER JOIN civicrm_membership_type ON
2271 (civicrm_membership.membership_type_id = civicrm_membership_type.id {$activeMembershipClause})
2272 WHERE {$whereClause}";
2274 $query = $baseQuery . " AND civicrm_membership.is_override IS NOT NULL AND civicrm_membership.status_override_end_date IS NOT NULL";
2275 $dao1 = CRM_Core_DAO
::executeQuery($query);
2276 while ($dao1->fetch()) {
2277 self
::processOverriddenUntilDateMembership($dao1);
2280 $query = $baseQuery . " AND (civicrm_membership.is_override = 0 OR civicrm_membership.is_override IS NULL)
2281 AND {$membershipStatusClause}
2282 AND civicrm_membership.owner_membership_id IS NULL ";
2284 $allMembershipTypes = CRM_Member_BAO_MembershipType
::getAllMembershipTypes();
2286 $dao2 = CRM_Core_DAO
::executeQuery($query, $queryParams);
2288 while ($dao2->fetch()) {
2291 // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses
2292 //get the membership status as per id.
2293 $newStatus = civicrm_api3('membership_status', 'calc',
2295 'membership_id' => $dao2->membership_id
,
2296 'ignore_admin_only' => TRUE,
2299 $statusId = $newStatus['id'] ??
NULL;
2301 //process only when status change.
2303 $statusId != $dao2->status_id
2306 'id' => $dao2->membership_id
,
2307 'skipStatusCal' => TRUE,
2308 'skipRecentView' => TRUE,
2309 'status_id' => $statusId,
2310 'createActivity' => TRUE,
2313 //process member record.
2314 civicrm_api3('membership', 'create', $memberParams);
2318 $result['is_error'] = 0;
2319 $result['messages'] = ts('Processed %1 membership records. Updated %2 records.', [
2327 * Set is_override for the 'overridden until date' membership to
2328 * False and clears the 'until date' field in case the 'until date'
2329 * is equal or after today date.
2331 * @param CRM_Core_DAO $membership
2332 * The membership to be processed
2334 * @throws \CiviCRM_API3_Exception
2336 private static function processOverriddenUntilDateMembership($membership) {
2337 $isOverriddenUntilDate = !empty($membership->is_override
) && !empty($membership->status_override_end_date
);
2338 if (!$isOverriddenUntilDate) {
2342 $todayDate = new DateTime();
2343 $todayDate->setTime(0, 0);
2345 $overrideEndDate = new DateTime($membership->status_override_end_date
);
2346 $overrideEndDate->setTime(0, 0);
2348 $datesDifference = $todayDate->diff($overrideEndDate);
2349 $daysDifference = (int) $datesDifference->format('%R%a');
2350 if ($daysDifference <= 0) {
2352 'id' => $membership->membership_id
,
2353 'is_override' => FALSE,
2354 'status_override_end_date' => 'null',
2356 civicrm_api3('membership', 'create', $params);
2361 * Returns the membership types for a particular contact
2362 * who has lifetime membership without end date.
2364 * @param int $contactID
2365 * @param bool $isTest
2366 * @param bool $onlyLifeTime
2370 public static function getAllContactMembership($contactID, $isTest = FALSE, $onlyLifeTime = FALSE) {
2371 $contactMembershipType = [];
2373 return $contactMembershipType;
2376 $dao = new CRM_Member_DAO_Membership();
2377 $dao->contact_id
= $contactID;
2378 $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
2379 $dao->whereAdd("status_id != $pendingStatusId");
2382 $dao->is_test
= $isTest;
2385 $dao->whereAdd('is_test IS NULL OR is_test = 0');
2388 if ($onlyLifeTime) {
2389 $dao->whereAdd('end_date IS NULL');
2393 while ($dao->fetch()) {
2395 CRM_Core_DAO
::storeValues($dao, $membership);
2396 $contactMembershipType[$dao->membership_type_id
] = $membership;
2398 return $contactMembershipType;
2402 * Record contribution record associated with membership.
2403 * This will update an existing contribution if $params['contribution_id'] is passed in.
2404 * This will create a MembershipPayment to link the contribution and membership
2406 * @param array $params
2407 * Array of submitted params.
2409 * @return CRM_Contribute_BAO_Contribution
2410 * @throws \CRM_Core_Exception
2411 * @throws \CiviCRM_API3_Exception
2413 public static function recordMembershipContribution(&$params) {
2414 $contributionParams = [];
2415 $config = CRM_Core_Config
::singleton();
2416 $contributionParams['currency'] = $config->defaultCurrency
;
2417 $contributionParams['receipt_date'] = !empty($params['receipt_date']) ?
$params['receipt_date'] : 'null';
2418 $contributionParams['source'] = $params['contribution_source'] ??
NULL;
2419 $contributionParams['non_deductible_amount'] = 'null';
2420 $contributionParams['skipCleanMoney'] = TRUE;
2421 $contributionParams['payment_processor'] = $params['payment_processor_id'] ??
NULL;
2422 $contributionSoftParams = $params['soft_credit'] ??
NULL;
2423 $recordContribution = [
2428 'financial_type_id',
2429 'payment_instrument_id',
2433 'contribution_status_id',
2440 'contribution_recur_id',
2444 foreach ($recordContribution as $f) {
2445 $contributionParams[$f] = $params[$f] ??
NULL;
2448 if (!empty($params['contribution_id'])) {
2449 $contributionParams['id'] = $params['contribution_id'];
2451 // make entry in batch entity batch table
2452 if (!empty($params['batch_id'])) {
2453 $contributionParams['batch_id'] = $params['batch_id'];
2456 if (!empty($params['contribution_contact_id'])) {
2457 // deal with possibility of a different person paying for contribution
2458 $contributionParams['contact_id'] = $params['contribution_contact_id'];
2461 if (!empty($params['processPriceSet']) &&
2462 !empty($params['lineItems'])
2464 $contributionParams['line_item'] = $params['lineItems'] ??
NULL;
2467 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams);
2469 //CRM-13981, create new soft-credit record as to record payment from different person for this membership
2470 if (!empty($contributionSoftParams)) {
2471 if (!empty($params['batch_id'])) {
2472 foreach ($contributionSoftParams as $contributionSoft) {
2473 $contributionSoft['contribution_id'] = $contribution->id
;
2474 $contributionSoft['currency'] = $contribution->currency
;
2475 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoft);
2479 $contributionSoftParams['contribution_id'] = $contribution->id
;
2480 $contributionSoftParams['currency'] = $contribution->currency
;
2481 $contributionSoftParams['amount'] = $contribution->total_amount
;
2482 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoftParams);
2486 // store contribution id
2487 $params['contribution_id'] = $contribution->id
;
2489 // Create membership payment if it does not already exist
2490 $membershipPayment = civicrm_api3('MembershipPayment', 'get', [
2491 'contribution_id' => $contribution->id
,
2493 if (empty($membershipPayment['count'])) {
2494 civicrm_api3('MembershipPayment', 'create', [
2495 'membership_id' => $params['membership_id'],
2496 'contribution_id' => $contribution->id
,
2500 return $contribution;
2504 * @todo document me - I seem a bit out of date....
2506 public static function _getActTypes() {
2507 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2508 self
::$_renewalActType = CRM_Utils_Array
::key('Membership Renewal', $activityTypes);
2509 self
::$_signupActType = CRM_Utils_Array
::key('Membership Signup', $activityTypes);
2513 * Get all Cancelled Membership(s) for a contact
2515 * @param int $contactID
2517 * @param bool $isTest
2521 * Array of membership type
2523 public static function getContactsCancelledMembership($contactID, $isTest = FALSE) {
2527 $query = 'SELECT membership_type_id FROM civicrm_membership WHERE contact_id = %1 AND status_id = %2 AND is_test = %3';
2529 1 => [$contactID, 'Integer'],
2534 CRM_Member_PseudoConstant
::membershipStatus(
2536 " name = 'Cancelled' ",
2544 3 => [$isTest, 'Boolean'],
2547 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
2548 $cancelledMembershipIds = [];
2549 while ($dao->fetch()) {
2550 $cancelledMembershipIds[] = $dao->membership_type_id
;
2552 return $cancelledMembershipIds;
2556 * Merges the memberships from otherContactID to mainContactID.
2558 * General idea is to merge memberships in regards to their type. We
2559 * move the other contact’s contributions to the main contact’s
2560 * membership which has the same type (if any) and then we update
2561 * membership to avoid loosing `join_date`, `end_date`, and
2562 * `status_id`. In this function, we don’t touch the contributions
2563 * directly (CRM_Dedupe_Merger::moveContactBelongings() takes care
2566 * This function adds new SQL queries to the $sqlQueries parameter.
2568 * @param int $mainContactID
2569 * Contact id of main contact record.
2570 * @param int $otherContactID
2571 * Contact id of record which is going to merge.
2572 * @param array $sqlQueries
2573 * (reference) array of SQL queries to be executed.
2574 * @param array $tables
2575 * List of tables that have to be merged.
2576 * @param array $tableOperations
2577 * Special options/params for some tables to be merged.
2579 * @see CRM_Dedupe_Merger::cpTables()
2581 public static function mergeMemberships($mainContactID, $otherContactID, &$sqlQueries, $tables, $tableOperations) {
2583 * If the user requests not to merge memberships but to add them,
2584 * just attribute the `civicrm_membership` to the
2585 * `$mainContactID`. We have to do this here since the general
2586 * merge process is bypassed by this function.
2588 if (array_key_exists("civicrm_membership", $tableOperations) && $tableOperations['civicrm_membership']['add']) {
2589 $sqlQueries[] = "UPDATE IGNORE civicrm_membership SET contact_id = $mainContactID WHERE contact_id = $otherContactID";
2594 * Retrieve all memberships that belongs to each contacts and
2595 * keep track of each membership type.
2597 $mainContactMemberships = [];
2598 $otherContactMemberships = [];
2600 $sql = "SELECT id, membership_type_id FROM civicrm_membership membership WHERE contact_id = %1";
2601 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$mainContactID, "Integer"]]);
2602 while ($dao->fetch()) {
2603 $mainContactMemberships[$dao->id
] = $dao->membership_type_id
;
2606 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$otherContactID, "Integer"]]);
2607 while ($dao->fetch()) {
2608 $otherContactMemberships[$dao->id
] = $dao->membership_type_id
;
2612 * For each membership, move related contributions to the main
2613 * contact’s membership (by updating `membership_payments`). Then,
2614 * update membership’s `join_date` (if the other membership’s
2615 * join_date is older) and `end_date` (if the other membership’s
2616 * `end_date` is newer) and `status_id` (if the newly calculated
2617 * status is different).
2619 * FIXME: what should we do if we have multiple memberships with
2620 * the same type (currently we only take the first one)?
2623 foreach ($otherContactMemberships as $otherMembershipId => $otherMembershipTypeId) {
2624 if ($newMembershipId = array_search($otherMembershipTypeId, $mainContactMemberships)) {
2627 * Move other membership’s contributions to the main one only
2628 * if user requested to merge contributions.
2630 if (!empty($tables) && in_array('civicrm_contribution', $tables)) {
2631 $newSql[] = "UPDATE civicrm_membership_payment SET membership_id=$newMembershipId WHERE membership_id=$otherMembershipId";
2634 $sql = "SELECT * FROM civicrm_membership membership WHERE id = %1";
2636 $newMembership = CRM_Member_DAO_Membership
::findById($newMembershipId);
2637 $otherMembership = CRM_Member_DAO_Membership
::findById($otherMembershipId);
2640 if (new DateTime($otherMembership->join_date
) < new DateTime($newMembership->join_date
)) {
2641 $updates["join_date"] = $otherMembership->join_date
;
2644 if (new DateTime($otherMembership->end_date
) > new DateTime($newMembership->end_date
)) {
2645 $updates["end_date"] = $otherMembership->end_date
;
2648 if (count($updates)) {
2653 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
2654 $updates["start_date"] ??
$newMembership->start_date
,
2655 $updates["end_date"] ??
$newMembership->end_date
,
2656 $updates["join_date"] ??
$newMembership->join_date
,
2663 if (!empty($status['id']) and $status['id'] != $newMembership->status_id
) {
2664 $updates['status_id'] = $status['id'];
2668 foreach ($updates as $k => $v) {
2669 $updates_sql[] = "$k = '{$v}'";
2672 $newSql[] = sprintf("UPDATE civicrm_membership SET %s WHERE id=%s", implode(", ", $updates_sql), $newMembershipId);
2673 $newSql[] = sprintf("DELETE FROM civicrm_membership WHERE id=%s", $otherMembershipId);
2679 $sqlQueries = array_merge($sqlQueries, $newSql);
2683 * Update membership status to deceased.
2684 * function return the status message for updated membership.
2686 * @param array $deceasedParams
2691 * @param string $contactType
2693 * @return null|string
2694 * $updateMembershipMsg string status message for updated membership.
2696 public static function updateMembershipStatus($deceasedParams, $contactType) {
2697 $updateMembershipMsg = NULL;
2698 $contactId = $deceasedParams['contact_id'];
2699 $deceasedDate = $deceasedParams['deceased_date'];
2701 // process to set membership status to deceased for both active/inactive membership
2703 $contactType === 'Individual' &&
2704 !empty($deceasedParams['is_deceased'])
2707 $userId = CRM_Core_Session
::getLoggedInContactID() ?
: $contactId;
2709 // get deceased status id
2710 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2711 $deceasedStatusId = array_search('Deceased', $allStatus);
2712 if (!$deceasedStatusId) {
2713 return $updateMembershipMsg;
2716 $today = CRM_Utils_Time
::time();
2717 if ($deceasedDate && CRM_Utils_Time
::strtotime($deceasedDate) > $today) {
2718 return $updateMembershipMsg;
2721 // get non deceased membership
2722 $dao = new CRM_Member_DAO_Membership();
2723 $dao->contact_id
= $contactId;
2724 $dao->whereAdd("status_id != $deceasedStatusId");
2726 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2727 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2729 while ($dao->fetch()) {
2730 // update status to deceased (for both active/inactive membership )
2731 CRM_Core_DAO
::setFieldValue('CRM_Member_DAO_Membership', $dao->id
,
2732 'status_id', $deceasedStatusId
2735 // add membership log
2737 'membership_id' => $dao->id
,
2738 'status_id' => $deceasedStatusId,
2739 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
2740 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
2741 'modified_id' => $userId,
2742 'modified_date' => CRM_Utils_Time
::date('Ymd'),
2743 'membership_type_id' => $dao->membership_type_id
,
2744 'max_related' => $dao->max_related
,
2747 CRM_Member_BAO_MembershipLog
::add($membershipLog);
2749 //create activity when membership status is changed
2751 'subject' => "Status changed from {$allStatus[$dao->status_id]} to {$allStatus[$deceasedStatusId]}",
2752 'source_contact_id' => $userId,
2753 'target_contact_id' => $dao->contact_id
,
2754 'source_record_id' => $dao->id
,
2755 'activity_type_id' => array_search('Change Membership Status', $activityTypes),
2759 'activity_date_time' => CRM_Utils_Time
::date('Y-m-d H:i:s'),
2761 'is_current_revision' => 1,
2764 civicrm_api('activity', 'create', $activityParam);
2771 CRM_Core_Session
::setStatus(ts("%1 Current membership(s) for this contact have been set to 'Deceased' status.",
2776 return $updateMembershipMsg;