3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
12 use Civi\API\Exception\UnauthorizedException
;
13 use Civi\Api4\MembershipType
;
18 * @copyright CiviCRM LLC https://civicrm.org/licensing
20 class CRM_Member_BAO_Membership
extends CRM_Member_DAO_Membership
{
23 * Static field for all the membership information that we can potentially import.
27 public static $_importableFields = NULL;
29 public static $_renewalActType = NULL;
31 public static $_signupActType = NULL;
36 public function __construct() {
37 parent
::__construct();
41 * Takes an associative array and creates a membership object.
43 * the function extracts all the params it needs to initialize the created
44 * membership object. The params array could contain additional unused name/value
47 * @param array $params
48 * (reference ) an assoc array of name/value pairs.
50 * @return CRM_Member_BAO_Membership
51 * @throws \CiviCRM_API3_Exception
53 public static function add(&$params) {
54 $oldStatus = $oldType = NULL;
56 CRM_Utils_Hook
::pre('edit', 'Membership', $params['id'], $params);
59 CRM_Utils_Hook
::pre('create', 'Membership', NULL, $params);
62 // we do this after the hooks are called in case it has been altered
64 $membershipObj = new CRM_Member_DAO_Membership();
65 $membershipObj->id
= $id;
66 $membershipObj->find();
67 while ($membershipObj->fetch()) {
68 $oldStatus = $membershipObj->status_id
;
69 $oldType = $membershipObj->membership_type_id
;
73 if (array_key_exists('is_override', $params) && !$params['is_override']) {
74 $params['is_override'] = 'null';
77 $membership = new CRM_Member_BAO_Membership();
78 $membership->copyValues($params);
79 $membership->id
= $id;
83 if (empty($membership->contact_id
) ||
empty($membership->status_id
)) {
84 // this means we are in renewal mode and are just updating the membership
85 // record or this is an API update call and all fields are not present in the update record
86 // however the hooks don't care and want all data CRM-7784
87 $tempMembership = new CRM_Member_DAO_Membership();
88 $tempMembership->id
= $membership->id
;
89 $tempMembership->find(TRUE);
90 $membership = $tempMembership;
93 //get the log start date.
94 //it is set during renewal of membership.
95 $logStartDate = $params['log_start_date'] ??
NULL;
96 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : CRM_Utils_Date
::isoToMysql($membership->start_date
);
97 $values = self
::getStatusANDTypeValues($membership->id
);
100 'membership_id' => $membership->id
,
101 'status_id' => $membership->status_id
,
102 'start_date' => $logStartDate,
103 'end_date' => CRM_Utils_Date
::isoToMysql($membership->end_date
),
104 'modified_date' => CRM_Utils_Time
::date('Ymd'),
105 'membership_type_id' => $values[$membership->id
]['membership_type_id'],
106 'max_related' => $membership->max_related
,
109 if (!empty($params['modified_id'])) {
110 $membershipLog['modified_id'] = $params['modified_id'];
112 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
113 elseif (CRM_Core_Session
::singleton()->get('userID')) {
114 $membershipLog['modified_id'] = CRM_Core_Session
::singleton()->get('userID');
117 $membershipLog['modified_id'] = $membership->contact_id
;
120 CRM_Member_BAO_MembershipLog
::add($membershipLog);
122 // reset the group contact cache since smart groups might be affected due to this
123 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
125 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
127 'status_id' => $params['membership_activity_status'] ??
'Completed',
129 if (in_array($allStatus[$membership->status_id
], ['Pending', 'Grace'])) {
130 $activityParams['status_id'] = 'Scheduled';
132 $activityParams['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', $activityParams['status_id']);
134 $targetContactID = $membership->contact_id
;
135 if (!empty($params['is_for_organization'])) {
136 // @todo - deprecate is_for_organization, require modified_id
137 $targetContactID = $params['modified_id'] ??
NULL;
140 // add custom field values
141 if (!empty($params['custom']) && is_array($params['custom'])
143 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_membership', $membership->id
);
147 if ($membership->status_id
!= $oldStatus) {
148 CRM_Activity_BAO_Activity
::addActivity($membership,
149 'Change Membership Status',
152 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
153 'source_contact_id' => $membershipLog['modified_id'],
154 'priority_id' => 'Normal',
158 if (isset($membership->membership_type_id
) && $membership->membership_type_id
!= $oldType) {
159 $membershipTypes = CRM_Member_BAO_Membership
::buildOptions('membership_type_id', 'get');
160 CRM_Activity_BAO_Activity
::addActivity($membership,
161 'Change Membership Type',
164 'subject' => "Type changed from {$membershipTypes[$oldType]} to {$membershipTypes[$membership->membership_type_id]}",
165 'source_contact_id' => $membershipLog['modified_id'],
166 'priority_id' => 'Normal',
171 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
172 $activityParams['id'] = civicrm_api3('Activity', 'Get', [
173 'source_record_id' => $membership->id
,
174 'activity_type_id' => $activityType,
175 'status_id' => 'Scheduled',
177 // 1. Update Schedule Membership Signup/Renwal activity to completed on successful payment of pending membership
178 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
179 if (!empty($params['membership_activity_status']) && (!empty($activityParams['id']) ||
$activityType == 'Membership Renewal')) {
180 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $targetContactID, $activityParams);
185 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
188 CRM_Activity_BAO_Activity
::addActivity($membership, 'Membership Signup', $targetContactID, $activityParams);
189 CRM_Utils_Hook
::post('create', 'Membership', $membership->id
, $membership);
196 * Fetch the object and store the values in the values array.
198 * @param array $params
199 * Input parameters to find object.
200 * @param array $values
201 * Output values of the object.
202 * @param bool $active
203 * Do you want only active memberships to.
206 * @return CRM_Member_BAO_Membership|null
207 * The found object or null
209 public static function &getValues(&$params, &$values, $active = FALSE) {
210 if (empty($params)) {
213 $membership = new CRM_Member_BAO_Membership();
215 $membership->copyValues($params);
218 while ($membership->fetch()) {
220 (!CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
221 $membership->status_id
,
228 CRM_Core_DAO
::storeValues($membership, $values[$membership->id
]);
229 $memberships[$membership->id
] = $membership;
236 * Takes an associative array and creates a membership object.
238 * @param array $params
239 * (reference ) an assoc array of name/value pairs.
241 * Deprecated parameter The array that holds all the db ids.
243 * @return CRM_Member_BAO_Membership|CRM_Core_Error
244 * @throws \CiviCRM_API3_Exception
246 * @throws CRM_Core_Exception
248 public static function create(&$params, $ids = []) {
250 if (!empty($params['membership_type_id'])) {
251 $memTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipType($params['membership_type_id']);
252 $isLifeTime = $memTypeDetails['duration_unit'] === 'lifetime' ?
TRUE : FALSE;
254 // always calculate status if is_override/skipStatusCal is not true.
255 // giving respect to is_override during import. CRM-4012
257 // To skip status calculation we should use 'skipStatusCal'.
258 // eg pay later membership, membership update cron CRM-3984
260 if (empty($params['skipStatusCal'])) {
262 foreach (['start_date', 'end_date', 'join_date'] as $dateField) {
263 if (!empty($params[$dateField]) && $params[$dateField] !== 'null' && strpos($params[$dateField], date('Ymd', CRM_Utils_Time
::strtotime(trim($params[$dateField])))) !== 0) {
264 $params[$dateField] = date('Ymd', CRM_Utils_Time
::strtotime(trim($params[$dateField])));
265 // @todo enable this once core is using the api.
266 // CRM_Core_Error::deprecatedWarning('Relying on the BAO to clean up dates is deprecated. Call membership create via the api');
268 if (!empty($params['id']) && empty($params[$dateField]) && !($isLifeTime && $dateField == 'end_date')) {
269 $fieldsToLoad[] = $dateField;
272 if (!empty($fieldsToLoad)) {
273 $membership = civicrm_api3('Membership', 'getsingle', ['id' => $params['id'], 'return' => $fieldsToLoad]);
274 foreach ($fieldsToLoad as $fieldToLoad) {
275 $params[$fieldToLoad] = $membership[$fieldToLoad];
278 if (empty($params['id'])
279 && (empty($params['start_date']) ||
empty($params['join_date']) ||
(empty($params['end_date']) && !$isLifeTime))) {
280 // This is a new membership, calculate the membership dates.
281 $calcDates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType(
282 $params['membership_type_id'],
283 $params['join_date'] ??
NULL,
284 $params['start_date'] ??
NULL,
285 $params['end_date'] ??
NULL,
286 $params['num_terms'] ??
1
292 $params['start_date'] = $params['start_date'] ??
($calcDates['start_date'] ??
'null');
293 $params['end_date'] = $params['end_date'] ??
($calcDates['end_date'] ??
'null');
294 $params['join_date'] = $params['join_date'] ??
($calcDates['join_date'] ??
'null');
296 //fix for CRM-3570, during import exclude the statuses those having is_admin = 1
297 $excludeIsAdmin = $params['exclude_is_admin'] ??
FALSE;
299 //CRM-3724 always skip is_admin if is_override != true.
300 if (!$excludeIsAdmin && empty($params['is_override'])) {
301 $excludeIsAdmin = TRUE;
304 if (empty($params['status_id']) && empty($params['is_override'])) {
305 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($params['start_date'], $params['end_date'], $params['join_date'],
306 'now', $excludeIsAdmin, $params['membership_type_id'] ??
NULL, $params
308 if (empty($calcStatus)) {
309 throw new CRM_Core_Exception(ts("The membership cannot be saved because the status cannot be calculated for start_date: {$params['start_date']} end_date {$params['end_date']} join_date {$params['join_date']} as at " . CRM_Utils_Time
::date('Y-m-d H:i:s')));
311 $params['status_id'] = $calcStatus['id'];
315 // data cleanup only: all verifications on number of related memberships are done upstream in:
316 // CRM_Member_BAO_Membership::createRelatedMemberships()
317 // CRM_Contact_BAO_Relationship::relatedMemberships()
318 if (!empty($params['owner_membership_id'])) {
319 unset($params['max_related']);
322 // if membership allows related, default max_related to value in membership_type
323 if (!array_key_exists('max_related', $params) && !empty($params['membership_type_id'])) {
324 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipType($params['membership_type_id']);
325 if (isset($membershipType['relationship_type_id'])) {
326 $params['max_related'] = $membershipType['max_related'] ??
NULL;
331 $transaction = new CRM_Core_Transaction();
333 $params['id'] = $params['id'] ??
$ids['membership'] ??
NULL;
334 $membership = self
::add($params);
336 if (is_a($membership, 'CRM_Core_Error')) {
337 $transaction->rollback();
341 $params['membership_id'] = $membership->id
;
342 // For api v4 we skip all of this stuff. There is an expectation that v4 users either use
343 // the order api, or handle any financial / related processing themselves.
344 // Note that the processing below is fairly intertwined with core usage and in some places
345 // problematic or to be removed.
346 // Note the choice of 'version' as a parameter is to make it
347 // unavailable through apiv3.
348 // once we are rid of direct calls to the BAO::create from core
349 // we will deprecate this stuff into the v3 api.
350 if (($params['version'] ??
0) !== 4) {
351 // @todo further cleanup required to remove use of $ids['contribution'] from here
352 if (isset($ids['membership'])) {
353 $contributionID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment',
358 // @todo this is a temporary step to removing $ids['contribution'] completely
359 if (empty($params['contribution_id']) && !empty($contributionID)) {
360 $params['contribution_id'] = $contributionID;
364 // This code ensures a line item is created but it is recommended you pass in 'skipLineItem' or 'line_item'
365 if (empty($params['line_item']) && !empty($params['membership_type_id']) && empty($params['skipLineItem'])) {
366 CRM_Price_BAO_LineItem
::getLineItemArray($params, NULL, 'membership', $params['membership_type_id']);
368 $params['skipLineItem'] = TRUE;
370 // Record contribution for this membership and create a MembershipPayment
371 // @todo deprecate this.
372 if (!empty($params['contribution_status_id'])) {
373 $memInfo = array_merge($params, ['membership_id' => $membership->id
]);
374 $params['contribution'] = self
::recordMembershipContribution($memInfo);
377 // If the membership has no associated contribution then we ensure
378 // the line items are 'correct' here. This is a lazy legacy
379 // hack whereby they are deleted and recreated
380 if (empty($contributionID)) {
381 if (!empty($params['lineItems'])) {
382 $params['line_item'] = $params['lineItems'];
384 // do cleanup line items if membership edit the Membership type.
385 if (!empty($ids['membership'])) {
386 CRM_Price_BAO_LineItem
::deleteLineItems($ids['membership'], 'civicrm_membership');
388 // @todo - we should ONLY do the below if a contribution is created. Let's
389 // get some deprecation notices in here & see where it's hit & work to eliminate.
390 // This could happen if there is no contribution or we are in one of many
391 // weird and wonderful flows. This is scary code. Keep adding tests.
392 if (!empty($params['line_item']) && empty($params['contribution_id'])) {
394 foreach ($params['line_item'] as $priceSetId => $lineItems) {
395 foreach ($lineItems as $lineIndex => $lineItem) {
396 $lineMembershipType = $lineItem['membership_type_id'] ??
NULL;
397 if (!empty($params['contribution'])) {
398 $params['line_item'][$priceSetId][$lineIndex]['contribution_id'] = $params['contribution']->id
;
400 if ($lineMembershipType && $lineMembershipType == ($params['membership_type_id'] ??
NULL)) {
401 $params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $membership->id
;
402 $params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_membership';
404 elseif (!$lineMembershipType && !empty($params['contribution'])) {
405 $params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $params['contribution']->id
;
406 $params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_contribution';
410 CRM_Price_BAO_LineItem
::processPriceSet(
412 $params['line_item'],
413 $params['contribution'] ??
NULL
419 $transaction->commit();
421 self
::createRelatedMemberships($params, $membership);
423 if (empty($params['skipRecentView'])) {
424 self
::addToRecentItems($membership);
431 * @param \CRM_Member_DAO_Membership $membership
433 private static function addToRecentItems($membership) {
434 $url = CRM_Utils_System
::url('civicrm/contact/view/membership',
435 "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
437 if (empty($membership->membership_type_id
)) {
438 // ie in an update situation.
439 $membership->find(TRUE);
441 $title = CRM_Contact_BAO_Contact
::displayName($membership->contact_id
) . ' - ' . ts('Membership Type:')
442 . ' ' . CRM_Core_PseudoConstant
::getLabel('CRM_Member_BAO_Membership', 'membership_type_id', $membership->membership_type_id
);
445 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::UPDATE
)) {
446 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
447 "action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
450 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::DELETE
)) {
451 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
452 "action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
456 // add the recently created Membership
457 CRM_Utils_Recent
::add($title,
461 $membership->contact_id
,
468 * Check the membership extended through relationship.
470 * @param int $membershipTypeID
471 * Membership type id.
472 * @param int $contactId
478 * array of contact_id of all related contacts.
480 * @throws \CRM_Core_Exception
481 * @throws \CiviCRM_API3_Exception
483 public static function checkMembershipRelationship($membershipTypeID, $contactId, $action = CRM_Core_Action
::ADD
) {
486 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipType($membershipTypeID);
489 if (isset($membershipType['relationship_type_id'])) {
490 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
491 CRM_Contact_BAO_Relationship
::CURRENT
493 if ($action & CRM_Core_Action
::UPDATE
) {
494 $pastRelationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
495 CRM_Contact_BAO_Relationship
::PAST
497 $relationships = array_merge($relationships, $pastRelationships);
501 if (!empty($relationships)) {
502 // check for each contact relationships
503 foreach ($relationships as $values) {
504 //get details of the relationship type
505 $relType = ['id' => $values['civicrm_relationship_type_id']];
507 CRM_Contact_BAO_RelationshipType
::retrieve($relType, $relValues);
508 // Check if contact's relationship type exists in membership type
510 $bidirectional = FALSE;
511 foreach ($membershipType['relationship_type_id'] as $key => $value) {
512 $relTypeDirs[] = $value . '_' . $membershipType['relationship_direction'][$key];
513 if (in_array($value, $relType) &&
514 $relValues['name_a_b'] == $relValues['name_b_a']
516 $bidirectional = TRUE;
520 $relTypeDir = $values['civicrm_relationship_type_id'] . '_' . $values['rtype'];
521 if ($bidirectional ||
in_array($relTypeDir, $relTypeDirs)) {
522 // $values['status'] is going to have value for
523 // current or past relationships.
524 $contacts[$values['cid']] = $values['status'];
529 // Sort by contact_id ascending
535 * Retrieve DB object based on input parameters.
537 * It also stores all the retrieved values in the default array.
539 * @param array $params
540 * (reference ) an assoc array of name/value pairs.
541 * @param array $defaults
542 * (reference ) an assoc array to hold the name / value pairs.
543 * in a hierarchical manner
545 * @return CRM_Member_BAO_Membership
547 public static function retrieve(&$params, &$defaults) {
548 $membership = new CRM_Member_DAO_Membership();
550 $membership->copyValues($params);
552 if ($membership->find(TRUE)) {
553 CRM_Core_DAO
::storeValues($membership, $defaults);
555 //get the membership status and type values.
556 $statusANDType = self
::getStatusANDTypeValues($membership->id
);
557 foreach (['status', 'membership_type'] as $fld) {
558 $defaults[$fld] = $statusANDType[$membership->id
][$fld] ??
NULL;
560 if (!empty($statusANDType[$membership->id
]['is_current_member'])) {
561 $defaults['active'] = TRUE;
571 * Get membership status and membership type values.
573 * @param int $membershipId
574 * Membership id of values to return.
577 * Array of key value pairs
579 public static function getStatusANDTypeValues($membershipId) {
581 if (!$membershipId) {
585 SELECT membership.id as id,
586 status.id as status_id,
587 status.label as status,
588 status.is_current_member as is_current_member,
589 type.id as membership_type_id,
590 type.name as membership_type,
591 type.relationship_type_id as relationship_type_id
592 FROM civicrm_membership membership
593 INNER JOIN civicrm_membership_status status ON ( status.id = membership.status_id )
594 INNER JOIN civicrm_membership_type type ON ( type.id = membership.membership_type_id )
595 WHERE membership.id = %1';
596 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$membershipId, 'Positive']]);
601 'membership_type_id',
603 'relationship_type_id',
605 while ($dao->fetch()) {
606 foreach ($properties as $property) {
607 $values[$dao->id
][$property] = $dao->$property;
617 * Wrapper for most delete calls. Use this unless you JUST want to delete related memberships w/o deleting the parent.
619 * @param int $membershipId
620 * Membership id that needs to be deleted.
621 * @param bool $preserveContrib
624 * Id of deleted Membership on success, false otherwise.
626 public static function del($membershipId, $preserveContrib = FALSE) {
627 //delete related first and then delete parent.
628 self
::deleteRelatedMemberships($membershipId);
629 return self
::deleteMembership($membershipId, $preserveContrib);
635 * @param int $membershipId
636 * Membership id that needs to be deleted.
637 * @param bool $preserveContrib
640 * Id of deleted Membership on success, false otherwise.
642 public static function deleteMembership($membershipId, $preserveContrib = FALSE) {
643 // CRM-12147, retrieve membership data before we delete it for hooks
644 $params = ['id' => $membershipId];
646 $memberships = self
::getValues($params, $memValues);
648 $membership = $memberships[$membershipId];
650 CRM_Utils_Hook
::pre('delete', 'Membership', $membershipId, $memValues);
652 $transaction = new CRM_Core_Transaction();
655 //delete activity record
656 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
659 $deleteActivity = FALSE;
660 $membershipActivities = [
662 'Membership Renewal',
663 'Change Membership Status',
664 'Change Membership Type',
665 'Membership Renewal Reminder',
667 foreach ($membershipActivities as $membershipActivity) {
668 $activityId = array_search($membershipActivity, $activityTypes);
670 $params['activity_type_id'][] = $activityId;
671 $deleteActivity = TRUE;
674 if ($deleteActivity) {
675 $params['source_record_id'] = $membershipId;
676 CRM_Activity_BAO_Activity
::deleteActivity($params);
678 self
::deleteMembershipPayment($membershipId, $preserveContrib);
679 CRM_Price_BAO_LineItem
::deleteLineItems($membershipId, 'civicrm_membership');
681 $results = $membership->delete();
682 $transaction->commit();
684 CRM_Utils_Hook
::post('delete', 'Membership', $membership->id
, $membership);
690 * Delete related memberships.
692 * @param int $ownerMembershipId
693 * @param int $contactId
697 public static function deleteRelatedMemberships($ownerMembershipId, $contactId = NULL) {
698 if (!$ownerMembershipId && !$contactId) {
702 $membership = new CRM_Member_DAO_Membership();
703 $membership->owner_membership_id
= $ownerMembershipId;
706 $membership->contact_id
= $contactId;
710 while ($membership->fetch()) {
711 //delete related first and then delete parent.
712 self
::deleteRelatedMemberships($membership->id
);
713 self
::deleteMembership($membership->id
);
718 * Obtain active/inactive memberships from the list of memberships passed to it.
720 * @param array $memberships
721 * Membership records.
722 * @param string $status
723 * Active or inactive.
726 * array of memberships based on status
728 public static function activeMembers($memberships, $status = 'active') {
730 if ($status == 'active') {
731 foreach ($memberships as $f => $v) {
732 if (!empty($v['active'])) {
738 elseif ($status == 'inactive') {
739 foreach ($memberships as $f => $v) {
740 if (empty($v['active'])) {
750 * Return Membership Block info in Contribution Pages.
753 * Contribution page id.
757 public static function getMembershipBlock($pageID) {
758 $membershipBlock = [];
759 $dao = new CRM_Member_DAO_MembershipBlock();
760 $dao->entity_table
= 'civicrm_contribution_page';
762 $dao->entity_id
= $pageID;
764 if ($dao->find(TRUE)) {
765 CRM_Core_DAO
::storeValues($dao, $membershipBlock);
766 if (!empty($membershipBlock['membership_types'])) {
767 $membershipTypes = CRM_Utils_String
::unserialize($membershipBlock['membership_types']);
768 if (!is_array($membershipTypes)) {
769 return $membershipBlock;
772 foreach ($membershipTypes as $key => $value) {
773 $membershipBlock['auto_renew'][$key] = $value;
774 $memTypes[$key] = $key;
776 $membershipBlock['membership_types'] = implode(',', $memTypes);
783 return $membershipBlock;
787 * Return a current membership of given contact.
789 * NB: if more than one membership meets criteria, a randomly selected one is returned.
791 * @param int $contactID
793 * @param int $memType
794 * Membership type, null to retrieve all types.
796 * @param int $membershipId
797 * If provided, then determine if it is current.
798 * @param bool $onlySameParentOrg
799 * True if only Memberships with same parent org as the $memType wanted, false otherwise.
802 * @throws \CiviCRM_API3_Exception
804 public static function getContactMembership($contactID, $memType, $isTest, $membershipId = NULL, $onlySameParentOrg = FALSE) {
805 //check for owner membership id, if it exists update that membership instead: CRM-15992
807 $ownerMemberId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
809 'owner_membership_id', 'id'
811 if ($ownerMemberId) {
812 $membershipId = $ownerMemberId;
813 $contactID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
820 $dao = new CRM_Member_DAO_Membership();
822 $dao->id
= $membershipId;
824 $dao->contact_id
= $contactID;
825 $dao->membership_type_id
= $memType;
827 //fetch proper membership record.
829 $dao->is_test
= $isTest;
832 $dao->whereAdd('is_test IS NULL OR is_test = 0');
835 //avoid pending membership as current membership: CRM-3027
836 $statusIds = [array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus())];
837 if (!$membershipId) {
839 $statusIds[] = array_search(
841 CRM_Member_PseudoConstant
::membershipStatus(
843 " name = 'Cancelled' ",
850 $dao->whereAdd('status_id NOT IN ( ' . implode(',', $statusIds) . ')');
852 // order by start date to find most recent membership first, CRM-4545
853 $dao->orderBy('start_date DESC');
856 if ($onlySameParentOrg && $memType) {
857 // require the same parent org as the $memType
858 $params = ['id' => $memType];
859 $membershipType = [];
860 if (CRM_Member_BAO_MembershipType
::retrieve($params, $membershipType)) {
861 $memberTypesSameParentOrg = civicrm_api3('MembershipType', 'get', [
862 'member_of_contact_id' => $membershipType['member_of_contact_id'],
867 $memberTypesSameParentOrgList = implode(',', array_keys($memberTypesSameParentOrg['values'] ??
[]));
868 $dao->whereAdd('membership_type_id IN (' . $memberTypesSameParentOrgList . ')');
872 if ($dao->find(TRUE)) {
874 CRM_Core_DAO
::storeValues($dao, $membership);
875 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
876 $membership['status_id'],
877 'is_current_member', 'id'
879 $ownerMemberId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
881 'owner_membership_id', 'id'
883 if ($ownerMemberId) {
884 $membership['id'] = $membership['membership_id'] = $ownerMemberId;
885 $membership['membership_contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
894 if ($onlySameParentOrg && $memType) {
895 // see if there is a membership that has same parent as $memType but different parent than $membershipID
896 if ($dao->id
&& CRM_Core_Permission
::check('edit memberships')) {
897 // CRM-10016, This is probably a backend renewal, and make sure we return the same membership thats being renewed.
904 unset($dao->membership_type_id
);
905 if ($dao->find(TRUE)) {
907 CRM_Core_DAO
::storeValues($dao, $membership);
908 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
909 $membership['status_id'],
910 'is_current_member', 'id'
919 * Combine all the importable fields from the lower levels object.
921 * @param string $contactType
923 * @param bool $status
926 * array of importable Fields
927 * @throws \CRM_Core_Exception
929 public static function importableFields($contactType = 'Individual', $status = TRUE) {
930 $fields = Civi
::cache('fields')->get('membership_importable_fields' . $contactType . $status);
933 $fields = ['' => ['title' => '- ' . ts('do not import') . ' -']];
936 $fields = ['' => ['title' => '- ' . ts('Membership Fields') . ' -']];
939 $tmpFields = CRM_Member_DAO_Membership
::import();
940 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
942 // Using new Dedupe rule.
944 'contact_type' => $contactType,
945 'used' => 'Unsupervised',
947 $fieldsArray = CRM_Dedupe_BAO_DedupeRule
::dedupeRuleFields($ruleParams);
949 $tmpContactField = [];
950 if (is_array($fieldsArray)) {
951 foreach ($fieldsArray as $value) {
952 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
957 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
958 $tmpContactField[trim($value)] = $contactFields[trim($value)] ??
NULL;
960 $title = $tmpContactField[trim($value)]['title'] . " " . ts('(match to contact)');
963 $title = $tmpContactField[trim($value)]['title'];
965 $tmpContactField[trim($value)]['title'] = $title;
968 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
969 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
971 $tmpFields['membership_contact_id']['title'] .= ' ' . ts('(match to contact)');
973 $fields = array_merge($fields, $tmpContactField);
974 $fields = array_merge($fields, $tmpFields);
975 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
976 Civi
::cache('fields')->set('membership_importable_fields' . $contactType . $status, $fields);
982 * Get all exportable fields.
984 * @return array return array of all exportable fields
986 public static function &exportableFields() {
987 $expFieldMembership = CRM_Member_DAO_Membership
::export();
989 $expFieldsMemType = CRM_Member_DAO_MembershipType
::export();
990 $fields = array_merge($expFieldMembership, $expFieldsMemType);
991 $fields = array_merge($fields, $expFieldMembership);
992 $membershipStatus = [
993 'membership_status' => [
994 'title' => ts('Membership Status'),
995 'name' => 'membership_status',
996 'type' => CRM_Utils_Type
::T_STRING
,
997 'where' => 'civicrm_membership_status.name',
1000 //CRM-6161 fix for customdata export
1001 $fields = array_merge($fields, $membershipStatus, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1002 $fields['membership_status_id'] = $membershipStatus['membership_status'];
1007 * Get membership joins/renewals for a specified membership type.
1009 * Specifically, retrieves a count of memberships whose "Membership
1010 * Signup" or "Membership Renewal" activity falls in the given date range.
1011 * Dates match the pattern "yyyy-mm-dd".
1013 * @param int $membershipTypeId
1014 * Membership type id.
1015 * @param int $startDate
1016 * Date on which to start counting.
1017 * @param int $endDate
1018 * Date on which to end counting.
1019 * @param bool|int $isTest if true, membership is for a test site
1020 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1023 * the number of members of type $membershipTypeId whose
1024 * start_date is between $startDate and $endDate
1026 public static function getMembershipStarts($membershipTypeId, $startDate, $endDate, $isTest = 0, $isOwner = 0) {
1027 // Ensure that the dates that are passed to the query are in the format of yyyy-mm-dd
1028 $dates = ['startDate', 'endDate'];
1029 foreach ($dates as $date) {
1030 if (strlen($
$date) === 8) {
1031 $
$date = date('Y-m-d', CRM_Utils_Time
::strtotime($
$date));
1035 $testClause = 'membership.is_test = 1';
1037 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1040 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1041 self
::_getActTypes();
1044 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1049 SELECT COUNT(DISTINCT membership.id) as member_count
1050 FROM civicrm_membership membership
1051 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id in (%1, %2))
1052 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1053 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1054 WHERE membership.membership_type_id = %3
1055 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1058 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1061 1 => [self
::$_signupActType, 'Integer'],
1062 2 => [self
::$_renewalActType, 'Integer'],
1063 3 => [$membershipTypeId, 'Integer'],
1066 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1067 return (int) $memberCount;
1071 * Get a count of membership for a specified membership type, optionally for a specified date.
1073 * The date must have the form yyyy-mm-dd.
1075 * If $date is omitted, this function counts as a member anyone whose
1076 * membership status_id indicates they're a current member.
1077 * If $date is given, this function counts as a member anyone who:
1078 * -- Has a start_date before $date and end_date after $date, or
1079 * -- Has a start_date before $date and is currently a member, as indicated
1080 * by the the membership's status_id.
1081 * The second condition takes care of records that have no end_date. These
1082 * are assumed to be lifetime memberships.
1084 * @param int $membershipTypeId
1085 * Membership type id.
1086 * @param string $date
1087 * The date for which to retrieve the count.
1088 * @param bool|int $isTest if true, membership is for a test site
1089 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1092 * the number of members of type $membershipTypeId as of $date.
1094 public static function getMembershipCount($membershipTypeId, $date = NULL, $isTest = 0, $isOwner = 0) {
1095 if (!CRM_Utils_Rule
::date($date)) {
1096 throw new CRM_Core_Exception(ts('Invalid date "%1" (must have form yyyy-mm-dd).', [1 => $date]));
1100 1 => [$membershipTypeId, 'Integer'],
1101 2 => [$isTest, 'Boolean'],
1103 $query = "SELECT count(civicrm_membership.id ) as member_count
1104 FROM civicrm_membership left join civicrm_membership_status on ( civicrm_membership.status_id = civicrm_membership_status.id )
1105 WHERE civicrm_membership.membership_type_id = %1
1106 AND civicrm_membership.contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)
1107 AND civicrm_membership.is_test = %2";
1109 $query .= " AND civicrm_membership_status.is_current_member = 1";
1112 $query .= " AND civicrm_membership.start_date <= '$date' AND civicrm_membership_status.is_current_member = 1";
1115 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1116 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1117 return (int) $memberCount;
1121 * Function check the status of the membership before adding membership for a contact.
1125 public static function statusAvailabilty() {
1126 $membership = new CRM_Member_DAO_MembershipStatus();
1127 $membership->whereAdd('is_active=1');
1128 return $membership->count();
1132 * @deprecated This is not used anywhere and should be removed soon!
1133 * Function for updating a membership record's contribution_recur_id.
1135 * @param CRM_Member_DAO_Membership $membership
1136 * @param \CRM_Contribute_BAO_Contribution|\CRM_Contribute_DAO_Contribution $contribution
1138 public static function updateRecurMembership(CRM_Member_DAO_Membership
$membership, CRM_Contribute_BAO_Contribution
$contribution) {
1139 CRM_Core_Error
::deprecatedFunctionWarning('Use the API instead');
1141 if (empty($contribution->contribution_recur_id
)) {
1146 1 => [$contribution->contribution_recur_id
, 'Integer'],
1147 2 => [$membership->id
, 'Integer'],
1150 $sql = "UPDATE civicrm_membership SET contribution_recur_id = %1 WHERE id = %2";
1151 CRM_Core_DAO
::executeQuery($sql, $params);
1155 * Method to fix membership status of stale membership.
1157 * This method first checks if the membership is stale. If it is,
1158 * then status will be updated based on existing start and end
1159 * dates and log will be added for the status change.
1161 * @param array $currentMembership
1162 * Reference to the array.
1163 * containing all values of
1164 * the current membership
1165 * @param string|null $changeToday
1166 * In case today needs
1167 * to be customised, null otherwise
1169 * @throws \CRM_Core_Exception
1171 public static function fixMembershipStatusBeforeRenew(&$currentMembership, $changeToday = NULL) {
1174 $today = CRM_Utils_Date
::processDate($changeToday, NULL, FALSE, 'Y-m-d');
1177 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
1178 $currentMembership['start_date'] ??
NULL,
1179 $currentMembership['end_date'] ??
NULL,
1180 $currentMembership['join_date'] ??
NULL,
1183 $currentMembership['membership_type_id'],
1187 if (empty($status) ||
empty($status['id'])) {
1188 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.'));
1191 if ($status['id'] !== $currentMembership['status_id']) {
1192 $oldStatus = $currentMembership['status_id'];
1193 $memberDAO = new CRM_Member_DAO_Membership();
1194 $memberDAO->id
= $currentMembership['id'];
1195 $memberDAO->find(TRUE);
1197 $memberDAO->status_id
= $status['id'];
1199 CRM_Core_DAO
::storeValues($memberDAO, $currentMembership);
1201 $currentMembership['is_current_member'] = CRM_Core_DAO
::getFieldValue(
1202 'CRM_Member_DAO_MembershipStatus',
1203 $currentMembership['status_id'],
1209 'membership_id' => $currentMembership['id'],
1210 'status_id' => $status['id'],
1211 'start_date' => CRM_Utils_Date
::customFormat(
1212 $currentMembership['start_date'],
1215 'end_date' => CRM_Utils_Date
::customFormat(
1216 $currentMembership['end_date'],
1219 'modified_date' => date('Y-m-d H:i:s', CRM_Utils_Time
::strtotime($today)),
1220 'membership_type_id' => $currentMembership['membership_type_id'],
1221 'max_related' => $currentMembership['max_related'] ??
0,
1224 $session = CRM_Core_Session
::singleton();
1225 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
1226 if ($session->get('userID')) {
1227 $logParams['modified_id'] = $session->get('userID');
1230 $logParams['modified_id'] = $currentMembership['contact_id'];
1233 //Create activity for status change.
1234 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
1235 CRM_Activity_BAO_Activity
::addActivity($memberDAO,
1236 'Change Membership Status',
1239 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$status['id']]}",
1240 'source_contact_id' => $logParams['modified_id'],
1241 'priority_id' => 'Normal',
1245 CRM_Member_BAO_MembershipLog
::add($logParams);
1250 * Get the contribution page id from the membership record.
1252 * @param int $membershipID
1255 * contribution page id
1257 public static function getContributionPageId($membershipID) {
1259 SELECT c.contribution_page_id as pageID
1260 FROM civicrm_membership_payment mp, civicrm_contribution c
1261 WHERE mp.contribution_id = c.id
1262 AND c.contribution_page_id IS NOT NULL
1263 AND mp.membership_id = " . CRM_Utils_Type
::escape($membershipID, 'Integer')
1264 . " ORDER BY mp.id DESC";
1266 return CRM_Core_DAO
::singleValueQuery($query);
1270 * Updated related memberships.
1272 * @param int $ownerMembershipId
1273 * Owner Membership Id.
1274 * @param array $params
1275 * Formatted array of key => value.
1277 public static function updateRelatedMemberships($ownerMembershipId, $params) {
1278 $membership = new CRM_Member_DAO_Membership();
1279 $membership->owner_membership_id
= $ownerMembershipId;
1280 $membership->find();
1282 while ($membership->fetch()) {
1283 $relatedMembership = new CRM_Member_DAO_Membership();
1284 $relatedMembership->id
= $membership->id
;
1285 $relatedMembership->copyValues($params);
1286 $relatedMembership->save();
1292 * Get list of membership fields for profile.
1294 * For now we only allow custom membership fields to be in
1298 * FIXME: This param is ignored
1301 * the list of membership fields
1303 public static function getMembershipFields($mode = NULL) {
1304 $fields = CRM_Member_DAO_Membership
::export();
1306 unset($fields['membership_contact_id']);
1307 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1309 $membershipType = CRM_Member_DAO_MembershipType
::export();
1311 $membershipStatus = CRM_Member_DAO_MembershipStatus
::export();
1313 $fields = array_merge($fields, $membershipType, $membershipStatus);
1319 * Get the sort name of a contact for a particular membership.
1322 * Id of the membership.
1324 * @return null|string
1325 * sort name of the contact if found
1327 public static function sortName($id) {
1328 $id = CRM_Utils_Type
::escape($id, 'Integer');
1331 SELECT civicrm_contact.sort_name
1332 FROM civicrm_membership, civicrm_contact
1333 WHERE civicrm_membership.contact_id = civicrm_contact.id
1334 AND civicrm_membership.id = {$id}
1336 return CRM_Core_DAO
::singleValueQuery($query);
1340 * Create memberships for related contacts, taking into account the maximum related memberships.
1342 * @param array $params
1343 * Array of key - value pairs.
1344 * @param CRM_Core_DAO $dao
1345 * Membership object.
1347 * @throws \CRM_Core_Exception
1348 * @throws \CiviCRM_API3_Exception
1350 public static function createRelatedMemberships($params, $dao) {
1351 unset($params['membership_id']);
1352 $membership = new CRM_Member_DAO_Membership();
1353 $membership->id
= $dao->id
;
1355 // required since create method doesn't return all the
1356 // parameters in the returned membership object
1357 if (!$membership->find(TRUE)) {
1360 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1361 // FIXME : While updating/ renewing the
1362 // membership, if the relationship is PAST then
1363 // the membership of the related contact must be
1365 // For that, getting Membership Status for which
1366 // is_current_member is 0. It works for the
1367 // generated data as there is only one membership
1368 // status having is_current_member = 0.
1369 // But this wont work exactly if there will be
1370 // more than one status having is_current_member = 0.
1371 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
1372 $membershipStatus->is_current_member
= 0;
1373 if ($membershipStatus->find(TRUE)) {
1374 $expiredStatusId = $membershipStatus->id
;
1377 $expiredStatusId = array_search('Expired', CRM_Member_PseudoConstant
::membershipStatus());
1380 $relatedContacts = [];
1381 $allRelatedContacts = CRM_Member_BAO_Membership
::checkMembershipRelationship($membership->membership_type_id
,
1382 $membership->contact_id
,
1383 $params['action'] ??
NULL
1386 // CRM-4213, CRM-19735 check for loops, using static variable to record contacts already processed.
1387 // Remove repeated related contacts, which already inherited membership of this type$relatedContactIds[$membership->contact_id][$membership->membership_type_id] = TRUE;
1388 foreach ($allRelatedContacts as $cid => $status) {
1389 // relatedContactIDs is always empty now - will remove next roud because of whitespace readability.
1390 if (empty($relatedContactIds[$cid]) ||
empty($relatedContactIds[$cid][$membership->membership_type_id
])) {
1391 $relatedContactIds[$cid][$membership->membership_type_id
] = TRUE;
1393 //don't create membership again for owner contact.
1394 $nestedRelationship = FALSE;
1395 if ($membership->owner_membership_id
) {
1396 $nestedRelMembership = new CRM_Member_DAO_Membership();
1397 $nestedRelMembership->id
= $membership->owner_membership_id
;
1398 $nestedRelMembership->contact_id
= $cid;
1399 $nestedRelationship = $nestedRelMembership->find(TRUE);
1401 if (!$nestedRelationship) {
1402 $relatedContacts[$cid] = $status;
1407 //lets cleanup related membership if any.
1408 if (empty($relatedContacts)) {
1409 self
::deleteRelatedMemberships($membership->id
);
1412 // Edit the params array
1413 unset($params['id']);
1414 // Reminder should be sent only to the direct membership
1415 unset($params['reminder_date']);
1416 // unset the custom value ids
1417 if (isset($params['custom']) && is_array($params['custom'])) {
1418 foreach ($params['custom'] as $k => $values) {
1419 foreach ($values as $i => $value) {
1420 unset($params['custom'][$k][$i]['id']);
1424 if (!isset($params['membership_type_id'])) {
1425 $params['membership_type_id'] = $membership->membership_type_id
;
1428 // max_related should be set in the parent membership
1429 unset($params['max_related']);
1430 // Number of inherited memberships available - NULL is interpreted as unlimited, '0' as none
1431 $numRelatedAvailable = ($membership->max_related
== NULL ? PHP_INT_MAX
: $membership->max_related
);
1432 // will be used to queue potential memberships to be created.
1435 foreach ($relatedContacts as $contactId => $relationshipStatus) {
1436 //use existing membership record.
1437 $relMembership = new CRM_Member_DAO_Membership();
1438 $relMembership->contact_id
= $contactId;
1439 $relMembership->owner_membership_id
= $membership->id
;
1441 if ($relMembership->find(TRUE)) {
1442 $params['id'] = $relMembership->id
;
1445 unset($params['id']);
1448 $params['contact_id'] = $contactId;
1449 $params['owner_membership_id'] = $membership->id
;
1451 // set status_id as it might have been changed for
1452 // past relationship
1453 $params['status_id'] = $membership->status_id
;
1455 if ($deceasedStatusId &&
1456 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'is_deceased')
1458 $params['status_id'] = $deceasedStatusId;
1460 elseif ((($params['action'] ??
NULL) & CRM_Core_Action
::UPDATE
) &&
1461 ($relationshipStatus == CRM_Contact_BAO_Relationship
::PAST
)
1463 $params['status_id'] = $expiredStatusId;
1466 //don't calculate status again in create( );
1467 $params['skipStatusCal'] = TRUE;
1469 //do create activity if we changed status.
1470 if ($params['status_id'] != $relMembership->status_id
) {
1471 $params['createActivity'] = TRUE;
1474 //CRM-20707 - include start/end date
1475 $params['start_date'] = $membership->start_date
;
1476 $params['end_date'] = $membership->end_date
;
1478 // we should not created contribution record for related contacts, CRM-3371
1479 unset($params['contribution_status_id']);
1481 //CRM-16857: Do not create multiple line-items for inherited membership through priceset.
1482 unset($params['lineItems']);
1483 unset($params['line_item']);
1485 // CRM-20966: Do not create membership_payment record for inherited membership.
1486 unset($params['relate_contribution_id']);
1488 if (($params['status_id'] == $deceasedStatusId) ||
($params['status_id'] == $expiredStatusId)) {
1489 // related membership is not active so does not count towards maximum
1490 if (!self
::hasExistingInheritedMembership($params)) {
1491 civicrm_api3('Membership', 'create', $params);
1495 // related membership already exists, so this is just an update
1496 if (isset($params['id'])) {
1497 if ($numRelatedAvailable > 0) {
1498 CRM_Member_BAO_Membership
::create($params);
1499 $numRelatedAvailable--;
1502 // we have run out of inherited memberships, so delete extras
1503 self
::deleteMembership($params['id']);
1505 // we need to first check if there will remain inherited memberships, so queue it up
1512 // now go over the queue and create any available related memberships
1513 foreach ($queue as $params) {
1514 if ($numRelatedAvailable <= 0) {
1517 if (!self
::hasExistingInheritedMembership($params)) {
1518 CRM_Member_BAO_Membership
::create($params);
1520 $numRelatedAvailable--;
1526 * Delete the record that are associated with this Membership Payment.
1528 * @param int $membershipId
1529 * @param bool $preserveContrib
1532 * $membershipPayment deleted membership payment object
1534 public static function deleteMembershipPayment($membershipId, $preserveContrib = FALSE) {
1536 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
1537 $membershipPayment->membership_id
= $membershipId;
1538 $membershipPayment->find();
1540 while ($membershipPayment->fetch()) {
1541 if (!$preserveContrib) {
1542 CRM_Contribute_BAO_Contribution
::deleteContribution($membershipPayment->contribution_id
);
1544 CRM_Utils_Hook
::pre('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1545 $membershipPayment->delete();
1546 CRM_Utils_Hook
::post('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1548 return $membershipPayment;
1552 * Build an array of available membership types in the current context.
1554 * While core does not do anything context specific extensions may filter
1555 * or alter amounts based on user details.
1557 * @param CRM_Core_Form $form
1558 * @param array $membershipTypeID
1559 * @param bool $activeOnly
1560 * Do we only want active ones?
1561 * (probably this should default to TRUE but as a newly added parameter we are leaving default b
1562 * behaviour unchanged).
1566 * @throws \CiviCRM_API3_Exception
1568 public static function buildMembershipTypeValues($form, $membershipTypeID = [], $activeOnly = FALSE) {
1569 $membershipTypeIDS = (array) $membershipTypeID;
1570 $membershipTypeValues = CRM_Member_BAO_MembershipType
::getAllMembershipTypes();
1572 // MembershipTypes are already filtered by domain, filter as appropriate by is_active & a passed in list of ids.
1573 foreach ($membershipTypeValues as $id => $type) {
1574 if (($activeOnly && empty($type['is_active']))
1575 ||
(!empty($membershipTypeIDS) && !in_array($id, $membershipTypeIDS, FALSE))
1577 unset($membershipTypeValues[$id]);
1581 CRM_Utils_Hook
::membershipTypeValues($form, $membershipTypeValues);
1582 return $membershipTypeValues;
1586 * Get membership record count for a Contact.
1588 * @param int $contactID
1589 * @param bool $activeOnly
1592 * @throws \API_Exception
1594 public static function getContactMembershipCount(int $contactID, $activeOnly = FALSE): int {
1596 $membershipTypes = MembershipType
::get(TRUE)
1600 $addWhere = " AND membership_type_id IN (0)";
1601 if (!empty($membershipTypes)) {
1602 $addWhere = " AND membership_type_id IN (" . implode(',', array_keys($membershipTypes)) . ")";
1605 $select = "SELECT COUNT(*) FROM civicrm_membership ";
1606 $where = "WHERE civicrm_membership.contact_id = {$contactID} AND civicrm_membership.is_test = 0 ";
1608 // CRM-6627, all status below 3 (active, pending, grace) are considered active
1610 $select .= " INNER JOIN civicrm_membership_status ON civicrm_membership.status_id = civicrm_membership_status.id ";
1611 $where .= " and civicrm_membership_status.is_current_member = 1";
1614 $query = $select . $where . $addWhere;
1615 return (int) CRM_Core_DAO
::singleValueQuery($query);
1617 catch (UnauthorizedException
$e) {
1623 * Check whether payment processor supports cancellation of membership subscription.
1628 * @param bool $isNotCancelled
1632 public static function isCancelSubscriptionSupported($mid, $isNotCancelled = TRUE) {
1633 $cacheKeyString = "$mid";
1634 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
1636 static $supportsCancel = [];
1638 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
1639 $supportsCancel[$cacheKeyString] = FALSE;
1640 $isCancelled = FALSE;
1642 if ($isNotCancelled) {
1643 $isCancelled = self
::isSubscriptionCancelled($mid);
1646 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($mid, 'membership', 'obj');
1647 if (!empty($paymentObject)) {
1648 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
1651 return $supportsCancel[$cacheKeyString];
1655 * Check whether subscription is already cancelled.
1661 * contribution status
1663 public static function isSubscriptionCancelled($mid) {
1665 SELECT cr.contribution_status_id
1666 FROM civicrm_contribution_recur cr
1667 LEFT JOIN civicrm_membership mem ON ( cr.id = mem.contribution_recur_id )
1668 WHERE mem.id = %1 LIMIT 1";
1669 $params = [1 => [$mid, 'Integer']];
1670 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
1671 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
1672 if ($status == 'Cancelled') {
1679 * Get membership joins for a specified membership type.
1681 * Specifically, retrieves a count of still current memberships whose
1682 * join_date and start_date are within a specified date range. Dates match
1683 * the pattern "yyyy-mm-dd".
1685 * @param int $membershipTypeId
1686 * Membership type id.
1687 * @param int $startDate
1688 * Date on which to start counting.
1689 * @param int $endDate
1690 * Date on which to end counting.
1691 * @param bool|int $isTest if true, membership is for a test site
1694 * the number of members of type $membershipTypeId
1695 * whose join_date is between $startDate and $endDate and
1696 * whose start_date is between $startDate and $endDate
1698 public static function getMembershipJoins($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1699 $testClause = 'membership.is_test = 1';
1701 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1703 if (!self
::$_signupActType) {
1704 self
::_getActTypes();
1707 if (!self
::$_signupActType) {
1712 SELECT COUNT(DISTINCT membership.id) as member_count
1713 FROM civicrm_membership membership
1714 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1715 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1716 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1717 WHERE membership.membership_type_id = %2
1718 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1722 1 => [self
::$_signupActType, 'Integer'],
1723 2 => [$membershipTypeId, 'Integer'],
1726 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1728 return (int) $memberCount;
1732 * Get membership renewals for a specified membership type.
1734 * Specifically, retrieves a count of still current memberships
1735 * whose join_date is before and start_date is within a specified date
1736 * range. Dates match the pattern "yyyy-mm-dd".
1738 * @param int $membershipTypeId
1739 * Membership type id.
1740 * @param int $startDate
1741 * Date on which to start counting.
1742 * @param int $endDate
1743 * Date on which to end counting.
1744 * @param bool|int $isTest if true, membership is for a test site
1747 * returns the number of members of type $membershipTypeId
1748 * whose join_date is before $startDate and
1749 * whose start_date is between $startDate and $endDate
1751 public static function getMembershipRenewals($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1752 $testClause = 'membership.is_test = 1';
1754 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1756 if (!self
::$_renewalActType) {
1757 self
::_getActTypes();
1760 if (!self
::$_renewalActType) {
1765 SELECT COUNT(DISTINCT membership.id) as member_count
1766 FROM civicrm_membership membership
1767 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1768 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1769 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1770 WHERE membership.membership_type_id = %2
1771 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1775 1 => [self
::$_renewalActType, 'Integer'],
1776 2 => [$membershipTypeId, 'Integer'],
1778 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1780 return (int) $memberCount;
1786 * @param int $contactID
1787 * @param int $membershipTypeID
1788 * @param bool $is_test
1789 * @param string $changeToday
1790 * @param int $modifiedID
1791 * @param $customFieldsFormatted
1792 * @param $numRenewTerms
1793 * @param int $membershipID
1795 * @param int $contributionRecurID
1796 * @param $membershipSource
1797 * @param $isPayLater
1798 * @param array $memParams
1799 * @param null|CRM_Contribute_BAO_Contribution $contribution
1800 * @param array $lineItems
1803 * @throws \CRM_Core_Exception
1804 * @throws \CiviCRM_API3_Exception
1806 public static function processMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $contributionRecurID, $membershipSource, $isPayLater, $memParams = [], $contribution = NULL, $lineItems = []) {
1807 CRM_Core_Error
::deprecatedFunctionWarning('use the order api, BAO functions should only be called from unit tested core code.');
1808 $renewalMode = $updateStatusId = FALSE;
1809 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1811 $statusFormat = '%Y-%m-%d';
1812 $membershipTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipType($membershipTypeID);
1816 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
1817 // is the same as the parent org of an existing membership of the contact
1818 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($contactID, $membershipTypeID,
1819 $is_test, $membershipID, TRUE
1821 if ($currentMembership) {
1822 $renewalMode = TRUE;
1824 // Do NOT do anything.
1825 //1. membership with status : PENDING/CANCELLED (CRM-2395)
1826 //2. Paylater/IPN renew. CRM-4556.
1827 if ($pending ||
in_array($currentMembership['status_id'], [
1828 array_search('Pending', $allStatus),
1830 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1833 $memParams = array_merge([
1834 'id' => $currentMembership['id'],
1835 'contribution' => $contribution,
1836 'status_id' => $currentMembership['status_id'],
1837 'start_date' => $currentMembership['start_date'],
1838 'end_date' => $currentMembership['end_date'],
1839 'line_item' => $lineItems,
1840 'join_date' => $currentMembership['join_date'],
1841 'membership_type_id' => $membershipTypeID,
1842 'max_related' => !empty($membershipTypeDetails['max_related']) ?
$membershipTypeDetails['max_related'] : NULL,
1843 'membership_activity_status' => ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed',
1845 if ($contributionRecurID) {
1846 $memParams['contribution_recur_id'] = $contributionRecurID;
1849 $membership = self
::create($memParams);
1850 return [$membership, $renewalMode, $dates];
1853 // Check and fix the membership if it is STALE
1854 self
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
1856 // Now Renew the membership
1857 if (!$currentMembership['is_current_member']) {
1858 // membership is not CURRENT
1860 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1861 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($currentMembership['id'],
1867 $currentMembership['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1868 foreach (['start_date', 'end_date'] as $dateType) {
1869 $currentMembership[$dateType] = $dates[$dateType] ??
NULL;
1871 $currentMembership['is_test'] = $is_test;
1873 if (!empty($membershipSource)) {
1874 $currentMembership['source'] = $membershipSource;
1877 if (!empty($currentMembership['id'])) {
1878 $ids['membership'] = $currentMembership['id'];
1880 $memParams = array_merge($currentMembership, $memParams);
1881 $memParams['membership_type_id'] = $membershipTypeID;
1883 //set the log start date.
1884 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1888 // CURRENT Membership
1889 $membership = new CRM_Member_DAO_Membership();
1890 $membership->id
= $currentMembership['id'];
1891 $membership->find(TRUE);
1892 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1893 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
1899 // Insert renewed dates for CURRENT membership
1900 $memParams['join_date'] = CRM_Utils_Date
::isoToMysql($membership->join_date
);
1901 $memParams['start_date'] = CRM_Utils_Date
::isoToMysql($membership->start_date
);
1902 $memParams['end_date'] = $dates['end_date'] ??
NULL;
1903 $memParams['membership_type_id'] = $membershipTypeID;
1905 //set the log start date.
1906 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1909 if (!empty($membershipSource)) {
1910 $memParams['source'] = $membershipSource;
1912 elseif (empty($membership->source
)) {
1913 $memParams['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
1914 $currentMembership['id'],
1919 if (!empty($currentMembership['id'])) {
1920 $ids['membership'] = $currentMembership['id'];
1922 $memParams['membership_activity_status'] = ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed';
1927 $memParams = array_merge([
1928 'contact_id' => $contactID,
1929 'membership_type_id' => $membershipTypeID,
1933 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
1935 foreach (['join_date', 'start_date', 'end_date'] as $dateType) {
1936 $memParams[$dateType] = $dates[$dateType] ??
NULL;
1939 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(CRM_Utils_Date
::customFormat($dates['start_date'],
1942 CRM_Utils_Date
::customFormat($dates['end_date'],
1945 CRM_Utils_Date
::customFormat($dates['join_date'],
1953 $updateStatusId = $status['id'] ??
NULL;
1956 // if IPN/Pay-Later set status to: PENDING
1957 $updateStatusId = array_search('Pending', $allStatus);
1960 if (!empty($membershipSource)) {
1961 $memParams['source'] = $membershipSource;
1963 $memParams['is_test'] = $is_test;
1964 $memParams['is_pay_later'] = $isPayLater;
1966 // Putting this in an IF is precautionary as it seems likely that it would be ignored if empty, but
1967 // perhaps shouldn't be?
1968 if ($contributionRecurID) {
1969 $memParams['contribution_recur_id'] = $contributionRecurID;
1972 //if we decided status here and want to skip status
1973 //calculation in create( ); then need to pass 'skipStatusCal'.
1974 if ($updateStatusId) {
1975 $memParams['status_id'] = $updateStatusId;
1976 $memParams['skipStatusCal'] = TRUE;
1979 //since we are renewing,
1980 //make status override false.
1981 $memParams['is_override'] = FALSE;
1983 //CRM-4027, create log w/ individual contact.
1985 // @todo this param is likely unused now.
1986 $memParams['is_for_organization'] = TRUE;
1988 $params['modified_id'] = $modifiedID ??
$contactID;
1990 $memParams['contribution'] = $contribution;
1991 $memParams['custom'] = $customFieldsFormatted;
1992 // Load all line items & process all in membership. Don't do in contribution.
1993 // Relevant tests in api_v3_ContributionPageTest.
1994 $memParams['line_item'] = $lineItems;
1995 // @todo stop passing $ids (membership and userId may be set by this point)
1996 $membership = self
::create($memParams, $ids);
1998 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
1999 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
2000 $membership->find(TRUE);
2002 return [$membership, $renewalMode, $dates];
2006 * Get line items representing the default price set.
2008 * @param int $membershipOrg
2009 * @param int $membershipTypeID
2010 * @param float $total_amount
2011 * @param int $priceSetId
2015 public static function setQuickConfigMembershipParameters($membershipOrg, $membershipTypeID, $total_amount, $priceSetId) {
2016 $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
2018 // The name of the price field corresponds to the membership_type organization contact.
2020 'price_set_id' => $priceSetId,
2021 'name' => $membershipOrg,
2024 CRM_Price_BAO_PriceField
::retrieve($params, $results);
2026 if (!empty($results)) {
2027 $fields[$results['id']] = $priceSets['fields'][$results['id']];
2028 $fid = $results['id'];
2029 $editedFieldParams = [
2030 'price_field_id' => $results['id'],
2031 'membership_type_id' => $membershipTypeID,
2034 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $results);
2035 $fields[$fid]['options'][$results['id']] = $priceSets['fields'][$fid]['options'][$results['id']];
2036 if (!empty($total_amount)) {
2037 $fields[$fid]['options'][$results['id']]['amount'] = $total_amount;
2041 $fieldID = key($fields);
2043 'price_set_id' => $priceSetId,
2044 'price_sets' => $priceSets,
2045 'fields' => $fields,
2047 'price_' . $fieldID => $results['id'] ??
NULL,
2050 return $returnParams;
2054 * Update the status of all deceased members to deceased.
2057 * Count of updated contacts.
2059 * @throws \CiviCRM_API3_Exception
2060 * @throws \CRM_Core_Exception
2062 protected static function updateDeceasedMembersStatuses() {
2065 $deceasedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Deceased');
2067 // 'create' context for buildOptions returns only if enabled.
2068 $allStatus = self
::buildOptions('status_id', 'create');
2069 if (array_key_exists($deceasedStatusId, $allStatus) === FALSE) {
2070 // Deceased status is an admin status & is required. We want to fail early if
2071 // it is not present or active.
2072 // We could make the case 'some databases just don't use deceased so we will check
2073 // for the presence of a deceased contact in the DB before rejecting.
2074 if (CRM_Core_DAO
::singleValueQuery('
2075 SELECT count(*) FROM civicrm_contact WHERE is_deceased = 0'
2077 throw new CRM_Core_Exception(
2078 ts("Deceased Membership status is missing or not active. <a href='%1'>Click here to check</a>.",
2079 [1 => CRM_Utils_System
::url('civicrm/admin/member/membershipStatus', 'reset=1')]
2083 $deceasedDAO = CRM_Core_DAO
::executeQuery(
2085 SELECT membership.id as membership_id
2086 FROM civicrm_membership membership
2087 INNER JOIN civicrm_contact ON membership.contact_id = civicrm_contact.id
2088 INNER JOIN civicrm_membership_type ON membership.membership_type_id = civicrm_membership_type.id
2089 AND civicrm_membership_type.is_active = 1
2090 WHERE membership.is_test = 0
2091 AND civicrm_contact.is_deceased = 1
2092 AND membership.status_id <> %1
2094 [1 => [$deceasedStatusId, 'Integer']]
2096 while ($deceasedDAO->fetch()) {
2097 civicrm_api3('membership', 'create', [
2098 'id' => $deceasedDAO->membership_id
,
2099 'status_id' => $deceasedStatusId,
2100 'createActivity' => TRUE,
2101 'skipStatusCal' => TRUE,
2102 'skipRecentView' => TRUE,
2110 * Does the existing membership match the required membership.
2112 * Check before updating that the params are not a match - this is part of avoiding
2113 * a loop if we have already updated.
2115 * https://issues.civicrm.org/jira/browse/CRM-4213
2116 * @param array $params
2118 * @param array $membership
2122 protected static function matchesRequiredMembership($params, $membership) {
2123 foreach (['start_date', 'end_date'] as $date) {
2124 if (CRM_Utils_Time
::strtotime($params[$date]) !== CRM_Utils_Time
::strtotime($membership[$date])) {
2127 if ((int) $params['status_id'] !== (int) $membership['status_id']) {
2130 if ((int) $params['membership_type_id'] !== (int) $membership['membership_type_id']) {
2138 * Params of new membership.
2140 * @param array $params
2143 * @throws \CiviCRM_API3_Exception
2145 protected static function hasExistingInheritedMembership($params) {
2146 foreach (civicrm_api3('Membership', 'get', ['contact_id' => $params['contact_id']])['values'] as $membership) {
2147 if (!empty($membership['owner_membership_id'])
2148 && $membership['membership_type_id'] === $params['membership_type_id']
2149 && (int) $params['owner_membership_id'] !== (int) $membership['owner_membership_id']
2151 // Inheriting it from another contact, don't update here.
2154 if (self
::matchesRequiredMembership($params, $membership)) {
2162 * Process price set and line items.
2164 * @param int $membershipId
2165 * @param array $lineItem
2167 * @throws \CiviCRM_API3_Exception
2169 public function processPriceSet($membershipId, $lineItem) {
2170 //FIXME : need to move this too
2171 if (!$membershipId ||
!is_array($lineItem)
2172 || CRM_Utils_System
::isNull($lineItem)
2177 foreach ($lineItem as $priceSetId => $values) {
2181 foreach ($values as $line) {
2182 $line['entity_table'] = 'civicrm_membership';
2183 $line['entity_id'] = $membershipId;
2184 CRM_Price_BAO_LineItem
::create($line);
2190 * Retrieve the contribution id for the associated Membership id.
2191 * @todo we should get this off the line item
2193 * @param int $membershipId
2196 * if more than one payment associated with membership id need to be returned.
2200 * @todo we should get this off the line item
2203 public static function getMembershipContributionId($membershipId, $all = FALSE) {
2205 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
2206 $membershipPayment->membership_id
= $membershipId;
2207 if ($all && $membershipPayment->find()) {
2208 $contributionIds = [];
2209 while ($membershipPayment->fetch()) {
2210 $contributionIds[] = $membershipPayment->contribution_id
;
2212 return $contributionIds;
2215 if ($membershipPayment->find(TRUE)) {
2216 return $membershipPayment->contribution_id
;
2222 * The function checks and updates the status of all membership records for a given domain using the
2223 * calc_membership_status and update_contact_membership APIs.
2226 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
2228 * @param array $params
2229 * only_active_membership_types, exclude_test_memberships, exclude_membership_status_ids
2233 * @throws \CiviCRM_API3_Exception
2234 * @throws \CRM_Core_Exception
2236 public static function updateAllMembershipStatus($params = []) {
2237 // We want all of the statuses as id => name, even the disabled ones (cf.
2238 // CRM-15475), to identify which are Pending, Deceased, Cancelled, and
2240 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'validate');
2241 if (empty($params['exclude_membership_status_ids'])) {
2242 $params['exclude_membership_status_ids'] = [
2243 array_search('Pending', $allStatus),
2244 array_search('Cancelled', $allStatus),
2245 array_search('Expired', $allStatus) ?
: 0,
2246 array_search('Deceased', $allStatus),
2249 // Deceased is *always* excluded because it is has very specific processing below.
2250 elseif (!in_array(array_search('Deceased', $allStatus), $params['exclude_membership_status_ids'])) {
2251 $params['exclude_membership_status_ids'][] = array_search('Deceased', $allStatus);
2254 for ($index = 0; $index < count($params['exclude_membership_status_ids']); $index++
) {
2255 $queryParams[$index] = [$params['exclude_membership_status_ids'][$index], 'Integer'];
2257 $membershipStatusClause = 'civicrm_membership.status_id NOT IN (%' . implode(', %', array_keys($queryParams)) . ')';
2259 // Tests for this function are in api_v3_JobTest. Please add tests for all updates.
2261 $updateCount = $processCount = self
::updateDeceasedMembersStatuses();
2263 $whereClauses[] = 'civicrm_contact.is_deceased = 0';
2264 if ($params['exclude_test_memberships']) {
2265 $whereClauses[] = 'civicrm_membership.is_test = 0';
2267 $whereClause = implode(' AND ', $whereClauses);
2268 $activeMembershipClause = '';
2269 if ($params['only_active_membership_types']) {
2270 $activeMembershipClause = ' AND civicrm_membership_type.is_active = 1';
2273 // This query retrieves ALL memberships of active types.
2275 SELECT civicrm_membership.id as membership_id,
2276 civicrm_membership.is_override as is_override,
2277 civicrm_membership.status_override_end_date as status_override_end_date,
2278 civicrm_membership.membership_type_id as membership_type_id,
2279 civicrm_membership.status_id as status_id,
2280 civicrm_membership.join_date as join_date,
2281 civicrm_membership.start_date as start_date,
2282 civicrm_membership.end_date as end_date,
2283 civicrm_membership.source as source,
2284 civicrm_contact.id as contact_id,
2285 civicrm_membership.owner_membership_id as owner_membership_id,
2286 civicrm_membership.contribution_recur_id as recur_id
2287 FROM civicrm_membership
2288 INNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )
2289 INNER JOIN civicrm_membership_type ON
2290 (civicrm_membership.membership_type_id = civicrm_membership_type.id {$activeMembershipClause})
2291 WHERE {$whereClause}";
2293 $query = $baseQuery . " AND civicrm_membership.is_override IS NOT NULL AND civicrm_membership.status_override_end_date IS NOT NULL";
2294 $dao1 = CRM_Core_DAO
::executeQuery($query);
2295 while ($dao1->fetch()) {
2296 self
::processOverriddenUntilDateMembership($dao1);
2299 $query = $baseQuery . " AND (civicrm_membership.is_override = 0 OR civicrm_membership.is_override IS NULL)
2300 AND {$membershipStatusClause}
2301 AND civicrm_membership.owner_membership_id IS NULL ";
2303 $allMembershipTypes = CRM_Member_BAO_MembershipType
::getAllMembershipTypes();
2305 $dao2 = CRM_Core_DAO
::executeQuery($query, $queryParams);
2307 while ($dao2->fetch()) {
2310 // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses
2311 //get the membership status as per id.
2312 $newStatus = civicrm_api3('membership_status', 'calc',
2314 'membership_id' => $dao2->membership_id
,
2315 'ignore_admin_only' => TRUE,
2318 $statusId = $newStatus['id'] ??
NULL;
2320 //process only when status change.
2322 $statusId != $dao2->status_id
2325 'id' => $dao2->membership_id
,
2326 'skipStatusCal' => TRUE,
2327 'skipRecentView' => TRUE,
2328 'status_id' => $statusId,
2329 'createActivity' => TRUE,
2332 //process member record.
2333 civicrm_api3('membership', 'create', $memberParams);
2337 $result['is_error'] = 0;
2338 $result['messages'] = ts('Processed %1 membership records. Updated %2 records.', [
2346 * Set is_override for the 'overridden until date' membership to
2347 * False and clears the 'until date' field in case the 'until date'
2348 * is equal or after today date.
2350 * @param CRM_Core_DAO $membership
2351 * The membership to be processed
2353 * @throws \CiviCRM_API3_Exception
2355 private static function processOverriddenUntilDateMembership($membership) {
2356 $isOverriddenUntilDate = !empty($membership->is_override
) && !empty($membership->status_override_end_date
);
2357 if (!$isOverriddenUntilDate) {
2361 $todayDate = new DateTime();
2362 $todayDate->setTime(0, 0);
2364 $overrideEndDate = new DateTime($membership->status_override_end_date
);
2365 $overrideEndDate->setTime(0, 0);
2367 $datesDifference = $todayDate->diff($overrideEndDate);
2368 $daysDifference = (int) $datesDifference->format('%R%a');
2369 if ($daysDifference <= 0) {
2371 'id' => $membership->membership_id
,
2372 'is_override' => FALSE,
2373 'status_override_end_date' => 'null',
2375 civicrm_api3('membership', 'create', $params);
2380 * Returns the membership types for a particular contact
2381 * who has lifetime membership without end date.
2383 * @param int $contactID
2384 * @param bool $isTest
2385 * @param bool $onlyLifeTime
2389 public static function getAllContactMembership($contactID, $isTest = FALSE, $onlyLifeTime = FALSE) {
2390 $contactMembershipType = [];
2392 return $contactMembershipType;
2395 $dao = new CRM_Member_DAO_Membership();
2396 $dao->contact_id
= $contactID;
2397 $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
2398 $dao->whereAdd("status_id != $pendingStatusId");
2401 $dao->is_test
= $isTest;
2404 $dao->whereAdd('is_test IS NULL OR is_test = 0');
2407 if ($onlyLifeTime) {
2408 $dao->whereAdd('end_date IS NULL');
2412 while ($dao->fetch()) {
2414 CRM_Core_DAO
::storeValues($dao, $membership);
2415 $contactMembershipType[$dao->membership_type_id
] = $membership;
2417 return $contactMembershipType;
2421 * Record contribution record associated with membership.
2422 * This will update an existing contribution if $params['contribution_id'] is passed in.
2423 * This will create a MembershipPayment to link the contribution and membership
2425 * @param array $params
2426 * Array of submitted params.
2428 * @return CRM_Contribute_BAO_Contribution
2429 * @throws \CRM_Core_Exception
2430 * @throws \CiviCRM_API3_Exception
2432 public static function recordMembershipContribution(&$params) {
2433 $contributionParams = [];
2434 $config = CRM_Core_Config
::singleton();
2435 $contributionParams['currency'] = $config->defaultCurrency
;
2436 $contributionParams['receipt_date'] = !empty($params['receipt_date']) ?
$params['receipt_date'] : 'null';
2437 $contributionParams['source'] = $params['contribution_source'] ??
NULL;
2438 $contributionParams['non_deductible_amount'] = 'null';
2439 $contributionParams['skipCleanMoney'] = TRUE;
2440 $contributionParams['payment_processor'] = $params['payment_processor_id'] ??
NULL;
2441 $contributionSoftParams = $params['soft_credit'] ??
NULL;
2442 $recordContribution = [
2447 'financial_type_id',
2448 'payment_instrument_id',
2452 'contribution_status_id',
2459 'contribution_recur_id',
2463 foreach ($recordContribution as $f) {
2464 $contributionParams[$f] = $params[$f] ??
NULL;
2467 if (!empty($params['contribution_id'])) {
2468 $contributionParams['id'] = $params['contribution_id'];
2470 // make entry in batch entity batch table
2471 if (!empty($params['batch_id'])) {
2472 $contributionParams['batch_id'] = $params['batch_id'];
2475 if (!empty($params['contribution_contact_id'])) {
2476 // deal with possibility of a different person paying for contribution
2477 $contributionParams['contact_id'] = $params['contribution_contact_id'];
2480 if (!empty($params['processPriceSet']) &&
2481 !empty($params['lineItems'])
2483 $contributionParams['line_item'] = $params['lineItems'] ??
NULL;
2486 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams);
2488 //CRM-13981, create new soft-credit record as to record payment from different person for this membership
2489 if (!empty($contributionSoftParams)) {
2490 if (!empty($params['batch_id'])) {
2491 foreach ($contributionSoftParams as $contributionSoft) {
2492 $contributionSoft['contribution_id'] = $contribution->id
;
2493 $contributionSoft['currency'] = $contribution->currency
;
2494 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoft);
2498 $contributionSoftParams['contribution_id'] = $contribution->id
;
2499 $contributionSoftParams['currency'] = $contribution->currency
;
2500 $contributionSoftParams['amount'] = $contribution->total_amount
;
2501 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoftParams);
2505 // store contribution id
2506 $params['contribution_id'] = $contribution->id
;
2508 // Create membership payment if it does not already exist
2509 $membershipPayment = civicrm_api3('MembershipPayment', 'get', [
2510 'contribution_id' => $contribution->id
,
2512 if (empty($membershipPayment['count'])) {
2513 civicrm_api3('MembershipPayment', 'create', [
2514 'membership_id' => $params['membership_id'],
2515 'contribution_id' => $contribution->id
,
2519 return $contribution;
2523 * @todo document me - I seem a bit out of date....
2525 public static function _getActTypes() {
2526 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2527 self
::$_renewalActType = CRM_Utils_Array
::key('Membership Renewal', $activityTypes);
2528 self
::$_signupActType = CRM_Utils_Array
::key('Membership Signup', $activityTypes);
2532 * Get all Cancelled Membership(s) for a contact
2534 * @param int $contactID
2536 * @param bool $isTest
2540 * Array of membership type
2542 public static function getContactsCancelledMembership($contactID, $isTest = FALSE) {
2546 $query = 'SELECT membership_type_id FROM civicrm_membership WHERE contact_id = %1 AND status_id = %2 AND is_test = %3';
2548 1 => [$contactID, 'Integer'],
2553 CRM_Member_PseudoConstant
::membershipStatus(
2555 " name = 'Cancelled' ",
2563 3 => [$isTest, 'Boolean'],
2566 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
2567 $cancelledMembershipIds = [];
2568 while ($dao->fetch()) {
2569 $cancelledMembershipIds[] = $dao->membership_type_id
;
2571 return $cancelledMembershipIds;
2575 * Merges the memberships from otherContactID to mainContactID.
2577 * General idea is to merge memberships in regards to their type. We
2578 * move the other contact’s contributions to the main contact’s
2579 * membership which has the same type (if any) and then we update
2580 * membership to avoid loosing `join_date`, `end_date`, and
2581 * `status_id`. In this function, we don’t touch the contributions
2582 * directly (CRM_Dedupe_Merger::moveContactBelongings() takes care
2585 * This function adds new SQL queries to the $sqlQueries parameter.
2587 * @param int $mainContactID
2588 * Contact id of main contact record.
2589 * @param int $otherContactID
2590 * Contact id of record which is going to merge.
2591 * @param array $sqlQueries
2592 * (reference) array of SQL queries to be executed.
2593 * @param array $tables
2594 * List of tables that have to be merged.
2595 * @param array $tableOperations
2596 * Special options/params for some tables to be merged.
2598 * @see CRM_Dedupe_Merger::cpTables()
2600 public static function mergeMemberships($mainContactID, $otherContactID, &$sqlQueries, $tables, $tableOperations) {
2602 * If the user requests not to merge memberships but to add them,
2603 * just attribute the `civicrm_membership` to the
2604 * `$mainContactID`. We have to do this here since the general
2605 * merge process is bypassed by this function.
2607 if (array_key_exists("civicrm_membership", $tableOperations) && $tableOperations['civicrm_membership']['add']) {
2608 $sqlQueries[] = "UPDATE IGNORE civicrm_membership SET contact_id = $mainContactID WHERE contact_id = $otherContactID";
2613 * Retrieve all memberships that belongs to each contacts and
2614 * keep track of each membership type.
2616 $mainContactMemberships = [];
2617 $otherContactMemberships = [];
2619 $sql = "SELECT id, membership_type_id FROM civicrm_membership membership WHERE contact_id = %1";
2620 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$mainContactID, "Integer"]]);
2621 while ($dao->fetch()) {
2622 $mainContactMemberships[$dao->id
] = $dao->membership_type_id
;
2625 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$otherContactID, "Integer"]]);
2626 while ($dao->fetch()) {
2627 $otherContactMemberships[$dao->id
] = $dao->membership_type_id
;
2631 * For each membership, move related contributions to the main
2632 * contact’s membership (by updating `membership_payments`). Then,
2633 * update membership’s `join_date` (if the other membership’s
2634 * join_date is older) and `end_date` (if the other membership’s
2635 * `end_date` is newer) and `status_id` (if the newly calculated
2636 * status is different).
2638 * FIXME: what should we do if we have multiple memberships with
2639 * the same type (currently we only take the first one)?
2642 foreach ($otherContactMemberships as $otherMembershipId => $otherMembershipTypeId) {
2643 if ($newMembershipId = array_search($otherMembershipTypeId, $mainContactMemberships)) {
2646 * Move other membership’s contributions to the main one only
2647 * if user requested to merge contributions.
2649 if (!empty($tables) && in_array('civicrm_contribution', $tables)) {
2650 $newSql[] = "UPDATE civicrm_membership_payment SET membership_id=$newMembershipId WHERE membership_id=$otherMembershipId";
2653 $sql = "SELECT * FROM civicrm_membership membership WHERE id = %1";
2655 $newMembership = CRM_Member_DAO_Membership
::findById($newMembershipId);
2656 $otherMembership = CRM_Member_DAO_Membership
::findById($otherMembershipId);
2659 if (new DateTime($otherMembership->join_date
) < new DateTime($newMembership->join_date
)) {
2660 $updates["join_date"] = $otherMembership->join_date
;
2663 if (new DateTime($otherMembership->end_date
) > new DateTime($newMembership->end_date
)) {
2664 $updates["end_date"] = $otherMembership->end_date
;
2667 if (count($updates)) {
2672 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
2673 $updates["start_date"] ??
$newMembership->start_date
,
2674 $updates["end_date"] ??
$newMembership->end_date
,
2675 $updates["join_date"] ??
$newMembership->join_date
,
2682 if (!empty($status['id']) and $status['id'] != $newMembership->status_id
) {
2683 $updates['status_id'] = $status['id'];
2687 foreach ($updates as $k => $v) {
2688 $updates_sql[] = "$k = '{$v}'";
2691 $newSql[] = sprintf("UPDATE civicrm_membership SET %s WHERE id=%s", implode(", ", $updates_sql), $newMembershipId);
2692 $newSql[] = sprintf("DELETE FROM civicrm_membership WHERE id=%s", $otherMembershipId);
2698 $sqlQueries = array_merge($sqlQueries, $newSql);
2702 * Update membership status to deceased.
2703 * function return the status message for updated membership.
2705 * @param array $deceasedParams
2710 * @param string $contactType
2712 * @return null|string
2713 * $updateMembershipMsg string status message for updated membership.
2715 public static function updateMembershipStatus($deceasedParams, $contactType) {
2716 $updateMembershipMsg = NULL;
2717 $contactId = $deceasedParams['contact_id'];
2718 $deceasedDate = $deceasedParams['deceased_date'];
2720 // process to set membership status to deceased for both active/inactive membership
2722 $contactType === 'Individual' &&
2723 !empty($deceasedParams['is_deceased'])
2726 $userId = CRM_Core_Session
::getLoggedInContactID() ?
: $contactId;
2728 // get deceased status id
2729 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2730 $deceasedStatusId = array_search('Deceased', $allStatus);
2731 if (!$deceasedStatusId) {
2732 return $updateMembershipMsg;
2735 $today = CRM_Utils_Time
::time();
2736 if ($deceasedDate && CRM_Utils_Time
::strtotime($deceasedDate) > $today) {
2737 return $updateMembershipMsg;
2740 // get non deceased membership
2741 $dao = new CRM_Member_DAO_Membership();
2742 $dao->contact_id
= $contactId;
2743 $dao->whereAdd("status_id != $deceasedStatusId");
2745 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2746 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2748 while ($dao->fetch()) {
2749 // update status to deceased (for both active/inactive membership )
2750 CRM_Core_DAO
::setFieldValue('CRM_Member_DAO_Membership', $dao->id
,
2751 'status_id', $deceasedStatusId
2754 // add membership log
2756 'membership_id' => $dao->id
,
2757 'status_id' => $deceasedStatusId,
2758 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
2759 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
2760 'modified_id' => $userId,
2761 'modified_date' => CRM_Utils_Time
::date('Ymd'),
2762 'membership_type_id' => $dao->membership_type_id
,
2763 'max_related' => $dao->max_related
,
2766 CRM_Member_BAO_MembershipLog
::add($membershipLog);
2768 //create activity when membership status is changed
2770 'subject' => "Status changed from {$allStatus[$dao->status_id]} to {$allStatus[$deceasedStatusId]}",
2771 'source_contact_id' => $userId,
2772 'target_contact_id' => $dao->contact_id
,
2773 'source_record_id' => $dao->id
,
2774 'activity_type_id' => array_search('Change Membership Status', $activityTypes),
2778 'activity_date_time' => CRM_Utils_Time
::date('Y-m-d H:i:s'),
2780 'is_current_revision' => 1,
2783 civicrm_api('activity', 'create', $activityParam);
2790 CRM_Core_Session
::setStatus(ts("%1 Current membership(s) for this contact have been set to 'Deceased' status.",
2795 return $updateMembershipMsg;