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']) && empty($params['relate_contribution_id'])) {
348 $memInfo = array_merge($params, ['membership_id' => $membership->id
]);
349 $params['contribution'] = self
::recordMembershipContribution($memInfo);
352 // Add/update MembershipPayment record for this membership if it is a related contribution
353 // @todo remove this - called from one remaining place in CRM_Member_Form_Membership
354 if (!empty($params['relate_contribution_id'])) {
355 $membershipPaymentParams = [
356 'membership_id' => $membership->id
,
357 'membership_type_id' => $membership->membership_type_id
,
358 'contribution_id' => $params['relate_contribution_id'],
360 civicrm_api3('MembershipPayment', 'create', $membershipPaymentParams);
363 // If the membership has no associated contribution then we ensure
364 // the line items are 'correct' here. This is a lazy legacy
365 // hack whereby they are deleted and recreated
366 if (empty($contributionID)) {
367 if (!empty($params['lineItems'])) {
368 $params['line_item'] = $params['lineItems'];
370 // do cleanup line items if membership edit the Membership type.
371 if (!empty($ids['membership'])) {
372 CRM_Price_BAO_LineItem
::deleteLineItems($ids['membership'], 'civicrm_membership');
374 // @todo - we should ONLY do the below if a contribution is created. Let's
375 // get some deprecation notices in here & see where it's hit & work to eliminate.
376 // This could happen if there is no contribution or we are in one of many
377 // weird and wonderful flows. This is scary code. Keep adding tests.
378 if (!empty($params['line_item']) && empty($params['contribution_id'])) {
380 foreach ($params['line_item'] as $priceSetId => $lineItems) {
381 foreach ($lineItems as $lineIndex => $lineItem) {
382 $lineMembershipType = $lineItem['membership_type_id'] ??
NULL;
383 if (!empty($params['contribution'])) {
384 $params['line_item'][$priceSetId][$lineIndex]['contribution_id'] = $params['contribution']->id
;
386 if ($lineMembershipType && $lineMembershipType == ($params['membership_type_id'] ??
NULL)) {
387 $params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $membership->id
;
388 $params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_membership';
390 elseif (!$lineMembershipType && !empty($params['contribution'])) {
391 $params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $params['contribution']->id
;
392 $params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_contribution';
396 CRM_Price_BAO_LineItem
::processPriceSet(
398 $params['line_item'],
399 $params['contribution'] ??
NULL
404 $transaction->commit();
406 self
::createRelatedMemberships($params, $membership);
408 if (empty($params['skipRecentView'])) {
409 self
::addToRecentItems($membership);
416 * @param \CRM_Member_DAO_Membership $membership
418 private static function addToRecentItems($membership) {
419 $url = CRM_Utils_System
::url('civicrm/contact/view/membership',
420 "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
422 if (empty($membership->membership_type_id
)) {
423 // ie in an update situation.
424 $membership->find(TRUE);
426 $title = CRM_Contact_BAO_Contact
::displayName($membership->contact_id
) . ' - ' . ts('Membership Type:')
427 . ' ' . CRM_Core_PseudoConstant
::getLabel('CRM_Member_BAO_Membership', 'membership_type_id', $membership->membership_type_id
);
430 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::UPDATE
)) {
431 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
432 "action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
435 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::DELETE
)) {
436 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
437 "action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
441 // add the recently created Membership
442 CRM_Utils_Recent
::add($title,
446 $membership->contact_id
,
453 * Check the membership extended through relationship.
455 * @param int $membershipTypeID
456 * Membership type id.
457 * @param int $contactId
463 * array of contact_id of all related contacts.
465 * @throws \CRM_Core_Exception
466 * @throws \CiviCRM_API3_Exception
468 public static function checkMembershipRelationship($membershipTypeID, $contactId, $action = CRM_Core_Action
::ADD
) {
471 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipType($membershipTypeID);
474 if (isset($membershipType['relationship_type_id'])) {
475 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
476 CRM_Contact_BAO_Relationship
::CURRENT
478 if ($action & CRM_Core_Action
::UPDATE
) {
479 $pastRelationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
480 CRM_Contact_BAO_Relationship
::PAST
482 $relationships = array_merge($relationships, $pastRelationships);
486 if (!empty($relationships)) {
487 // check for each contact relationships
488 foreach ($relationships as $values) {
489 //get details of the relationship type
490 $relType = ['id' => $values['civicrm_relationship_type_id']];
492 CRM_Contact_BAO_RelationshipType
::retrieve($relType, $relValues);
493 // Check if contact's relationship type exists in membership type
495 $bidirectional = FALSE;
496 foreach ($membershipType['relationship_type_id'] as $key => $value) {
497 $relTypeDirs[] = $value . '_' . $membershipType['relationship_direction'][$key];
498 if (in_array($value, $relType) &&
499 $relValues['name_a_b'] == $relValues['name_b_a']
501 $bidirectional = TRUE;
505 $relTypeDir = $values['civicrm_relationship_type_id'] . '_' . $values['rtype'];
506 if ($bidirectional ||
in_array($relTypeDir, $relTypeDirs)) {
507 // $values['status'] is going to have value for
508 // current or past relationships.
509 $contacts[$values['cid']] = $values['status'];
514 // Sort by contact_id ascending
520 * Retrieve DB object based on input parameters.
522 * It also stores all the retrieved values in the default array.
524 * @param array $params
525 * (reference ) an assoc array of name/value pairs.
526 * @param array $defaults
527 * (reference ) an assoc array to hold the name / value pairs.
528 * in a hierarchical manner
530 * @return CRM_Member_BAO_Membership
532 public static function retrieve(&$params, &$defaults) {
533 $membership = new CRM_Member_DAO_Membership();
535 $membership->copyValues($params);
537 if ($membership->find(TRUE)) {
538 CRM_Core_DAO
::storeValues($membership, $defaults);
540 //get the membership status and type values.
541 $statusANDType = self
::getStatusANDTypeValues($membership->id
);
542 foreach (['status', 'membership_type'] as $fld) {
543 $defaults[$fld] = $statusANDType[$membership->id
][$fld] ??
NULL;
545 if (!empty($statusANDType[$membership->id
]['is_current_member'])) {
546 $defaults['active'] = TRUE;
556 * Get membership status and membership type values.
558 * @param int $membershipId
559 * Membership id of values to return.
562 * Array of key value pairs
564 public static function getStatusANDTypeValues($membershipId) {
566 if (!$membershipId) {
570 SELECT membership.id as id,
571 status.id as status_id,
572 status.label as status,
573 status.is_current_member as is_current_member,
574 type.id as membership_type_id,
575 type.name as membership_type,
576 type.relationship_type_id as relationship_type_id
577 FROM civicrm_membership membership
578 INNER JOIN civicrm_membership_status status ON ( status.id = membership.status_id )
579 INNER JOIN civicrm_membership_type type ON ( type.id = membership.membership_type_id )
580 WHERE membership.id = %1';
581 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$membershipId, 'Positive']]);
586 'membership_type_id',
588 'relationship_type_id',
590 while ($dao->fetch()) {
591 foreach ($properties as $property) {
592 $values[$dao->id
][$property] = $dao->$property;
602 * Wrapper for most delete calls. Use this unless you JUST want to delete related memberships w/o deleting the parent.
604 * @param int $membershipId
605 * Membership id that needs to be deleted.
606 * @param bool $preserveContrib
609 * Id of deleted Membership on success, false otherwise.
611 public static function del($membershipId, $preserveContrib = FALSE) {
612 //delete related first and then delete parent.
613 self
::deleteRelatedMemberships($membershipId);
614 return self
::deleteMembership($membershipId, $preserveContrib);
620 * @param int $membershipId
621 * Membership id that needs to be deleted.
622 * @param bool $preserveContrib
625 * Id of deleted Membership on success, false otherwise.
627 public static function deleteMembership($membershipId, $preserveContrib = FALSE) {
628 // CRM-12147, retrieve membership data before we delete it for hooks
629 $params = ['id' => $membershipId];
631 $memberships = self
::getValues($params, $memValues);
633 $membership = $memberships[$membershipId];
635 CRM_Utils_Hook
::pre('delete', 'Membership', $membershipId, $memValues);
637 $transaction = new CRM_Core_Transaction();
640 //delete activity record
641 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
644 $deleteActivity = FALSE;
645 $membershipActivities = [
647 'Membership Renewal',
648 'Change Membership Status',
649 'Change Membership Type',
650 'Membership Renewal Reminder',
652 foreach ($membershipActivities as $membershipActivity) {
653 $activityId = array_search($membershipActivity, $activityTypes);
655 $params['activity_type_id'][] = $activityId;
656 $deleteActivity = TRUE;
659 if ($deleteActivity) {
660 $params['source_record_id'] = $membershipId;
661 CRM_Activity_BAO_Activity
::deleteActivity($params);
663 self
::deleteMembershipPayment($membershipId, $preserveContrib);
664 CRM_Price_BAO_LineItem
::deleteLineItems($membershipId, 'civicrm_membership');
666 $results = $membership->delete();
667 $transaction->commit();
669 CRM_Utils_Hook
::post('delete', 'Membership', $membership->id
, $membership);
671 // delete the recently created Membership
672 $membershipRecent = [
673 'id' => $membershipId,
674 'type' => 'Membership',
676 CRM_Utils_Recent
::del($membershipRecent);
682 * Delete related memberships.
684 * @param int $ownerMembershipId
685 * @param int $contactId
689 public static function deleteRelatedMemberships($ownerMembershipId, $contactId = NULL) {
690 if (!$ownerMembershipId && !$contactId) {
694 $membership = new CRM_Member_DAO_Membership();
695 $membership->owner_membership_id
= $ownerMembershipId;
698 $membership->contact_id
= $contactId;
702 while ($membership->fetch()) {
703 //delete related first and then delete parent.
704 self
::deleteRelatedMemberships($membership->id
);
705 self
::deleteMembership($membership->id
);
710 * Obtain active/inactive memberships from the list of memberships passed to it.
712 * @param array $memberships
713 * Membership records.
714 * @param string $status
715 * Active or inactive.
718 * array of memberships based on status
720 public static function activeMembers($memberships, $status = 'active') {
722 if ($status == 'active') {
723 foreach ($memberships as $f => $v) {
724 if (!empty($v['active'])) {
730 elseif ($status == 'inactive') {
731 foreach ($memberships as $f => $v) {
732 if (empty($v['active'])) {
742 * Return Membership Block info in Contribution Pages.
745 * Contribution page id.
749 public static function getMembershipBlock($pageID) {
750 $membershipBlock = [];
751 $dao = new CRM_Member_DAO_MembershipBlock();
752 $dao->entity_table
= 'civicrm_contribution_page';
754 $dao->entity_id
= $pageID;
756 if ($dao->find(TRUE)) {
757 CRM_Core_DAO
::storeValues($dao, $membershipBlock);
758 if (!empty($membershipBlock['membership_types'])) {
759 $membershipTypes = CRM_Utils_String
::unserialize($membershipBlock['membership_types']);
760 if (!is_array($membershipTypes)) {
761 return $membershipBlock;
764 foreach ($membershipTypes as $key => $value) {
765 $membershipBlock['auto_renew'][$key] = $value;
766 $memTypes[$key] = $key;
768 $membershipBlock['membership_types'] = implode(',', $memTypes);
775 return $membershipBlock;
779 * Return a current membership of given contact.
781 * NB: if more than one membership meets criteria, a randomly selected one is returned.
783 * @param int $contactID
785 * @param int $memType
786 * Membership type, null to retrieve all types.
788 * @param int $membershipId
789 * If provided, then determine if it is current.
790 * @param bool $onlySameParentOrg
791 * True if only Memberships with same parent org as the $memType wanted, false otherwise.
794 * @throws \CiviCRM_API3_Exception
796 public static function getContactMembership($contactID, $memType, $isTest, $membershipId = NULL, $onlySameParentOrg = FALSE) {
797 //check for owner membership id, if it exists update that membership instead: CRM-15992
799 $ownerMemberId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
801 'owner_membership_id', 'id'
803 if ($ownerMemberId) {
804 $membershipId = $ownerMemberId;
805 $contactID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
812 $dao = new CRM_Member_DAO_Membership();
814 $dao->id
= $membershipId;
816 $dao->contact_id
= $contactID;
817 $dao->membership_type_id
= $memType;
819 //fetch proper membership record.
821 $dao->is_test
= $isTest;
824 $dao->whereAdd('is_test IS NULL OR is_test = 0');
827 //avoid pending membership as current membership: CRM-3027
828 $statusIds = [array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus())];
829 if (!$membershipId) {
831 $statusIds[] = array_search(
833 CRM_Member_PseudoConstant
::membershipStatus(
835 " name = 'Cancelled' ",
842 $dao->whereAdd('status_id NOT IN ( ' . implode(',', $statusIds) . ')');
844 // order by start date to find most recent membership first, CRM-4545
845 $dao->orderBy('start_date DESC');
848 if ($onlySameParentOrg && $memType) {
849 // require the same parent org as the $memType
850 $params = ['id' => $memType];
851 $membershipType = [];
852 if (CRM_Member_BAO_MembershipType
::retrieve($params, $membershipType)) {
853 $memberTypesSameParentOrg = civicrm_api3('MembershipType', 'get', [
854 'member_of_contact_id' => $membershipType['member_of_contact_id'],
859 $memberTypesSameParentOrgList = implode(',', array_keys($memberTypesSameParentOrg['values'] ??
[]));
860 $dao->whereAdd('membership_type_id IN (' . $memberTypesSameParentOrgList . ')');
864 if ($dao->find(TRUE)) {
866 CRM_Core_DAO
::storeValues($dao, $membership);
867 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
868 $membership['status_id'],
869 'is_current_member', 'id'
871 $ownerMemberId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
873 'owner_membership_id', 'id'
875 if ($ownerMemberId) {
876 $membership['id'] = $membership['membership_id'] = $ownerMemberId;
877 $membership['membership_contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
886 if ($onlySameParentOrg && $memType) {
887 // see if there is a membership that has same parent as $memType but different parent than $membershipID
888 if ($dao->id
&& CRM_Core_Permission
::check('edit memberships')) {
889 // CRM-10016, This is probably a backend renewal, and make sure we return the same membership thats being renewed.
896 unset($dao->membership_type_id
);
897 if ($dao->find(TRUE)) {
899 CRM_Core_DAO
::storeValues($dao, $membership);
900 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
901 $membership['status_id'],
902 'is_current_member', 'id'
911 * Combine all the importable fields from the lower levels object.
913 * @param string $contactType
915 * @param bool $status
918 * array of importable Fields
919 * @throws \CRM_Core_Exception
921 public static function importableFields($contactType = 'Individual', $status = TRUE) {
922 $fields = Civi
::cache('fields')->get('membership_importable_fields' . $contactType . $status);
925 $fields = ['' => ['title' => '- ' . ts('do not import') . ' -']];
928 $fields = ['' => ['title' => '- ' . ts('Membership Fields') . ' -']];
931 $tmpFields = CRM_Member_DAO_Membership
::import();
932 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
934 // Using new Dedupe rule.
936 'contact_type' => $contactType,
937 'used' => 'Unsupervised',
939 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
941 $tmpContactField = [];
942 if (is_array($fieldsArray)) {
943 foreach ($fieldsArray as $value) {
944 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
949 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
950 $tmpContactField[trim($value)] = $contactFields[trim($value)] ??
NULL;
952 $title = $tmpContactField[trim($value)]['title'] . " " . ts('(match to contact)');
955 $title = $tmpContactField[trim($value)]['title'];
957 $tmpContactField[trim($value)]['title'] = $title;
960 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
961 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
963 $tmpFields['membership_contact_id']['title'] .= ' ' . ts('(match to contact)');
965 $fields = array_merge($fields, $tmpContactField);
966 $fields = array_merge($fields, $tmpFields);
967 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
968 Civi
::cache('fields')->set('membership_importable_fields' . $contactType . $status, $fields);
974 * Get all exportable fields.
976 * @return array return array of all exportable fields
978 public static function &exportableFields() {
979 $expFieldMembership = CRM_Member_DAO_Membership
::export();
981 $expFieldsMemType = CRM_Member_DAO_MembershipType
::export();
982 $fields = array_merge($expFieldMembership, $expFieldsMemType);
983 $fields = array_merge($fields, $expFieldMembership);
984 $membershipStatus = [
985 'membership_status' => [
986 'title' => ts('Membership Status'),
987 'name' => 'membership_status',
988 'type' => CRM_Utils_Type
::T_STRING
,
989 'where' => 'civicrm_membership_status.name',
992 //CRM-6161 fix for customdata export
993 $fields = array_merge($fields, $membershipStatus, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
994 $fields['membership_status_id'] = $membershipStatus['membership_status'];
999 * Get membership joins/renewals for a specified membership type.
1001 * Specifically, retrieves a count of memberships whose "Membership
1002 * Signup" or "Membership Renewal" activity falls in the given date range.
1003 * Dates match the pattern "yyyy-mm-dd".
1005 * @param int $membershipTypeId
1006 * Membership type id.
1007 * @param int $startDate
1008 * Date on which to start counting.
1009 * @param int $endDate
1010 * Date on which to end counting.
1011 * @param bool|int $isTest if true, membership is for a test site
1012 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1015 * the number of members of type $membershipTypeId whose
1016 * start_date is between $startDate and $endDate
1018 public static function getMembershipStarts($membershipTypeId, $startDate, $endDate, $isTest = 0, $isOwner = 0) {
1019 // Ensure that the dates that are passed to the query are in the format of yyyy-mm-dd
1020 $dates = ['startDate', 'endDate'];
1021 foreach ($dates as $date) {
1022 if (strlen($
$date) === 8) {
1023 $
$date = date('Y-m-d', CRM_Utils_Time
::strtotime($
$date));
1027 $testClause = 'membership.is_test = 1';
1029 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1032 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1033 self
::_getActTypes();
1036 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1041 SELECT COUNT(DISTINCT membership.id) as member_count
1042 FROM civicrm_membership membership
1043 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id in (%1, %2))
1044 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1045 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1046 WHERE membership.membership_type_id = %3
1047 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1050 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1053 1 => [self
::$_signupActType, 'Integer'],
1054 2 => [self
::$_renewalActType, 'Integer'],
1055 3 => [$membershipTypeId, 'Integer'],
1058 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1059 return (int) $memberCount;
1063 * Get a count of membership for a specified membership type, optionally for a specified date.
1065 * The date must have the form yyyy-mm-dd.
1067 * If $date is omitted, this function counts as a member anyone whose
1068 * membership status_id indicates they're a current member.
1069 * If $date is given, this function counts as a member anyone who:
1070 * -- Has a start_date before $date and end_date after $date, or
1071 * -- Has a start_date before $date and is currently a member, as indicated
1072 * by the the membership's status_id.
1073 * The second condition takes care of records that have no end_date. These
1074 * are assumed to be lifetime memberships.
1076 * @param int $membershipTypeId
1077 * Membership type id.
1078 * @param string $date
1079 * The date for which to retrieve the count.
1080 * @param bool|int $isTest if true, membership is for a test site
1081 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1084 * the number of members of type $membershipTypeId as of $date.
1086 public static function getMembershipCount($membershipTypeId, $date = NULL, $isTest = 0, $isOwner = 0) {
1087 if (!CRM_Utils_Rule
::date($date)) {
1088 throw new CRM_Core_Exception(ts('Invalid date "%1" (must have form yyyy-mm-dd).', [1 => $date]));
1092 1 => [$membershipTypeId, 'Integer'],
1093 2 => [$isTest, 'Boolean'],
1095 $query = "SELECT count(civicrm_membership.id ) as member_count
1096 FROM civicrm_membership left join civicrm_membership_status on ( civicrm_membership.status_id = civicrm_membership_status.id )
1097 WHERE civicrm_membership.membership_type_id = %1
1098 AND civicrm_membership.contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)
1099 AND civicrm_membership.is_test = %2";
1101 $query .= " AND civicrm_membership_status.is_current_member = 1";
1104 $query .= " AND civicrm_membership.start_date <= '$date' AND civicrm_membership_status.is_current_member = 1";
1107 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1108 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1109 return (int) $memberCount;
1113 * Function check the status of the membership before adding membership for a contact.
1117 public static function statusAvailabilty() {
1118 $membership = new CRM_Member_DAO_MembershipStatus();
1119 $membership->whereAdd('is_active=1');
1120 return $membership->count();
1124 * @deprecated This is not used anywhere and should be removed soon!
1125 * Function for updating a membership record's contribution_recur_id.
1127 * @param CRM_Member_DAO_Membership $membership
1128 * @param \CRM_Contribute_BAO_Contribution|\CRM_Contribute_DAO_Contribution $contribution
1130 public static function updateRecurMembership(CRM_Member_DAO_Membership
$membership, CRM_Contribute_BAO_Contribution
$contribution) {
1131 CRM_Core_Error
::deprecatedFunctionWarning('Use the API instead');
1133 if (empty($contribution->contribution_recur_id
)) {
1138 1 => [$contribution->contribution_recur_id
, 'Integer'],
1139 2 => [$membership->id
, 'Integer'],
1142 $sql = "UPDATE civicrm_membership SET contribution_recur_id = %1 WHERE id = %2";
1143 CRM_Core_DAO
::executeQuery($sql, $params);
1147 * Method to fix membership status of stale membership.
1149 * This method first checks if the membership is stale. If it is,
1150 * then status will be updated based on existing start and end
1151 * dates and log will be added for the status change.
1153 * @param array $currentMembership
1154 * Reference to the array.
1155 * containing all values of
1156 * the current membership
1157 * @param string|null $changeToday
1158 * In case today needs
1159 * to be customised, null otherwise
1161 * @throws \CRM_Core_Exception
1163 public static function fixMembershipStatusBeforeRenew(&$currentMembership, $changeToday = NULL) {
1166 $today = CRM_Utils_Date
::processDate($changeToday, NULL, FALSE, 'Y-m-d');
1169 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
1170 $currentMembership['start_date'] ??
NULL,
1171 $currentMembership['end_date'] ??
NULL,
1172 $currentMembership['join_date'] ??
NULL,
1175 $currentMembership['membership_type_id'],
1179 if (empty($status) ||
empty($status['id'])) {
1180 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.'));
1183 if ($status['id'] !== $currentMembership['status_id']) {
1184 $oldStatus = $currentMembership['status_id'];
1185 $memberDAO = new CRM_Member_DAO_Membership();
1186 $memberDAO->id
= $currentMembership['id'];
1187 $memberDAO->find(TRUE);
1189 $memberDAO->status_id
= $status['id'];
1191 CRM_Core_DAO
::storeValues($memberDAO, $currentMembership);
1193 $currentMembership['is_current_member'] = CRM_Core_DAO
::getFieldValue(
1194 'CRM_Member_DAO_MembershipStatus',
1195 $currentMembership['status_id'],
1201 'membership_id' => $currentMembership['id'],
1202 'status_id' => $status['id'],
1203 'start_date' => CRM_Utils_Date
::customFormat(
1204 $currentMembership['start_date'],
1207 'end_date' => CRM_Utils_Date
::customFormat(
1208 $currentMembership['end_date'],
1211 'modified_date' => date('Y-m-d H:i:s', CRM_Utils_Time
::strtotime($today)),
1212 'membership_type_id' => $currentMembership['membership_type_id'],
1213 'max_related' => $currentMembership['max_related'] ??
0,
1216 $session = CRM_Core_Session
::singleton();
1217 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
1218 if ($session->get('userID')) {
1219 $logParams['modified_id'] = $session->get('userID');
1222 $logParams['modified_id'] = $currentMembership['contact_id'];
1225 //Create activity for status change.
1226 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
1227 CRM_Activity_BAO_Activity
::addActivity($memberDAO,
1228 'Change Membership Status',
1231 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$status['id']]}",
1232 'source_contact_id' => $logParams['modified_id'],
1233 'priority_id' => 'Normal',
1237 CRM_Member_BAO_MembershipLog
::add($logParams);
1242 * Get the contribution page id from the membership record.
1244 * @param int $membershipID
1247 * contribution page id
1249 public static function getContributionPageId($membershipID) {
1251 SELECT c.contribution_page_id as pageID
1252 FROM civicrm_membership_payment mp, civicrm_contribution c
1253 WHERE mp.contribution_id = c.id
1254 AND c.contribution_page_id IS NOT NULL
1255 AND mp.membership_id = " . CRM_Utils_Type
::escape($membershipID, 'Integer')
1256 . " ORDER BY mp.id DESC";
1258 return CRM_Core_DAO
::singleValueQuery($query);
1262 * Updated related memberships.
1264 * @param int $ownerMembershipId
1265 * Owner Membership Id.
1266 * @param array $params
1267 * Formatted array of key => value.
1269 public static function updateRelatedMemberships($ownerMembershipId, $params) {
1270 $membership = new CRM_Member_DAO_Membership();
1271 $membership->owner_membership_id
= $ownerMembershipId;
1272 $membership->find();
1274 while ($membership->fetch()) {
1275 $relatedMembership = new CRM_Member_DAO_Membership();
1276 $relatedMembership->id
= $membership->id
;
1277 $relatedMembership->copyValues($params);
1278 $relatedMembership->save();
1284 * Get list of membership fields for profile.
1286 * For now we only allow custom membership fields to be in
1290 * FIXME: This param is ignored
1293 * the list of membership fields
1295 public static function getMembershipFields($mode = NULL) {
1296 $fields = CRM_Member_DAO_Membership
::export();
1298 unset($fields['membership_contact_id']);
1299 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1301 $membershipType = CRM_Member_DAO_MembershipType
::export();
1303 $membershipStatus = CRM_Member_DAO_MembershipStatus
::export();
1305 $fields = array_merge($fields, $membershipType, $membershipStatus);
1311 * Get the sort name of a contact for a particular membership.
1314 * Id of the membership.
1316 * @return null|string
1317 * sort name of the contact if found
1319 public static function sortName($id) {
1320 $id = CRM_Utils_Type
::escape($id, 'Integer');
1323 SELECT civicrm_contact.sort_name
1324 FROM civicrm_membership, civicrm_contact
1325 WHERE civicrm_membership.contact_id = civicrm_contact.id
1326 AND civicrm_membership.id = {$id}
1328 return CRM_Core_DAO
::singleValueQuery($query);
1332 * Create memberships for related contacts, taking into account the maximum related memberships.
1334 * @param array $params
1335 * Array of key - value pairs.
1336 * @param CRM_Core_DAO $dao
1337 * Membership object.
1339 * @throws \CRM_Core_Exception
1340 * @throws \CiviCRM_API3_Exception
1342 public static function createRelatedMemberships($params, $dao) {
1343 unset($params['membership_id']);
1344 $membership = new CRM_Member_DAO_Membership();
1345 $membership->id
= $dao->id
;
1347 // required since create method doesn't return all the
1348 // parameters in the returned membership object
1349 if (!$membership->find(TRUE)) {
1352 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1353 // FIXME : While updating/ renewing the
1354 // membership, if the relationship is PAST then
1355 // the membership of the related contact must be
1357 // For that, getting Membership Status for which
1358 // is_current_member is 0. It works for the
1359 // generated data as there is only one membership
1360 // status having is_current_member = 0.
1361 // But this wont work exactly if there will be
1362 // more than one status having is_current_member = 0.
1363 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
1364 $membershipStatus->is_current_member
= 0;
1365 if ($membershipStatus->find(TRUE)) {
1366 $expiredStatusId = $membershipStatus->id
;
1369 $expiredStatusId = array_search('Expired', CRM_Member_PseudoConstant
::membershipStatus());
1372 $relatedContacts = [];
1373 $allRelatedContacts = CRM_Member_BAO_Membership
::checkMembershipRelationship($membership->membership_type_id
,
1374 $membership->contact_id
,
1375 $params['action'] ??
NULL
1378 // CRM-4213, CRM-19735 check for loops, using static variable to record contacts already processed.
1379 // Remove repeated related contacts, which already inherited membership of this type$relatedContactIds[$membership->contact_id][$membership->membership_type_id] = TRUE;
1380 foreach ($allRelatedContacts as $cid => $status) {
1381 // relatedContactIDs is always empty now - will remove next roud because of whitespace readability.
1382 if (empty($relatedContactIds[$cid]) ||
empty($relatedContactIds[$cid][$membership->membership_type_id
])) {
1383 $relatedContactIds[$cid][$membership->membership_type_id
] = TRUE;
1385 //don't create membership again for owner contact.
1386 $nestedRelationship = FALSE;
1387 if ($membership->owner_membership_id
) {
1388 $nestedRelMembership = new CRM_Member_DAO_Membership();
1389 $nestedRelMembership->id
= $membership->owner_membership_id
;
1390 $nestedRelMembership->contact_id
= $cid;
1391 $nestedRelationship = $nestedRelMembership->find(TRUE);
1393 if (!$nestedRelationship) {
1394 $relatedContacts[$cid] = $status;
1399 //lets cleanup related membership if any.
1400 if (empty($relatedContacts)) {
1401 self
::deleteRelatedMemberships($membership->id
);
1404 // Edit the params array
1405 unset($params['id']);
1406 // Reminder should be sent only to the direct membership
1407 unset($params['reminder_date']);
1408 // unset the custom value ids
1409 if (isset($params['custom']) && is_array($params['custom'])) {
1410 foreach ($params['custom'] as $k => $values) {
1411 foreach ($values as $i => $value) {
1412 unset($params['custom'][$k][$i]['id']);
1416 if (!isset($params['membership_type_id'])) {
1417 $params['membership_type_id'] = $membership->membership_type_id
;
1420 // max_related should be set in the parent membership
1421 unset($params['max_related']);
1422 // Number of inherited memberships available - NULL is interpreted as unlimited, '0' as none
1423 $numRelatedAvailable = ($membership->max_related
== NULL ? PHP_INT_MAX
: $membership->max_related
);
1424 // will be used to queue potential memberships to be created.
1427 foreach ($relatedContacts as $contactId => $relationshipStatus) {
1428 //use existing membership record.
1429 $relMembership = new CRM_Member_DAO_Membership();
1430 $relMembership->contact_id
= $contactId;
1431 $relMembership->owner_membership_id
= $membership->id
;
1433 if ($relMembership->find(TRUE)) {
1434 $params['id'] = $relMembership->id
;
1437 unset($params['id']);
1440 $params['contact_id'] = $contactId;
1441 $params['owner_membership_id'] = $membership->id
;
1443 // set status_id as it might have been changed for
1444 // past relationship
1445 $params['status_id'] = $membership->status_id
;
1447 if ($deceasedStatusId &&
1448 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'is_deceased')
1450 $params['status_id'] = $deceasedStatusId;
1452 elseif ((($params['action'] ??
NULL) & CRM_Core_Action
::UPDATE
) &&
1453 ($relationshipStatus == CRM_Contact_BAO_Relationship
::PAST
)
1455 $params['status_id'] = $expiredStatusId;
1458 //don't calculate status again in create( );
1459 $params['skipStatusCal'] = TRUE;
1461 //do create activity if we changed status.
1462 if ($params['status_id'] != $relMembership->status_id
) {
1463 $params['createActivity'] = TRUE;
1466 //CRM-20707 - include start/end date
1467 $params['start_date'] = $membership->start_date
;
1468 $params['end_date'] = $membership->end_date
;
1470 // we should not created contribution record for related contacts, CRM-3371
1471 unset($params['contribution_status_id']);
1473 //CRM-16857: Do not create multiple line-items for inherited membership through priceset.
1474 unset($params['lineItems']);
1475 unset($params['line_item']);
1477 // CRM-20966: Do not create membership_payment record for inherited membership.
1478 unset($params['relate_contribution_id']);
1480 if (($params['status_id'] == $deceasedStatusId) ||
($params['status_id'] == $expiredStatusId)) {
1481 // related membership is not active so does not count towards maximum
1482 if (!self
::hasExistingInheritedMembership($params)) {
1483 civicrm_api3('Membership', 'create', $params);
1487 // related membership already exists, so this is just an update
1488 if (isset($params['id'])) {
1489 if ($numRelatedAvailable > 0) {
1490 CRM_Member_BAO_Membership
::create($params);
1491 $numRelatedAvailable--;
1494 // we have run out of inherited memberships, so delete extras
1495 self
::deleteMembership($params['id']);
1497 // we need to first check if there will remain inherited memberships, so queue it up
1504 // now go over the queue and create any available related memberships
1505 foreach ($queue as $params) {
1506 if ($numRelatedAvailable <= 0) {
1509 if (!self
::hasExistingInheritedMembership($params)) {
1510 CRM_Member_BAO_Membership
::create($params);
1512 $numRelatedAvailable--;
1518 * Delete the record that are associated with this Membership Payment.
1520 * @param int $membershipId
1521 * @param bool $preserveContrib
1524 * $membershipPayment deleted membership payment object
1526 public static function deleteMembershipPayment($membershipId, $preserveContrib = FALSE) {
1528 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
1529 $membershipPayment->membership_id
= $membershipId;
1530 $membershipPayment->find();
1532 while ($membershipPayment->fetch()) {
1533 if (!$preserveContrib) {
1534 CRM_Contribute_BAO_Contribution
::deleteContribution($membershipPayment->contribution_id
);
1536 CRM_Utils_Hook
::pre('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1537 $membershipPayment->delete();
1538 CRM_Utils_Hook
::post('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1540 return $membershipPayment;
1544 * Build an array of available membership types in the current context.
1546 * While core does not do anything context specific extensions may filter
1547 * or alter amounts based on user details.
1549 * @param CRM_Core_Form $form
1550 * @param array $membershipTypeID
1551 * @param bool $activeOnly
1552 * Do we only want active ones?
1553 * (probably this should default to TRUE but as a newly added parameter we are leaving default b
1554 * behaviour unchanged).
1558 * @throws \CiviCRM_API3_Exception
1560 public static function buildMembershipTypeValues($form, $membershipTypeID = [], $activeOnly = FALSE) {
1561 $membershipTypeIDS = (array) $membershipTypeID;
1562 $membershipTypeValues = CRM_Member_BAO_MembershipType
::getAllMembershipTypes();
1564 // MembershipTypes are already filtered by domain, filter as appropriate by is_active & a passed in list of ids.
1565 foreach ($membershipTypeValues as $id => $type) {
1566 if (($activeOnly && empty($type['is_active']))
1567 ||
(!empty($membershipTypeIDS) && !in_array($id, $membershipTypeIDS, FALSE))
1569 unset($membershipTypeValues[$id]);
1573 CRM_Utils_Hook
::membershipTypeValues($form, $membershipTypeValues);
1574 return $membershipTypeValues;
1578 * Get membership record count for a Contact.
1580 * @param int $contactID
1581 * @param bool $activeOnly
1584 * @throws \API_Exception
1586 public static function getContactMembershipCount(int $contactID, $activeOnly = FALSE): int {
1588 $membershipTypes = MembershipType
::get(TRUE)
1592 $addWhere = " AND membership_type_id IN (0)";
1593 if (!empty($membershipTypes)) {
1594 $addWhere = " AND membership_type_id IN (" . implode(',', array_keys($membershipTypes)) . ")";
1597 $select = "SELECT COUNT(*) FROM civicrm_membership ";
1598 $where = "WHERE civicrm_membership.contact_id = {$contactID} AND civicrm_membership.is_test = 0 ";
1600 // CRM-6627, all status below 3 (active, pending, grace) are considered active
1602 $select .= " INNER JOIN civicrm_membership_status ON civicrm_membership.status_id = civicrm_membership_status.id ";
1603 $where .= " and civicrm_membership_status.is_current_member = 1";
1606 $query = $select . $where . $addWhere;
1607 return (int) CRM_Core_DAO
::singleValueQuery($query);
1609 catch (UnauthorizedException
$e) {
1615 * Check whether payment processor supports cancellation of membership subscription.
1620 * @param bool $isNotCancelled
1624 public static function isCancelSubscriptionSupported($mid, $isNotCancelled = TRUE) {
1625 $cacheKeyString = "$mid";
1626 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
1628 static $supportsCancel = [];
1630 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
1631 $supportsCancel[$cacheKeyString] = FALSE;
1632 $isCancelled = FALSE;
1634 if ($isNotCancelled) {
1635 $isCancelled = self
::isSubscriptionCancelled($mid);
1638 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($mid, 'membership', 'obj');
1639 if (!empty($paymentObject)) {
1640 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
1643 return $supportsCancel[$cacheKeyString];
1647 * Check whether subscription is already cancelled.
1653 * contribution status
1655 public static function isSubscriptionCancelled($mid) {
1657 SELECT cr.contribution_status_id
1658 FROM civicrm_contribution_recur cr
1659 LEFT JOIN civicrm_membership mem ON ( cr.id = mem.contribution_recur_id )
1660 WHERE mem.id = %1 LIMIT 1";
1661 $params = [1 => [$mid, 'Integer']];
1662 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
1663 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
1664 if ($status == 'Cancelled') {
1671 * Get membership joins for a specified membership type.
1673 * Specifically, retrieves a count of still current memberships whose
1674 * join_date and start_date are within a specified date range. Dates match
1675 * the pattern "yyyy-mm-dd".
1677 * @param int $membershipTypeId
1678 * Membership type id.
1679 * @param int $startDate
1680 * Date on which to start counting.
1681 * @param int $endDate
1682 * Date on which to end counting.
1683 * @param bool|int $isTest if true, membership is for a test site
1686 * the number of members of type $membershipTypeId
1687 * whose join_date is between $startDate and $endDate and
1688 * whose start_date is between $startDate and $endDate
1690 public static function getMembershipJoins($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1691 $testClause = 'membership.is_test = 1';
1693 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1695 if (!self
::$_signupActType) {
1696 self
::_getActTypes();
1699 if (!self
::$_signupActType) {
1704 SELECT COUNT(DISTINCT membership.id) as member_count
1705 FROM civicrm_membership membership
1706 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1707 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1708 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1709 WHERE membership.membership_type_id = %2
1710 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1714 1 => [self
::$_signupActType, 'Integer'],
1715 2 => [$membershipTypeId, 'Integer'],
1718 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1720 return (int) $memberCount;
1724 * Get membership renewals for a specified membership type.
1726 * Specifically, retrieves a count of still current memberships
1727 * whose join_date is before and start_date is within a specified date
1728 * range. Dates match the pattern "yyyy-mm-dd".
1730 * @param int $membershipTypeId
1731 * Membership type id.
1732 * @param int $startDate
1733 * Date on which to start counting.
1734 * @param int $endDate
1735 * Date on which to end counting.
1736 * @param bool|int $isTest if true, membership is for a test site
1739 * returns the number of members of type $membershipTypeId
1740 * whose join_date is before $startDate and
1741 * whose start_date is between $startDate and $endDate
1743 public static function getMembershipRenewals($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1744 $testClause = 'membership.is_test = 1';
1746 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1748 if (!self
::$_renewalActType) {
1749 self
::_getActTypes();
1752 if (!self
::$_renewalActType) {
1757 SELECT COUNT(DISTINCT membership.id) as member_count
1758 FROM civicrm_membership membership
1759 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1760 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1761 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1762 WHERE membership.membership_type_id = %2
1763 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1767 1 => [self
::$_renewalActType, 'Integer'],
1768 2 => [$membershipTypeId, 'Integer'],
1770 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1772 return (int) $memberCount;
1776 * @param int $contactID
1777 * @param int $membershipTypeID
1778 * @param bool $is_test
1779 * @param string $changeToday
1780 * @param int $modifiedID
1781 * @param $customFieldsFormatted
1782 * @param $numRenewTerms
1783 * @param int $membershipID
1785 * @param int $contributionRecurID
1786 * @param $membershipSource
1787 * @param $isPayLater
1788 * @param array $memParams
1789 * @param array $formDates
1790 * @param null|CRM_Contribute_BAO_Contribution $contribution
1791 * @param array $lineItems
1794 * @throws \CRM_Core_Exception
1795 * @throws \CiviCRM_API3_Exception
1797 public static function processMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $contributionRecurID, $membershipSource, $isPayLater, $memParams = [], $formDates = [], $contribution = NULL, $lineItems = []) {
1798 $renewalMode = $updateStatusId = FALSE;
1799 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1801 $statusFormat = '%Y-%m-%d';
1802 $membershipTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipType($membershipTypeID);
1806 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
1807 // is the same as the parent org of an existing membership of the contact
1808 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($contactID, $membershipTypeID,
1809 $is_test, $membershipID, TRUE
1811 if ($currentMembership) {
1812 $renewalMode = TRUE;
1814 // Do NOT do anything.
1815 //1. membership with status : PENDING/CANCELLED (CRM-2395)
1816 //2. Paylater/IPN renew. CRM-4556.
1817 if ($pending ||
in_array($currentMembership['status_id'], [
1818 array_search('Pending', $allStatus),
1820 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1823 $memParams = array_merge([
1824 'id' => $currentMembership['id'],
1825 'contribution' => $contribution,
1826 'status_id' => $currentMembership['status_id'],
1827 'start_date' => $currentMembership['start_date'],
1828 'end_date' => $currentMembership['end_date'],
1829 'line_item' => $lineItems,
1830 'join_date' => $currentMembership['join_date'],
1831 'membership_type_id' => $membershipTypeID,
1832 'max_related' => !empty($membershipTypeDetails['max_related']) ?
$membershipTypeDetails['max_related'] : NULL,
1833 'membership_activity_status' => ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed',
1835 if ($contributionRecurID) {
1836 $memParams['contribution_recur_id'] = $contributionRecurID;
1839 $membership = self
::create($memParams);
1840 return [$membership, $renewalMode, $dates];
1843 // Check and fix the membership if it is STALE
1844 self
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
1846 // Now Renew the membership
1847 if (!$currentMembership['is_current_member']) {
1848 // membership is not CURRENT
1850 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1851 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($currentMembership['id'],
1857 $currentMembership['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1858 foreach (['start_date', 'end_date'] as $dateType) {
1859 $currentMembership[$dateType] = $formDates[$dateType] ??
NULL;
1860 if (empty($currentMembership[$dateType])) {
1861 $currentMembership[$dateType] = $dates[$dateType] ??
NULL;
1864 $currentMembership['is_test'] = $is_test;
1866 if (!empty($membershipSource)) {
1867 $currentMembership['source'] = $membershipSource;
1870 if (!empty($currentMembership['id'])) {
1871 $ids['membership'] = $currentMembership['id'];
1873 $memParams = array_merge($currentMembership, $memParams);
1874 $memParams['membership_type_id'] = $membershipTypeID;
1876 //set the log start date.
1877 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1881 // CURRENT Membership
1882 $membership = new CRM_Member_DAO_Membership();
1883 $membership->id
= $currentMembership['id'];
1884 $membership->find(TRUE);
1885 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1886 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
1892 // Insert renewed dates for CURRENT membership
1893 $memParams['join_date'] = CRM_Utils_Date
::isoToMysql($membership->join_date
);
1894 $memParams['start_date'] = $formDates['start_date'] ?? CRM_Utils_Date
::isoToMysql($membership->start_date
);
1895 $memParams['end_date'] = $formDates['end_date'] ??
NULL;
1896 if (empty($memParams['end_date'])) {
1897 $memParams['end_date'] = $dates['end_date'] ??
NULL;
1899 $memParams['membership_type_id'] = $membershipTypeID;
1901 //set the log start date.
1902 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1905 if (!empty($membershipSource)) {
1906 $memParams['source'] = $membershipSource;
1908 elseif (empty($membership->source
)) {
1909 $memParams['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
1910 $currentMembership['id'],
1915 if (!empty($currentMembership['id'])) {
1916 $ids['membership'] = $currentMembership['id'];
1918 $memParams['membership_activity_status'] = ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed';
1923 $memParams = array_merge([
1924 'contact_id' => $contactID,
1925 'membership_type_id' => $membershipTypeID,
1929 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
1931 foreach (['join_date', 'start_date', 'end_date'] as $dateType) {
1932 $memParams[$dateType] = $formDates[$dateType] ??
NULL;
1933 if (empty($memParams[$dateType])) {
1934 $memParams[$dateType] = $dates[$dateType] ??
NULL;
1938 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(CRM_Utils_Date
::customFormat($dates['start_date'],
1941 CRM_Utils_Date
::customFormat($dates['end_date'],
1944 CRM_Utils_Date
::customFormat($dates['join_date'],
1952 $updateStatusId = $status['id'] ??
NULL;
1955 // if IPN/Pay-Later set status to: PENDING
1956 $updateStatusId = array_search('Pending', $allStatus);
1959 if (!empty($membershipSource)) {
1960 $memParams['source'] = $membershipSource;
1962 $memParams['is_test'] = $is_test;
1963 $memParams['is_pay_later'] = $isPayLater;
1965 // Putting this in an IF is precautionary as it seems likely that it would be ignored if empty, but
1966 // perhaps shouldn't be?
1967 if ($contributionRecurID) {
1968 $memParams['contribution_recur_id'] = $contributionRecurID;
1971 //if we decided status here and want to skip status
1972 //calculation in create( ); then need to pass 'skipStatusCal'.
1973 if ($updateStatusId) {
1974 $memParams['status_id'] = $updateStatusId;
1975 $memParams['skipStatusCal'] = TRUE;
1978 //since we are renewing,
1979 //make status override false.
1980 $memParams['is_override'] = FALSE;
1982 //CRM-4027, create log w/ individual contact.
1984 // @todo this param is likely unused now.
1985 $memParams['is_for_organization'] = TRUE;
1987 $params['modified_id'] = $modifiedID ??
$contactID;
1989 $memParams['contribution'] = $contribution;
1990 $memParams['custom'] = $customFieldsFormatted;
1991 // Load all line items & process all in membership. Don't do in contribution.
1992 // Relevant tests in api_v3_ContributionPageTest.
1993 $memParams['line_item'] = $lineItems;
1994 // @todo stop passing $ids (membership and userId may be set by this point)
1995 $membership = self
::create($memParams, $ids);
1997 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
1998 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
1999 $membership->find(TRUE);
2001 return [$membership, $renewalMode, $dates];
2005 * Get line items representing the default price set.
2007 * @param int $membershipOrg
2008 * @param int $membershipTypeID
2009 * @param float $total_amount
2010 * @param int $priceSetId
2014 public static function setQuickConfigMembershipParameters($membershipOrg, $membershipTypeID, $total_amount, $priceSetId) {
2015 $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
2017 // The name of the price field corresponds to the membership_type organization contact.
2019 'price_set_id' => $priceSetId,
2020 'name' => $membershipOrg,
2023 CRM_Price_BAO_PriceField
::retrieve($params, $results);
2025 if (!empty($results)) {
2026 $fields[$results['id']] = $priceSets['fields'][$results['id']];
2027 $fid = $results['id'];
2028 $editedFieldParams = [
2029 'price_field_id' => $results['id'],
2030 'membership_type_id' => $membershipTypeID,
2033 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $results);
2034 $fields[$fid]['options'][$results['id']] = $priceSets['fields'][$fid]['options'][$results['id']];
2035 if (!empty($total_amount)) {
2036 $fields[$fid]['options'][$results['id']]['amount'] = $total_amount;
2040 $fieldID = key($fields);
2042 'price_set_id' => $priceSetId,
2043 'price_sets' => $priceSets,
2044 'fields' => $fields,
2046 'price_' . $fieldID => $results['id'] ??
NULL,
2049 return $returnParams;
2053 * Update the status of all deceased members to deceased.
2056 * Count of updated contacts.
2058 * @throws \CiviCRM_API3_Exception
2059 * @throws \CRM_Core_Exception
2061 protected static function updateDeceasedMembersStatuses() {
2064 $deceasedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Deceased');
2066 // 'create' context for buildOptions returns only if enabled.
2067 $allStatus = self
::buildOptions('status_id', 'create');
2068 if (array_key_exists($deceasedStatusId, $allStatus) === FALSE) {
2069 // Deceased status is an admin status & is required. We want to fail early if
2070 // it is not present or active.
2071 // We could make the case 'some databases just don't use deceased so we will check
2072 // for the presence of a deceased contact in the DB before rejecting.
2073 if (CRM_Core_DAO
::singleValueQuery('
2074 SELECT count(*) FROM civicrm_contact WHERE is_deceased = 0'
2076 throw new CRM_Core_Exception(
2077 ts("Deceased Membership status is missing or not active. <a href='%1'>Click here to check</a>.",
2078 [1 => CRM_Utils_System
::url('civicrm/admin/member/membershipStatus', 'reset=1')]
2082 $deceasedDAO = CRM_Core_DAO
::executeQuery(
2084 SELECT membership.id as membership_id
2085 FROM civicrm_membership membership
2086 INNER JOIN civicrm_contact ON membership.contact_id = civicrm_contact.id
2087 INNER JOIN civicrm_membership_type ON membership.membership_type_id = civicrm_membership_type.id
2088 AND civicrm_membership_type.is_active = 1
2089 WHERE membership.is_test = 0
2090 AND civicrm_contact.is_deceased = 1
2091 AND membership.status_id <> %1
2093 [1 => [$deceasedStatusId, 'Integer']]
2095 while ($deceasedDAO->fetch()) {
2096 civicrm_api3('membership', 'create', [
2097 'id' => $deceasedDAO->membership_id
,
2098 'status_id' => $deceasedStatusId,
2099 'createActivity' => TRUE,
2100 'skipStatusCal' => TRUE,
2101 'skipRecentView' => TRUE,
2109 * Does the existing membership match the required membership.
2111 * Check before updating that the params are not a match - this is part of avoiding
2112 * a loop if we have already updated.
2114 * https://issues.civicrm.org/jira/browse/CRM-4213
2115 * @param array $params
2117 * @param array $membership
2121 protected static function matchesRequiredMembership($params, $membership) {
2122 foreach (['start_date', 'end_date'] as $date) {
2123 if (CRM_Utils_Time
::strtotime($params[$date]) !== CRM_Utils_Time
::strtotime($membership[$date])) {
2126 if ((int) $params['status_id'] !== (int) $membership['status_id']) {
2129 if ((int) $params['membership_type_id'] !== (int) $membership['membership_type_id']) {
2137 * Params of new membership.
2139 * @param array $params
2142 * @throws \CiviCRM_API3_Exception
2144 protected static function hasExistingInheritedMembership($params) {
2145 foreach (civicrm_api3('Membership', 'get', ['contact_id' => $params['contact_id']])['values'] as $membership) {
2146 if (!empty($membership['owner_membership_id'])
2147 && $membership['membership_type_id'] === $params['membership_type_id']
2148 && (int) $params['owner_membership_id'] !== (int) $membership['owner_membership_id']
2150 // Inheriting it from another contact, don't update here.
2153 if (self
::matchesRequiredMembership($params, $membership)) {
2161 * Process price set and line items.
2163 * @param int $membershipId
2164 * @param array $lineItem
2166 * @throws \CiviCRM_API3_Exception
2168 public function processPriceSet($membershipId, $lineItem) {
2169 //FIXME : need to move this too
2170 if (!$membershipId ||
!is_array($lineItem)
2171 || CRM_Utils_System
::isNull($lineItem)
2176 foreach ($lineItem as $priceSetId => $values) {
2180 foreach ($values as $line) {
2181 $line['entity_table'] = 'civicrm_membership';
2182 $line['entity_id'] = $membershipId;
2183 CRM_Price_BAO_LineItem
::create($line);
2189 * Retrieve the contribution id for the associated Membership id.
2190 * @todo we should get this off the line item
2192 * @param int $membershipId
2195 * if more than one payment associated with membership id need to be returned.
2199 * @todo we should get this off the line item
2202 public static function getMembershipContributionId($membershipId, $all = FALSE) {
2204 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
2205 $membershipPayment->membership_id
= $membershipId;
2206 if ($all && $membershipPayment->find()) {
2207 $contributionIds = [];
2208 while ($membershipPayment->fetch()) {
2209 $contributionIds[] = $membershipPayment->contribution_id
;
2211 return $contributionIds;
2214 if ($membershipPayment->find(TRUE)) {
2215 return $membershipPayment->contribution_id
;
2221 * The function checks and updates the status of all membership records for a given domain using the
2222 * calc_membership_status and update_contact_membership APIs.
2225 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
2227 * @param array $params
2228 * only_active_membership_types, exclude_test_memberships, exclude_membership_status_ids
2232 * @throws \CiviCRM_API3_Exception
2233 * @throws \CRM_Core_Exception
2235 public static function updateAllMembershipStatus($params = []) {
2236 // We want all of the statuses as id => name, even the disabled ones (cf.
2237 // CRM-15475), to identify which are Pending, Deceased, Cancelled, and
2239 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'validate');
2240 if (empty($params['exclude_membership_status_ids'])) {
2241 $params['exclude_membership_status_ids'] = [
2242 array_search('Pending', $allStatus),
2243 array_search('Cancelled', $allStatus),
2244 array_search('Expired', $allStatus) ?
: 0,
2245 array_search('Deceased', $allStatus),
2248 // Deceased is *always* excluded because it is has very specific processing below.
2249 elseif (!in_array(array_search('Deceased', $allStatus), $params['exclude_membership_status_ids'])) {
2250 $params['exclude_membership_status_ids'][] = array_search('Deceased', $allStatus);
2253 for ($index = 0; $index < count($params['exclude_membership_status_ids']); $index++
) {
2254 $queryParams[$index] = [$params['exclude_membership_status_ids'][$index], 'Integer'];
2256 $membershipStatusClause = 'civicrm_membership.status_id NOT IN (%' . implode(', %', array_keys($queryParams)) . ')';
2258 // Tests for this function are in api_v3_JobTest. Please add tests for all updates.
2260 $updateCount = $processCount = self
::updateDeceasedMembersStatuses();
2262 $whereClauses[] = 'civicrm_contact.is_deceased = 0';
2263 if ($params['exclude_test_memberships']) {
2264 $whereClauses[] = 'civicrm_membership.is_test = 0';
2266 $whereClause = implode(' AND ', $whereClauses);
2267 $activeMembershipClause = '';
2268 if ($params['only_active_membership_types']) {
2269 $activeMembershipClause = ' AND civicrm_membership_type.is_active = 1';
2272 // This query retrieves ALL memberships of active types.
2274 SELECT civicrm_membership.id as membership_id,
2275 civicrm_membership.is_override as is_override,
2276 civicrm_membership.status_override_end_date as status_override_end_date,
2277 civicrm_membership.membership_type_id as membership_type_id,
2278 civicrm_membership.status_id as status_id,
2279 civicrm_membership.join_date as join_date,
2280 civicrm_membership.start_date as start_date,
2281 civicrm_membership.end_date as end_date,
2282 civicrm_membership.source as source,
2283 civicrm_contact.id as contact_id,
2284 civicrm_membership.owner_membership_id as owner_membership_id,
2285 civicrm_membership.contribution_recur_id as recur_id
2286 FROM civicrm_membership
2287 INNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )
2288 INNER JOIN civicrm_membership_type ON
2289 (civicrm_membership.membership_type_id = civicrm_membership_type.id {$activeMembershipClause})
2290 WHERE {$whereClause}";
2292 $query = $baseQuery . " AND civicrm_membership.is_override IS NOT NULL AND civicrm_membership.status_override_end_date IS NOT NULL";
2293 $dao1 = CRM_Core_DAO
::executeQuery($query);
2294 while ($dao1->fetch()) {
2295 self
::processOverriddenUntilDateMembership($dao1);
2298 $query = $baseQuery . " AND (civicrm_membership.is_override = 0 OR civicrm_membership.is_override IS NULL)
2299 AND {$membershipStatusClause}
2300 AND civicrm_membership.owner_membership_id IS NULL ";
2302 $allMembershipTypes = CRM_Member_BAO_MembershipType
::getAllMembershipTypes();
2304 $dao2 = CRM_Core_DAO
::executeQuery($query, $queryParams);
2306 while ($dao2->fetch()) {
2309 // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses
2310 //get the membership status as per id.
2311 $newStatus = civicrm_api3('membership_status', 'calc',
2313 'membership_id' => $dao2->membership_id
,
2314 'ignore_admin_only' => TRUE,
2317 $statusId = $newStatus['id'] ??
NULL;
2319 //process only when status change.
2321 $statusId != $dao2->status_id
2324 'id' => $dao2->membership_id
,
2325 'skipStatusCal' => TRUE,
2326 'skipRecentView' => TRUE,
2327 'status_id' => $statusId,
2328 'createActivity' => TRUE,
2331 //process member record.
2332 civicrm_api3('membership', 'create', $memberParams);
2336 $result['is_error'] = 0;
2337 $result['messages'] = ts('Processed %1 membership records. Updated %2 records.', [
2345 * Set is_override for the 'overridden until date' membership to
2346 * False and clears the 'until date' field in case the 'until date'
2347 * is equal or after today date.
2349 * @param CRM_Core_DAO $membership
2350 * The membership to be processed
2352 * @throws \CiviCRM_API3_Exception
2354 private static function processOverriddenUntilDateMembership($membership) {
2355 $isOverriddenUntilDate = !empty($membership->is_override
) && !empty($membership->status_override_end_date
);
2356 if (!$isOverriddenUntilDate) {
2360 $todayDate = new DateTime();
2361 $todayDate->setTime(0, 0);
2363 $overrideEndDate = new DateTime($membership->status_override_end_date
);
2364 $overrideEndDate->setTime(0, 0);
2366 $datesDifference = $todayDate->diff($overrideEndDate);
2367 $daysDifference = (int) $datesDifference->format('%R%a');
2368 if ($daysDifference <= 0) {
2370 'id' => $membership->membership_id
,
2371 'is_override' => FALSE,
2372 'status_override_end_date' => 'null',
2374 civicrm_api3('membership', 'create', $params);
2379 * Returns the membership types for a particular contact
2380 * who has lifetime membership without end date.
2382 * @param int $contactID
2383 * @param bool $isTest
2384 * @param bool $onlyLifeTime
2388 public static function getAllContactMembership($contactID, $isTest = FALSE, $onlyLifeTime = FALSE) {
2389 $contactMembershipType = [];
2391 return $contactMembershipType;
2394 $dao = new CRM_Member_DAO_Membership();
2395 $dao->contact_id
= $contactID;
2396 $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
2397 $dao->whereAdd("status_id != $pendingStatusId");
2400 $dao->is_test
= $isTest;
2403 $dao->whereAdd('is_test IS NULL OR is_test = 0');
2406 if ($onlyLifeTime) {
2407 $dao->whereAdd('end_date IS NULL');
2411 while ($dao->fetch()) {
2413 CRM_Core_DAO
::storeValues($dao, $membership);
2414 $contactMembershipType[$dao->membership_type_id
] = $membership;
2416 return $contactMembershipType;
2420 * Record contribution record associated with membership.
2421 * This will update an existing contribution if $params['contribution_id'] is passed in.
2422 * This will create a MembershipPayment to link the contribution and membership
2424 * @param array $params
2425 * Array of submitted params.
2427 * @return CRM_Contribute_BAO_Contribution
2428 * @throws \CRM_Core_Exception
2429 * @throws \CiviCRM_API3_Exception
2431 public static function recordMembershipContribution(&$params) {
2432 $contributionParams = [];
2433 $config = CRM_Core_Config
::singleton();
2434 $contributionParams['currency'] = $config->defaultCurrency
;
2435 $contributionParams['receipt_date'] = !empty($params['receipt_date']) ?
$params['receipt_date'] : 'null';
2436 $contributionParams['source'] = $params['contribution_source'] ??
NULL;
2437 $contributionParams['non_deductible_amount'] = 'null';
2438 $contributionParams['skipCleanMoney'] = TRUE;
2439 $contributionParams['payment_processor'] = $params['payment_processor_id'] ??
NULL;
2440 $contributionSoftParams = $params['soft_credit'] ??
NULL;
2441 $recordContribution = [
2446 'financial_type_id',
2447 'payment_instrument_id',
2451 'contribution_status_id',
2458 'contribution_recur_id',
2462 foreach ($recordContribution as $f) {
2463 $contributionParams[$f] = $params[$f] ??
NULL;
2466 if (!empty($params['contribution_id'])) {
2467 $contributionParams['id'] = $params['contribution_id'];
2469 // make entry in batch entity batch table
2470 if (!empty($params['batch_id'])) {
2471 $contributionParams['batch_id'] = $params['batch_id'];
2474 if (!empty($params['contribution_contact_id'])) {
2475 // deal with possibility of a different person paying for contribution
2476 $contributionParams['contact_id'] = $params['contribution_contact_id'];
2479 if (!empty($params['processPriceSet']) &&
2480 !empty($params['lineItems'])
2482 $contributionParams['line_item'] = $params['lineItems'] ??
NULL;
2485 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams);
2487 //CRM-13981, create new soft-credit record as to record payment from different person for this membership
2488 if (!empty($contributionSoftParams)) {
2489 if (!empty($params['batch_id'])) {
2490 foreach ($contributionSoftParams as $contributionSoft) {
2491 $contributionSoft['contribution_id'] = $contribution->id
;
2492 $contributionSoft['currency'] = $contribution->currency
;
2493 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoft);
2497 $contributionSoftParams['contribution_id'] = $contribution->id
;
2498 $contributionSoftParams['currency'] = $contribution->currency
;
2499 $contributionSoftParams['amount'] = $contribution->total_amount
;
2500 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoftParams);
2504 // store contribution id
2505 $params['contribution_id'] = $contribution->id
;
2507 // Create membership payment if it does not already exist
2508 $membershipPayment = civicrm_api3('MembershipPayment', 'get', [
2509 'contribution_id' => $contribution->id
,
2511 if (empty($membershipPayment['count'])) {
2512 civicrm_api3('MembershipPayment', 'create', [
2513 'membership_id' => $params['membership_id'],
2514 'contribution_id' => $contribution->id
,
2518 return $contribution;
2522 * @todo document me - I seem a bit out of date....
2524 public static function _getActTypes() {
2525 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2526 self
::$_renewalActType = CRM_Utils_Array
::key('Membership Renewal', $activityTypes);
2527 self
::$_signupActType = CRM_Utils_Array
::key('Membership Signup', $activityTypes);
2531 * Get all Cancelled Membership(s) for a contact
2533 * @param int $contactID
2535 * @param bool $isTest
2539 * Array of membership type
2541 public static function getContactsCancelledMembership($contactID, $isTest = FALSE) {
2545 $query = 'SELECT membership_type_id FROM civicrm_membership WHERE contact_id = %1 AND status_id = %2 AND is_test = %3';
2547 1 => [$contactID, 'Integer'],
2552 CRM_Member_PseudoConstant
::membershipStatus(
2554 " name = 'Cancelled' ",
2562 3 => [$isTest, 'Boolean'],
2565 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
2566 $cancelledMembershipIds = [];
2567 while ($dao->fetch()) {
2568 $cancelledMembershipIds[] = $dao->membership_type_id
;
2570 return $cancelledMembershipIds;
2574 * Merges the memberships from otherContactID to mainContactID.
2576 * General idea is to merge memberships in regards to their type. We
2577 * move the other contact’s contributions to the main contact’s
2578 * membership which has the same type (if any) and then we update
2579 * membership to avoid loosing `join_date`, `end_date`, and
2580 * `status_id`. In this function, we don’t touch the contributions
2581 * directly (CRM_Dedupe_Merger::moveContactBelongings() takes care
2584 * This function adds new SQL queries to the $sqlQueries parameter.
2586 * @param int $mainContactID
2587 * Contact id of main contact record.
2588 * @param int $otherContactID
2589 * Contact id of record which is going to merge.
2590 * @param array $sqlQueries
2591 * (reference) array of SQL queries to be executed.
2592 * @param array $tables
2593 * List of tables that have to be merged.
2594 * @param array $tableOperations
2595 * Special options/params for some tables to be merged.
2597 * @see CRM_Dedupe_Merger::cpTables()
2599 public static function mergeMemberships($mainContactID, $otherContactID, &$sqlQueries, $tables, $tableOperations) {
2601 * If the user requests not to merge memberships but to add them,
2602 * just attribute the `civicrm_membership` to the
2603 * `$mainContactID`. We have to do this here since the general
2604 * merge process is bypassed by this function.
2606 if (array_key_exists("civicrm_membership", $tableOperations) && $tableOperations['civicrm_membership']['add']) {
2607 $sqlQueries[] = "UPDATE IGNORE civicrm_membership SET contact_id = $mainContactID WHERE contact_id = $otherContactID";
2612 * Retrieve all memberships that belongs to each contacts and
2613 * keep track of each membership type.
2615 $mainContactMemberships = [];
2616 $otherContactMemberships = [];
2618 $sql = "SELECT id, membership_type_id FROM civicrm_membership membership WHERE contact_id = %1";
2619 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$mainContactID, "Integer"]]);
2620 while ($dao->fetch()) {
2621 $mainContactMemberships[$dao->id
] = $dao->membership_type_id
;
2624 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$otherContactID, "Integer"]]);
2625 while ($dao->fetch()) {
2626 $otherContactMemberships[$dao->id
] = $dao->membership_type_id
;
2630 * For each membership, move related contributions to the main
2631 * contact’s membership (by updating `membership_payments`). Then,
2632 * update membership’s `join_date` (if the other membership’s
2633 * join_date is older) and `end_date` (if the other membership’s
2634 * `end_date` is newer) and `status_id` (if the newly calculated
2635 * status is different).
2637 * FIXME: what should we do if we have multiple memberships with
2638 * the same type (currently we only take the first one)?
2641 foreach ($otherContactMemberships as $otherMembershipId => $otherMembershipTypeId) {
2642 if ($newMembershipId = array_search($otherMembershipTypeId, $mainContactMemberships)) {
2645 * Move other membership’s contributions to the main one only
2646 * if user requested to merge contributions.
2648 if (!empty($tables) && in_array('civicrm_contribution', $tables)) {
2649 $newSql[] = "UPDATE civicrm_membership_payment SET membership_id=$newMembershipId WHERE membership_id=$otherMembershipId";
2652 $sql = "SELECT * FROM civicrm_membership membership WHERE id = %1";
2654 $newMembership = CRM_Member_DAO_Membership
::findById($newMembershipId);
2655 $otherMembership = CRM_Member_DAO_Membership
::findById($otherMembershipId);
2658 if (new DateTime($otherMembership->join_date
) < new DateTime($newMembership->join_date
)) {
2659 $updates["join_date"] = $otherMembership->join_date
;
2662 if (new DateTime($otherMembership->end_date
) > new DateTime($newMembership->end_date
)) {
2663 $updates["end_date"] = $otherMembership->end_date
;
2666 if (count($updates)) {
2671 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
2672 $updates["start_date"] ??
$newMembership->start_date
,
2673 $updates["end_date"] ??
$newMembership->end_date
,
2674 $updates["join_date"] ??
$newMembership->join_date
,
2681 if (!empty($status['id']) and $status['id'] != $newMembership->status_id
) {
2682 $updates['status_id'] = $status['id'];
2686 foreach ($updates as $k => $v) {
2687 $updates_sql[] = "$k = '{$v}'";
2690 $newSql[] = sprintf("UPDATE civicrm_membership SET %s WHERE id=%s", implode(", ", $updates_sql), $newMembershipId);
2691 $newSql[] = sprintf("DELETE FROM civicrm_membership WHERE id=%s", $otherMembershipId);
2697 $sqlQueries = array_merge($sqlQueries, $newSql);
2701 * Update membership status to deceased.
2702 * function return the status message for updated membership.
2704 * @param array $deceasedParams
2709 * @param string $contactType
2711 * @return null|string
2712 * $updateMembershipMsg string status message for updated membership.
2714 public static function updateMembershipStatus($deceasedParams, $contactType) {
2715 $updateMembershipMsg = NULL;
2716 $contactId = $deceasedParams['contact_id'];
2717 $deceasedDate = $deceasedParams['deceased_date'];
2719 // process to set membership status to deceased for both active/inactive membership
2721 $contactType === 'Individual' &&
2722 !empty($deceasedParams['is_deceased'])
2725 $userId = CRM_Core_Session
::getLoggedInContactID() ?
: $contactId;
2727 // get deceased status id
2728 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2729 $deceasedStatusId = array_search('Deceased', $allStatus);
2730 if (!$deceasedStatusId) {
2731 return $updateMembershipMsg;
2734 $today = CRM_Utils_Time
::time();
2735 if ($deceasedDate && CRM_Utils_Time
::strtotime($deceasedDate) > $today) {
2736 return $updateMembershipMsg;
2739 // get non deceased membership
2740 $dao = new CRM_Member_DAO_Membership();
2741 $dao->contact_id
= $contactId;
2742 $dao->whereAdd("status_id != $deceasedStatusId");
2744 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2745 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2747 while ($dao->fetch()) {
2748 // update status to deceased (for both active/inactive membership )
2749 CRM_Core_DAO
::setFieldValue('CRM_Member_DAO_Membership', $dao->id
,
2750 'status_id', $deceasedStatusId
2753 // add membership log
2755 'membership_id' => $dao->id
,
2756 'status_id' => $deceasedStatusId,
2757 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
2758 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
2759 'modified_id' => $userId,
2760 'modified_date' => CRM_Utils_Time
::date('Ymd'),
2761 'membership_type_id' => $dao->membership_type_id
,
2762 'max_related' => $dao->max_related
,
2765 CRM_Member_BAO_MembershipLog
::add($membershipLog);
2767 //create activity when membership status is changed
2769 'subject' => "Status changed from {$allStatus[$dao->status_id]} to {$allStatus[$deceasedStatusId]}",
2770 'source_contact_id' => $userId,
2771 'target_contact_id' => $dao->contact_id
,
2772 'source_record_id' => $dao->id
,
2773 'activity_type_id' => array_search('Change Membership Status', $activityTypes),
2777 'activity_date_time' => CRM_Utils_Time
::date('Y-m-d H:i:s'),
2779 'is_current_revision' => 1,
2782 civicrm_api('activity', 'create', $activityParam);
2789 CRM_Core_Session
::setStatus(ts("%1 Current membership(s) for this contact have been set to 'Deceased' status.",
2794 return $updateMembershipMsg;