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;
1765 * @param int $contactID
1766 * @param int $membershipTypeID
1767 * @param bool $is_test
1768 * @param string $changeToday
1769 * @param int $modifiedID
1770 * @param $customFieldsFormatted
1771 * @param $numRenewTerms
1772 * @param int $membershipID
1774 * @param int $contributionRecurID
1775 * @param $membershipSource
1776 * @param $isPayLater
1777 * @param array $memParams
1778 * @param null|CRM_Contribute_BAO_Contribution $contribution
1779 * @param array $lineItems
1782 * @throws \CRM_Core_Exception
1783 * @throws \CiviCRM_API3_Exception
1785 public static function processMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $contributionRecurID, $membershipSource, $isPayLater, $memParams = [], $contribution = NULL, $lineItems = []) {
1786 $renewalMode = $updateStatusId = FALSE;
1787 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1789 $statusFormat = '%Y-%m-%d';
1790 $membershipTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipType($membershipTypeID);
1794 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
1795 // is the same as the parent org of an existing membership of the contact
1796 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($contactID, $membershipTypeID,
1797 $is_test, $membershipID, TRUE
1799 if ($currentMembership) {
1800 $renewalMode = TRUE;
1802 // Do NOT do anything.
1803 //1. membership with status : PENDING/CANCELLED (CRM-2395)
1804 //2. Paylater/IPN renew. CRM-4556.
1805 if ($pending ||
in_array($currentMembership['status_id'], [
1806 array_search('Pending', $allStatus),
1808 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1811 $memParams = array_merge([
1812 'id' => $currentMembership['id'],
1813 'contribution' => $contribution,
1814 'status_id' => $currentMembership['status_id'],
1815 'start_date' => $currentMembership['start_date'],
1816 'end_date' => $currentMembership['end_date'],
1817 'line_item' => $lineItems,
1818 'join_date' => $currentMembership['join_date'],
1819 'membership_type_id' => $membershipTypeID,
1820 'max_related' => !empty($membershipTypeDetails['max_related']) ?
$membershipTypeDetails['max_related'] : NULL,
1821 'membership_activity_status' => ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed',
1823 if ($contributionRecurID) {
1824 $memParams['contribution_recur_id'] = $contributionRecurID;
1827 $membership = self
::create($memParams);
1828 return [$membership, $renewalMode, $dates];
1831 // Check and fix the membership if it is STALE
1832 self
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
1834 // Now Renew the membership
1835 if (!$currentMembership['is_current_member']) {
1836 // membership is not CURRENT
1838 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1839 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($currentMembership['id'],
1845 $currentMembership['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1846 foreach (['start_date', 'end_date'] as $dateType) {
1847 $currentMembership[$dateType] = $dates[$dateType] ??
NULL;
1849 $currentMembership['is_test'] = $is_test;
1851 if (!empty($membershipSource)) {
1852 $currentMembership['source'] = $membershipSource;
1855 if (!empty($currentMembership['id'])) {
1856 $ids['membership'] = $currentMembership['id'];
1858 $memParams = array_merge($currentMembership, $memParams);
1859 $memParams['membership_type_id'] = $membershipTypeID;
1861 //set the log start date.
1862 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1866 // CURRENT Membership
1867 $membership = new CRM_Member_DAO_Membership();
1868 $membership->id
= $currentMembership['id'];
1869 $membership->find(TRUE);
1870 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1871 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
1877 // Insert renewed dates for CURRENT membership
1878 $memParams['join_date'] = CRM_Utils_Date
::isoToMysql($membership->join_date
);
1879 $memParams['start_date'] = CRM_Utils_Date
::isoToMysql($membership->start_date
);
1880 $memParams['end_date'] = $dates['end_date'] ??
NULL;
1881 $memParams['membership_type_id'] = $membershipTypeID;
1883 //set the log start date.
1884 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1887 if (!empty($membershipSource)) {
1888 $memParams['source'] = $membershipSource;
1890 elseif (empty($membership->source
)) {
1891 $memParams['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
1892 $currentMembership['id'],
1897 if (!empty($currentMembership['id'])) {
1898 $ids['membership'] = $currentMembership['id'];
1900 $memParams['membership_activity_status'] = ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed';
1905 $memParams = array_merge([
1906 'contact_id' => $contactID,
1907 'membership_type_id' => $membershipTypeID,
1911 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
1913 foreach (['join_date', 'start_date', 'end_date'] as $dateType) {
1914 $memParams[$dateType] = $dates[$dateType] ??
NULL;
1917 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(CRM_Utils_Date
::customFormat($dates['start_date'],
1920 CRM_Utils_Date
::customFormat($dates['end_date'],
1923 CRM_Utils_Date
::customFormat($dates['join_date'],
1931 $updateStatusId = $status['id'] ??
NULL;
1934 // if IPN/Pay-Later set status to: PENDING
1935 $updateStatusId = array_search('Pending', $allStatus);
1938 if (!empty($membershipSource)) {
1939 $memParams['source'] = $membershipSource;
1941 $memParams['is_test'] = $is_test;
1942 $memParams['is_pay_later'] = $isPayLater;
1944 // Putting this in an IF is precautionary as it seems likely that it would be ignored if empty, but
1945 // perhaps shouldn't be?
1946 if ($contributionRecurID) {
1947 $memParams['contribution_recur_id'] = $contributionRecurID;
1950 //if we decided status here and want to skip status
1951 //calculation in create( ); then need to pass 'skipStatusCal'.
1952 if ($updateStatusId) {
1953 $memParams['status_id'] = $updateStatusId;
1954 $memParams['skipStatusCal'] = TRUE;
1957 //since we are renewing,
1958 //make status override false.
1959 $memParams['is_override'] = FALSE;
1961 //CRM-4027, create log w/ individual contact.
1963 // @todo this param is likely unused now.
1964 $memParams['is_for_organization'] = TRUE;
1966 $params['modified_id'] = $modifiedID ??
$contactID;
1968 $memParams['contribution'] = $contribution;
1969 $memParams['custom'] = $customFieldsFormatted;
1970 // Load all line items & process all in membership. Don't do in contribution.
1971 // Relevant tests in api_v3_ContributionPageTest.
1972 $memParams['line_item'] = $lineItems;
1973 // @todo stop passing $ids (membership and userId may be set by this point)
1974 $membership = self
::create($memParams, $ids);
1976 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
1977 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
1978 $membership->find(TRUE);
1980 return [$membership, $renewalMode, $dates];
1984 * Get line items representing the default price set.
1986 * @param int $membershipOrg
1987 * @param int $membershipTypeID
1988 * @param float $total_amount
1989 * @param int $priceSetId
1993 public static function setQuickConfigMembershipParameters($membershipOrg, $membershipTypeID, $total_amount, $priceSetId) {
1994 $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
1996 // The name of the price field corresponds to the membership_type organization contact.
1998 'price_set_id' => $priceSetId,
1999 'name' => $membershipOrg,
2002 CRM_Price_BAO_PriceField
::retrieve($params, $results);
2004 if (!empty($results)) {
2005 $fields[$results['id']] = $priceSets['fields'][$results['id']];
2006 $fid = $results['id'];
2007 $editedFieldParams = [
2008 'price_field_id' => $results['id'],
2009 'membership_type_id' => $membershipTypeID,
2012 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $results);
2013 $fields[$fid]['options'][$results['id']] = $priceSets['fields'][$fid]['options'][$results['id']];
2014 if (!empty($total_amount)) {
2015 $fields[$fid]['options'][$results['id']]['amount'] = $total_amount;
2019 $fieldID = key($fields);
2021 'price_set_id' => $priceSetId,
2022 'price_sets' => $priceSets,
2023 'fields' => $fields,
2025 'price_' . $fieldID => $results['id'] ??
NULL,
2028 return $returnParams;
2032 * Update the status of all deceased members to deceased.
2035 * Count of updated contacts.
2037 * @throws \CiviCRM_API3_Exception
2038 * @throws \CRM_Core_Exception
2040 protected static function updateDeceasedMembersStatuses() {
2043 $deceasedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Deceased');
2045 // 'create' context for buildOptions returns only if enabled.
2046 $allStatus = self
::buildOptions('status_id', 'create');
2047 if (array_key_exists($deceasedStatusId, $allStatus) === FALSE) {
2048 // Deceased status is an admin status & is required. We want to fail early if
2049 // it is not present or active.
2050 // We could make the case 'some databases just don't use deceased so we will check
2051 // for the presence of a deceased contact in the DB before rejecting.
2052 if (CRM_Core_DAO
::singleValueQuery('
2053 SELECT count(*) FROM civicrm_contact WHERE is_deceased = 0'
2055 throw new CRM_Core_Exception(
2056 ts("Deceased Membership status is missing or not active. <a href='%1'>Click here to check</a>.",
2057 [1 => CRM_Utils_System
::url('civicrm/admin/member/membershipStatus', 'reset=1')]
2061 $deceasedDAO = CRM_Core_DAO
::executeQuery(
2063 SELECT membership.id as membership_id
2064 FROM civicrm_membership membership
2065 INNER JOIN civicrm_contact ON membership.contact_id = civicrm_contact.id
2066 INNER JOIN civicrm_membership_type ON membership.membership_type_id = civicrm_membership_type.id
2067 AND civicrm_membership_type.is_active = 1
2068 WHERE membership.is_test = 0
2069 AND civicrm_contact.is_deceased = 1
2070 AND membership.status_id <> %1
2072 [1 => [$deceasedStatusId, 'Integer']]
2074 while ($deceasedDAO->fetch()) {
2075 civicrm_api3('membership', 'create', [
2076 'id' => $deceasedDAO->membership_id
,
2077 'status_id' => $deceasedStatusId,
2078 'createActivity' => TRUE,
2079 'skipStatusCal' => TRUE,
2080 'skipRecentView' => TRUE,
2088 * Does the existing membership match the required membership.
2090 * Check before updating that the params are not a match - this is part of avoiding
2091 * a loop if we have already updated.
2093 * https://issues.civicrm.org/jira/browse/CRM-4213
2094 * @param array $params
2096 * @param array $membership
2100 protected static function matchesRequiredMembership($params, $membership) {
2101 foreach (['start_date', 'end_date'] as $date) {
2102 if (CRM_Utils_Time
::strtotime($params[$date]) !== CRM_Utils_Time
::strtotime($membership[$date])) {
2105 if ((int) $params['status_id'] !== (int) $membership['status_id']) {
2108 if ((int) $params['membership_type_id'] !== (int) $membership['membership_type_id']) {
2116 * Params of new membership.
2118 * @param array $params
2121 * @throws \CiviCRM_API3_Exception
2123 protected static function hasExistingInheritedMembership($params) {
2124 foreach (civicrm_api3('Membership', 'get', ['contact_id' => $params['contact_id']])['values'] as $membership) {
2125 if (!empty($membership['owner_membership_id'])
2126 && $membership['membership_type_id'] === $params['membership_type_id']
2127 && (int) $params['owner_membership_id'] !== (int) $membership['owner_membership_id']
2129 // Inheriting it from another contact, don't update here.
2132 if (self
::matchesRequiredMembership($params, $membership)) {
2140 * Process price set and line items.
2142 * @param int $membershipId
2143 * @param array $lineItem
2145 * @throws \CiviCRM_API3_Exception
2147 public function processPriceSet($membershipId, $lineItem) {
2148 //FIXME : need to move this too
2149 if (!$membershipId ||
!is_array($lineItem)
2150 || CRM_Utils_System
::isNull($lineItem)
2155 foreach ($lineItem as $priceSetId => $values) {
2159 foreach ($values as $line) {
2160 $line['entity_table'] = 'civicrm_membership';
2161 $line['entity_id'] = $membershipId;
2162 CRM_Price_BAO_LineItem
::create($line);
2168 * Retrieve the contribution id for the associated Membership id.
2169 * @todo we should get this off the line item
2171 * @param int $membershipId
2174 * if more than one payment associated with membership id need to be returned.
2178 * @todo we should get this off the line item
2181 public static function getMembershipContributionId($membershipId, $all = FALSE) {
2183 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
2184 $membershipPayment->membership_id
= $membershipId;
2185 if ($all && $membershipPayment->find()) {
2186 $contributionIds = [];
2187 while ($membershipPayment->fetch()) {
2188 $contributionIds[] = $membershipPayment->contribution_id
;
2190 return $contributionIds;
2193 if ($membershipPayment->find(TRUE)) {
2194 return $membershipPayment->contribution_id
;
2200 * The function checks and updates the status of all membership records for a given domain using the
2201 * calc_membership_status and update_contact_membership APIs.
2204 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
2206 * @param array $params
2207 * only_active_membership_types, exclude_test_memberships, exclude_membership_status_ids
2211 * @throws \CiviCRM_API3_Exception
2212 * @throws \CRM_Core_Exception
2214 public static function updateAllMembershipStatus($params = []) {
2215 // We want all of the statuses as id => name, even the disabled ones (cf.
2216 // CRM-15475), to identify which are Pending, Deceased, Cancelled, and
2218 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'validate');
2219 if (empty($params['exclude_membership_status_ids'])) {
2220 $params['exclude_membership_status_ids'] = [
2221 array_search('Pending', $allStatus),
2222 array_search('Cancelled', $allStatus),
2223 array_search('Expired', $allStatus) ?
: 0,
2224 array_search('Deceased', $allStatus),
2227 // Deceased is *always* excluded because it is has very specific processing below.
2228 elseif (!in_array(array_search('Deceased', $allStatus), $params['exclude_membership_status_ids'])) {
2229 $params['exclude_membership_status_ids'][] = array_search('Deceased', $allStatus);
2232 for ($index = 0; $index < count($params['exclude_membership_status_ids']); $index++
) {
2233 $queryParams[$index] = [$params['exclude_membership_status_ids'][$index], 'Integer'];
2235 $membershipStatusClause = 'civicrm_membership.status_id NOT IN (%' . implode(', %', array_keys($queryParams)) . ')';
2237 // Tests for this function are in api_v3_JobTest. Please add tests for all updates.
2239 $updateCount = $processCount = self
::updateDeceasedMembersStatuses();
2241 $whereClauses[] = 'civicrm_contact.is_deceased = 0';
2242 if ($params['exclude_test_memberships']) {
2243 $whereClauses[] = 'civicrm_membership.is_test = 0';
2245 $whereClause = implode(' AND ', $whereClauses);
2246 $activeMembershipClause = '';
2247 if ($params['only_active_membership_types']) {
2248 $activeMembershipClause = ' AND civicrm_membership_type.is_active = 1';
2251 // This query retrieves ALL memberships of active types.
2253 SELECT civicrm_membership.id as membership_id,
2254 civicrm_membership.is_override as is_override,
2255 civicrm_membership.status_override_end_date as status_override_end_date,
2256 civicrm_membership.membership_type_id as membership_type_id,
2257 civicrm_membership.status_id as status_id,
2258 civicrm_membership.join_date as join_date,
2259 civicrm_membership.start_date as start_date,
2260 civicrm_membership.end_date as end_date,
2261 civicrm_membership.source as source,
2262 civicrm_contact.id as contact_id,
2263 civicrm_membership.owner_membership_id as owner_membership_id,
2264 civicrm_membership.contribution_recur_id as recur_id
2265 FROM civicrm_membership
2266 INNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )
2267 INNER JOIN civicrm_membership_type ON
2268 (civicrm_membership.membership_type_id = civicrm_membership_type.id {$activeMembershipClause})
2269 WHERE {$whereClause}";
2271 $query = $baseQuery . " AND civicrm_membership.is_override IS NOT NULL AND civicrm_membership.status_override_end_date IS NOT NULL";
2272 $dao1 = CRM_Core_DAO
::executeQuery($query);
2273 while ($dao1->fetch()) {
2274 self
::processOverriddenUntilDateMembership($dao1);
2277 $query = $baseQuery . " AND (civicrm_membership.is_override = 0 OR civicrm_membership.is_override IS NULL)
2278 AND {$membershipStatusClause}
2279 AND civicrm_membership.owner_membership_id IS NULL ";
2281 $allMembershipTypes = CRM_Member_BAO_MembershipType
::getAllMembershipTypes();
2283 $dao2 = CRM_Core_DAO
::executeQuery($query, $queryParams);
2285 while ($dao2->fetch()) {
2288 // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses
2289 //get the membership status as per id.
2290 $newStatus = civicrm_api3('membership_status', 'calc',
2292 'membership_id' => $dao2->membership_id
,
2293 'ignore_admin_only' => TRUE,
2296 $statusId = $newStatus['id'] ??
NULL;
2298 //process only when status change.
2300 $statusId != $dao2->status_id
2303 'id' => $dao2->membership_id
,
2304 'skipStatusCal' => TRUE,
2305 'skipRecentView' => TRUE,
2306 'status_id' => $statusId,
2307 'createActivity' => TRUE,
2310 //process member record.
2311 civicrm_api3('membership', 'create', $memberParams);
2315 $result['is_error'] = 0;
2316 $result['messages'] = ts('Processed %1 membership records. Updated %2 records.', [
2324 * Set is_override for the 'overridden until date' membership to
2325 * False and clears the 'until date' field in case the 'until date'
2326 * is equal or after today date.
2328 * @param CRM_Core_DAO $membership
2329 * The membership to be processed
2331 * @throws \CiviCRM_API3_Exception
2333 private static function processOverriddenUntilDateMembership($membership) {
2334 $isOverriddenUntilDate = !empty($membership->is_override
) && !empty($membership->status_override_end_date
);
2335 if (!$isOverriddenUntilDate) {
2339 $todayDate = new DateTime();
2340 $todayDate->setTime(0, 0);
2342 $overrideEndDate = new DateTime($membership->status_override_end_date
);
2343 $overrideEndDate->setTime(0, 0);
2345 $datesDifference = $todayDate->diff($overrideEndDate);
2346 $daysDifference = (int) $datesDifference->format('%R%a');
2347 if ($daysDifference <= 0) {
2349 'id' => $membership->membership_id
,
2350 'is_override' => FALSE,
2351 'status_override_end_date' => 'null',
2353 civicrm_api3('membership', 'create', $params);
2358 * Returns the membership types for a particular contact
2359 * who has lifetime membership without end date.
2361 * @param int $contactID
2362 * @param bool $isTest
2363 * @param bool $onlyLifeTime
2367 public static function getAllContactMembership($contactID, $isTest = FALSE, $onlyLifeTime = FALSE) {
2368 $contactMembershipType = [];
2370 return $contactMembershipType;
2373 $dao = new CRM_Member_DAO_Membership();
2374 $dao->contact_id
= $contactID;
2375 $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
2376 $dao->whereAdd("status_id != $pendingStatusId");
2379 $dao->is_test
= $isTest;
2382 $dao->whereAdd('is_test IS NULL OR is_test = 0');
2385 if ($onlyLifeTime) {
2386 $dao->whereAdd('end_date IS NULL');
2390 while ($dao->fetch()) {
2392 CRM_Core_DAO
::storeValues($dao, $membership);
2393 $contactMembershipType[$dao->membership_type_id
] = $membership;
2395 return $contactMembershipType;
2399 * Record contribution record associated with membership.
2400 * This will update an existing contribution if $params['contribution_id'] is passed in.
2401 * This will create a MembershipPayment to link the contribution and membership
2403 * @param array $params
2404 * Array of submitted params.
2406 * @return CRM_Contribute_BAO_Contribution
2407 * @throws \CRM_Core_Exception
2408 * @throws \CiviCRM_API3_Exception
2410 public static function recordMembershipContribution(&$params) {
2411 $contributionParams = [];
2412 $config = CRM_Core_Config
::singleton();
2413 $contributionParams['currency'] = $config->defaultCurrency
;
2414 $contributionParams['receipt_date'] = !empty($params['receipt_date']) ?
$params['receipt_date'] : 'null';
2415 $contributionParams['source'] = $params['contribution_source'] ??
NULL;
2416 $contributionParams['non_deductible_amount'] = 'null';
2417 $contributionParams['skipCleanMoney'] = TRUE;
2418 $contributionParams['payment_processor'] = $params['payment_processor_id'] ??
NULL;
2419 $contributionSoftParams = $params['soft_credit'] ??
NULL;
2420 $recordContribution = [
2425 'financial_type_id',
2426 'payment_instrument_id',
2430 'contribution_status_id',
2437 'contribution_recur_id',
2441 foreach ($recordContribution as $f) {
2442 $contributionParams[$f] = $params[$f] ??
NULL;
2445 if (!empty($params['contribution_id'])) {
2446 $contributionParams['id'] = $params['contribution_id'];
2448 // make entry in batch entity batch table
2449 if (!empty($params['batch_id'])) {
2450 $contributionParams['batch_id'] = $params['batch_id'];
2453 if (!empty($params['contribution_contact_id'])) {
2454 // deal with possibility of a different person paying for contribution
2455 $contributionParams['contact_id'] = $params['contribution_contact_id'];
2458 if (!empty($params['processPriceSet']) &&
2459 !empty($params['lineItems'])
2461 $contributionParams['line_item'] = $params['lineItems'] ??
NULL;
2464 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams);
2466 //CRM-13981, create new soft-credit record as to record payment from different person for this membership
2467 if (!empty($contributionSoftParams)) {
2468 if (!empty($params['batch_id'])) {
2469 foreach ($contributionSoftParams as $contributionSoft) {
2470 $contributionSoft['contribution_id'] = $contribution->id
;
2471 $contributionSoft['currency'] = $contribution->currency
;
2472 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoft);
2476 $contributionSoftParams['contribution_id'] = $contribution->id
;
2477 $contributionSoftParams['currency'] = $contribution->currency
;
2478 $contributionSoftParams['amount'] = $contribution->total_amount
;
2479 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoftParams);
2483 // store contribution id
2484 $params['contribution_id'] = $contribution->id
;
2486 // Create membership payment if it does not already exist
2487 $membershipPayment = civicrm_api3('MembershipPayment', 'get', [
2488 'contribution_id' => $contribution->id
,
2490 if (empty($membershipPayment['count'])) {
2491 civicrm_api3('MembershipPayment', 'create', [
2492 'membership_id' => $params['membership_id'],
2493 'contribution_id' => $contribution->id
,
2497 return $contribution;
2501 * @todo document me - I seem a bit out of date....
2503 public static function _getActTypes() {
2504 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2505 self
::$_renewalActType = CRM_Utils_Array
::key('Membership Renewal', $activityTypes);
2506 self
::$_signupActType = CRM_Utils_Array
::key('Membership Signup', $activityTypes);
2510 * Get all Cancelled Membership(s) for a contact
2512 * @param int $contactID
2514 * @param bool $isTest
2518 * Array of membership type
2520 public static function getContactsCancelledMembership($contactID, $isTest = FALSE) {
2524 $query = 'SELECT membership_type_id FROM civicrm_membership WHERE contact_id = %1 AND status_id = %2 AND is_test = %3';
2526 1 => [$contactID, 'Integer'],
2531 CRM_Member_PseudoConstant
::membershipStatus(
2533 " name = 'Cancelled' ",
2541 3 => [$isTest, 'Boolean'],
2544 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
2545 $cancelledMembershipIds = [];
2546 while ($dao->fetch()) {
2547 $cancelledMembershipIds[] = $dao->membership_type_id
;
2549 return $cancelledMembershipIds;
2553 * Merges the memberships from otherContactID to mainContactID.
2555 * General idea is to merge memberships in regards to their type. We
2556 * move the other contact’s contributions to the main contact’s
2557 * membership which has the same type (if any) and then we update
2558 * membership to avoid loosing `join_date`, `end_date`, and
2559 * `status_id`. In this function, we don’t touch the contributions
2560 * directly (CRM_Dedupe_Merger::moveContactBelongings() takes care
2563 * This function adds new SQL queries to the $sqlQueries parameter.
2565 * @param int $mainContactID
2566 * Contact id of main contact record.
2567 * @param int $otherContactID
2568 * Contact id of record which is going to merge.
2569 * @param array $sqlQueries
2570 * (reference) array of SQL queries to be executed.
2571 * @param array $tables
2572 * List of tables that have to be merged.
2573 * @param array $tableOperations
2574 * Special options/params for some tables to be merged.
2576 * @see CRM_Dedupe_Merger::cpTables()
2578 public static function mergeMemberships($mainContactID, $otherContactID, &$sqlQueries, $tables, $tableOperations) {
2580 * If the user requests not to merge memberships but to add them,
2581 * just attribute the `civicrm_membership` to the
2582 * `$mainContactID`. We have to do this here since the general
2583 * merge process is bypassed by this function.
2585 if (array_key_exists("civicrm_membership", $tableOperations) && $tableOperations['civicrm_membership']['add']) {
2586 $sqlQueries[] = "UPDATE IGNORE civicrm_membership SET contact_id = $mainContactID WHERE contact_id = $otherContactID";
2591 * Retrieve all memberships that belongs to each contacts and
2592 * keep track of each membership type.
2594 $mainContactMemberships = [];
2595 $otherContactMemberships = [];
2597 $sql = "SELECT id, membership_type_id FROM civicrm_membership membership WHERE contact_id = %1";
2598 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$mainContactID, "Integer"]]);
2599 while ($dao->fetch()) {
2600 $mainContactMemberships[$dao->id
] = $dao->membership_type_id
;
2603 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$otherContactID, "Integer"]]);
2604 while ($dao->fetch()) {
2605 $otherContactMemberships[$dao->id
] = $dao->membership_type_id
;
2609 * For each membership, move related contributions to the main
2610 * contact’s membership (by updating `membership_payments`). Then,
2611 * update membership’s `join_date` (if the other membership’s
2612 * join_date is older) and `end_date` (if the other membership’s
2613 * `end_date` is newer) and `status_id` (if the newly calculated
2614 * status is different).
2616 * FIXME: what should we do if we have multiple memberships with
2617 * the same type (currently we only take the first one)?
2620 foreach ($otherContactMemberships as $otherMembershipId => $otherMembershipTypeId) {
2621 if ($newMembershipId = array_search($otherMembershipTypeId, $mainContactMemberships)) {
2624 * Move other membership’s contributions to the main one only
2625 * if user requested to merge contributions.
2627 if (!empty($tables) && in_array('civicrm_contribution', $tables)) {
2628 $newSql[] = "UPDATE civicrm_membership_payment SET membership_id=$newMembershipId WHERE membership_id=$otherMembershipId";
2631 $sql = "SELECT * FROM civicrm_membership membership WHERE id = %1";
2633 $newMembership = CRM_Member_DAO_Membership
::findById($newMembershipId);
2634 $otherMembership = CRM_Member_DAO_Membership
::findById($otherMembershipId);
2637 if (new DateTime($otherMembership->join_date
) < new DateTime($newMembership->join_date
)) {
2638 $updates["join_date"] = $otherMembership->join_date
;
2641 if (new DateTime($otherMembership->end_date
) > new DateTime($newMembership->end_date
)) {
2642 $updates["end_date"] = $otherMembership->end_date
;
2645 if (count($updates)) {
2650 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
2651 $updates["start_date"] ??
$newMembership->start_date
,
2652 $updates["end_date"] ??
$newMembership->end_date
,
2653 $updates["join_date"] ??
$newMembership->join_date
,
2660 if (!empty($status['id']) and $status['id'] != $newMembership->status_id
) {
2661 $updates['status_id'] = $status['id'];
2665 foreach ($updates as $k => $v) {
2666 $updates_sql[] = "$k = '{$v}'";
2669 $newSql[] = sprintf("UPDATE civicrm_membership SET %s WHERE id=%s", implode(", ", $updates_sql), $newMembershipId);
2670 $newSql[] = sprintf("DELETE FROM civicrm_membership WHERE id=%s", $otherMembershipId);
2676 $sqlQueries = array_merge($sqlQueries, $newSql);
2680 * Update membership status to deceased.
2681 * function return the status message for updated membership.
2683 * @param array $deceasedParams
2688 * @param string $contactType
2690 * @return null|string
2691 * $updateMembershipMsg string status message for updated membership.
2693 public static function updateMembershipStatus($deceasedParams, $contactType) {
2694 $updateMembershipMsg = NULL;
2695 $contactId = $deceasedParams['contact_id'];
2696 $deceasedDate = $deceasedParams['deceased_date'];
2698 // process to set membership status to deceased for both active/inactive membership
2700 $contactType === 'Individual' &&
2701 !empty($deceasedParams['is_deceased'])
2704 $userId = CRM_Core_Session
::getLoggedInContactID() ?
: $contactId;
2706 // get deceased status id
2707 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2708 $deceasedStatusId = array_search('Deceased', $allStatus);
2709 if (!$deceasedStatusId) {
2710 return $updateMembershipMsg;
2713 $today = CRM_Utils_Time
::time();
2714 if ($deceasedDate && CRM_Utils_Time
::strtotime($deceasedDate) > $today) {
2715 return $updateMembershipMsg;
2718 // get non deceased membership
2719 $dao = new CRM_Member_DAO_Membership();
2720 $dao->contact_id
= $contactId;
2721 $dao->whereAdd("status_id != $deceasedStatusId");
2723 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2724 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2726 while ($dao->fetch()) {
2727 // update status to deceased (for both active/inactive membership )
2728 CRM_Core_DAO
::setFieldValue('CRM_Member_DAO_Membership', $dao->id
,
2729 'status_id', $deceasedStatusId
2732 // add membership log
2734 'membership_id' => $dao->id
,
2735 'status_id' => $deceasedStatusId,
2736 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
2737 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
2738 'modified_id' => $userId,
2739 'modified_date' => CRM_Utils_Time
::date('Ymd'),
2740 'membership_type_id' => $dao->membership_type_id
,
2741 'max_related' => $dao->max_related
,
2744 CRM_Member_BAO_MembershipLog
::add($membershipLog);
2746 //create activity when membership status is changed
2748 'subject' => "Status changed from {$allStatus[$dao->status_id]} to {$allStatus[$deceasedStatusId]}",
2749 'source_contact_id' => $userId,
2750 'target_contact_id' => $dao->contact_id
,
2751 'source_record_id' => $dao->id
,
2752 'activity_type_id' => array_search('Change Membership Status', $activityTypes),
2756 'activity_date_time' => CRM_Utils_Time
::date('Y-m-d H:i:s'),
2758 'is_current_revision' => 1,
2761 civicrm_api('activity', 'create', $activityParam);
2768 CRM_Core_Session
::setStatus(ts("%1 Current membership(s) for this contact have been set to 'Deceased' status.",
2773 return $updateMembershipMsg;