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 = []) {
249 // always calculate status if is_override/skipStatusCal is not true.
250 // giving respect to is_override during import. CRM-4012
252 // To skip status calculation we should use 'skipStatusCal'.
253 // eg pay later membership, membership update cron CRM-3984
255 if (empty($params['is_override']) && empty($params['skipStatusCal'])) {
257 foreach (['start_date', 'end_date', 'join_date'] as $dateField) {
258 if (!empty($params[$dateField]) && $params[$dateField] !== 'null' && strpos($params[$dateField], date('Ymd', CRM_Utils_Time
::strtotime(trim($params[$dateField])))) !== 0) {
259 $params[$dateField] = date('Ymd', CRM_Utils_Time
::strtotime(trim($params[$dateField])));
260 // @todo enable this once core is using the api.
261 // CRM_Core_Error::deprecatedWarning('Relying on the BAO to clean up dates is deprecated. Call membership create via the api');
263 if (!empty($params['id']) && empty($params[$dateField])) {
264 $fieldsToLoad[] = $dateField;
267 if (!empty($fieldsToLoad)) {
268 $membership = civicrm_api3('Membership', 'getsingle', ['id' => $params['id'], 'return' => $fieldsToLoad]);
269 foreach ($fieldsToLoad as $fieldToLoad) {
270 $params[$fieldToLoad] = $membership[$fieldToLoad];
273 $params['start_date'] = $params['start_date'] ?
: 'null';
274 $params['end_date'] = $params['end_date'] ?
: 'null';
275 $params['join_date'] = $params['join_date'] ?
: 'null';
277 //fix for CRM-3570, during import exclude the statuses those having is_admin = 1
278 $excludeIsAdmin = $params['exclude_is_admin'] ??
FALSE;
280 //CRM-3724 always skip is_admin if is_override != true.
281 if (!$excludeIsAdmin && empty($params['is_override'])) {
282 $excludeIsAdmin = TRUE;
285 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($params['start_date'], $params['end_date'], $params['join_date'],
286 'now', $excludeIsAdmin, $params['membership_type_id'] ??
NULL, $params
288 if (empty($calcStatus)) {
289 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')));
291 $params['status_id'] = $calcStatus['id'];
294 // data cleanup only: all verifications on number of related memberships are done upstream in:
295 // CRM_Member_BAO_Membership::createRelatedMemberships()
296 // CRM_Contact_BAO_Relationship::relatedMemberships()
297 if (!empty($params['owner_membership_id'])) {
298 unset($params['max_related']);
301 // if membership allows related, default max_related to value in membership_type
302 if (!array_key_exists('max_related', $params) && !empty($params['membership_type_id'])) {
303 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipType($params['membership_type_id']);
304 if (isset($membershipType['relationship_type_id'])) {
305 $params['max_related'] = $membershipType['max_related'] ??
NULL;
310 $transaction = new CRM_Core_Transaction();
312 $params['id'] = $params['id'] ??
$ids['membership'] ??
NULL;
313 $membership = self
::add($params);
315 if (is_a($membership, 'CRM_Core_Error')) {
316 $transaction->rollback();
320 $params['membership_id'] = $membership->id
;
321 // @todo further cleanup required to remove use of $ids['contribution'] from here
322 if (isset($ids['membership'])) {
323 $contributionID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment',
328 // @todo this is a temporary step to removing $ids['contribution'] completely
329 if (empty($params['contribution_id']) && !empty($contributionID)) {
330 $params['contribution_id'] = $contributionID;
334 // This code ensures a line item is created but it is recommended you pass in 'skipLineItem' or 'line_item'
335 if (empty($params['line_item']) && !empty($params['membership_type_id']) && empty($params['skipLineItem'])) {
336 CRM_Price_BAO_LineItem
::getLineItemArray($params, NULL, 'membership', $params['membership_type_id']);
338 $params['skipLineItem'] = TRUE;
340 // Record contribution for this membership and create a MembershipPayment
341 // @todo deprecate this.
342 if (!empty($params['contribution_status_id']) && empty($params['relate_contribution_id'])) {
343 $memInfo = array_merge($params, ['membership_id' => $membership->id
]);
344 $params['contribution'] = self
::recordMembershipContribution($memInfo);
347 // Add/update MembershipPayment record for this membership if it is a related contribution
348 // @todo remove this - called from one remaining place in CRM_Member_Form_Membership
349 if (!empty($params['relate_contribution_id'])) {
350 $membershipPaymentParams = [
351 'membership_id' => $membership->id
,
352 'membership_type_id' => $membership->membership_type_id
,
353 'contribution_id' => $params['relate_contribution_id'],
355 civicrm_api3('MembershipPayment', 'create', $membershipPaymentParams);
358 // If the membership has no associated contribution then we ensure
359 // the line items are 'correct' here. This is a lazy legacy
360 // hack whereby they are deleted and recreated
361 if (empty($contributionID)) {
362 if (!empty($params['lineItems'])) {
363 $params['line_item'] = $params['lineItems'];
365 // do cleanup line items if membership edit the Membership type.
366 if (!empty($ids['membership'])) {
367 CRM_Price_BAO_LineItem
::deleteLineItems($ids['membership'], 'civicrm_membership');
369 // @todo - we should ONLY do the below if a contribution is created. Let's
370 // get some deprecation notices in here & see where it's hit & work to eliminate.
371 // This could happen if there is no contribution or we are in one of many
372 // weird and wonderful flows. This is scary code. Keep adding tests.
373 if (!empty($params['line_item']) && empty($params['contribution_id'])) {
375 foreach ($params['line_item'] as $priceSetId => $lineItems) {
376 foreach ($lineItems as $lineIndex => $lineItem) {
377 $lineMembershipType = $lineItem['membership_type_id'] ??
NULL;
378 if (!empty($params['contribution'])) {
379 $params['line_item'][$priceSetId][$lineIndex]['contribution_id'] = $params['contribution']->id
;
381 if ($lineMembershipType && $lineMembershipType == ($params['membership_type_id'] ??
NULL)) {
382 $params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $membership->id
;
383 $params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_membership';
385 elseif (!$lineMembershipType && !empty($params['contribution'])) {
386 $params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $params['contribution']->id
;
387 $params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_contribution';
391 CRM_Price_BAO_LineItem
::processPriceSet(
393 $params['line_item'],
394 $params['contribution'] ??
NULL
399 $transaction->commit();
401 self
::createRelatedMemberships($params, $membership);
403 if (empty($params['skipRecentView'])) {
404 self
::addToRecentItems($membership);
411 * @param \CRM_Member_DAO_Membership $membership
413 private static function addToRecentItems($membership) {
414 $url = CRM_Utils_System
::url('civicrm/contact/view/membership',
415 "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
417 if (empty($membership->membership_type_id
)) {
418 // ie in an update situation.
419 $membership->find(TRUE);
421 $title = CRM_Contact_BAO_Contact
::displayName($membership->contact_id
) . ' - ' . ts('Membership Type:')
422 . ' ' . CRM_Core_PseudoConstant
::getLabel('CRM_Member_BAO_Membership', 'membership_type_id', $membership->membership_type_id
);
425 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::UPDATE
)) {
426 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
427 "action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
430 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::DELETE
)) {
431 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
432 "action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
436 // add the recently created Membership
437 CRM_Utils_Recent
::add($title,
441 $membership->contact_id
,
448 * Check the membership extended through relationship.
450 * @param int $membershipTypeID
451 * Membership type id.
452 * @param int $contactId
458 * array of contact_id of all related contacts.
460 * @throws \CRM_Core_Exception
461 * @throws \CiviCRM_API3_Exception
463 public static function checkMembershipRelationship($membershipTypeID, $contactId, $action = CRM_Core_Action
::ADD
) {
466 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipType($membershipTypeID);
469 if (isset($membershipType['relationship_type_id'])) {
470 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
471 CRM_Contact_BAO_Relationship
::CURRENT
473 if ($action & CRM_Core_Action
::UPDATE
) {
474 $pastRelationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
475 CRM_Contact_BAO_Relationship
::PAST
477 $relationships = array_merge($relationships, $pastRelationships);
481 if (!empty($relationships)) {
482 // check for each contact relationships
483 foreach ($relationships as $values) {
484 //get details of the relationship type
485 $relType = ['id' => $values['civicrm_relationship_type_id']];
487 CRM_Contact_BAO_RelationshipType
::retrieve($relType, $relValues);
488 // Check if contact's relationship type exists in membership type
490 $bidirectional = FALSE;
491 foreach ($membershipType['relationship_type_id'] as $key => $value) {
492 $relTypeDirs[] = $value . '_' . $membershipType['relationship_direction'][$key];
493 if (in_array($value, $relType) &&
494 $relValues['name_a_b'] == $relValues['name_b_a']
496 $bidirectional = TRUE;
500 $relTypeDir = $values['civicrm_relationship_type_id'] . '_' . $values['rtype'];
501 if ($bidirectional ||
in_array($relTypeDir, $relTypeDirs)) {
502 // $values['status'] is going to have value for
503 // current or past relationships.
504 $contacts[$values['cid']] = $values['status'];
509 // Sort by contact_id ascending
515 * Retrieve DB object based on input parameters.
517 * It also stores all the retrieved values in the default array.
519 * @param array $params
520 * (reference ) an assoc array of name/value pairs.
521 * @param array $defaults
522 * (reference ) an assoc array to hold the name / value pairs.
523 * in a hierarchical manner
525 * @return CRM_Member_BAO_Membership
527 public static function retrieve(&$params, &$defaults) {
528 $membership = new CRM_Member_DAO_Membership();
530 $membership->copyValues($params);
532 if ($membership->find(TRUE)) {
533 CRM_Core_DAO
::storeValues($membership, $defaults);
535 //get the membership status and type values.
536 $statusANDType = self
::getStatusANDTypeValues($membership->id
);
537 foreach (['status', 'membership_type'] as $fld) {
538 $defaults[$fld] = $statusANDType[$membership->id
][$fld] ??
NULL;
540 if (!empty($statusANDType[$membership->id
]['is_current_member'])) {
541 $defaults['active'] = TRUE;
551 * Get membership status and membership type values.
553 * @param int $membershipId
554 * Membership id of values to return.
557 * Array of key value pairs
559 public static function getStatusANDTypeValues($membershipId) {
561 if (!$membershipId) {
565 SELECT membership.id as id,
566 status.id as status_id,
567 status.label as status,
568 status.is_current_member as is_current_member,
569 type.id as membership_type_id,
570 type.name as membership_type,
571 type.relationship_type_id as relationship_type_id
572 FROM civicrm_membership membership
573 INNER JOIN civicrm_membership_status status ON ( status.id = membership.status_id )
574 INNER JOIN civicrm_membership_type type ON ( type.id = membership.membership_type_id )
575 WHERE membership.id = %1';
576 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$membershipId, 'Positive']]);
581 'membership_type_id',
583 'relationship_type_id',
585 while ($dao->fetch()) {
586 foreach ($properties as $property) {
587 $values[$dao->id
][$property] = $dao->$property;
597 * Wrapper for most delete calls. Use this unless you JUST want to delete related memberships w/o deleting the parent.
599 * @param int $membershipId
600 * Membership id that needs to be deleted.
601 * @param bool $preserveContrib
604 * Id of deleted Membership on success, false otherwise.
606 public static function del($membershipId, $preserveContrib = FALSE) {
607 //delete related first and then delete parent.
608 self
::deleteRelatedMemberships($membershipId);
609 return self
::deleteMembership($membershipId, $preserveContrib);
615 * @param int $membershipId
616 * Membership id that needs to be deleted.
617 * @param bool $preserveContrib
620 * Id of deleted Membership on success, false otherwise.
622 public static function deleteMembership($membershipId, $preserveContrib = FALSE) {
623 // CRM-12147, retrieve membership data before we delete it for hooks
624 $params = ['id' => $membershipId];
626 $memberships = self
::getValues($params, $memValues);
628 $membership = $memberships[$membershipId];
630 CRM_Utils_Hook
::pre('delete', 'Membership', $membershipId, $memValues);
632 $transaction = new CRM_Core_Transaction();
635 //delete activity record
636 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
639 $deleteActivity = FALSE;
640 $membershipActivities = [
642 'Membership Renewal',
643 'Change Membership Status',
644 'Change Membership Type',
645 'Membership Renewal Reminder',
647 foreach ($membershipActivities as $membershipActivity) {
648 $activityId = array_search($membershipActivity, $activityTypes);
650 $params['activity_type_id'][] = $activityId;
651 $deleteActivity = TRUE;
654 if ($deleteActivity) {
655 $params['source_record_id'] = $membershipId;
656 CRM_Activity_BAO_Activity
::deleteActivity($params);
658 self
::deleteMembershipPayment($membershipId, $preserveContrib);
659 CRM_Price_BAO_LineItem
::deleteLineItems($membershipId, 'civicrm_membership');
661 $results = $membership->delete();
662 $transaction->commit();
664 CRM_Utils_Hook
::post('delete', 'Membership', $membership->id
, $membership);
666 // delete the recently created Membership
667 $membershipRecent = [
668 'id' => $membershipId,
669 'type' => 'Membership',
671 CRM_Utils_Recent
::del($membershipRecent);
677 * Delete related memberships.
679 * @param int $ownerMembershipId
680 * @param int $contactId
684 public static function deleteRelatedMemberships($ownerMembershipId, $contactId = NULL) {
685 if (!$ownerMembershipId && !$contactId) {
689 $membership = new CRM_Member_DAO_Membership();
690 $membership->owner_membership_id
= $ownerMembershipId;
693 $membership->contact_id
= $contactId;
697 while ($membership->fetch()) {
698 //delete related first and then delete parent.
699 self
::deleteRelatedMemberships($membership->id
);
700 self
::deleteMembership($membership->id
);
705 * Obtain active/inactive memberships from the list of memberships passed to it.
707 * @param array $memberships
708 * Membership records.
709 * @param string $status
710 * Active or inactive.
713 * array of memberships based on status
715 public static function activeMembers($memberships, $status = 'active') {
717 if ($status == 'active') {
718 foreach ($memberships as $f => $v) {
719 if (!empty($v['active'])) {
725 elseif ($status == 'inactive') {
726 foreach ($memberships as $f => $v) {
727 if (empty($v['active'])) {
737 * Return Membership Block info in Contribution Pages.
740 * Contribution page id.
744 public static function getMembershipBlock($pageID) {
745 $membershipBlock = [];
746 $dao = new CRM_Member_DAO_MembershipBlock();
747 $dao->entity_table
= 'civicrm_contribution_page';
749 $dao->entity_id
= $pageID;
751 if ($dao->find(TRUE)) {
752 CRM_Core_DAO
::storeValues($dao, $membershipBlock);
753 if (!empty($membershipBlock['membership_types'])) {
754 $membershipTypes = CRM_Utils_String
::unserialize($membershipBlock['membership_types']);
755 if (!is_array($membershipTypes)) {
756 return $membershipBlock;
759 foreach ($membershipTypes as $key => $value) {
760 $membershipBlock['auto_renew'][$key] = $value;
761 $memTypes[$key] = $key;
763 $membershipBlock['membership_types'] = implode(',', $memTypes);
770 return $membershipBlock;
774 * Return a current membership of given contact.
776 * NB: if more than one membership meets criteria, a randomly selected one is returned.
778 * @param int $contactID
780 * @param int $memType
781 * Membership type, null to retrieve all types.
783 * @param int $membershipId
784 * If provided, then determine if it is current.
785 * @param bool $onlySameParentOrg
786 * True if only Memberships with same parent org as the $memType wanted, false otherwise.
789 * @throws \CiviCRM_API3_Exception
791 public static function getContactMembership($contactID, $memType, $isTest, $membershipId = NULL, $onlySameParentOrg = FALSE) {
792 //check for owner membership id, if it exists update that membership instead: CRM-15992
794 $ownerMemberId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
796 'owner_membership_id', 'id'
798 if ($ownerMemberId) {
799 $membershipId = $ownerMemberId;
800 $contactID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
807 $dao = new CRM_Member_DAO_Membership();
809 $dao->id
= $membershipId;
811 $dao->contact_id
= $contactID;
812 $dao->membership_type_id
= $memType;
814 //fetch proper membership record.
816 $dao->is_test
= $isTest;
819 $dao->whereAdd('is_test IS NULL OR is_test = 0');
822 //avoid pending membership as current membership: CRM-3027
823 $statusIds = [array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus())];
824 if (!$membershipId) {
826 $statusIds[] = array_search(
828 CRM_Member_PseudoConstant
::membershipStatus(
830 " name = 'Cancelled' ",
837 $dao->whereAdd('status_id NOT IN ( ' . implode(',', $statusIds) . ')');
839 // order by start date to find most recent membership first, CRM-4545
840 $dao->orderBy('start_date DESC');
843 if ($onlySameParentOrg && $memType) {
844 // require the same parent org as the $memType
845 $params = ['id' => $memType];
846 $membershipType = [];
847 if (CRM_Member_BAO_MembershipType
::retrieve($params, $membershipType)) {
848 $memberTypesSameParentOrg = civicrm_api3('MembershipType', 'get', [
849 'member_of_contact_id' => $membershipType['member_of_contact_id'],
854 $memberTypesSameParentOrgList = implode(',', array_keys($memberTypesSameParentOrg['values'] ??
[]));
855 $dao->whereAdd('membership_type_id IN (' . $memberTypesSameParentOrgList . ')');
859 if ($dao->find(TRUE)) {
861 CRM_Core_DAO
::storeValues($dao, $membership);
862 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
863 $membership['status_id'],
864 'is_current_member', 'id'
866 $ownerMemberId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
868 'owner_membership_id', 'id'
870 if ($ownerMemberId) {
871 $membership['id'] = $membership['membership_id'] = $ownerMemberId;
872 $membership['membership_contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
881 if ($onlySameParentOrg && $memType) {
882 // see if there is a membership that has same parent as $memType but different parent than $membershipID
883 if ($dao->id
&& CRM_Core_Permission
::check('edit memberships')) {
884 // CRM-10016, This is probably a backend renewal, and make sure we return the same membership thats being renewed.
891 unset($dao->membership_type_id
);
892 if ($dao->find(TRUE)) {
894 CRM_Core_DAO
::storeValues($dao, $membership);
895 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
896 $membership['status_id'],
897 'is_current_member', 'id'
906 * Combine all the importable fields from the lower levels object.
908 * @param string $contactType
910 * @param bool $status
913 * array of importable Fields
914 * @throws \CRM_Core_Exception
916 public static function importableFields($contactType = 'Individual', $status = TRUE) {
917 $fields = Civi
::cache('fields')->get('membership_importable_fields' . $contactType . $status);
920 $fields = ['' => ['title' => '- ' . ts('do not import') . ' -']];
923 $fields = ['' => ['title' => '- ' . ts('Membership Fields') . ' -']];
926 $tmpFields = CRM_Member_DAO_Membership
::import();
927 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
929 // Using new Dedupe rule.
931 'contact_type' => $contactType,
932 'used' => 'Unsupervised',
934 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
936 $tmpContactField = [];
937 if (is_array($fieldsArray)) {
938 foreach ($fieldsArray as $value) {
939 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
944 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
945 $tmpContactField[trim($value)] = $contactFields[trim($value)] ??
NULL;
947 $title = $tmpContactField[trim($value)]['title'] . " " . ts('(match to contact)');
950 $title = $tmpContactField[trim($value)]['title'];
952 $tmpContactField[trim($value)]['title'] = $title;
955 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
956 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
958 $tmpFields['membership_contact_id']['title'] .= ' ' . ts('(match to contact)');
960 $fields = array_merge($fields, $tmpContactField);
961 $fields = array_merge($fields, $tmpFields);
962 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
963 Civi
::cache('fields')->set('membership_importable_fields' . $contactType . $status, $fields);
969 * Get all exportable fields.
971 * @return array return array of all exportable fields
973 public static function &exportableFields() {
974 $expFieldMembership = CRM_Member_DAO_Membership
::export();
976 $expFieldsMemType = CRM_Member_DAO_MembershipType
::export();
977 $fields = array_merge($expFieldMembership, $expFieldsMemType);
978 $fields = array_merge($fields, $expFieldMembership);
979 $membershipStatus = [
980 'membership_status' => [
981 'title' => ts('Membership Status'),
982 'name' => 'membership_status',
983 'type' => CRM_Utils_Type
::T_STRING
,
984 'where' => 'civicrm_membership_status.name',
987 //CRM-6161 fix for customdata export
988 $fields = array_merge($fields, $membershipStatus, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
989 $fields['membership_status_id'] = $membershipStatus['membership_status'];
994 * Get membership joins/renewals for a specified membership type.
996 * Specifically, retrieves a count of memberships whose "Membership
997 * Signup" or "Membership Renewal" activity falls in the given date range.
998 * Dates match the pattern "yyyy-mm-dd".
1000 * @param int $membershipTypeId
1001 * Membership type id.
1002 * @param int $startDate
1003 * Date on which to start counting.
1004 * @param int $endDate
1005 * Date on which to end counting.
1006 * @param bool|int $isTest if true, membership is for a test site
1007 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1010 * the number of members of type $membershipTypeId whose
1011 * start_date is between $startDate and $endDate
1013 public static function getMembershipStarts($membershipTypeId, $startDate, $endDate, $isTest = 0, $isOwner = 0) {
1014 // Ensure that the dates that are passed to the query are in the format of yyyy-mm-dd
1015 $dates = ['startDate', 'endDate'];
1016 foreach ($dates as $date) {
1017 if (strlen($
$date) === 8) {
1018 $
$date = date('Y-m-d', CRM_Utils_Time
::strtotime($
$date));
1022 $testClause = 'membership.is_test = 1';
1024 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1027 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1028 self
::_getActTypes();
1031 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1036 SELECT COUNT(DISTINCT membership.id) as member_count
1037 FROM civicrm_membership membership
1038 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id in (%1, %2))
1039 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1040 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1041 WHERE membership.membership_type_id = %3
1042 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1045 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1048 1 => [self
::$_signupActType, 'Integer'],
1049 2 => [self
::$_renewalActType, 'Integer'],
1050 3 => [$membershipTypeId, 'Integer'],
1053 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1054 return (int) $memberCount;
1058 * Get a count of membership for a specified membership type, optionally for a specified date.
1060 * The date must have the form yyyy-mm-dd.
1062 * If $date is omitted, this function counts as a member anyone whose
1063 * membership status_id indicates they're a current member.
1064 * If $date is given, this function counts as a member anyone who:
1065 * -- Has a start_date before $date and end_date after $date, or
1066 * -- Has a start_date before $date and is currently a member, as indicated
1067 * by the the membership's status_id.
1068 * The second condition takes care of records that have no end_date. These
1069 * are assumed to be lifetime memberships.
1071 * @param int $membershipTypeId
1072 * Membership type id.
1073 * @param string $date
1074 * The date for which to retrieve the count.
1075 * @param bool|int $isTest if true, membership is for a test site
1076 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1079 * the number of members of type $membershipTypeId as of $date.
1081 public static function getMembershipCount($membershipTypeId, $date = NULL, $isTest = 0, $isOwner = 0) {
1082 if (!CRM_Utils_Rule
::date($date)) {
1083 throw new CRM_Core_Exception(ts('Invalid date "%1" (must have form yyyy-mm-dd).', [1 => $date]));
1087 1 => [$membershipTypeId, 'Integer'],
1088 2 => [$isTest, 'Boolean'],
1090 $query = "SELECT count(civicrm_membership.id ) as member_count
1091 FROM civicrm_membership left join civicrm_membership_status on ( civicrm_membership.status_id = civicrm_membership_status.id )
1092 WHERE civicrm_membership.membership_type_id = %1
1093 AND civicrm_membership.contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)
1094 AND civicrm_membership.is_test = %2";
1096 $query .= " AND civicrm_membership_status.is_current_member = 1";
1099 $query .= " AND civicrm_membership.start_date <= '$date' AND civicrm_membership_status.is_current_member = 1";
1102 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1103 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1104 return (int) $memberCount;
1108 * Function check the status of the membership before adding membership for a contact.
1112 public static function statusAvailabilty() {
1113 $membership = new CRM_Member_DAO_MembershipStatus();
1114 $membership->whereAdd('is_active=1');
1115 return $membership->count();
1119 * @deprecated This is not used anywhere and should be removed soon!
1120 * Function for updating a membership record's contribution_recur_id.
1122 * @param CRM_Member_DAO_Membership $membership
1123 * @param \CRM_Contribute_BAO_Contribution|\CRM_Contribute_DAO_Contribution $contribution
1125 public static function updateRecurMembership(CRM_Member_DAO_Membership
$membership, CRM_Contribute_BAO_Contribution
$contribution) {
1126 CRM_Core_Error
::deprecatedFunctionWarning('Use the API instead');
1128 if (empty($contribution->contribution_recur_id
)) {
1133 1 => [$contribution->contribution_recur_id
, 'Integer'],
1134 2 => [$membership->id
, 'Integer'],
1137 $sql = "UPDATE civicrm_membership SET contribution_recur_id = %1 WHERE id = %2";
1138 CRM_Core_DAO
::executeQuery($sql, $params);
1142 * Method to fix membership status of stale membership.
1144 * This method first checks if the membership is stale. If it is,
1145 * then status will be updated based on existing start and end
1146 * dates and log will be added for the status change.
1148 * @param array $currentMembership
1149 * Reference to the array.
1150 * containing all values of
1151 * the current membership
1152 * @param string|null $changeToday
1153 * In case today needs
1154 * to be customised, null otherwise
1156 * @throws \CRM_Core_Exception
1158 public static function fixMembershipStatusBeforeRenew(&$currentMembership, $changeToday = NULL) {
1161 $today = CRM_Utils_Date
::processDate($changeToday, NULL, FALSE, 'Y-m-d');
1164 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
1165 $currentMembership['start_date'] ??
NULL,
1166 $currentMembership['end_date'] ??
NULL,
1167 $currentMembership['join_date'] ??
NULL,
1170 $currentMembership['membership_type_id'],
1174 if (empty($status) ||
empty($status['id'])) {
1175 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.'));
1178 if ($status['id'] !== $currentMembership['status_id']) {
1179 $oldStatus = $currentMembership['status_id'];
1180 $memberDAO = new CRM_Member_DAO_Membership();
1181 $memberDAO->id
= $currentMembership['id'];
1182 $memberDAO->find(TRUE);
1184 $memberDAO->status_id
= $status['id'];
1186 CRM_Core_DAO
::storeValues($memberDAO, $currentMembership);
1188 $currentMembership['is_current_member'] = CRM_Core_DAO
::getFieldValue(
1189 'CRM_Member_DAO_MembershipStatus',
1190 $currentMembership['status_id'],
1196 'membership_id' => $currentMembership['id'],
1197 'status_id' => $status['id'],
1198 'start_date' => CRM_Utils_Date
::customFormat(
1199 $currentMembership['start_date'],
1202 'end_date' => CRM_Utils_Date
::customFormat(
1203 $currentMembership['end_date'],
1206 'modified_date' => date('Y-m-d H:i:s', CRM_Utils_Time
::strtotime($today)),
1207 'membership_type_id' => $currentMembership['membership_type_id'],
1208 'max_related' => $currentMembership['max_related'] ??
0,
1211 $session = CRM_Core_Session
::singleton();
1212 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
1213 if ($session->get('userID')) {
1214 $logParams['modified_id'] = $session->get('userID');
1217 $logParams['modified_id'] = $currentMembership['contact_id'];
1220 //Create activity for status change.
1221 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
1222 CRM_Activity_BAO_Activity
::addActivity($memberDAO,
1223 'Change Membership Status',
1226 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$status['id']]}",
1227 'source_contact_id' => $logParams['modified_id'],
1228 'priority_id' => 'Normal',
1232 CRM_Member_BAO_MembershipLog
::add($logParams);
1237 * Get the contribution page id from the membership record.
1239 * @param int $membershipID
1242 * contribution page id
1244 public static function getContributionPageId($membershipID) {
1246 SELECT c.contribution_page_id as pageID
1247 FROM civicrm_membership_payment mp, civicrm_contribution c
1248 WHERE mp.contribution_id = c.id
1249 AND c.contribution_page_id IS NOT NULL
1250 AND mp.membership_id = " . CRM_Utils_Type
::escape($membershipID, 'Integer')
1251 . " ORDER BY mp.id DESC";
1253 return CRM_Core_DAO
::singleValueQuery($query);
1257 * Updated related memberships.
1259 * @param int $ownerMembershipId
1260 * Owner Membership Id.
1261 * @param array $params
1262 * Formatted array of key => value.
1264 public static function updateRelatedMemberships($ownerMembershipId, $params) {
1265 $membership = new CRM_Member_DAO_Membership();
1266 $membership->owner_membership_id
= $ownerMembershipId;
1267 $membership->find();
1269 while ($membership->fetch()) {
1270 $relatedMembership = new CRM_Member_DAO_Membership();
1271 $relatedMembership->id
= $membership->id
;
1272 $relatedMembership->copyValues($params);
1273 $relatedMembership->save();
1279 * Get list of membership fields for profile.
1281 * For now we only allow custom membership fields to be in
1285 * FIXME: This param is ignored
1288 * the list of membership fields
1290 public static function getMembershipFields($mode = NULL) {
1291 $fields = CRM_Member_DAO_Membership
::export();
1293 unset($fields['membership_contact_id']);
1294 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1296 $membershipType = CRM_Member_DAO_MembershipType
::export();
1298 $membershipStatus = CRM_Member_DAO_MembershipStatus
::export();
1300 $fields = array_merge($fields, $membershipType, $membershipStatus);
1306 * Get the sort name of a contact for a particular membership.
1309 * Id of the membership.
1311 * @return null|string
1312 * sort name of the contact if found
1314 public static function sortName($id) {
1315 $id = CRM_Utils_Type
::escape($id, 'Integer');
1318 SELECT civicrm_contact.sort_name
1319 FROM civicrm_membership, civicrm_contact
1320 WHERE civicrm_membership.contact_id = civicrm_contact.id
1321 AND civicrm_membership.id = {$id}
1323 return CRM_Core_DAO
::singleValueQuery($query);
1327 * Create memberships for related contacts, taking into account the maximum related memberships.
1329 * @param array $params
1330 * Array of key - value pairs.
1331 * @param CRM_Core_DAO $dao
1332 * Membership object.
1334 * @throws \CRM_Core_Exception
1335 * @throws \CiviCRM_API3_Exception
1337 public static function createRelatedMemberships($params, $dao) {
1338 unset($params['membership_id']);
1339 $membership = new CRM_Member_DAO_Membership();
1340 $membership->id
= $dao->id
;
1342 // required since create method doesn't return all the
1343 // parameters in the returned membership object
1344 if (!$membership->find(TRUE)) {
1347 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1348 // FIXME : While updating/ renewing the
1349 // membership, if the relationship is PAST then
1350 // the membership of the related contact must be
1352 // For that, getting Membership Status for which
1353 // is_current_member is 0. It works for the
1354 // generated data as there is only one membership
1355 // status having is_current_member = 0.
1356 // But this wont work exactly if there will be
1357 // more than one status having is_current_member = 0.
1358 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
1359 $membershipStatus->is_current_member
= 0;
1360 if ($membershipStatus->find(TRUE)) {
1361 $expiredStatusId = $membershipStatus->id
;
1364 $expiredStatusId = array_search('Expired', CRM_Member_PseudoConstant
::membershipStatus());
1367 $relatedContacts = [];
1368 $allRelatedContacts = CRM_Member_BAO_Membership
::checkMembershipRelationship($membership->membership_type_id
,
1369 $membership->contact_id
,
1370 $params['action'] ??
NULL
1373 // CRM-4213, CRM-19735 check for loops, using static variable to record contacts already processed.
1374 // Remove repeated related contacts, which already inherited membership of this type$relatedContactIds[$membership->contact_id][$membership->membership_type_id] = TRUE;
1375 foreach ($allRelatedContacts as $cid => $status) {
1376 // relatedContactIDs is always empty now - will remove next roud because of whitespace readability.
1377 if (empty($relatedContactIds[$cid]) ||
empty($relatedContactIds[$cid][$membership->membership_type_id
])) {
1378 $relatedContactIds[$cid][$membership->membership_type_id
] = TRUE;
1380 //don't create membership again for owner contact.
1381 $nestedRelationship = FALSE;
1382 if ($membership->owner_membership_id
) {
1383 $nestedRelMembership = new CRM_Member_DAO_Membership();
1384 $nestedRelMembership->id
= $membership->owner_membership_id
;
1385 $nestedRelMembership->contact_id
= $cid;
1386 $nestedRelationship = $nestedRelMembership->find(TRUE);
1388 if (!$nestedRelationship) {
1389 $relatedContacts[$cid] = $status;
1394 //lets cleanup related membership if any.
1395 if (empty($relatedContacts)) {
1396 self
::deleteRelatedMemberships($membership->id
);
1399 // Edit the params array
1400 unset($params['id']);
1401 // Reminder should be sent only to the direct membership
1402 unset($params['reminder_date']);
1403 // unset the custom value ids
1404 if (isset($params['custom']) && is_array($params['custom'])) {
1405 foreach ($params['custom'] as $k => $values) {
1406 foreach ($values as $i => $value) {
1407 unset($params['custom'][$k][$i]['id']);
1411 if (!isset($params['membership_type_id'])) {
1412 $params['membership_type_id'] = $membership->membership_type_id
;
1415 // max_related should be set in the parent membership
1416 unset($params['max_related']);
1417 // Number of inherited memberships available - NULL is interpreted as unlimited, '0' as none
1418 $numRelatedAvailable = ($membership->max_related
== NULL ? PHP_INT_MAX
: $membership->max_related
);
1419 // will be used to queue potential memberships to be created.
1422 foreach ($relatedContacts as $contactId => $relationshipStatus) {
1423 //use existing membership record.
1424 $relMembership = new CRM_Member_DAO_Membership();
1425 $relMembership->contact_id
= $contactId;
1426 $relMembership->owner_membership_id
= $membership->id
;
1428 if ($relMembership->find(TRUE)) {
1429 $params['id'] = $relMembership->id
;
1432 unset($params['id']);
1435 $params['contact_id'] = $contactId;
1436 $params['owner_membership_id'] = $membership->id
;
1438 // set status_id as it might have been changed for
1439 // past relationship
1440 $params['status_id'] = $membership->status_id
;
1442 if ($deceasedStatusId &&
1443 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'is_deceased')
1445 $params['status_id'] = $deceasedStatusId;
1447 elseif ((($params['action'] ??
NULL) & CRM_Core_Action
::UPDATE
) &&
1448 ($relationshipStatus == CRM_Contact_BAO_Relationship
::PAST
)
1450 $params['status_id'] = $expiredStatusId;
1453 //don't calculate status again in create( );
1454 $params['skipStatusCal'] = TRUE;
1456 //do create activity if we changed status.
1457 if ($params['status_id'] != $relMembership->status_id
) {
1458 $params['createActivity'] = TRUE;
1461 //CRM-20707 - include start/end date
1462 $params['start_date'] = $membership->start_date
;
1463 $params['end_date'] = $membership->end_date
;
1465 // we should not created contribution record for related contacts, CRM-3371
1466 unset($params['contribution_status_id']);
1468 //CRM-16857: Do not create multiple line-items for inherited membership through priceset.
1469 unset($params['lineItems']);
1470 unset($params['line_item']);
1472 // CRM-20966: Do not create membership_payment record for inherited membership.
1473 unset($params['relate_contribution_id']);
1475 if (($params['status_id'] == $deceasedStatusId) ||
($params['status_id'] == $expiredStatusId)) {
1476 // related membership is not active so does not count towards maximum
1477 if (!self
::hasExistingInheritedMembership($params)) {
1478 civicrm_api3('Membership', 'create', $params);
1482 // related membership already exists, so this is just an update
1483 if (isset($params['id'])) {
1484 if ($numRelatedAvailable > 0) {
1485 CRM_Member_BAO_Membership
::create($params);
1486 $numRelatedAvailable--;
1489 // we have run out of inherited memberships, so delete extras
1490 self
::deleteMembership($params['id']);
1492 // we need to first check if there will remain inherited memberships, so queue it up
1499 // now go over the queue and create any available related memberships
1500 foreach ($queue as $params) {
1501 if ($numRelatedAvailable <= 0) {
1504 if (!self
::hasExistingInheritedMembership($params)) {
1505 CRM_Member_BAO_Membership
::create($params);
1507 $numRelatedAvailable--;
1513 * Delete the record that are associated with this Membership Payment.
1515 * @param int $membershipId
1516 * @param bool $preserveContrib
1519 * $membershipPayment deleted membership payment object
1521 public static function deleteMembershipPayment($membershipId, $preserveContrib = FALSE) {
1523 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
1524 $membershipPayment->membership_id
= $membershipId;
1525 $membershipPayment->find();
1527 while ($membershipPayment->fetch()) {
1528 if (!$preserveContrib) {
1529 CRM_Contribute_BAO_Contribution
::deleteContribution($membershipPayment->contribution_id
);
1531 CRM_Utils_Hook
::pre('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1532 $membershipPayment->delete();
1533 CRM_Utils_Hook
::post('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1535 return $membershipPayment;
1539 * Build an array of available membership types in the current context.
1541 * While core does not do anything context specific extensions may filter
1542 * or alter amounts based on user details.
1544 * @param CRM_Core_Form $form
1545 * @param array $membershipTypeID
1546 * @param bool $activeOnly
1547 * Do we only want active ones?
1548 * (probably this should default to TRUE but as a newly added parameter we are leaving default b
1549 * behaviour unchanged).
1553 * @throws \CiviCRM_API3_Exception
1555 public static function buildMembershipTypeValues($form, $membershipTypeID = [], $activeOnly = FALSE) {
1556 $membershipTypeIDS = (array) $membershipTypeID;
1557 $membershipTypeValues = CRM_Member_BAO_MembershipType
::getAllMembershipTypes();
1559 // MembershipTypes are already filtered by domain, filter as appropriate by is_active & a passed in list of ids.
1560 foreach ($membershipTypeValues as $id => $type) {
1561 if (($activeOnly && empty($type['is_active']))
1562 ||
(!empty($membershipTypeIDS) && !in_array($id, $membershipTypeIDS, FALSE))
1564 unset($membershipTypeValues[$id]);
1568 CRM_Utils_Hook
::membershipTypeValues($form, $membershipTypeValues);
1569 return $membershipTypeValues;
1573 * Get membership record count for a Contact.
1575 * @param int $contactID
1576 * @param bool $activeOnly
1579 * @throws \API_Exception
1581 public static function getContactMembershipCount(int $contactID, $activeOnly = FALSE): int {
1583 $membershipTypes = MembershipType
::get(TRUE)
1587 $addWhere = " AND membership_type_id IN (0)";
1588 if (!empty($membershipTypes)) {
1589 $addWhere = " AND membership_type_id IN (" . implode(',', array_keys($membershipTypes)) . ")";
1592 $select = "SELECT COUNT(*) FROM civicrm_membership ";
1593 $where = "WHERE civicrm_membership.contact_id = {$contactID} AND civicrm_membership.is_test = 0 ";
1595 // CRM-6627, all status below 3 (active, pending, grace) are considered active
1597 $select .= " INNER JOIN civicrm_membership_status ON civicrm_membership.status_id = civicrm_membership_status.id ";
1598 $where .= " and civicrm_membership_status.is_current_member = 1";
1601 $query = $select . $where . $addWhere;
1602 return (int) CRM_Core_DAO
::singleValueQuery($query);
1604 catch (UnauthorizedException
$e) {
1610 * Check whether payment processor supports cancellation of membership subscription.
1615 * @param bool $isNotCancelled
1619 public static function isCancelSubscriptionSupported($mid, $isNotCancelled = TRUE) {
1620 $cacheKeyString = "$mid";
1621 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
1623 static $supportsCancel = [];
1625 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
1626 $supportsCancel[$cacheKeyString] = FALSE;
1627 $isCancelled = FALSE;
1629 if ($isNotCancelled) {
1630 $isCancelled = self
::isSubscriptionCancelled($mid);
1633 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($mid, 'membership', 'obj');
1634 if (!empty($paymentObject)) {
1635 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
1638 return $supportsCancel[$cacheKeyString];
1642 * Check whether subscription is already cancelled.
1648 * contribution status
1650 public static function isSubscriptionCancelled($mid) {
1652 SELECT cr.contribution_status_id
1653 FROM civicrm_contribution_recur cr
1654 LEFT JOIN civicrm_membership mem ON ( cr.id = mem.contribution_recur_id )
1655 WHERE mem.id = %1 LIMIT 1";
1656 $params = [1 => [$mid, 'Integer']];
1657 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
1658 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
1659 if ($status == 'Cancelled') {
1666 * Get membership joins for a specified membership type.
1668 * Specifically, retrieves a count of still current memberships whose
1669 * join_date and start_date are within a specified date range. Dates match
1670 * the pattern "yyyy-mm-dd".
1672 * @param int $membershipTypeId
1673 * Membership type id.
1674 * @param int $startDate
1675 * Date on which to start counting.
1676 * @param int $endDate
1677 * Date on which to end counting.
1678 * @param bool|int $isTest if true, membership is for a test site
1681 * the number of members of type $membershipTypeId
1682 * whose join_date is between $startDate and $endDate and
1683 * whose start_date is between $startDate and $endDate
1685 public static function getMembershipJoins($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1686 $testClause = 'membership.is_test = 1';
1688 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1690 if (!self
::$_signupActType) {
1691 self
::_getActTypes();
1694 if (!self
::$_signupActType) {
1699 SELECT COUNT(DISTINCT membership.id) as member_count
1700 FROM civicrm_membership membership
1701 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1702 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1703 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1704 WHERE membership.membership_type_id = %2
1705 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1709 1 => [self
::$_signupActType, 'Integer'],
1710 2 => [$membershipTypeId, 'Integer'],
1713 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1715 return (int) $memberCount;
1719 * Get membership renewals for a specified membership type.
1721 * Specifically, retrieves a count of still current memberships
1722 * whose join_date is before and start_date is within a specified date
1723 * range. Dates match the pattern "yyyy-mm-dd".
1725 * @param int $membershipTypeId
1726 * Membership type id.
1727 * @param int $startDate
1728 * Date on which to start counting.
1729 * @param int $endDate
1730 * Date on which to end counting.
1731 * @param bool|int $isTest if true, membership is for a test site
1734 * returns the number of members of type $membershipTypeId
1735 * whose join_date is before $startDate and
1736 * whose start_date is between $startDate and $endDate
1738 public static function getMembershipRenewals($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1739 $testClause = 'membership.is_test = 1';
1741 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1743 if (!self
::$_renewalActType) {
1744 self
::_getActTypes();
1747 if (!self
::$_renewalActType) {
1752 SELECT COUNT(DISTINCT membership.id) as member_count
1753 FROM civicrm_membership membership
1754 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1755 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1756 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1757 WHERE membership.membership_type_id = %2
1758 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1762 1 => [self
::$_renewalActType, 'Integer'],
1763 2 => [$membershipTypeId, 'Integer'],
1765 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1767 return (int) $memberCount;
1771 * @param int $contactID
1772 * @param int $membershipTypeID
1773 * @param bool $is_test
1774 * @param string $changeToday
1775 * @param int $modifiedID
1776 * @param $customFieldsFormatted
1777 * @param $numRenewTerms
1778 * @param int $membershipID
1780 * @param int $contributionRecurID
1781 * @param $membershipSource
1782 * @param $isPayLater
1783 * @param array $memParams
1784 * @param array $formDates
1785 * @param null|CRM_Contribute_BAO_Contribution $contribution
1786 * @param array $lineItems
1789 * @throws \CRM_Core_Exception
1790 * @throws \CiviCRM_API3_Exception
1792 public static function processMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $contributionRecurID, $membershipSource, $isPayLater, $memParams = [], $formDates = [], $contribution = NULL, $lineItems = []) {
1793 $renewalMode = $updateStatusId = FALSE;
1794 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1796 $statusFormat = '%Y-%m-%d';
1797 $membershipTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipType($membershipTypeID);
1801 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
1802 // is the same as the parent org of an existing membership of the contact
1803 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($contactID, $membershipTypeID,
1804 $is_test, $membershipID, TRUE
1806 if ($currentMembership) {
1807 $renewalMode = TRUE;
1809 // Do NOT do anything.
1810 //1. membership with status : PENDING/CANCELLED (CRM-2395)
1811 //2. Paylater/IPN renew. CRM-4556.
1812 if ($pending ||
in_array($currentMembership['status_id'], [
1813 array_search('Pending', $allStatus),
1815 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1818 $memParams = array_merge([
1819 'id' => $currentMembership['id'],
1820 'contribution' => $contribution,
1821 'status_id' => $currentMembership['status_id'],
1822 'start_date' => $currentMembership['start_date'],
1823 'end_date' => $currentMembership['end_date'],
1824 'line_item' => $lineItems,
1825 'join_date' => $currentMembership['join_date'],
1826 'membership_type_id' => $membershipTypeID,
1827 'max_related' => !empty($membershipTypeDetails['max_related']) ?
$membershipTypeDetails['max_related'] : NULL,
1828 'membership_activity_status' => ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed',
1830 if ($contributionRecurID) {
1831 $memParams['contribution_recur_id'] = $contributionRecurID;
1834 $membership = self
::create($memParams);
1835 return [$membership, $renewalMode, $dates];
1838 // Check and fix the membership if it is STALE
1839 self
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
1841 // Now Renew the membership
1842 if (!$currentMembership['is_current_member']) {
1843 // membership is not CURRENT
1845 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1846 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($currentMembership['id'],
1852 $currentMembership['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1853 foreach (['start_date', 'end_date'] as $dateType) {
1854 $currentMembership[$dateType] = $formDates[$dateType] ??
NULL;
1855 if (empty($currentMembership[$dateType])) {
1856 $currentMembership[$dateType] = $dates[$dateType] ??
NULL;
1859 $currentMembership['is_test'] = $is_test;
1861 if (!empty($membershipSource)) {
1862 $currentMembership['source'] = $membershipSource;
1865 if (!empty($currentMembership['id'])) {
1866 $ids['membership'] = $currentMembership['id'];
1868 $memParams = array_merge($currentMembership, $memParams);
1869 $memParams['membership_type_id'] = $membershipTypeID;
1871 //set the log start date.
1872 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1876 // CURRENT Membership
1877 $membership = new CRM_Member_DAO_Membership();
1878 $membership->id
= $currentMembership['id'];
1879 $membership->find(TRUE);
1880 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1881 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
1887 // Insert renewed dates for CURRENT membership
1888 $memParams['join_date'] = CRM_Utils_Date
::isoToMysql($membership->join_date
);
1889 $memParams['start_date'] = $formDates['start_date'] ?? CRM_Utils_Date
::isoToMysql($membership->start_date
);
1890 $memParams['end_date'] = $formDates['end_date'] ??
NULL;
1891 if (empty($memParams['end_date'])) {
1892 $memParams['end_date'] = $dates['end_date'] ??
NULL;
1894 $memParams['membership_type_id'] = $membershipTypeID;
1896 //set the log start date.
1897 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1900 if (!empty($membershipSource)) {
1901 $memParams['source'] = $membershipSource;
1903 elseif (empty($membership->source
)) {
1904 $memParams['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
1905 $currentMembership['id'],
1910 if (!empty($currentMembership['id'])) {
1911 $ids['membership'] = $currentMembership['id'];
1913 $memParams['membership_activity_status'] = ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed';
1918 $memParams = array_merge([
1919 'contact_id' => $contactID,
1920 'membership_type_id' => $membershipTypeID,
1924 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
1926 foreach (['join_date', 'start_date', 'end_date'] as $dateType) {
1927 $memParams[$dateType] = $formDates[$dateType] ??
NULL;
1928 if (empty($memParams[$dateType])) {
1929 $memParams[$dateType] = $dates[$dateType] ??
NULL;
1933 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(CRM_Utils_Date
::customFormat($dates['start_date'],
1936 CRM_Utils_Date
::customFormat($dates['end_date'],
1939 CRM_Utils_Date
::customFormat($dates['join_date'],
1947 $updateStatusId = $status['id'] ??
NULL;
1950 // if IPN/Pay-Later set status to: PENDING
1951 $updateStatusId = array_search('Pending', $allStatus);
1954 if (!empty($membershipSource)) {
1955 $memParams['source'] = $membershipSource;
1957 $memParams['is_test'] = $is_test;
1958 $memParams['is_pay_later'] = $isPayLater;
1960 // Putting this in an IF is precautionary as it seems likely that it would be ignored if empty, but
1961 // perhaps shouldn't be?
1962 if ($contributionRecurID) {
1963 $memParams['contribution_recur_id'] = $contributionRecurID;
1966 //if we decided status here and want to skip status
1967 //calculation in create( ); then need to pass 'skipStatusCal'.
1968 if ($updateStatusId) {
1969 $memParams['status_id'] = $updateStatusId;
1970 $memParams['skipStatusCal'] = TRUE;
1973 //since we are renewing,
1974 //make status override false.
1975 $memParams['is_override'] = FALSE;
1977 //CRM-4027, create log w/ individual contact.
1979 // @todo this param is likely unused now.
1980 $memParams['is_for_organization'] = TRUE;
1982 $params['modified_id'] = $modifiedID ??
$contactID;
1984 $memParams['contribution'] = $contribution;
1985 $memParams['custom'] = $customFieldsFormatted;
1986 // Load all line items & process all in membership. Don't do in contribution.
1987 // Relevant tests in api_v3_ContributionPageTest.
1988 $memParams['line_item'] = $lineItems;
1989 // @todo stop passing $ids (membership and userId may be set by this point)
1990 $membership = self
::create($memParams, $ids);
1992 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
1993 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
1994 $membership->find(TRUE);
1996 return [$membership, $renewalMode, $dates];
2000 * Get line items representing the default price set.
2002 * @param int $membershipOrg
2003 * @param int $membershipTypeID
2004 * @param float $total_amount
2005 * @param int $priceSetId
2009 public static function setQuickConfigMembershipParameters($membershipOrg, $membershipTypeID, $total_amount, $priceSetId) {
2010 $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
2012 // The name of the price field corresponds to the membership_type organization contact.
2014 'price_set_id' => $priceSetId,
2015 'name' => $membershipOrg,
2018 CRM_Price_BAO_PriceField
::retrieve($params, $results);
2020 if (!empty($results)) {
2021 $fields[$results['id']] = $priceSets['fields'][$results['id']];
2022 $fid = $results['id'];
2023 $editedFieldParams = [
2024 'price_field_id' => $results['id'],
2025 'membership_type_id' => $membershipTypeID,
2028 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $results);
2029 $fields[$fid]['options'][$results['id']] = $priceSets['fields'][$fid]['options'][$results['id']];
2030 if (!empty($total_amount)) {
2031 $fields[$fid]['options'][$results['id']]['amount'] = $total_amount;
2035 $fieldID = key($fields);
2037 'price_set_id' => $priceSetId,
2038 'price_sets' => $priceSets,
2039 'fields' => $fields,
2041 'price_' . $fieldID => $results['id'] ??
NULL,
2044 return $returnParams;
2048 * Update the status of all deceased members to deceased.
2051 * Count of updated contacts.
2053 * @throws \CiviCRM_API3_Exception
2054 * @throws \CRM_Core_Exception
2056 protected static function updateDeceasedMembersStatuses() {
2059 $deceasedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Deceased');
2061 // 'create' context for buildOptions returns only if enabled.
2062 $allStatus = self
::buildOptions('status_id', 'create');
2063 if (array_key_exists($deceasedStatusId, $allStatus) === FALSE) {
2064 // Deceased status is an admin status & is required. We want to fail early if
2065 // it is not present or active.
2066 // We could make the case 'some databases just don't use deceased so we will check
2067 // for the presence of a deceased contact in the DB before rejecting.
2068 if (CRM_Core_DAO
::singleValueQuery('
2069 SELECT count(*) FROM civicrm_contact WHERE is_deceased = 0'
2071 throw new CRM_Core_Exception(
2072 ts("Deceased Membership status is missing or not active. <a href='%1'>Click here to check</a>.",
2073 [1 => CRM_Utils_System
::url('civicrm/admin/member/membershipStatus', 'reset=1')]
2077 $deceasedDAO = CRM_Core_DAO
::executeQuery(
2079 SELECT membership.id as membership_id
2080 FROM civicrm_membership membership
2081 INNER JOIN civicrm_contact ON membership.contact_id = civicrm_contact.id
2082 INNER JOIN civicrm_membership_type ON membership.membership_type_id = civicrm_membership_type.id
2083 AND civicrm_membership_type.is_active = 1
2084 WHERE membership.is_test = 0
2085 AND civicrm_contact.is_deceased = 1
2086 AND membership.status_id <> %1
2088 [1 => [$deceasedStatusId, 'Integer']]
2090 while ($deceasedDAO->fetch()) {
2091 civicrm_api3('membership', 'create', [
2092 'id' => $deceasedDAO->membership_id
,
2093 'status_id' => $deceasedStatusId,
2094 'createActivity' => TRUE,
2095 'skipStatusCal' => TRUE,
2096 'skipRecentView' => TRUE,
2104 * Does the existing membership match the required membership.
2106 * Check before updating that the params are not a match - this is part of avoiding
2107 * a loop if we have already updated.
2109 * https://issues.civicrm.org/jira/browse/CRM-4213
2110 * @param array $params
2112 * @param array $membership
2116 protected static function matchesRequiredMembership($params, $membership) {
2117 foreach (['start_date', 'end_date'] as $date) {
2118 if (CRM_Utils_Time
::strtotime($params[$date]) !== CRM_Utils_Time
::strtotime($membership[$date])) {
2121 if ((int) $params['status_id'] !== (int) $membership['status_id']) {
2124 if ((int) $params['membership_type_id'] !== (int) $membership['membership_type_id']) {
2132 * Params of new membership.
2134 * @param array $params
2137 * @throws \CiviCRM_API3_Exception
2139 protected static function hasExistingInheritedMembership($params) {
2140 foreach (civicrm_api3('Membership', 'get', ['contact_id' => $params['contact_id']])['values'] as $membership) {
2141 if (!empty($membership['owner_membership_id'])
2142 && $membership['membership_type_id'] === $params['membership_type_id']
2143 && (int) $params['owner_membership_id'] !== (int) $membership['owner_membership_id']
2145 // Inheriting it from another contact, don't update here.
2148 if (self
::matchesRequiredMembership($params, $membership)) {
2156 * Process price set and line items.
2158 * @param int $membershipId
2159 * @param array $lineItem
2161 * @throws \CiviCRM_API3_Exception
2163 public function processPriceSet($membershipId, $lineItem) {
2164 //FIXME : need to move this too
2165 if (!$membershipId ||
!is_array($lineItem)
2166 || CRM_Utils_System
::isNull($lineItem)
2171 foreach ($lineItem as $priceSetId => $values) {
2175 foreach ($values as $line) {
2176 $line['entity_table'] = 'civicrm_membership';
2177 $line['entity_id'] = $membershipId;
2178 CRM_Price_BAO_LineItem
::create($line);
2184 * Retrieve the contribution id for the associated Membership id.
2185 * @todo we should get this off the line item
2187 * @param int $membershipId
2190 * if more than one payment associated with membership id need to be returned.
2194 * @todo we should get this off the line item
2197 public static function getMembershipContributionId($membershipId, $all = FALSE) {
2199 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
2200 $membershipPayment->membership_id
= $membershipId;
2201 if ($all && $membershipPayment->find()) {
2202 $contributionIds = [];
2203 while ($membershipPayment->fetch()) {
2204 $contributionIds[] = $membershipPayment->contribution_id
;
2206 return $contributionIds;
2209 if ($membershipPayment->find(TRUE)) {
2210 return $membershipPayment->contribution_id
;
2216 * The function checks and updates the status of all membership records for a given domain using the
2217 * calc_membership_status and update_contact_membership APIs.
2220 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
2222 * @param array $params
2223 * only_active_membership_types, exclude_test_memberships, exclude_membership_status_ids
2227 * @throws \CiviCRM_API3_Exception
2228 * @throws \CRM_Core_Exception
2230 public static function updateAllMembershipStatus($params = []) {
2231 // We want all of the statuses as id => name, even the disabled ones (cf.
2232 // CRM-15475), to identify which are Pending, Deceased, Cancelled, and
2234 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'validate');
2235 if (empty($params['exclude_membership_status_ids'])) {
2236 $params['exclude_membership_status_ids'] = [
2237 array_search('Pending', $allStatus),
2238 array_search('Cancelled', $allStatus),
2239 array_search('Expired', $allStatus) ?
: 0,
2240 array_search('Deceased', $allStatus),
2243 // Deceased is *always* excluded because it is has very specific processing below.
2244 elseif (!in_array(array_search('Deceased', $allStatus), $params['exclude_membership_status_ids'])) {
2245 $params['exclude_membership_status_ids'][] = array_search('Deceased', $allStatus);
2248 for ($index = 0; $index < count($params['exclude_membership_status_ids']); $index++
) {
2249 $queryParams[$index] = [$params['exclude_membership_status_ids'][$index], 'Integer'];
2251 $membershipStatusClause = 'civicrm_membership.status_id NOT IN (%' . implode(', %', array_keys($queryParams)) . ')';
2253 // Tests for this function are in api_v3_JobTest. Please add tests for all updates.
2255 $updateCount = $processCount = self
::updateDeceasedMembersStatuses();
2257 $whereClauses[] = 'civicrm_contact.is_deceased = 0';
2258 if ($params['exclude_test_memberships']) {
2259 $whereClauses[] = 'civicrm_membership.is_test = 0';
2261 $whereClause = implode(' AND ', $whereClauses);
2262 $activeMembershipClause = '';
2263 if ($params['only_active_membership_types']) {
2264 $activeMembershipClause = ' AND civicrm_membership_type.is_active = 1';
2267 // This query retrieves ALL memberships of active types.
2269 SELECT civicrm_membership.id as membership_id,
2270 civicrm_membership.is_override as is_override,
2271 civicrm_membership.status_override_end_date as status_override_end_date,
2272 civicrm_membership.membership_type_id as membership_type_id,
2273 civicrm_membership.status_id as status_id,
2274 civicrm_membership.join_date as join_date,
2275 civicrm_membership.start_date as start_date,
2276 civicrm_membership.end_date as end_date,
2277 civicrm_membership.source as source,
2278 civicrm_contact.id as contact_id,
2279 civicrm_membership.owner_membership_id as owner_membership_id,
2280 civicrm_membership.contribution_recur_id as recur_id
2281 FROM civicrm_membership
2282 INNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )
2283 INNER JOIN civicrm_membership_type ON
2284 (civicrm_membership.membership_type_id = civicrm_membership_type.id {$activeMembershipClause})
2285 WHERE {$whereClause}";
2287 $query = $baseQuery . " AND civicrm_membership.is_override IS NOT NULL AND civicrm_membership.status_override_end_date IS NOT NULL";
2288 $dao1 = CRM_Core_DAO
::executeQuery($query);
2289 while ($dao1->fetch()) {
2290 self
::processOverriddenUntilDateMembership($dao1);
2293 $query = $baseQuery . " AND (civicrm_membership.is_override = 0 OR civicrm_membership.is_override IS NULL)
2294 AND {$membershipStatusClause}
2295 AND civicrm_membership.owner_membership_id IS NULL ";
2297 $allMembershipTypes = CRM_Member_BAO_MembershipType
::getAllMembershipTypes();
2299 $dao2 = CRM_Core_DAO
::executeQuery($query, $queryParams);
2301 while ($dao2->fetch()) {
2304 // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses
2305 //get the membership status as per id.
2306 $newStatus = civicrm_api3('membership_status', 'calc',
2308 'membership_id' => $dao2->membership_id
,
2309 'ignore_admin_only' => TRUE,
2312 $statusId = $newStatus['id'] ??
NULL;
2314 //process only when status change.
2316 $statusId != $dao2->status_id
2319 'id' => $dao2->membership_id
,
2320 'skipStatusCal' => TRUE,
2321 'skipRecentView' => TRUE,
2322 'status_id' => $statusId,
2323 'createActivity' => TRUE,
2326 //process member record.
2327 civicrm_api3('membership', 'create', $memberParams);
2331 $result['is_error'] = 0;
2332 $result['messages'] = ts('Processed %1 membership records. Updated %2 records.', [
2340 * Set is_override for the 'overridden until date' membership to
2341 * False and clears the 'until date' field in case the 'until date'
2342 * is equal or after today date.
2344 * @param CRM_Core_DAO $membership
2345 * The membership to be processed
2347 * @throws \CiviCRM_API3_Exception
2349 private static function processOverriddenUntilDateMembership($membership) {
2350 $isOverriddenUntilDate = !empty($membership->is_override
) && !empty($membership->status_override_end_date
);
2351 if (!$isOverriddenUntilDate) {
2355 $todayDate = new DateTime();
2356 $todayDate->setTime(0, 0);
2358 $overrideEndDate = new DateTime($membership->status_override_end_date
);
2359 $overrideEndDate->setTime(0, 0);
2361 $datesDifference = $todayDate->diff($overrideEndDate);
2362 $daysDifference = (int) $datesDifference->format('%R%a');
2363 if ($daysDifference <= 0) {
2365 'id' => $membership->membership_id
,
2366 'is_override' => FALSE,
2367 'status_override_end_date' => 'null',
2369 civicrm_api3('membership', 'create', $params);
2374 * Returns the membership types for a particular contact
2375 * who has lifetime membership without end date.
2377 * @param int $contactID
2378 * @param bool $isTest
2379 * @param bool $onlyLifeTime
2383 public static function getAllContactMembership($contactID, $isTest = FALSE, $onlyLifeTime = FALSE) {
2384 $contactMembershipType = [];
2386 return $contactMembershipType;
2389 $dao = new CRM_Member_DAO_Membership();
2390 $dao->contact_id
= $contactID;
2391 $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
2392 $dao->whereAdd("status_id != $pendingStatusId");
2395 $dao->is_test
= $isTest;
2398 $dao->whereAdd('is_test IS NULL OR is_test = 0');
2401 if ($onlyLifeTime) {
2402 $dao->whereAdd('end_date IS NULL');
2406 while ($dao->fetch()) {
2408 CRM_Core_DAO
::storeValues($dao, $membership);
2409 $contactMembershipType[$dao->membership_type_id
] = $membership;
2411 return $contactMembershipType;
2415 * Record contribution record associated with membership.
2416 * This will update an existing contribution if $params['contribution_id'] is passed in.
2417 * This will create a MembershipPayment to link the contribution and membership
2419 * @param array $params
2420 * Array of submitted params.
2422 * @return CRM_Contribute_BAO_Contribution
2423 * @throws \CRM_Core_Exception
2424 * @throws \CiviCRM_API3_Exception
2426 public static function recordMembershipContribution(&$params) {
2427 $contributionParams = [];
2428 $config = CRM_Core_Config
::singleton();
2429 $contributionParams['currency'] = $config->defaultCurrency
;
2430 $contributionParams['receipt_date'] = !empty($params['receipt_date']) ?
$params['receipt_date'] : 'null';
2431 $contributionParams['source'] = $params['contribution_source'] ??
NULL;
2432 $contributionParams['non_deductible_amount'] = 'null';
2433 $contributionParams['skipCleanMoney'] = TRUE;
2434 $contributionParams['payment_processor'] = $params['payment_processor_id'] ??
NULL;
2435 $contributionSoftParams = $params['soft_credit'] ??
NULL;
2436 $recordContribution = [
2441 'financial_type_id',
2442 'payment_instrument_id',
2446 'contribution_status_id',
2453 'contribution_recur_id',
2457 foreach ($recordContribution as $f) {
2458 $contributionParams[$f] = $params[$f] ??
NULL;
2461 if (!empty($params['contribution_id'])) {
2462 $contributionParams['id'] = $params['contribution_id'];
2464 // make entry in batch entity batch table
2465 if (!empty($params['batch_id'])) {
2466 $contributionParams['batch_id'] = $params['batch_id'];
2469 if (!empty($params['contribution_contact_id'])) {
2470 // deal with possibility of a different person paying for contribution
2471 $contributionParams['contact_id'] = $params['contribution_contact_id'];
2474 if (!empty($params['processPriceSet']) &&
2475 !empty($params['lineItems'])
2477 $contributionParams['line_item'] = $params['lineItems'] ??
NULL;
2480 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams);
2482 //CRM-13981, create new soft-credit record as to record payment from different person for this membership
2483 if (!empty($contributionSoftParams)) {
2484 if (!empty($params['batch_id'])) {
2485 foreach ($contributionSoftParams as $contributionSoft) {
2486 $contributionSoft['contribution_id'] = $contribution->id
;
2487 $contributionSoft['currency'] = $contribution->currency
;
2488 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoft);
2492 $contributionSoftParams['contribution_id'] = $contribution->id
;
2493 $contributionSoftParams['currency'] = $contribution->currency
;
2494 $contributionSoftParams['amount'] = $contribution->total_amount
;
2495 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoftParams);
2499 // store contribution id
2500 $params['contribution_id'] = $contribution->id
;
2502 // Create membership payment if it does not already exist
2503 $membershipPayment = civicrm_api3('MembershipPayment', 'get', [
2504 'contribution_id' => $contribution->id
,
2506 if (empty($membershipPayment['count'])) {
2507 civicrm_api3('MembershipPayment', 'create', [
2508 'membership_id' => $params['membership_id'],
2509 'contribution_id' => $contribution->id
,
2513 return $contribution;
2517 * @todo document me - I seem a bit out of date....
2519 public static function _getActTypes() {
2520 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2521 self
::$_renewalActType = CRM_Utils_Array
::key('Membership Renewal', $activityTypes);
2522 self
::$_signupActType = CRM_Utils_Array
::key('Membership Signup', $activityTypes);
2526 * Get all Cancelled Membership(s) for a contact
2528 * @param int $contactID
2530 * @param bool $isTest
2534 * Array of membership type
2536 public static function getContactsCancelledMembership($contactID, $isTest = FALSE) {
2540 $query = 'SELECT membership_type_id FROM civicrm_membership WHERE contact_id = %1 AND status_id = %2 AND is_test = %3';
2542 1 => [$contactID, 'Integer'],
2547 CRM_Member_PseudoConstant
::membershipStatus(
2549 " name = 'Cancelled' ",
2557 3 => [$isTest, 'Boolean'],
2560 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
2561 $cancelledMembershipIds = [];
2562 while ($dao->fetch()) {
2563 $cancelledMembershipIds[] = $dao->membership_type_id
;
2565 return $cancelledMembershipIds;
2569 * Merges the memberships from otherContactID to mainContactID.
2571 * General idea is to merge memberships in regards to their type. We
2572 * move the other contact’s contributions to the main contact’s
2573 * membership which has the same type (if any) and then we update
2574 * membership to avoid loosing `join_date`, `end_date`, and
2575 * `status_id`. In this function, we don’t touch the contributions
2576 * directly (CRM_Dedupe_Merger::moveContactBelongings() takes care
2579 * This function adds new SQL queries to the $sqlQueries parameter.
2581 * @param int $mainContactID
2582 * Contact id of main contact record.
2583 * @param int $otherContactID
2584 * Contact id of record which is going to merge.
2585 * @param array $sqlQueries
2586 * (reference) array of SQL queries to be executed.
2587 * @param array $tables
2588 * List of tables that have to be merged.
2589 * @param array $tableOperations
2590 * Special options/params for some tables to be merged.
2592 * @see CRM_Dedupe_Merger::cpTables()
2594 public static function mergeMemberships($mainContactID, $otherContactID, &$sqlQueries, $tables, $tableOperations) {
2596 * If the user requests not to merge memberships but to add them,
2597 * just attribute the `civicrm_membership` to the
2598 * `$mainContactID`. We have to do this here since the general
2599 * merge process is bypassed by this function.
2601 if (array_key_exists("civicrm_membership", $tableOperations) && $tableOperations['civicrm_membership']['add']) {
2602 $sqlQueries[] = "UPDATE IGNORE civicrm_membership SET contact_id = $mainContactID WHERE contact_id = $otherContactID";
2607 * Retrieve all memberships that belongs to each contacts and
2608 * keep track of each membership type.
2610 $mainContactMemberships = [];
2611 $otherContactMemberships = [];
2613 $sql = "SELECT id, membership_type_id FROM civicrm_membership membership WHERE contact_id = %1";
2614 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$mainContactID, "Integer"]]);
2615 while ($dao->fetch()) {
2616 $mainContactMemberships[$dao->id
] = $dao->membership_type_id
;
2619 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$otherContactID, "Integer"]]);
2620 while ($dao->fetch()) {
2621 $otherContactMemberships[$dao->id
] = $dao->membership_type_id
;
2625 * For each membership, move related contributions to the main
2626 * contact’s membership (by updating `membership_payments`). Then,
2627 * update membership’s `join_date` (if the other membership’s
2628 * join_date is older) and `end_date` (if the other membership’s
2629 * `end_date` is newer) and `status_id` (if the newly calculated
2630 * status is different).
2632 * FIXME: what should we do if we have multiple memberships with
2633 * the same type (currently we only take the first one)?
2636 foreach ($otherContactMemberships as $otherMembershipId => $otherMembershipTypeId) {
2637 if ($newMembershipId = array_search($otherMembershipTypeId, $mainContactMemberships)) {
2640 * Move other membership’s contributions to the main one only
2641 * if user requested to merge contributions.
2643 if (!empty($tables) && in_array('civicrm_contribution', $tables)) {
2644 $newSql[] = "UPDATE civicrm_membership_payment SET membership_id=$newMembershipId WHERE membership_id=$otherMembershipId";
2647 $sql = "SELECT * FROM civicrm_membership membership WHERE id = %1";
2649 $newMembership = CRM_Member_DAO_Membership
::findById($newMembershipId);
2650 $otherMembership = CRM_Member_DAO_Membership
::findById($otherMembershipId);
2653 if (new DateTime($otherMembership->join_date
) < new DateTime($newMembership->join_date
)) {
2654 $updates["join_date"] = $otherMembership->join_date
;
2657 if (new DateTime($otherMembership->end_date
) > new DateTime($newMembership->end_date
)) {
2658 $updates["end_date"] = $otherMembership->end_date
;
2661 if (count($updates)) {
2666 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
2667 $updates["start_date"] ??
$newMembership->start_date
,
2668 $updates["end_date"] ??
$newMembership->end_date
,
2669 $updates["join_date"] ??
$newMembership->join_date
,
2676 if (!empty($status['id']) and $status['id'] != $newMembership->status_id
) {
2677 $updates['status_id'] = $status['id'];
2681 foreach ($updates as $k => $v) {
2682 $updates_sql[] = "$k = '{$v}'";
2685 $newSql[] = sprintf("UPDATE civicrm_membership SET %s WHERE id=%s", implode(", ", $updates_sql), $newMembershipId);
2686 $newSql[] = sprintf("DELETE FROM civicrm_membership WHERE id=%s", $otherMembershipId);
2692 $sqlQueries = array_merge($sqlQueries, $newSql);
2696 * Update membership status to deceased.
2697 * function return the status message for updated membership.
2699 * @param array $deceasedParams
2704 * @param string $contactType
2706 * @return null|string
2707 * $updateMembershipMsg string status message for updated membership.
2709 public static function updateMembershipStatus($deceasedParams, $contactType) {
2710 $updateMembershipMsg = NULL;
2711 $contactId = $deceasedParams['contact_id'];
2712 $deceasedDate = $deceasedParams['deceased_date'];
2714 // process to set membership status to deceased for both active/inactive membership
2716 $contactType === 'Individual' &&
2717 !empty($deceasedParams['is_deceased'])
2720 $userId = CRM_Core_Session
::getLoggedInContactID() ?
: $contactId;
2722 // get deceased status id
2723 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2724 $deceasedStatusId = array_search('Deceased', $allStatus);
2725 if (!$deceasedStatusId) {
2726 return $updateMembershipMsg;
2729 $today = CRM_Utils_Time
::time();
2730 if ($deceasedDate && CRM_Utils_Time
::strtotime($deceasedDate) > $today) {
2731 return $updateMembershipMsg;
2734 // get non deceased membership
2735 $dao = new CRM_Member_DAO_Membership();
2736 $dao->contact_id
= $contactId;
2737 $dao->whereAdd("status_id != $deceasedStatusId");
2739 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2740 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2742 while ($dao->fetch()) {
2743 // update status to deceased (for both active/inactive membership )
2744 CRM_Core_DAO
::setFieldValue('CRM_Member_DAO_Membership', $dao->id
,
2745 'status_id', $deceasedStatusId
2748 // add membership log
2750 'membership_id' => $dao->id
,
2751 'status_id' => $deceasedStatusId,
2752 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
2753 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
2754 'modified_id' => $userId,
2755 'modified_date' => CRM_Utils_Time
::date('Ymd'),
2756 'membership_type_id' => $dao->membership_type_id
,
2757 'max_related' => $dao->max_related
,
2760 CRM_Member_BAO_MembershipLog
::add($membershipLog);
2762 //create activity when membership status is changed
2764 'subject' => "Status changed from {$allStatus[$dao->status_id]} to {$allStatus[$deceasedStatusId]}",
2765 'source_contact_id' => $userId,
2766 'target_contact_id' => $dao->contact_id
,
2767 'source_record_id' => $dao->id
,
2768 'activity_type_id' => array_search('Change Membership Status', $activityTypes),
2772 'activity_date_time' => CRM_Utils_Time
::date('Y-m-d H:i:s'),
2774 'is_current_revision' => 1,
2777 civicrm_api('activity', 'create', $activityParam);
2784 CRM_Core_Session
::setStatus(ts("%1 Current membership(s) for this contact have been set to 'Deceased' status.",
2789 return $updateMembershipMsg;