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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Member_BAO_Membership
extends CRM_Member_DAO_Membership
{
20 * Static field for all the membership information that we can potentially import.
24 public static $_importableFields = NULL;
26 public static $_renewalActType = NULL;
28 public static $_signupActType = NULL;
33 public function __construct() {
34 parent
::__construct();
38 * Takes an associative array and creates a membership object.
40 * the function extracts all the params it needs to initialize the created
41 * membership object. The params array could contain additional unused name/value
44 * @param array $params
45 * (reference ) an assoc array of name/value pairs.
47 * @return CRM_Member_BAO_Membership
48 * @throws \CiviCRM_API3_Exception
50 public static function add(&$params) {
51 $oldStatus = $oldType = NULL;
53 CRM_Utils_Hook
::pre('edit', 'Membership', $params['id'], $params);
56 CRM_Utils_Hook
::pre('create', 'Membership', NULL, $params);
59 // we do this after the hooks are called in case it has been altered
61 $membershipObj = new CRM_Member_DAO_Membership();
62 $membershipObj->id
= $id;
63 $membershipObj->find();
64 while ($membershipObj->fetch()) {
65 $oldStatus = $membershipObj->status_id
;
66 $oldType = $membershipObj->membership_type_id
;
70 if (array_key_exists('is_override', $params) && !$params['is_override']) {
71 $params['is_override'] = 'null';
74 $membership = new CRM_Member_BAO_Membership();
75 $membership->copyValues($params);
76 $membership->id
= $id;
80 if (empty($membership->contact_id
) ||
empty($membership->status_id
)) {
81 // this means we are in renewal mode and are just updating the membership
82 // record or this is an API update call and all fields are not present in the update record
83 // however the hooks don't care and want all data CRM-7784
84 $tempMembership = new CRM_Member_DAO_Membership();
85 $tempMembership->id
= $membership->id
;
86 $tempMembership->find(TRUE);
87 $membership = $tempMembership;
90 //get the log start date.
91 //it is set during renewal of membership.
92 $logStartDate = $params['log_start_date'] ??
NULL;
93 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : CRM_Utils_Date
::isoToMysql($membership->start_date
);
94 $values = self
::getStatusANDTypeValues($membership->id
);
97 'membership_id' => $membership->id
,
98 'status_id' => $membership->status_id
,
99 'start_date' => $logStartDate,
100 'end_date' => CRM_Utils_Date
::isoToMysql($membership->end_date
),
101 'modified_date' => CRM_Utils_Time
::date('Ymd'),
102 'membership_type_id' => $values[$membership->id
]['membership_type_id'],
103 'max_related' => $membership->max_related
,
106 if (!empty($params['modified_id'])) {
107 $membershipLog['modified_id'] = $params['modified_id'];
109 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
110 elseif (CRM_Core_Session
::singleton()->get('userID')) {
111 $membershipLog['modified_id'] = CRM_Core_Session
::singleton()->get('userID');
114 $membershipLog['modified_id'] = $membership->contact_id
;
117 CRM_Member_BAO_MembershipLog
::add($membershipLog);
119 // reset the group contact cache since smart groups might be affected due to this
120 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
122 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
124 'status_id' => $params['membership_activity_status'] ??
'Completed',
126 if (in_array($allStatus[$membership->status_id
], ['Pending', 'Grace'])) {
127 $activityParams['status_id'] = 'Scheduled';
129 $activityParams['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', $activityParams['status_id']);
131 $targetContactID = $membership->contact_id
;
132 if (!empty($params['is_for_organization'])) {
133 // @todo - deprecate is_for_organization, require modified_id
134 $targetContactID = $params['modified_id'] ??
NULL;
137 // add custom field values
138 if (!empty($params['custom']) && is_array($params['custom'])
140 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_membership', $membership->id
);
144 if ($membership->status_id
!= $oldStatus) {
145 CRM_Activity_BAO_Activity
::addActivity($membership,
146 'Change Membership Status',
149 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
150 'source_contact_id' => $membershipLog['modified_id'],
151 'priority_id' => 'Normal',
155 if (isset($membership->membership_type_id
) && $membership->membership_type_id
!= $oldType) {
156 $membershipTypes = CRM_Member_BAO_Membership
::buildOptions('membership_type_id', 'get');
157 CRM_Activity_BAO_Activity
::addActivity($membership,
158 'Change Membership Type',
161 'subject' => "Type changed from {$membershipTypes[$oldType]} to {$membershipTypes[$membership->membership_type_id]}",
162 'source_contact_id' => $membershipLog['modified_id'],
163 'priority_id' => 'Normal',
168 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
169 $activityParams['id'] = civicrm_api3('Activity', 'Get', [
170 'source_record_id' => $membership->id
,
171 'activity_type_id' => $activityType,
172 'status_id' => 'Scheduled',
174 // 1. Update Schedule Membership Signup/Renwal activity to completed on successful payment of pending membership
175 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
176 if (!empty($params['membership_activity_status']) && (!empty($activityParams['id']) ||
$activityType == 'Membership Renewal')) {
177 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $targetContactID, $activityParams);
182 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
185 CRM_Activity_BAO_Activity
::addActivity($membership, 'Membership Signup', $targetContactID, $activityParams);
186 CRM_Utils_Hook
::post('create', 'Membership', $membership->id
, $membership);
193 * Fetch the object and store the values in the values array.
195 * @param array $params
196 * Input parameters to find object.
197 * @param array $values
198 * Output values of the object.
199 * @param bool $active
200 * Do you want only active memberships to.
203 * @return CRM_Member_BAO_Membership|null
204 * The found object or null
206 public static function &getValues(&$params, &$values, $active = FALSE) {
207 if (empty($params)) {
210 $membership = new CRM_Member_BAO_Membership();
212 $membership->copyValues($params);
215 while ($membership->fetch()) {
217 (!CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
218 $membership->status_id
,
225 CRM_Core_DAO
::storeValues($membership, $values[$membership->id
]);
226 $memberships[$membership->id
] = $membership;
233 * Takes an associative array and creates a membership object.
235 * @param array $params
236 * (reference ) an assoc array of name/value pairs.
238 * Deprecated parameter The array that holds all the db ids.
240 * @return CRM_Member_BAO_Membership|CRM_Core_Error
241 * @throws \CiviCRM_API3_Exception
243 * @throws CRM_Core_Exception
245 public static function create(&$params, $ids = []) {
246 // always calculate status if is_override/skipStatusCal is not true.
247 // giving respect to is_override during import. CRM-4012
249 // To skip status calculation we should use 'skipStatusCal'.
250 // eg pay later membership, membership update cron CRM-3984
252 if (empty($params['is_override']) && empty($params['skipStatusCal'])) {
254 foreach (['start_date', 'end_date', 'join_date'] as $dateField) {
255 if (!empty($params[$dateField]) && $params[$dateField] !== 'null' && strpos($params[$dateField], date('Ymd', CRM_Utils_Time
::strtotime(trim($params[$dateField])))) !== 0) {
256 $params[$dateField] = date('Ymd', CRM_Utils_Time
::strtotime(trim($params[$dateField])));
257 // @todo enable this once core is using the api.
258 // CRM_Core_Error::deprecatedWarning('Relying on the BAO to clean up dates is deprecated. Call membership create via the api');
260 if (!empty($params['id']) && empty($params[$dateField])) {
261 $fieldsToLoad[] = $dateField;
264 if (!empty($fieldsToLoad)) {
265 $membership = civicrm_api3('Membership', 'getsingle', ['id' => $params['id'], 'return' => $fieldsToLoad]);
266 foreach ($fieldsToLoad as $fieldToLoad) {
267 $params[$fieldToLoad] = $membership[$fieldToLoad];
270 $params['start_date'] = $params['start_date'] ?
: 'null';
271 $params['end_date'] = $params['end_date'] ?
: 'null';
272 $params['join_date'] = $params['join_date'] ?
: 'null';
274 //fix for CRM-3570, during import exclude the statuses those having is_admin = 1
275 $excludeIsAdmin = $params['exclude_is_admin'] ??
FALSE;
277 //CRM-3724 always skip is_admin if is_override != true.
278 if (!$excludeIsAdmin && empty($params['is_override'])) {
279 $excludeIsAdmin = TRUE;
282 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($params['start_date'], $params['end_date'], $params['join_date'],
283 'now', $excludeIsAdmin, $params['membership_type_id'] ??
NULL, $params
285 if (empty($calcStatus)) {
286 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')));
288 $params['status_id'] = $calcStatus['id'];
291 // data cleanup only: all verifications on number of related memberships are done upstream in:
292 // CRM_Member_BAO_Membership::createRelatedMemberships()
293 // CRM_Contact_BAO_Relationship::relatedMemberships()
294 if (!empty($params['owner_membership_id'])) {
295 unset($params['max_related']);
298 // if membership allows related, default max_related to value in membership_type
299 if (!array_key_exists('max_related', $params) && !empty($params['membership_type_id'])) {
300 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipType($params['membership_type_id']);
301 if (isset($membershipType['relationship_type_id'])) {
302 $params['max_related'] = $membershipType['max_related'] ??
NULL;
307 $transaction = new CRM_Core_Transaction();
309 $params['id'] = $params['id'] ??
$ids['membership'] ??
NULL;
310 $membership = self
::add($params);
312 if (is_a($membership, 'CRM_Core_Error')) {
313 $transaction->rollback();
317 $params['membership_id'] = $membership->id
;
318 // @todo further cleanup required to remove use of $ids['contribution'] from here
319 if (isset($ids['membership'])) {
320 $contributionID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment',
325 // @todo this is a temporary step to removing $ids['contribution'] completely
326 if (empty($params['contribution_id']) && !empty($contributionID)) {
327 $params['contribution_id'] = $contributionID;
331 // This code ensures a line item is created but it is recommended you pass in 'skipLineItem' or 'line_item'
332 if (empty($params['line_item']) && !empty($params['membership_type_id']) && empty($params['skipLineItem'])) {
333 CRM_Price_BAO_LineItem
::getLineItemArray($params, NULL, 'membership', $params['membership_type_id']);
335 $params['skipLineItem'] = TRUE;
337 // Record contribution for this membership and create a MembershipPayment
338 // @todo deprecate this.
339 if (!empty($params['contribution_status_id']) && empty($params['relate_contribution_id'])) {
340 $memInfo = array_merge($params, ['membership_id' => $membership->id
]);
341 $params['contribution'] = self
::recordMembershipContribution($memInfo);
344 // Add/update MembershipPayment record for this membership if it is a related contribution
345 // @todo remove this - called from one remaining place in CRM_Member_Form_Membership
346 if (!empty($params['relate_contribution_id'])) {
347 $membershipPaymentParams = [
348 'membership_id' => $membership->id
,
349 'membership_type_id' => $membership->membership_type_id
,
350 'contribution_id' => $params['relate_contribution_id'],
352 civicrm_api3('MembershipPayment', 'create', $membershipPaymentParams);
355 // If the membership has no associated contribution then we ensure
356 // the line items are 'correct' here. This is a lazy legacy
357 // hack whereby they are deleted and recreated
358 if (empty($contributionID)) {
359 if (!empty($params['lineItems'])) {
360 $params['line_item'] = $params['lineItems'];
362 // do cleanup line items if membership edit the Membership type.
363 if (!empty($ids['membership'])) {
364 CRM_Price_BAO_LineItem
::deleteLineItems($ids['membership'], 'civicrm_membership');
366 // @todo - we should ONLY do the below if a contribution is created. Let's
367 // get some deprecation notices in here & see where it's hit & work to eliminate.
368 // This could happen if there is no contribution or we are in one of many
369 // weird and wonderful flows. This is scary code. Keep adding tests.
370 if (!empty($params['line_item']) && empty($params['contribution_id'])) {
372 foreach ($params['line_item'] as $priceSetId => $lineItems) {
373 foreach ($lineItems as $lineIndex => $lineItem) {
374 $lineMembershipType = $lineItem['membership_type_id'] ??
NULL;
375 if (!empty($params['contribution'])) {
376 $params['line_item'][$priceSetId][$lineIndex]['contribution_id'] = $params['contribution']->id
;
378 if ($lineMembershipType && $lineMembershipType == ($params['membership_type_id'] ??
NULL)) {
379 $params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $membership->id
;
380 $params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_membership';
382 elseif (!$lineMembershipType && !empty($params['contribution'])) {
383 $params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $params['contribution']->id
;
384 $params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_contribution';
388 CRM_Price_BAO_LineItem
::processPriceSet(
390 $params['line_item'],
391 $params['contribution'] ??
NULL
396 $transaction->commit();
398 self
::createRelatedMemberships($params, $membership);
400 if (empty($params['skipRecentView'])) {
401 self
::addToRecentItems($membership);
408 * @param \CRM_Member_DAO_Membership $membership
410 private static function addToRecentItems($membership) {
411 $url = CRM_Utils_System
::url('civicrm/contact/view/membership',
412 "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
414 if (empty($membership->membership_type_id
)) {
415 // ie in an update situation.
416 $membership->find(TRUE);
418 $title = CRM_Contact_BAO_Contact
::displayName($membership->contact_id
) . ' - ' . ts('Membership Type:')
419 . ' ' . CRM_Core_PseudoConstant
::getLabel('CRM_Member_BAO_Membership', 'membership_type_id', $membership->membership_type_id
);
422 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::UPDATE
)) {
423 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
424 "action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
427 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::DELETE
)) {
428 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
429 "action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
433 // add the recently created Membership
434 CRM_Utils_Recent
::add($title,
438 $membership->contact_id
,
445 * Check the membership extended through relationship.
447 * @param int $membershipTypeID
448 * Membership type id.
449 * @param int $contactId
455 * array of contact_id of all related contacts.
457 * @throws \CRM_Core_Exception
458 * @throws \CiviCRM_API3_Exception
460 public static function checkMembershipRelationship($membershipTypeID, $contactId, $action = CRM_Core_Action
::ADD
) {
463 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipType($membershipTypeID);
466 if (isset($membershipType['relationship_type_id'])) {
467 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
468 CRM_Contact_BAO_Relationship
::CURRENT
470 if ($action & CRM_Core_Action
::UPDATE
) {
471 $pastRelationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
472 CRM_Contact_BAO_Relationship
::PAST
474 $relationships = array_merge($relationships, $pastRelationships);
478 if (!empty($relationships)) {
479 // check for each contact relationships
480 foreach ($relationships as $values) {
481 //get details of the relationship type
482 $relType = ['id' => $values['civicrm_relationship_type_id']];
484 CRM_Contact_BAO_RelationshipType
::retrieve($relType, $relValues);
485 // Check if contact's relationship type exists in membership type
487 $bidirectional = FALSE;
488 foreach ($membershipType['relationship_type_id'] as $key => $value) {
489 $relTypeDirs[] = $value . '_' . $membershipType['relationship_direction'][$key];
490 if (in_array($value, $relType) &&
491 $relValues['name_a_b'] == $relValues['name_b_a']
493 $bidirectional = TRUE;
497 $relTypeDir = $values['civicrm_relationship_type_id'] . '_' . $values['rtype'];
498 if ($bidirectional ||
in_array($relTypeDir, $relTypeDirs)) {
499 // $values['status'] is going to have value for
500 // current or past relationships.
501 $contacts[$values['cid']] = $values['status'];
506 // Sort by contact_id ascending
512 * Retrieve DB object based on input parameters.
514 * It also stores all the retrieved values in the default array.
516 * @param array $params
517 * (reference ) an assoc array of name/value pairs.
518 * @param array $defaults
519 * (reference ) an assoc array to hold the name / value pairs.
520 * in a hierarchical manner
522 * @return CRM_Member_BAO_Membership
524 public static function retrieve(&$params, &$defaults) {
525 $membership = new CRM_Member_DAO_Membership();
527 $membership->copyValues($params);
529 if ($membership->find(TRUE)) {
530 CRM_Core_DAO
::storeValues($membership, $defaults);
532 //get the membership status and type values.
533 $statusANDType = self
::getStatusANDTypeValues($membership->id
);
534 foreach (['status', 'membership_type'] as $fld) {
535 $defaults[$fld] = $statusANDType[$membership->id
][$fld] ??
NULL;
537 if (!empty($statusANDType[$membership->id
]['is_current_member'])) {
538 $defaults['active'] = TRUE;
548 * Get membership status and membership type values.
550 * @param int $membershipId
551 * Membership id of values to return.
554 * Array of key value pairs
556 public static function getStatusANDTypeValues($membershipId) {
558 if (!$membershipId) {
562 SELECT membership.id as id,
563 status.id as status_id,
564 status.label as status,
565 status.is_current_member as is_current_member,
566 type.id as membership_type_id,
567 type.name as membership_type,
568 type.relationship_type_id as relationship_type_id
569 FROM civicrm_membership membership
570 INNER JOIN civicrm_membership_status status ON ( status.id = membership.status_id )
571 INNER JOIN civicrm_membership_type type ON ( type.id = membership.membership_type_id )
572 WHERE membership.id = %1';
573 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$membershipId, 'Positive']]);
578 'membership_type_id',
580 'relationship_type_id',
582 while ($dao->fetch()) {
583 foreach ($properties as $property) {
584 $values[$dao->id
][$property] = $dao->$property;
594 * Wrapper for most delete calls. Use this unless you JUST want to delete related memberships w/o deleting the parent.
596 * @param int $membershipId
597 * Membership id that needs to be deleted.
598 * @param bool $preserveContrib
601 * Id of deleted Membership on success, false otherwise.
603 public static function del($membershipId, $preserveContrib = FALSE) {
604 //delete related first and then delete parent.
605 self
::deleteRelatedMemberships($membershipId);
606 return self
::deleteMembership($membershipId, $preserveContrib);
612 * @param int $membershipId
613 * Membership id that needs to be deleted.
614 * @param bool $preserveContrib
617 * Id of deleted Membership on success, false otherwise.
619 public static function deleteMembership($membershipId, $preserveContrib = FALSE) {
620 // CRM-12147, retrieve membership data before we delete it for hooks
621 $params = ['id' => $membershipId];
623 $memberships = self
::getValues($params, $memValues);
625 $membership = $memberships[$membershipId];
627 CRM_Utils_Hook
::pre('delete', 'Membership', $membershipId, $memValues);
629 $transaction = new CRM_Core_Transaction();
632 //delete activity record
633 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
636 $deleteActivity = FALSE;
637 $membershipActivities = [
639 'Membership Renewal',
640 'Change Membership Status',
641 'Change Membership Type',
642 'Membership Renewal Reminder',
644 foreach ($membershipActivities as $membershipActivity) {
645 $activityId = array_search($membershipActivity, $activityTypes);
647 $params['activity_type_id'][] = $activityId;
648 $deleteActivity = TRUE;
651 if ($deleteActivity) {
652 $params['source_record_id'] = $membershipId;
653 CRM_Activity_BAO_Activity
::deleteActivity($params);
655 self
::deleteMembershipPayment($membershipId, $preserveContrib);
656 CRM_Price_BAO_LineItem
::deleteLineItems($membershipId, 'civicrm_membership');
658 $results = $membership->delete();
659 $transaction->commit();
661 CRM_Utils_Hook
::post('delete', 'Membership', $membership->id
, $membership);
663 // delete the recently created Membership
664 $membershipRecent = [
665 'id' => $membershipId,
666 'type' => 'Membership',
668 CRM_Utils_Recent
::del($membershipRecent);
674 * Delete related memberships.
676 * @param int $ownerMembershipId
677 * @param int $contactId
681 public static function deleteRelatedMemberships($ownerMembershipId, $contactId = NULL) {
682 if (!$ownerMembershipId && !$contactId) {
686 $membership = new CRM_Member_DAO_Membership();
687 $membership->owner_membership_id
= $ownerMembershipId;
690 $membership->contact_id
= $contactId;
694 while ($membership->fetch()) {
695 //delete related first and then delete parent.
696 self
::deleteRelatedMemberships($membership->id
);
697 self
::deleteMembership($membership->id
);
702 * Obtain active/inactive memberships from the list of memberships passed to it.
704 * @param array $memberships
705 * Membership records.
706 * @param string $status
707 * Active or inactive.
710 * array of memberships based on status
712 public static function activeMembers($memberships, $status = 'active') {
714 if ($status == 'active') {
715 foreach ($memberships as $f => $v) {
716 if (!empty($v['active'])) {
722 elseif ($status == 'inactive') {
723 foreach ($memberships as $f => $v) {
724 if (empty($v['active'])) {
734 * Return Membership Block info in Contribution Pages.
737 * Contribution page id.
741 public static function getMembershipBlock($pageID) {
742 $membershipBlock = [];
743 $dao = new CRM_Member_DAO_MembershipBlock();
744 $dao->entity_table
= 'civicrm_contribution_page';
746 $dao->entity_id
= $pageID;
748 if ($dao->find(TRUE)) {
749 CRM_Core_DAO
::storeValues($dao, $membershipBlock);
750 if (!empty($membershipBlock['membership_types'])) {
751 $membershipTypes = CRM_Utils_String
::unserialize($membershipBlock['membership_types']);
752 if (!is_array($membershipTypes)) {
753 return $membershipBlock;
756 foreach ($membershipTypes as $key => $value) {
757 $membershipBlock['auto_renew'][$key] = $value;
758 $memTypes[$key] = $key;
760 $membershipBlock['membership_types'] = implode(',', $memTypes);
767 return $membershipBlock;
771 * Return a current membership of given contact.
773 * NB: if more than one membership meets criteria, a randomly selected one is returned.
775 * @param int $contactID
777 * @param int $memType
778 * Membership type, null to retrieve all types.
780 * @param int $membershipId
781 * If provided, then determine if it is current.
782 * @param bool $onlySameParentOrg
783 * True if only Memberships with same parent org as the $memType wanted, false otherwise.
786 * @throws \CiviCRM_API3_Exception
788 public static function getContactMembership($contactID, $memType, $isTest, $membershipId = NULL, $onlySameParentOrg = FALSE) {
789 //check for owner membership id, if it exists update that membership instead: CRM-15992
791 $ownerMemberId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
793 'owner_membership_id', 'id'
795 if ($ownerMemberId) {
796 $membershipId = $ownerMemberId;
797 $contactID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
804 $dao = new CRM_Member_DAO_Membership();
806 $dao->id
= $membershipId;
808 $dao->contact_id
= $contactID;
809 $dao->membership_type_id
= $memType;
811 //fetch proper membership record.
813 $dao->is_test
= $isTest;
816 $dao->whereAdd('is_test IS NULL OR is_test = 0');
819 //avoid pending membership as current membership: CRM-3027
820 $statusIds = [array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus())];
821 if (!$membershipId) {
823 $statusIds[] = array_search(
825 CRM_Member_PseudoConstant
::membershipStatus(
827 " name = 'Cancelled' ",
834 $dao->whereAdd('status_id NOT IN ( ' . implode(',', $statusIds) . ')');
836 // order by start date to find most recent membership first, CRM-4545
837 $dao->orderBy('start_date DESC');
840 if ($onlySameParentOrg && $memType) {
841 // require the same parent org as the $memType
842 $params = ['id' => $memType];
843 $membershipType = [];
844 if (CRM_Member_BAO_MembershipType
::retrieve($params, $membershipType)) {
845 $memberTypesSameParentOrg = civicrm_api3('MembershipType', 'get', [
846 'member_of_contact_id' => $membershipType['member_of_contact_id'],
851 $memberTypesSameParentOrgList = implode(',', array_keys($memberTypesSameParentOrg['values'] ??
[]));
852 $dao->whereAdd('membership_type_id IN (' . $memberTypesSameParentOrgList . ')');
856 if ($dao->find(TRUE)) {
858 CRM_Core_DAO
::storeValues($dao, $membership);
859 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
860 $membership['status_id'],
861 'is_current_member', 'id'
863 $ownerMemberId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
865 'owner_membership_id', 'id'
867 if ($ownerMemberId) {
868 $membership['id'] = $membership['membership_id'] = $ownerMemberId;
869 $membership['membership_contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
878 if ($onlySameParentOrg && $memType) {
879 // see if there is a membership that has same parent as $memType but different parent than $membershipID
880 if ($dao->id
&& CRM_Core_Permission
::check('edit memberships')) {
881 // CRM-10016, This is probably a backend renewal, and make sure we return the same membership thats being renewed.
888 unset($dao->membership_type_id
);
889 if ($dao->find(TRUE)) {
891 CRM_Core_DAO
::storeValues($dao, $membership);
892 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
893 $membership['status_id'],
894 'is_current_member', 'id'
903 * Combine all the importable fields from the lower levels object.
905 * @param string $contactType
907 * @param bool $status
910 * array of importable Fields
911 * @throws \CRM_Core_Exception
913 public static function importableFields($contactType = 'Individual', $status = TRUE) {
914 $fields = Civi
::cache('fields')->get('membership_importable_fields' . $contactType . $status);
917 $fields = ['' => ['title' => '- ' . ts('do not import') . ' -']];
920 $fields = ['' => ['title' => '- ' . ts('Membership Fields') . ' -']];
923 $tmpFields = CRM_Member_DAO_Membership
::import();
924 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
926 // Using new Dedupe rule.
928 'contact_type' => $contactType,
929 'used' => 'Unsupervised',
931 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
933 $tmpContactField = [];
934 if (is_array($fieldsArray)) {
935 foreach ($fieldsArray as $value) {
936 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
941 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
942 $tmpContactField[trim($value)] = $contactFields[trim($value)] ??
NULL;
944 $title = $tmpContactField[trim($value)]['title'] . " " . ts('(match to contact)');
947 $title = $tmpContactField[trim($value)]['title'];
949 $tmpContactField[trim($value)]['title'] = $title;
952 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
953 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . ' ' . ts('(match to contact)');
955 $tmpFields['membership_contact_id']['title'] .= ' ' . ts('(match to contact)');
957 $fields = array_merge($fields, $tmpContactField);
958 $fields = array_merge($fields, $tmpFields);
959 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
960 Civi
::cache('fields')->set('membership_importable_fields' . $contactType . $status, $fields);
966 * Get all exportable fields.
968 * @return array return array of all exportable fields
970 public static function &exportableFields() {
971 $expFieldMembership = CRM_Member_DAO_Membership
::export();
973 $expFieldsMemType = CRM_Member_DAO_MembershipType
::export();
974 $fields = array_merge($expFieldMembership, $expFieldsMemType);
975 $fields = array_merge($fields, $expFieldMembership);
976 $membershipStatus = [
977 'membership_status' => [
978 'title' => ts('Membership Status'),
979 'name' => 'membership_status',
980 'type' => CRM_Utils_Type
::T_STRING
,
981 'where' => 'civicrm_membership_status.name',
984 //CRM-6161 fix for customdata export
985 $fields = array_merge($fields, $membershipStatus, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
986 $fields['membership_status_id'] = $membershipStatus['membership_status'];
991 * Get membership joins/renewals for a specified membership type.
993 * Specifically, retrieves a count of memberships whose "Membership
994 * Signup" or "Membership Renewal" activity falls in the given date range.
995 * Dates match the pattern "yyyy-mm-dd".
997 * @param int $membershipTypeId
998 * Membership type id.
999 * @param int $startDate
1000 * Date on which to start counting.
1001 * @param int $endDate
1002 * Date on which to end counting.
1003 * @param bool|int $isTest if true, membership is for a test site
1004 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1007 * the number of members of type $membershipTypeId whose
1008 * start_date is between $startDate and $endDate
1010 public static function getMembershipStarts($membershipTypeId, $startDate, $endDate, $isTest = 0, $isOwner = 0) {
1011 // Ensure that the dates that are passed to the query are in the format of yyyy-mm-dd
1012 $dates = ['startDate', 'endDate'];
1013 foreach ($dates as $date) {
1014 if (strlen($
$date) === 8) {
1015 $
$date = date('Y-m-d', CRM_Utils_Time
::strtotime($
$date));
1019 $testClause = 'membership.is_test = 1';
1021 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1024 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1025 self
::_getActTypes();
1028 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1033 SELECT COUNT(DISTINCT membership.id) as member_count
1034 FROM civicrm_membership membership
1035 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id in (%1, %2))
1036 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1037 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1038 WHERE membership.membership_type_id = %3
1039 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1042 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1045 1 => [self
::$_signupActType, 'Integer'],
1046 2 => [self
::$_renewalActType, 'Integer'],
1047 3 => [$membershipTypeId, 'Integer'],
1050 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1051 return (int) $memberCount;
1055 * Get a count of membership for a specified membership type, optionally for a specified date.
1057 * The date must have the form yyyy-mm-dd.
1059 * If $date is omitted, this function counts as a member anyone whose
1060 * membership status_id indicates they're a current member.
1061 * If $date is given, this function counts as a member anyone who:
1062 * -- Has a start_date before $date and end_date after $date, or
1063 * -- Has a start_date before $date and is currently a member, as indicated
1064 * by the the membership's status_id.
1065 * The second condition takes care of records that have no end_date. These
1066 * are assumed to be lifetime memberships.
1068 * @param int $membershipTypeId
1069 * Membership type id.
1070 * @param string $date
1071 * The date for which to retrieve the count.
1072 * @param bool|int $isTest if true, membership is for a test site
1073 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1076 * the number of members of type $membershipTypeId as of $date.
1078 public static function getMembershipCount($membershipTypeId, $date = NULL, $isTest = 0, $isOwner = 0) {
1079 if (!CRM_Utils_Rule
::date($date)) {
1080 throw new CRM_Core_Exception(ts('Invalid date "%1" (must have form yyyy-mm-dd).', [1 => $date]));
1084 1 => [$membershipTypeId, 'Integer'],
1085 2 => [$isTest, 'Boolean'],
1087 $query = "SELECT count(civicrm_membership.id ) as member_count
1088 FROM civicrm_membership left join civicrm_membership_status on ( civicrm_membership.status_id = civicrm_membership_status.id )
1089 WHERE civicrm_membership.membership_type_id = %1
1090 AND civicrm_membership.contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)
1091 AND civicrm_membership.is_test = %2";
1093 $query .= " AND civicrm_membership_status.is_current_member = 1";
1096 $query .= " AND civicrm_membership.start_date <= '$date' AND civicrm_membership_status.is_current_member = 1";
1099 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1100 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1101 return (int) $memberCount;
1105 * Function check the status of the membership before adding membership for a contact.
1109 public static function statusAvailabilty() {
1110 $membership = new CRM_Member_DAO_MembershipStatus();
1111 $membership->whereAdd('is_active=1');
1112 return $membership->count();
1116 * @deprecated This is not used anywhere and should be removed soon!
1117 * Function for updating a membership record's contribution_recur_id.
1119 * @param CRM_Member_DAO_Membership $membership
1120 * @param \CRM_Contribute_BAO_Contribution|\CRM_Contribute_DAO_Contribution $contribution
1122 public static function updateRecurMembership(CRM_Member_DAO_Membership
$membership, CRM_Contribute_BAO_Contribution
$contribution) {
1123 CRM_Core_Error
::deprecatedFunctionWarning('Use the API instead');
1125 if (empty($contribution->contribution_recur_id
)) {
1130 1 => [$contribution->contribution_recur_id
, 'Integer'],
1131 2 => [$membership->id
, 'Integer'],
1134 $sql = "UPDATE civicrm_membership SET contribution_recur_id = %1 WHERE id = %2";
1135 CRM_Core_DAO
::executeQuery($sql, $params);
1139 * Method to fix membership status of stale membership.
1141 * This method first checks if the membership is stale. If it is,
1142 * then status will be updated based on existing start and end
1143 * dates and log will be added for the status change.
1145 * @param array $currentMembership
1146 * Reference to the array.
1147 * containing all values of
1148 * the current membership
1149 * @param string|null $changeToday
1150 * In case today needs
1151 * to be customised, null otherwise
1153 * @throws \CRM_Core_Exception
1155 public static function fixMembershipStatusBeforeRenew(&$currentMembership, $changeToday = NULL) {
1158 $today = CRM_Utils_Date
::processDate($changeToday, NULL, FALSE, 'Y-m-d');
1161 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
1162 $currentMembership['start_date'] ??
NULL,
1163 $currentMembership['end_date'] ??
NULL,
1164 $currentMembership['join_date'] ??
NULL,
1167 $currentMembership['membership_type_id'],
1171 if (empty($status) ||
empty($status['id'])) {
1172 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.'));
1175 if ($status['id'] !== $currentMembership['status_id']) {
1176 $oldStatus = $currentMembership['status_id'];
1177 $memberDAO = new CRM_Member_DAO_Membership();
1178 $memberDAO->id
= $currentMembership['id'];
1179 $memberDAO->find(TRUE);
1181 $memberDAO->status_id
= $status['id'];
1183 CRM_Core_DAO
::storeValues($memberDAO, $currentMembership);
1185 $currentMembership['is_current_member'] = CRM_Core_DAO
::getFieldValue(
1186 'CRM_Member_DAO_MembershipStatus',
1187 $currentMembership['status_id'],
1193 'membership_id' => $currentMembership['id'],
1194 'status_id' => $status['id'],
1195 'start_date' => CRM_Utils_Date
::customFormat(
1196 $currentMembership['start_date'],
1199 'end_date' => CRM_Utils_Date
::customFormat(
1200 $currentMembership['end_date'],
1203 'modified_date' => date('Y-m-d H:i:s', CRM_Utils_Time
::strtotime($today)),
1204 'membership_type_id' => $currentMembership['membership_type_id'],
1205 'max_related' => $currentMembership['max_related'] ??
0,
1208 $session = CRM_Core_Session
::singleton();
1209 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
1210 if ($session->get('userID')) {
1211 $logParams['modified_id'] = $session->get('userID');
1214 $logParams['modified_id'] = $currentMembership['contact_id'];
1217 //Create activity for status change.
1218 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
1219 CRM_Activity_BAO_Activity
::addActivity($memberDAO,
1220 'Change Membership Status',
1223 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$status['id']]}",
1224 'source_contact_id' => $logParams['modified_id'],
1225 'priority_id' => 'Normal',
1229 CRM_Member_BAO_MembershipLog
::add($logParams);
1234 * Get the contribution page id from the membership record.
1236 * @param int $membershipID
1239 * contribution page id
1241 public static function getContributionPageId($membershipID) {
1243 SELECT c.contribution_page_id as pageID
1244 FROM civicrm_membership_payment mp, civicrm_contribution c
1245 WHERE mp.contribution_id = c.id
1246 AND c.contribution_page_id IS NOT NULL
1247 AND mp.membership_id = " . CRM_Utils_Type
::escape($membershipID, 'Integer')
1248 . " ORDER BY mp.id DESC";
1250 return CRM_Core_DAO
::singleValueQuery($query);
1254 * Updated related memberships.
1256 * @param int $ownerMembershipId
1257 * Owner Membership Id.
1258 * @param array $params
1259 * Formatted array of key => value.
1261 public static function updateRelatedMemberships($ownerMembershipId, $params) {
1262 $membership = new CRM_Member_DAO_Membership();
1263 $membership->owner_membership_id
= $ownerMembershipId;
1264 $membership->find();
1266 while ($membership->fetch()) {
1267 $relatedMembership = new CRM_Member_DAO_Membership();
1268 $relatedMembership->id
= $membership->id
;
1269 $relatedMembership->copyValues($params);
1270 $relatedMembership->save();
1276 * Get list of membership fields for profile.
1278 * For now we only allow custom membership fields to be in
1282 * FIXME: This param is ignored
1285 * the list of membership fields
1287 public static function getMembershipFields($mode = NULL) {
1288 $fields = CRM_Member_DAO_Membership
::export();
1290 unset($fields['membership_contact_id']);
1291 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1293 $membershipType = CRM_Member_DAO_MembershipType
::export();
1295 $membershipStatus = CRM_Member_DAO_MembershipStatus
::export();
1297 $fields = array_merge($fields, $membershipType, $membershipStatus);
1303 * Get the sort name of a contact for a particular membership.
1306 * Id of the membership.
1308 * @return null|string
1309 * sort name of the contact if found
1311 public static function sortName($id) {
1312 $id = CRM_Utils_Type
::escape($id, 'Integer');
1315 SELECT civicrm_contact.sort_name
1316 FROM civicrm_membership, civicrm_contact
1317 WHERE civicrm_membership.contact_id = civicrm_contact.id
1318 AND civicrm_membership.id = {$id}
1320 return CRM_Core_DAO
::singleValueQuery($query);
1324 * Create memberships for related contacts, taking into account the maximum related memberships.
1326 * @param array $params
1327 * Array of key - value pairs.
1328 * @param CRM_Core_DAO $dao
1329 * Membership object.
1331 * @throws \CRM_Core_Exception
1332 * @throws \CiviCRM_API3_Exception
1334 public static function createRelatedMemberships($params, $dao) {
1335 unset($params['membership_id']);
1336 $membership = new CRM_Member_DAO_Membership();
1337 $membership->id
= $dao->id
;
1339 // required since create method doesn't return all the
1340 // parameters in the returned membership object
1341 if (!$membership->find(TRUE)) {
1344 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1345 // FIXME : While updating/ renewing the
1346 // membership, if the relationship is PAST then
1347 // the membership of the related contact must be
1349 // For that, getting Membership Status for which
1350 // is_current_member is 0. It works for the
1351 // generated data as there is only one membership
1352 // status having is_current_member = 0.
1353 // But this wont work exactly if there will be
1354 // more than one status having is_current_member = 0.
1355 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
1356 $membershipStatus->is_current_member
= 0;
1357 if ($membershipStatus->find(TRUE)) {
1358 $expiredStatusId = $membershipStatus->id
;
1361 $expiredStatusId = array_search('Expired', CRM_Member_PseudoConstant
::membershipStatus());
1364 $relatedContacts = [];
1365 $allRelatedContacts = CRM_Member_BAO_Membership
::checkMembershipRelationship($membership->membership_type_id
,
1366 $membership->contact_id
,
1367 $params['action'] ??
NULL
1370 // CRM-4213, CRM-19735 check for loops, using static variable to record contacts already processed.
1371 // Remove repeated related contacts, which already inherited membership of this type$relatedContactIds[$membership->contact_id][$membership->membership_type_id] = TRUE;
1372 foreach ($allRelatedContacts as $cid => $status) {
1373 // relatedContactIDs is always empty now - will remove next roud because of whitespace readability.
1374 if (empty($relatedContactIds[$cid]) ||
empty($relatedContactIds[$cid][$membership->membership_type_id
])) {
1375 $relatedContactIds[$cid][$membership->membership_type_id
] = TRUE;
1377 //don't create membership again for owner contact.
1378 $nestedRelationship = FALSE;
1379 if ($membership->owner_membership_id
) {
1380 $nestedRelMembership = new CRM_Member_DAO_Membership();
1381 $nestedRelMembership->id
= $membership->owner_membership_id
;
1382 $nestedRelMembership->contact_id
= $cid;
1383 $nestedRelationship = $nestedRelMembership->find(TRUE);
1385 if (!$nestedRelationship) {
1386 $relatedContacts[$cid] = $status;
1391 //lets cleanup related membership if any.
1392 if (empty($relatedContacts)) {
1393 self
::deleteRelatedMemberships($membership->id
);
1396 // Edit the params array
1397 unset($params['id']);
1398 // Reminder should be sent only to the direct membership
1399 unset($params['reminder_date']);
1400 // unset the custom value ids
1401 if (isset($params['custom']) && is_array($params['custom'])) {
1402 foreach ($params['custom'] as $k => $values) {
1403 foreach ($values as $i => $value) {
1404 unset($params['custom'][$k][$i]['id']);
1408 if (!isset($params['membership_type_id'])) {
1409 $params['membership_type_id'] = $membership->membership_type_id
;
1412 // max_related should be set in the parent membership
1413 unset($params['max_related']);
1414 // Number of inherited memberships available - NULL is interpreted as unlimited, '0' as none
1415 $numRelatedAvailable = ($membership->max_related
== NULL ? PHP_INT_MAX
: $membership->max_related
);
1416 // will be used to queue potential memberships to be created.
1419 foreach ($relatedContacts as $contactId => $relationshipStatus) {
1420 //use existing membership record.
1421 $relMembership = new CRM_Member_DAO_Membership();
1422 $relMembership->contact_id
= $contactId;
1423 $relMembership->owner_membership_id
= $membership->id
;
1425 if ($relMembership->find(TRUE)) {
1426 $params['id'] = $relMembership->id
;
1429 unset($params['id']);
1432 $params['contact_id'] = $contactId;
1433 $params['owner_membership_id'] = $membership->id
;
1435 // set status_id as it might have been changed for
1436 // past relationship
1437 $params['status_id'] = $membership->status_id
;
1439 if ($deceasedStatusId &&
1440 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'is_deceased')
1442 $params['status_id'] = $deceasedStatusId;
1444 elseif ((($params['action'] ??
NULL) & CRM_Core_Action
::UPDATE
) &&
1445 ($relationshipStatus == CRM_Contact_BAO_Relationship
::PAST
)
1447 $params['status_id'] = $expiredStatusId;
1450 //don't calculate status again in create( );
1451 $params['skipStatusCal'] = TRUE;
1453 //do create activity if we changed status.
1454 if ($params['status_id'] != $relMembership->status_id
) {
1455 $params['createActivity'] = TRUE;
1458 //CRM-20707 - include start/end date
1459 $params['start_date'] = $membership->start_date
;
1460 $params['end_date'] = $membership->end_date
;
1462 // we should not created contribution record for related contacts, CRM-3371
1463 unset($params['contribution_status_id']);
1465 //CRM-16857: Do not create multiple line-items for inherited membership through priceset.
1466 unset($params['lineItems']);
1467 unset($params['line_item']);
1469 // CRM-20966: Do not create membership_payment record for inherited membership.
1470 unset($params['relate_contribution_id']);
1472 if (($params['status_id'] == $deceasedStatusId) ||
($params['status_id'] == $expiredStatusId)) {
1473 // related membership is not active so does not count towards maximum
1474 if (!self
::hasExistingInheritedMembership($params)) {
1475 civicrm_api3('Membership', 'create', $params);
1479 // related membership already exists, so this is just an update
1480 if (isset($params['id'])) {
1481 if ($numRelatedAvailable > 0) {
1482 CRM_Member_BAO_Membership
::create($params);
1483 $numRelatedAvailable--;
1486 // we have run out of inherited memberships, so delete extras
1487 self
::deleteMembership($params['id']);
1489 // we need to first check if there will remain inherited memberships, so queue it up
1496 // now go over the queue and create any available related memberships
1497 foreach ($queue as $params) {
1498 if ($numRelatedAvailable <= 0) {
1501 if (!self
::hasExistingInheritedMembership($params)) {
1502 CRM_Member_BAO_Membership
::create($params);
1504 $numRelatedAvailable--;
1510 * Delete the record that are associated with this Membership Payment.
1512 * @param int $membershipId
1513 * @param bool $preserveContrib
1516 * $membershipPayment deleted membership payment object
1518 public static function deleteMembershipPayment($membershipId, $preserveContrib = FALSE) {
1520 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
1521 $membershipPayment->membership_id
= $membershipId;
1522 $membershipPayment->find();
1524 while ($membershipPayment->fetch()) {
1525 if (!$preserveContrib) {
1526 CRM_Contribute_BAO_Contribution
::deleteContribution($membershipPayment->contribution_id
);
1528 CRM_Utils_Hook
::pre('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1529 $membershipPayment->delete();
1530 CRM_Utils_Hook
::post('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1532 return $membershipPayment;
1536 * Build an array of available membership types in the current context.
1538 * While core does not do anything context specific extensions may filter
1539 * or alter amounts based on user details.
1541 * @param CRM_Core_Form $form
1542 * @param array $membershipTypeID
1543 * @param bool $activeOnly
1544 * Do we only want active ones?
1545 * (probably this should default to TRUE but as a newly added parameter we are leaving default b
1546 * behaviour unchanged).
1550 * @throws \CiviCRM_API3_Exception
1552 public static function buildMembershipTypeValues($form, $membershipTypeID = [], $activeOnly = FALSE) {
1553 $membershipTypeIDS = (array) $membershipTypeID;
1554 $membershipTypeValues = CRM_Member_BAO_MembershipType
::getAllMembershipTypes();
1556 // MembershipTypes are already filtered by domain, filter as appropriate by is_active & a passed in list of ids.
1557 foreach ($membershipTypeValues as $id => $type) {
1558 if (($activeOnly && empty($type['is_active']))
1559 ||
(!empty($membershipTypeIDS) && !in_array($id, $membershipTypeIDS, FALSE))
1561 unset($membershipTypeValues[$id]);
1565 CRM_Utils_Hook
::membershipTypeValues($form, $membershipTypeValues);
1566 return $membershipTypeValues;
1570 * Get membership record count for a Contact.
1572 * @param int $contactID
1573 * @param bool $activeOnly
1575 * @return null|string
1577 public static function getContactMembershipCount($contactID, $activeOnly = FALSE) {
1578 $membershipTypes = \Civi\Api4\MembershipType
::get(TRUE)
1582 $addWhere = " AND membership_type_id IN (0)";
1583 if (!empty($membershipTypes)) {
1584 $addWhere = " AND membership_type_id IN (" . implode(',', array_keys($membershipTypes)) . ")";
1587 $select = "SELECT count(*) FROM civicrm_membership ";
1588 $where = "WHERE civicrm_membership.contact_id = {$contactID} AND civicrm_membership.is_test = 0 ";
1590 // CRM-6627, all status below 3 (active, pending, grace) are considered active
1592 $select .= " INNER JOIN civicrm_membership_status ON civicrm_membership.status_id = civicrm_membership_status.id ";
1593 $where .= " and civicrm_membership_status.is_current_member = 1";
1596 $query = $select . $where . $addWhere;
1597 return CRM_Core_DAO
::singleValueQuery($query);
1601 * Check whether payment processor supports cancellation of membership subscription.
1606 * @param bool $isNotCancelled
1610 public static function isCancelSubscriptionSupported($mid, $isNotCancelled = TRUE) {
1611 $cacheKeyString = "$mid";
1612 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
1614 static $supportsCancel = [];
1616 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
1617 $supportsCancel[$cacheKeyString] = FALSE;
1618 $isCancelled = FALSE;
1620 if ($isNotCancelled) {
1621 $isCancelled = self
::isSubscriptionCancelled($mid);
1624 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($mid, 'membership', 'obj');
1625 if (!empty($paymentObject)) {
1626 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
1629 return $supportsCancel[$cacheKeyString];
1633 * Check whether subscription is already cancelled.
1639 * contribution status
1641 public static function isSubscriptionCancelled($mid) {
1643 SELECT cr.contribution_status_id
1644 FROM civicrm_contribution_recur cr
1645 LEFT JOIN civicrm_membership mem ON ( cr.id = mem.contribution_recur_id )
1646 WHERE mem.id = %1 LIMIT 1";
1647 $params = [1 => [$mid, 'Integer']];
1648 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
1649 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
1650 if ($status == 'Cancelled') {
1657 * Get membership joins for a specified membership type.
1659 * Specifically, retrieves a count of still current memberships whose
1660 * join_date and start_date are within a specified date range. Dates match
1661 * the pattern "yyyy-mm-dd".
1663 * @param int $membershipTypeId
1664 * Membership type id.
1665 * @param int $startDate
1666 * Date on which to start counting.
1667 * @param int $endDate
1668 * Date on which to end counting.
1669 * @param bool|int $isTest if true, membership is for a test site
1672 * the number of members of type $membershipTypeId
1673 * whose join_date is between $startDate and $endDate and
1674 * whose start_date is between $startDate and $endDate
1676 public static function getMembershipJoins($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1677 $testClause = 'membership.is_test = 1';
1679 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1681 if (!self
::$_signupActType) {
1682 self
::_getActTypes();
1685 if (!self
::$_signupActType) {
1690 SELECT COUNT(DISTINCT membership.id) as member_count
1691 FROM civicrm_membership membership
1692 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1693 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1694 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1695 WHERE membership.membership_type_id = %2
1696 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1700 1 => [self
::$_signupActType, 'Integer'],
1701 2 => [$membershipTypeId, 'Integer'],
1704 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1706 return (int) $memberCount;
1710 * Get membership renewals for a specified membership type.
1712 * Specifically, retrieves a count of still current memberships
1713 * whose join_date is before and start_date is within a specified date
1714 * range. Dates match the pattern "yyyy-mm-dd".
1716 * @param int $membershipTypeId
1717 * Membership type id.
1718 * @param int $startDate
1719 * Date on which to start counting.
1720 * @param int $endDate
1721 * Date on which to end counting.
1722 * @param bool|int $isTest if true, membership is for a test site
1725 * returns the number of members of type $membershipTypeId
1726 * whose join_date is before $startDate and
1727 * whose start_date is between $startDate and $endDate
1729 public static function getMembershipRenewals($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1730 $testClause = 'membership.is_test = 1';
1732 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1734 if (!self
::$_renewalActType) {
1735 self
::_getActTypes();
1738 if (!self
::$_renewalActType) {
1743 SELECT COUNT(DISTINCT membership.id) as member_count
1744 FROM civicrm_membership membership
1745 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1746 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1747 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1748 WHERE membership.membership_type_id = %2
1749 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1753 1 => [self
::$_renewalActType, 'Integer'],
1754 2 => [$membershipTypeId, 'Integer'],
1756 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1758 return (int) $memberCount;
1762 * @param int $contactID
1763 * @param int $membershipTypeID
1764 * @param bool $is_test
1765 * @param string $changeToday
1766 * @param int $modifiedID
1767 * @param $customFieldsFormatted
1768 * @param $numRenewTerms
1769 * @param int $membershipID
1771 * @param int $contributionRecurID
1772 * @param $membershipSource
1773 * @param $isPayLater
1774 * @param array $memParams
1775 * @param array $formDates
1776 * @param null|CRM_Contribute_BAO_Contribution $contribution
1777 * @param array $lineItems
1780 * @throws \CRM_Core_Exception
1781 * @throws \CiviCRM_API3_Exception
1783 public static function processMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $contributionRecurID, $membershipSource, $isPayLater, $memParams = [], $formDates = [], $contribution = NULL, $lineItems = []) {
1784 $renewalMode = $updateStatusId = FALSE;
1785 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1787 $statusFormat = '%Y-%m-%d';
1788 $membershipTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipType($membershipTypeID);
1792 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
1793 // is the same as the parent org of an existing membership of the contact
1794 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($contactID, $membershipTypeID,
1795 $is_test, $membershipID, TRUE
1797 if ($currentMembership) {
1798 $renewalMode = TRUE;
1800 // Do NOT do anything.
1801 //1. membership with status : PENDING/CANCELLED (CRM-2395)
1802 //2. Paylater/IPN renew. CRM-4556.
1803 if ($pending ||
in_array($currentMembership['status_id'], [
1804 array_search('Pending', $allStatus),
1806 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1809 $memParams = array_merge([
1810 'id' => $currentMembership['id'],
1811 'contribution' => $contribution,
1812 'status_id' => $currentMembership['status_id'],
1813 'start_date' => $currentMembership['start_date'],
1814 'end_date' => $currentMembership['end_date'],
1815 'line_item' => $lineItems,
1816 'join_date' => $currentMembership['join_date'],
1817 'membership_type_id' => $membershipTypeID,
1818 'max_related' => !empty($membershipTypeDetails['max_related']) ?
$membershipTypeDetails['max_related'] : NULL,
1819 'membership_activity_status' => ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed',
1821 if ($contributionRecurID) {
1822 $memParams['contribution_recur_id'] = $contributionRecurID;
1825 $membership = self
::create($memParams);
1826 return [$membership, $renewalMode, $dates];
1829 // Check and fix the membership if it is STALE
1830 self
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
1832 // Now Renew the membership
1833 if (!$currentMembership['is_current_member']) {
1834 // membership is not CURRENT
1836 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1837 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($currentMembership['id'],
1843 $currentMembership['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1844 foreach (['start_date', 'end_date'] as $dateType) {
1845 $currentMembership[$dateType] = $formDates[$dateType] ??
NULL;
1846 if (empty($currentMembership[$dateType])) {
1847 $currentMembership[$dateType] = $dates[$dateType] ??
NULL;
1850 $currentMembership['is_test'] = $is_test;
1852 if (!empty($membershipSource)) {
1853 $currentMembership['source'] = $membershipSource;
1856 if (!empty($currentMembership['id'])) {
1857 $ids['membership'] = $currentMembership['id'];
1859 $memParams = array_merge($currentMembership, $memParams);
1860 $memParams['membership_type_id'] = $membershipTypeID;
1862 //set the log start date.
1863 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1867 // CURRENT Membership
1868 $membership = new CRM_Member_DAO_Membership();
1869 $membership->id
= $currentMembership['id'];
1870 $membership->find(TRUE);
1871 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1872 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
1878 // Insert renewed dates for CURRENT membership
1879 $memParams['join_date'] = CRM_Utils_Date
::isoToMysql($membership->join_date
);
1880 $memParams['start_date'] = $formDates['start_date'] ?? CRM_Utils_Date
::isoToMysql($membership->start_date
);
1881 $memParams['end_date'] = $formDates['end_date'] ??
NULL;
1882 if (empty($memParams['end_date'])) {
1883 $memParams['end_date'] = $dates['end_date'] ??
NULL;
1885 $memParams['membership_type_id'] = $membershipTypeID;
1887 //set the log start date.
1888 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1891 if (!empty($membershipSource)) {
1892 $memParams['source'] = $membershipSource;
1894 elseif (empty($membership->source
)) {
1895 $memParams['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
1896 $currentMembership['id'],
1901 if (!empty($currentMembership['id'])) {
1902 $ids['membership'] = $currentMembership['id'];
1904 $memParams['membership_activity_status'] = ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed';
1909 $memParams = array_merge([
1910 'contact_id' => $contactID,
1911 'membership_type_id' => $membershipTypeID,
1915 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
1917 foreach (['join_date', 'start_date', 'end_date'] as $dateType) {
1918 $memParams[$dateType] = $formDates[$dateType] ??
NULL;
1919 if (empty($memParams[$dateType])) {
1920 $memParams[$dateType] = $dates[$dateType] ??
NULL;
1924 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(CRM_Utils_Date
::customFormat($dates['start_date'],
1927 CRM_Utils_Date
::customFormat($dates['end_date'],
1930 CRM_Utils_Date
::customFormat($dates['join_date'],
1938 $updateStatusId = $status['id'] ??
NULL;
1941 // if IPN/Pay-Later set status to: PENDING
1942 $updateStatusId = array_search('Pending', $allStatus);
1945 if (!empty($membershipSource)) {
1946 $memParams['source'] = $membershipSource;
1948 $memParams['is_test'] = $is_test;
1949 $memParams['is_pay_later'] = $isPayLater;
1951 // Putting this in an IF is precautionary as it seems likely that it would be ignored if empty, but
1952 // perhaps shouldn't be?
1953 if ($contributionRecurID) {
1954 $memParams['contribution_recur_id'] = $contributionRecurID;
1957 //if we decided status here and want to skip status
1958 //calculation in create( ); then need to pass 'skipStatusCal'.
1959 if ($updateStatusId) {
1960 $memParams['status_id'] = $updateStatusId;
1961 $memParams['skipStatusCal'] = TRUE;
1964 //since we are renewing,
1965 //make status override false.
1966 $memParams['is_override'] = FALSE;
1968 //CRM-4027, create log w/ individual contact.
1970 // @todo this param is likely unused now.
1971 $memParams['is_for_organization'] = TRUE;
1973 $params['modified_id'] = $modifiedID ??
$contactID;
1975 $memParams['contribution'] = $contribution;
1976 $memParams['custom'] = $customFieldsFormatted;
1977 // Load all line items & process all in membership. Don't do in contribution.
1978 // Relevant tests in api_v3_ContributionPageTest.
1979 $memParams['line_item'] = $lineItems;
1980 // @todo stop passing $ids (membership and userId may be set by this point)
1981 $membership = self
::create($memParams, $ids);
1983 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
1984 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
1985 $membership->find(TRUE);
1987 return [$membership, $renewalMode, $dates];
1991 * Get line items representing the default price set.
1993 * @param int $membershipOrg
1994 * @param int $membershipTypeID
1995 * @param float $total_amount
1996 * @param int $priceSetId
2000 public static function setQuickConfigMembershipParameters($membershipOrg, $membershipTypeID, $total_amount, $priceSetId) {
2001 $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
2003 // The name of the price field corresponds to the membership_type organization contact.
2005 'price_set_id' => $priceSetId,
2006 'name' => $membershipOrg,
2009 CRM_Price_BAO_PriceField
::retrieve($params, $results);
2011 if (!empty($results)) {
2012 $fields[$results['id']] = $priceSets['fields'][$results['id']];
2013 $fid = $results['id'];
2014 $editedFieldParams = [
2015 'price_field_id' => $results['id'],
2016 'membership_type_id' => $membershipTypeID,
2019 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $results);
2020 $fields[$fid]['options'][$results['id']] = $priceSets['fields'][$fid]['options'][$results['id']];
2021 if (!empty($total_amount)) {
2022 $fields[$fid]['options'][$results['id']]['amount'] = $total_amount;
2026 $fieldID = key($fields);
2028 'price_set_id' => $priceSetId,
2029 'price_sets' => $priceSets,
2030 'fields' => $fields,
2032 'price_' . $fieldID => $results['id'] ??
NULL,
2035 return $returnParams;
2039 * Update the status of all deceased members to deceased.
2042 * Count of updated contacts.
2044 * @throws \CiviCRM_API3_Exception
2045 * @throws \CRM_Core_Exception
2047 protected static function updateDeceasedMembersStatuses() {
2050 $deceasedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Deceased');
2052 // 'create' context for buildOptions returns only if enabled.
2053 $allStatus = self
::buildOptions('status_id', 'create');
2054 if (array_key_exists($deceasedStatusId, $allStatus) === FALSE) {
2055 // Deceased status is an admin status & is required. We want to fail early if
2056 // it is not present or active.
2057 // We could make the case 'some databases just don't use deceased so we will check
2058 // for the presence of a deceased contact in the DB before rejecting.
2059 if (CRM_Core_DAO
::singleValueQuery('
2060 SELECT count(*) FROM civicrm_contact WHERE is_deceased = 0'
2062 throw new CRM_Core_Exception(
2063 ts("Deceased Membership status is missing or not active. <a href='%1'>Click here to check</a>.",
2064 [1 => CRM_Utils_System
::url('civicrm/admin/member/membershipStatus', 'reset=1')]
2068 $deceasedDAO = CRM_Core_DAO
::executeQuery(
2070 SELECT membership.id as membership_id
2071 FROM civicrm_membership membership
2072 INNER JOIN civicrm_contact ON membership.contact_id = civicrm_contact.id
2073 INNER JOIN civicrm_membership_type ON membership.membership_type_id = civicrm_membership_type.id
2074 AND civicrm_membership_type.is_active = 1
2075 WHERE membership.is_test = 0
2076 AND civicrm_contact.is_deceased = 1
2077 AND membership.status_id <> %1
2079 [1 => [$deceasedStatusId, 'Integer']]
2081 while ($deceasedDAO->fetch()) {
2082 civicrm_api3('membership', 'create', [
2083 'id' => $deceasedDAO->membership_id
,
2084 'status_id' => $deceasedStatusId,
2085 'createActivity' => TRUE,
2086 'skipStatusCal' => TRUE,
2087 'skipRecentView' => TRUE,
2095 * Does the existing membership match the required membership.
2097 * Check before updating that the params are not a match - this is part of avoiding
2098 * a loop if we have already updated.
2100 * https://issues.civicrm.org/jira/browse/CRM-4213
2101 * @param array $params
2103 * @param array $membership
2107 protected static function matchesRequiredMembership($params, $membership) {
2108 foreach (['start_date', 'end_date'] as $date) {
2109 if (CRM_Utils_Time
::strtotime($params[$date]) !== CRM_Utils_Time
::strtotime($membership[$date])) {
2112 if ((int) $params['status_id'] !== (int) $membership['status_id']) {
2115 if ((int) $params['membership_type_id'] !== (int) $membership['membership_type_id']) {
2123 * Params of new membership.
2125 * @param array $params
2128 * @throws \CiviCRM_API3_Exception
2130 protected static function hasExistingInheritedMembership($params) {
2131 foreach (civicrm_api3('Membership', 'get', ['contact_id' => $params['contact_id']])['values'] as $membership) {
2132 if (!empty($membership['owner_membership_id'])
2133 && $membership['membership_type_id'] === $params['membership_type_id']
2134 && (int) $params['owner_membership_id'] !== (int) $membership['owner_membership_id']
2136 // Inheriting it from another contact, don't update here.
2139 if (self
::matchesRequiredMembership($params, $membership)) {
2147 * Process price set and line items.
2149 * @param int $membershipId
2150 * @param array $lineItem
2152 * @throws \CiviCRM_API3_Exception
2154 public function processPriceSet($membershipId, $lineItem) {
2155 //FIXME : need to move this too
2156 if (!$membershipId ||
!is_array($lineItem)
2157 || CRM_Utils_System
::isNull($lineItem)
2162 foreach ($lineItem as $priceSetId => $values) {
2166 foreach ($values as $line) {
2167 $line['entity_table'] = 'civicrm_membership';
2168 $line['entity_id'] = $membershipId;
2169 CRM_Price_BAO_LineItem
::create($line);
2175 * Retrieve the contribution id for the associated Membership id.
2176 * @todo we should get this off the line item
2178 * @param int $membershipId
2181 * if more than one payment associated with membership id need to be returned.
2185 * @todo we should get this off the line item
2188 public static function getMembershipContributionId($membershipId, $all = FALSE) {
2190 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
2191 $membershipPayment->membership_id
= $membershipId;
2192 if ($all && $membershipPayment->find()) {
2193 $contributionIds = [];
2194 while ($membershipPayment->fetch()) {
2195 $contributionIds[] = $membershipPayment->contribution_id
;
2197 return $contributionIds;
2200 if ($membershipPayment->find(TRUE)) {
2201 return $membershipPayment->contribution_id
;
2207 * The function checks and updates the status of all membership records for a given domain using the
2208 * calc_membership_status and update_contact_membership APIs.
2211 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
2213 * @param array $params
2214 * only_active_membership_types, exclude_test_memberships, exclude_membership_status_ids
2218 * @throws \CiviCRM_API3_Exception
2219 * @throws \CRM_Core_Exception
2221 public static function updateAllMembershipStatus($params = []) {
2222 // We want all of the statuses as id => name, even the disabled ones (cf.
2223 // CRM-15475), to identify which are Pending, Deceased, Cancelled, and
2225 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'validate');
2226 if (empty($params['exclude_membership_status_ids'])) {
2227 $params['exclude_membership_status_ids'] = [
2228 array_search('Pending', $allStatus),
2229 array_search('Cancelled', $allStatus),
2230 array_search('Expired', $allStatus) ?
: 0,
2231 array_search('Deceased', $allStatus),
2234 // Deceased is *always* excluded because it is has very specific processing below.
2235 elseif (!in_array(array_search('Deceased', $allStatus), $params['exclude_membership_status_ids'])) {
2236 $params['exclude_membership_status_ids'][] = array_search('Deceased', $allStatus);
2239 for ($index = 0; $index < count($params['exclude_membership_status_ids']); $index++
) {
2240 $queryParams[$index] = [$params['exclude_membership_status_ids'][$index], 'Integer'];
2242 $membershipStatusClause = 'civicrm_membership.status_id NOT IN (%' . implode(', %', array_keys($queryParams)) . ')';
2244 // Tests for this function are in api_v3_JobTest. Please add tests for all updates.
2246 $updateCount = $processCount = self
::updateDeceasedMembersStatuses();
2248 $whereClauses[] = 'civicrm_contact.is_deceased = 0';
2249 if ($params['exclude_test_memberships']) {
2250 $whereClauses[] = 'civicrm_membership.is_test = 0';
2252 $whereClause = implode(' AND ', $whereClauses);
2253 $activeMembershipClause = '';
2254 if ($params['only_active_membership_types']) {
2255 $activeMembershipClause = ' AND civicrm_membership_type.is_active = 1';
2258 // This query retrieves ALL memberships of active types.
2260 SELECT civicrm_membership.id as membership_id,
2261 civicrm_membership.is_override as is_override,
2262 civicrm_membership.status_override_end_date as status_override_end_date,
2263 civicrm_membership.membership_type_id as membership_type_id,
2264 civicrm_membership.status_id as status_id,
2265 civicrm_membership.join_date as join_date,
2266 civicrm_membership.start_date as start_date,
2267 civicrm_membership.end_date as end_date,
2268 civicrm_membership.source as source,
2269 civicrm_contact.id as contact_id,
2270 civicrm_membership.owner_membership_id as owner_membership_id,
2271 civicrm_membership.contribution_recur_id as recur_id
2272 FROM civicrm_membership
2273 INNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )
2274 INNER JOIN civicrm_membership_type ON
2275 (civicrm_membership.membership_type_id = civicrm_membership_type.id {$activeMembershipClause})
2276 WHERE {$whereClause}";
2278 $query = $baseQuery . " AND civicrm_membership.is_override IS NOT NULL AND civicrm_membership.status_override_end_date IS NOT NULL";
2279 $dao1 = CRM_Core_DAO
::executeQuery($query);
2280 while ($dao1->fetch()) {
2281 self
::processOverriddenUntilDateMembership($dao1);
2284 $query = $baseQuery . " AND (civicrm_membership.is_override = 0 OR civicrm_membership.is_override IS NULL)
2285 AND {$membershipStatusClause}
2286 AND civicrm_membership.owner_membership_id IS NULL ";
2288 $allMembershipTypes = CRM_Member_BAO_MembershipType
::getAllMembershipTypes();
2290 $dao2 = CRM_Core_DAO
::executeQuery($query, $queryParams);
2292 while ($dao2->fetch()) {
2295 // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses
2296 //get the membership status as per id.
2297 $newStatus = civicrm_api3('membership_status', 'calc',
2299 'membership_id' => $dao2->membership_id
,
2300 'ignore_admin_only' => TRUE,
2303 $statusId = $newStatus['id'] ??
NULL;
2305 //process only when status change.
2307 $statusId != $dao2->status_id
2310 'id' => $dao2->membership_id
,
2311 'skipStatusCal' => TRUE,
2312 'skipRecentView' => TRUE,
2313 'status_id' => $statusId,
2314 'createActivity' => TRUE,
2317 //process member record.
2318 civicrm_api3('membership', 'create', $memberParams);
2322 $result['is_error'] = 0;
2323 $result['messages'] = ts('Processed %1 membership records. Updated %2 records.', [
2331 * Set is_override for the 'overridden until date' membership to
2332 * False and clears the 'until date' field in case the 'until date'
2333 * is equal or after today date.
2335 * @param CRM_Core_DAO $membership
2336 * The membership to be processed
2338 * @throws \CiviCRM_API3_Exception
2340 private static function processOverriddenUntilDateMembership($membership) {
2341 $isOverriddenUntilDate = !empty($membership->is_override
) && !empty($membership->status_override_end_date
);
2342 if (!$isOverriddenUntilDate) {
2346 $todayDate = new DateTime();
2347 $todayDate->setTime(0, 0);
2349 $overrideEndDate = new DateTime($membership->status_override_end_date
);
2350 $overrideEndDate->setTime(0, 0);
2352 $datesDifference = $todayDate->diff($overrideEndDate);
2353 $daysDifference = (int) $datesDifference->format('%R%a');
2354 if ($daysDifference <= 0) {
2356 'id' => $membership->membership_id
,
2357 'is_override' => FALSE,
2358 'status_override_end_date' => 'null',
2360 civicrm_api3('membership', 'create', $params);
2365 * Returns the membership types for a particular contact
2366 * who has lifetime membership without end date.
2368 * @param int $contactID
2369 * @param bool $isTest
2370 * @param bool $onlyLifeTime
2374 public static function getAllContactMembership($contactID, $isTest = FALSE, $onlyLifeTime = FALSE) {
2375 $contactMembershipType = [];
2377 return $contactMembershipType;
2380 $dao = new CRM_Member_DAO_Membership();
2381 $dao->contact_id
= $contactID;
2382 $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
2383 $dao->whereAdd("status_id != $pendingStatusId");
2386 $dao->is_test
= $isTest;
2389 $dao->whereAdd('is_test IS NULL OR is_test = 0');
2392 if ($onlyLifeTime) {
2393 $dao->whereAdd('end_date IS NULL');
2397 while ($dao->fetch()) {
2399 CRM_Core_DAO
::storeValues($dao, $membership);
2400 $contactMembershipType[$dao->membership_type_id
] = $membership;
2402 return $contactMembershipType;
2406 * Record contribution record associated with membership.
2407 * This will update an existing contribution if $params['contribution_id'] is passed in.
2408 * This will create a MembershipPayment to link the contribution and membership
2410 * @param array $params
2411 * Array of submitted params.
2413 * @return CRM_Contribute_BAO_Contribution
2414 * @throws \CRM_Core_Exception
2415 * @throws \CiviCRM_API3_Exception
2417 public static function recordMembershipContribution(&$params) {
2418 $contributionParams = [];
2419 $config = CRM_Core_Config
::singleton();
2420 $contributionParams['currency'] = $config->defaultCurrency
;
2421 $contributionParams['receipt_date'] = !empty($params['receipt_date']) ?
$params['receipt_date'] : 'null';
2422 $contributionParams['source'] = $params['contribution_source'] ??
NULL;
2423 $contributionParams['non_deductible_amount'] = 'null';
2424 $contributionParams['skipCleanMoney'] = TRUE;
2425 $contributionParams['payment_processor'] = $params['payment_processor_id'] ??
NULL;
2426 $contributionSoftParams = $params['soft_credit'] ??
NULL;
2427 $recordContribution = [
2432 'financial_type_id',
2433 'payment_instrument_id',
2437 'contribution_status_id',
2444 'contribution_recur_id',
2448 foreach ($recordContribution as $f) {
2449 $contributionParams[$f] = $params[$f] ??
NULL;
2452 if (!empty($params['contribution_id'])) {
2453 $contributionParams['id'] = $params['contribution_id'];
2455 // make entry in batch entity batch table
2456 if (!empty($params['batch_id'])) {
2457 $contributionParams['batch_id'] = $params['batch_id'];
2460 if (!empty($params['contribution_contact_id'])) {
2461 // deal with possibility of a different person paying for contribution
2462 $contributionParams['contact_id'] = $params['contribution_contact_id'];
2465 if (!empty($params['processPriceSet']) &&
2466 !empty($params['lineItems'])
2468 $contributionParams['line_item'] = $params['lineItems'] ??
NULL;
2471 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams);
2473 //CRM-13981, create new soft-credit record as to record payment from different person for this membership
2474 if (!empty($contributionSoftParams)) {
2475 if (!empty($params['batch_id'])) {
2476 foreach ($contributionSoftParams as $contributionSoft) {
2477 $contributionSoft['contribution_id'] = $contribution->id
;
2478 $contributionSoft['currency'] = $contribution->currency
;
2479 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoft);
2483 $contributionSoftParams['contribution_id'] = $contribution->id
;
2484 $contributionSoftParams['currency'] = $contribution->currency
;
2485 $contributionSoftParams['amount'] = $contribution->total_amount
;
2486 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoftParams);
2490 // store contribution id
2491 $params['contribution_id'] = $contribution->id
;
2493 // Create membership payment if it does not already exist
2494 $membershipPayment = civicrm_api3('MembershipPayment', 'get', [
2495 'contribution_id' => $contribution->id
,
2497 if (empty($membershipPayment['count'])) {
2498 civicrm_api3('MembershipPayment', 'create', [
2499 'membership_id' => $params['membership_id'],
2500 'contribution_id' => $contribution->id
,
2504 return $contribution;
2508 * @todo document me - I seem a bit out of date....
2510 public static function _getActTypes() {
2511 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2512 self
::$_renewalActType = CRM_Utils_Array
::key('Membership Renewal', $activityTypes);
2513 self
::$_signupActType = CRM_Utils_Array
::key('Membership Signup', $activityTypes);
2517 * Get all Cancelled Membership(s) for a contact
2519 * @param int $contactID
2521 * @param bool $isTest
2525 * Array of membership type
2527 public static function getContactsCancelledMembership($contactID, $isTest = FALSE) {
2531 $query = 'SELECT membership_type_id FROM civicrm_membership WHERE contact_id = %1 AND status_id = %2 AND is_test = %3';
2533 1 => [$contactID, 'Integer'],
2538 CRM_Member_PseudoConstant
::membershipStatus(
2540 " name = 'Cancelled' ",
2548 3 => [$isTest, 'Boolean'],
2551 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
2552 $cancelledMembershipIds = [];
2553 while ($dao->fetch()) {
2554 $cancelledMembershipIds[] = $dao->membership_type_id
;
2556 return $cancelledMembershipIds;
2560 * Merges the memberships from otherContactID to mainContactID.
2562 * General idea is to merge memberships in regards to their type. We
2563 * move the other contact’s contributions to the main contact’s
2564 * membership which has the same type (if any) and then we update
2565 * membership to avoid loosing `join_date`, `end_date`, and
2566 * `status_id`. In this function, we don’t touch the contributions
2567 * directly (CRM_Dedupe_Merger::moveContactBelongings() takes care
2570 * This function adds new SQL queries to the $sqlQueries parameter.
2572 * @param int $mainContactID
2573 * Contact id of main contact record.
2574 * @param int $otherContactID
2575 * Contact id of record which is going to merge.
2576 * @param array $sqlQueries
2577 * (reference) array of SQL queries to be executed.
2578 * @param array $tables
2579 * List of tables that have to be merged.
2580 * @param array $tableOperations
2581 * Special options/params for some tables to be merged.
2583 * @see CRM_Dedupe_Merger::cpTables()
2585 public static function mergeMemberships($mainContactID, $otherContactID, &$sqlQueries, $tables, $tableOperations) {
2587 * If the user requests not to merge memberships but to add them,
2588 * just attribute the `civicrm_membership` to the
2589 * `$mainContactID`. We have to do this here since the general
2590 * merge process is bypassed by this function.
2592 if (array_key_exists("civicrm_membership", $tableOperations) && $tableOperations['civicrm_membership']['add']) {
2593 $sqlQueries[] = "UPDATE IGNORE civicrm_membership SET contact_id = $mainContactID WHERE contact_id = $otherContactID";
2598 * Retrieve all memberships that belongs to each contacts and
2599 * keep track of each membership type.
2601 $mainContactMemberships = [];
2602 $otherContactMemberships = [];
2604 $sql = "SELECT id, membership_type_id FROM civicrm_membership membership WHERE contact_id = %1";
2605 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$mainContactID, "Integer"]]);
2606 while ($dao->fetch()) {
2607 $mainContactMemberships[$dao->id
] = $dao->membership_type_id
;
2610 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$otherContactID, "Integer"]]);
2611 while ($dao->fetch()) {
2612 $otherContactMemberships[$dao->id
] = $dao->membership_type_id
;
2616 * For each membership, move related contributions to the main
2617 * contact’s membership (by updating `membership_payments`). Then,
2618 * update membership’s `join_date` (if the other membership’s
2619 * join_date is older) and `end_date` (if the other membership’s
2620 * `end_date` is newer) and `status_id` (if the newly calculated
2621 * status is different).
2623 * FIXME: what should we do if we have multiple memberships with
2624 * the same type (currently we only take the first one)?
2627 foreach ($otherContactMemberships as $otherMembershipId => $otherMembershipTypeId) {
2628 if ($newMembershipId = array_search($otherMembershipTypeId, $mainContactMemberships)) {
2631 * Move other membership’s contributions to the main one only
2632 * if user requested to merge contributions.
2634 if (!empty($tables) && in_array('civicrm_contribution', $tables)) {
2635 $newSql[] = "UPDATE civicrm_membership_payment SET membership_id=$newMembershipId WHERE membership_id=$otherMembershipId";
2638 $sql = "SELECT * FROM civicrm_membership membership WHERE id = %1";
2640 $newMembership = CRM_Member_DAO_Membership
::findById($newMembershipId);
2641 $otherMembership = CRM_Member_DAO_Membership
::findById($otherMembershipId);
2644 if (new DateTime($otherMembership->join_date
) < new DateTime($newMembership->join_date
)) {
2645 $updates["join_date"] = $otherMembership->join_date
;
2648 if (new DateTime($otherMembership->end_date
) > new DateTime($newMembership->end_date
)) {
2649 $updates["end_date"] = $otherMembership->end_date
;
2652 if (count($updates)) {
2657 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
2658 $updates["start_date"] ??
$newMembership->start_date
,
2659 $updates["end_date"] ??
$newMembership->end_date
,
2660 $updates["join_date"] ??
$newMembership->join_date
,
2667 if (!empty($status['id']) and $status['id'] != $newMembership->status_id
) {
2668 $updates['status_id'] = $status['id'];
2672 foreach ($updates as $k => $v) {
2673 $updates_sql[] = "$k = '{$v}'";
2676 $newSql[] = sprintf("UPDATE civicrm_membership SET %s WHERE id=%s", implode(", ", $updates_sql), $newMembershipId);
2677 $newSql[] = sprintf("DELETE FROM civicrm_membership WHERE id=%s", $otherMembershipId);
2683 $sqlQueries = array_merge($sqlQueries, $newSql);
2687 * Update membership status to deceased.
2688 * function return the status message for updated membership.
2690 * @param array $deceasedParams
2695 * @param string $contactType
2697 * @return null|string
2698 * $updateMembershipMsg string status message for updated membership.
2700 public static function updateMembershipStatus($deceasedParams, $contactType) {
2701 $updateMembershipMsg = NULL;
2702 $contactId = $deceasedParams['contact_id'];
2703 $deceasedDate = $deceasedParams['deceased_date'];
2705 // process to set membership status to deceased for both active/inactive membership
2707 $contactType === 'Individual' &&
2708 !empty($deceasedParams['is_deceased'])
2711 $userId = CRM_Core_Session
::getLoggedInContactID() ?
: $contactId;
2713 // get deceased status id
2714 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2715 $deceasedStatusId = array_search('Deceased', $allStatus);
2716 if (!$deceasedStatusId) {
2717 return $updateMembershipMsg;
2720 $today = CRM_Utils_Time
::time();
2721 if ($deceasedDate && CRM_Utils_Time
::strtotime($deceasedDate) > $today) {
2722 return $updateMembershipMsg;
2725 // get non deceased membership
2726 $dao = new CRM_Member_DAO_Membership();
2727 $dao->contact_id
= $contactId;
2728 $dao->whereAdd("status_id != $deceasedStatusId");
2730 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2731 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2733 while ($dao->fetch()) {
2734 // update status to deceased (for both active/inactive membership )
2735 CRM_Core_DAO
::setFieldValue('CRM_Member_DAO_Membership', $dao->id
,
2736 'status_id', $deceasedStatusId
2739 // add membership log
2741 'membership_id' => $dao->id
,
2742 'status_id' => $deceasedStatusId,
2743 'start_date' => CRM_Utils_Date
::isoToMysql($dao->start_date
),
2744 'end_date' => CRM_Utils_Date
::isoToMysql($dao->end_date
),
2745 'modified_id' => $userId,
2746 'modified_date' => CRM_Utils_Time
::date('Ymd'),
2747 'membership_type_id' => $dao->membership_type_id
,
2748 'max_related' => $dao->max_related
,
2751 CRM_Member_BAO_MembershipLog
::add($membershipLog);
2753 //create activity when membership status is changed
2755 'subject' => "Status changed from {$allStatus[$dao->status_id]} to {$allStatus[$deceasedStatusId]}",
2756 'source_contact_id' => $userId,
2757 'target_contact_id' => $dao->contact_id
,
2758 'source_record_id' => $dao->id
,
2759 'activity_type_id' => array_search('Change Membership Status', $activityTypes),
2763 'activity_date_time' => CRM_Utils_Time
::date('Y-m-d H:i:s'),
2765 'is_current_revision' => 1,
2768 civicrm_api('activity', 'create', $activityParam);
2775 CRM_Core_Session
::setStatus(ts("%1 Current membership(s) for this contact have been set to 'Deceased' status.",
2780 return $updateMembershipMsg;