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 * The array that holds all the db ids.
49 * @return CRM_Member_BAO_Membership
50 * @throws \CiviCRM_API3_Exception
52 public static function add(&$params, $ids = []) {
53 $oldStatus = $oldType = NULL;
54 $params['id'] = CRM_Utils_Array
::value('id', $params, CRM_Utils_Array
::value('membership', $ids));
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 = CRM_Utils_Array
::value('log_start_date', $params);
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' => date('Ymd'),
105 'membership_type_id' => $values[$membership->id
]['membership_type_id'],
106 'max_related' => $membership->max_related
,
109 $session = CRM_Core_Session
::singleton();
110 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
111 if ($session->get('userID')) {
112 $membershipLog['modified_id'] = $session->get('userID');
114 elseif (!empty($ids['userId'])) {
115 $membershipLog['modified_id'] = $ids['userId'];
118 $membershipLog['modified_id'] = $membership->contact_id
;
121 CRM_Member_BAO_MembershipLog
::add($membershipLog);
123 // reset the group contact cache since smart groups might be affected due to this
124 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
126 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
128 'status_id' => CRM_Utils_Array
::value('membership_activity_status', $params, 'Completed'),
130 if (in_array($allStatus[$membership->status_id
], ['Pending', 'Grace'])) {
131 $activityParams['status_id'] = 'Scheduled';
133 $activityParams['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', $activityParams['status_id']);
135 $targetContactID = $membership->contact_id
;
136 if (!empty($params['is_for_organization'])) {
137 $targetContactID = CRM_Utils_Array
::value('userId', $ids);
140 if ($membership->status_id
!= $oldStatus) {
141 CRM_Activity_BAO_Activity
::addActivity($membership,
142 'Change Membership Status',
145 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
146 'source_contact_id' => $membershipLog['modified_id'],
147 'priority_id' => 'Normal',
151 if (isset($membership->membership_type_id
) && $membership->membership_type_id
!= $oldType) {
152 $membershipTypes = CRM_Member_BAO_Membership
::buildOptions('membership_type_id', 'get');
153 CRM_Activity_BAO_Activity
::addActivity($membership,
154 'Change Membership Type',
157 'subject' => "Type changed from {$membershipTypes[$oldType]} to {$membershipTypes[$membership->membership_type_id]}",
158 'source_contact_id' => $membershipLog['modified_id'],
159 'priority_id' => 'Normal',
164 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
165 $activityParams['id'] = CRM_Utils_Array
::value('id',
166 civicrm_api3('Activity', 'Get',
168 'source_record_id' => $membership->id
,
169 'activity_type_id' => $activityType,
170 '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'])) {
253 $dates = ['start_date', 'end_date', 'join_date'];
254 // Declare these out of courtesy as IDEs don't pick up the setting of them below.
255 $start_date = $end_date = $join_date = NULL;
256 foreach ($dates as $date) {
257 $
$date = $params[$date] = CRM_Utils_Date
::processDate(CRM_Utils_Array
::value($date, $params), NULL, TRUE, 'Ymd');
260 //fix for CRM-3570, during import exclude the statuses those having is_admin = 1
261 $excludeIsAdmin = CRM_Utils_Array
::value('exclude_is_admin', $params, FALSE);
263 //CRM-3724 always skip is_admin if is_override != true.
264 if (!$excludeIsAdmin && empty($params['is_override'])) {
265 $excludeIsAdmin = TRUE;
268 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($start_date, $end_date, $join_date,
269 'today', $excludeIsAdmin, CRM_Utils_Array
::value('membership_type_id', $params), $params
271 if (empty($calcStatus)) {
272 // Redirect the form in case of error
273 // @todo this redirect in the BAO layer is really bad & should be moved to the form layer
274 // however since we have no idea how (if) this is triggered we can't safely move / remove it
275 // NB I tried really hard to trigger this error from backoffice membership form in order to test it
276 // and am convinced form validation is complete on that form WRT this error.
278 'message_title' => ts('No valid membership status for given dates.'),
279 'legacy_redirect_path' => 'civicrm/contact/view',
280 'legacy_redirect_query' => "reset=1&force=1&cid={$params['contact_id']}&selectedChild=member",
282 throw new CRM_Core_Exception(ts(
283 "The membership cannot be saved because the status cannot be calculated for start_date: $start_date end_date $end_date join_date $join_date as at " . 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
::getMembershipTypeDetails($params['membership_type_id']);
301 if (isset($membershipType['relationship_type_id'])) {
302 $params['max_related'] = CRM_Utils_Array
::value('max_related', $membershipType);
307 $transaction = new CRM_Core_Transaction();
309 // @todo remove $ids from here - $ids['contribution'] is not used or set by add. $ids['userId'] is used. $ids['membership'] is used if $params['id'] is not set
310 $membership = self
::add($params, $ids);
312 if (is_a($membership, 'CRM_Core_Error')) {
313 $transaction->rollback();
317 // add custom field values
318 if (!empty($params['custom']) && is_array($params['custom'])
320 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_membership', $membership->id
);
323 $params['membership_id'] = $membership->id
;
324 // @todo further cleanup required to remove use of $ids['contribution'] from here
325 if (isset($ids['membership'])) {
326 $ids['contribution'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment',
331 // @todo this is a temporary step to removing $ids['contribution'] completely
332 if (empty($params['contribution_id']) && !empty($ids['contribution'])) {
333 $params['contribution_id'] = $ids['contribution'];
337 // This code ensures a line item is created but it is recommended you pass in 'skipLineItem' or 'line_item'
338 if (empty($params['line_item']) && !empty($params['membership_type_id']) && empty($params['skipLineItem'])) {
339 CRM_Price_BAO_LineItem
::getLineItemArray($params, NULL, 'membership', $params['membership_type_id']);
341 $params['skipLineItem'] = TRUE;
343 // Record contribution for this membership and create a MembershipPayment
344 if (!empty($params['contribution_status_id']) && empty($params['relate_contribution_id'])) {
345 $memInfo = array_merge($params, ['membership_id' => $membership->id
]);
346 $params['contribution'] = self
::recordMembershipContribution($memInfo);
349 // Add/update MembershipPayment record for this membership if it is a related contribution
350 if (!empty($params['relate_contribution_id'])) {
351 $membershipPaymentParams = [
352 'membership_id' => $membership->id
,
353 'membership_type_id' => $membership->membership_type_id
,
354 'contribution_id' => $params['relate_contribution_id'],
356 civicrm_api3('MembershipPayment', 'create', $membershipPaymentParams);
359 if (!empty($params['lineItems'])) {
360 $params['line_item'] = $params['lineItems'];
363 // do cleanup line items if membership edit the Membership type.
364 if (empty($ids['contribution']) && !empty($ids['membership'])) {
365 CRM_Price_BAO_LineItem
::deleteLineItems($ids['membership'], 'civicrm_membership');
367 // @todo - we should ONLY do the below if a contribution is created. Let's
368 // get some deprecation notices in here & see where it's hit & work to eliminate.
369 // This could happen if there is no contribution or we are in one of many
370 // weird and wonderful flows. This is scary code. Keep adding tests.
371 if (!empty($params['line_item']) && empty($ids['contribution']) && empty($params['contribution_id'])) {
373 foreach ($params['line_item'] as $priceSetId => $lineItems) {
374 foreach ($lineItems as $lineIndex => $lineItem) {
375 $lineMembershipType = CRM_Utils_Array
::value('membership_type_id', $lineItem);
376 if (!empty($params['contribution'])) {
377 $params['line_item'][$priceSetId][$lineIndex]['contribution_id'] = $params['contribution']->id
;
379 if ($lineMembershipType && $lineMembershipType == CRM_Utils_Array
::value('membership_type_id', $params)) {
380 $params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $membership->id
;
381 $params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_membership';
383 elseif (!$lineMembershipType && !empty($params['contribution'])) {
384 $params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $params['contribution']->id
;
385 $params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_contribution';
389 CRM_Price_BAO_LineItem
::processPriceSet(
391 $params['line_item'],
392 CRM_Utils_Array
::value('contribution', $params)
396 $transaction->commit();
398 self
::createRelatedMemberships($params, $membership);
400 // do not add to recent items for import, CRM-4399
401 if (empty($params['skipRecentView'])) {
402 $url = CRM_Utils_System
::url('civicrm/contact/view/membership',
403 "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
405 if (empty($membership->membership_type_id
)) {
406 // ie in an update situation.
407 $membership->find(TRUE);
409 $membershipTypes = CRM_Member_PseudoConstant
::membershipType();
410 $title = CRM_Contact_BAO_Contact
::displayName($membership->contact_id
) . ' - ' . ts('Membership Type:') . ' ' . $membershipTypes[$membership->membership_type_id
];
413 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::UPDATE
)) {
414 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
415 "action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
418 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::DELETE
)) {
419 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
420 "action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
424 // add the recently created Membership
425 CRM_Utils_Recent
::add($title,
429 $membership->contact_id
,
439 * Check the membership extended through relationship.
441 * @param int $membershipTypeID
442 * Membership type id.
443 * @param int $contactId
449 * array of contact_id of all related contacts.
451 * @throws \CRM_Core_Exception
452 * @throws \CiviCRM_API3_Exception
454 public static function checkMembershipRelationship($membershipTypeID, $contactId, $action = CRM_Core_Action
::ADD
) {
457 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipTypeID);
459 if (isset($membershipType['relationship_type_id'])) {
460 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
461 CRM_Contact_BAO_Relationship
::CURRENT
463 if ($action & CRM_Core_Action
::UPDATE
) {
464 $pastRelationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
465 CRM_Contact_BAO_Relationship
::PAST
467 $relationships = array_merge($relationships, $pastRelationships);
471 if (!empty($relationships)) {
472 // check for each contact relationships
473 foreach ($relationships as $values) {
474 //get details of the relationship type
475 $relType = ['id' => $values['civicrm_relationship_type_id']];
477 CRM_Contact_BAO_RelationshipType
::retrieve($relType, $relValues);
478 // Check if contact's relationship type exists in membership type
480 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_type_id']);
481 $relDirections = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_direction']);
482 $bidirectional = FALSE;
483 foreach ($relTypeIds as $key => $value) {
484 $relTypeDirs[] = $value . '_' . $relDirections[$key];
485 if (in_array($value, $relType) &&
486 $relValues['name_a_b'] == $relValues['name_b_a']
488 $bidirectional = TRUE;
492 $relTypeDir = $values['civicrm_relationship_type_id'] . '_' . $values['rtype'];
493 if ($bidirectional ||
in_array($relTypeDir, $relTypeDirs)) {
494 // $values['status'] is going to have value for
495 // current or past relationships.
496 $contacts[$values['cid']] = $values['status'];
501 // Sort by contact_id ascending
507 * Retrieve DB object based on input parameters.
509 * It also stores all the retrieved values in the default array.
511 * @param array $params
512 * (reference ) an assoc array of name/value pairs.
513 * @param array $defaults
514 * (reference ) an assoc array to hold the name / value pairs.
515 * in a hierarchical manner
517 * @return CRM_Member_BAO_Membership
519 public static function retrieve(&$params, &$defaults) {
520 $membership = new CRM_Member_DAO_Membership();
522 $membership->copyValues($params);
524 if ($membership->find(TRUE)) {
525 CRM_Core_DAO
::storeValues($membership, $defaults);
527 //get the membership status and type values.
528 $statusANDType = self
::getStatusANDTypeValues($membership->id
);
529 foreach (['status', 'membership_type'] as $fld) {
530 $defaults[$fld] = CRM_Utils_Array
::value($fld, $statusANDType[$membership->id
]);
532 if (!empty($statusANDType[$membership->id
]['is_current_member'])) {
533 $defaults['active'] = TRUE;
543 * Get membership status and membership type values.
545 * @param int $membershipId
546 * Membership id of values to return.
549 * Array of key value pairs
551 public static function getStatusANDTypeValues($membershipId) {
553 if (!$membershipId) {
557 SELECT membership.id as id,
558 status.id as status_id,
559 status.label as status,
560 status.is_current_member as is_current_member,
561 type.id as membership_type_id,
562 type.name as membership_type,
563 type.relationship_type_id as relationship_type_id
564 FROM civicrm_membership membership
565 INNER JOIN civicrm_membership_status status ON ( status.id = membership.status_id )
566 INNER JOIN civicrm_membership_type type ON ( type.id = membership.membership_type_id )
567 WHERE membership.id = %1';
568 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$membershipId, 'Positive']]);
573 'membership_type_id',
575 'relationship_type_id',
577 while ($dao->fetch()) {
578 foreach ($properties as $property) {
579 $values[$dao->id
][$property] = $dao->$property;
589 * Wrapper for most delete calls. Use this unless you JUST want to delete related memberships w/o deleting the parent.
591 * @param int $membershipId
592 * Membership id that needs to be deleted.
593 * @param bool $preserveContrib
596 * Id of deleted Membership on success, false otherwise.
598 public static function del($membershipId, $preserveContrib = FALSE) {
599 //delete related first and then delete parent.
600 self
::deleteRelatedMemberships($membershipId);
601 return self
::deleteMembership($membershipId, $preserveContrib);
607 * @param int $membershipId
608 * Membership id that needs to be deleted.
609 * @param bool $preserveContrib
612 * Id of deleted Membership on success, false otherwise.
614 public static function deleteMembership($membershipId, $preserveContrib = FALSE) {
615 // CRM-12147, retrieve membership data before we delete it for hooks
616 $params = ['id' => $membershipId];
618 $memberships = self
::getValues($params, $memValues);
620 $membership = $memberships[$membershipId];
622 CRM_Utils_Hook
::pre('delete', 'Membership', $membershipId, $memValues);
624 $transaction = new CRM_Core_Transaction();
627 //delete activity record
628 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
631 $deleteActivity = FALSE;
632 $membershipActivities = [
634 'Membership Renewal',
635 'Change Membership Status',
636 'Change Membership Type',
637 'Membership Renewal Reminder',
639 foreach ($membershipActivities as $membershipActivity) {
640 $activityId = array_search($membershipActivity, $activityTypes);
642 $params['activity_type_id'][] = $activityId;
643 $deleteActivity = TRUE;
646 if ($deleteActivity) {
647 $params['source_record_id'] = $membershipId;
648 CRM_Activity_BAO_Activity
::deleteActivity($params);
650 self
::deleteMembershipPayment($membershipId, $preserveContrib);
652 $results = $membership->delete();
653 $transaction->commit();
655 CRM_Utils_Hook
::post('delete', 'Membership', $membership->id
, $membership);
657 // delete the recently created Membership
658 $membershipRecent = [
659 'id' => $membershipId,
660 'type' => 'Membership',
662 CRM_Utils_Recent
::del($membershipRecent);
668 * Delete related memberships.
670 * @param int $ownerMembershipId
671 * @param int $contactId
675 public static function deleteRelatedMemberships($ownerMembershipId, $contactId = NULL) {
676 if (!$ownerMembershipId && !$contactId) {
680 $membership = new CRM_Member_DAO_Membership();
681 $membership->owner_membership_id
= $ownerMembershipId;
684 $membership->contact_id
= $contactId;
688 while ($membership->fetch()) {
689 //delete related first and then delete parent.
690 self
::deleteRelatedMemberships($membership->id
);
691 self
::deleteMembership($membership->id
);
696 * Obtain active/inactive memberships from the list of memberships passed to it.
698 * @param array $memberships
699 * Membership records.
700 * @param string $status
701 * Active or inactive.
704 * array of memberships based on status
706 public static function activeMembers($memberships, $status = 'active') {
708 if ($status == 'active') {
709 foreach ($memberships as $f => $v) {
710 if (!empty($v['active'])) {
716 elseif ($status == 'inactive') {
717 foreach ($memberships as $f => $v) {
718 if (empty($v['active'])) {
728 * Return Membership Block info in Contribution Pages.
731 * Contribution page id.
735 public static function getMembershipBlock($pageID) {
736 $membershipBlock = [];
737 $dao = new CRM_Member_DAO_MembershipBlock();
738 $dao->entity_table
= 'civicrm_contribution_page';
740 $dao->entity_id
= $pageID;
742 if ($dao->find(TRUE)) {
743 CRM_Core_DAO
::storeValues($dao, $membershipBlock);
744 if (!empty($membershipBlock['membership_types'])) {
745 $membershipTypes = CRM_Utils_String
::unserialize($membershipBlock['membership_types']);
746 if (!is_array($membershipTypes)) {
747 return $membershipBlock;
750 foreach ($membershipTypes as $key => $value) {
751 $membershipBlock['auto_renew'][$key] = $value;
752 $memTypes[$key] = $key;
754 $membershipBlock['membership_types'] = implode(',', $memTypes);
761 return $membershipBlock;
765 * Return a current membership of given contact.
767 * NB: if more than one membership meets criteria, a randomly selected one is returned.
769 * @param int $contactID
771 * @param int $memType
772 * Membership type, null to retrieve all types.
774 * @param int $membershipId
775 * If provided, then determine if it is current.
776 * @param bool $onlySameParentOrg
777 * True if only Memberships with same parent org as the $memType wanted, false otherwise.
780 * @throws \CiviCRM_API3_Exception
782 public static function getContactMembership($contactID, $memType, $isTest, $membershipId = NULL, $onlySameParentOrg = FALSE) {
783 //check for owner membership id, if it exists update that membership instead: CRM-15992
785 $ownerMemberId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
787 'owner_membership_id', 'id'
789 if ($ownerMemberId) {
790 $membershipId = $ownerMemberId;
791 $contactID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
798 $dao = new CRM_Member_DAO_Membership();
800 $dao->id
= $membershipId;
802 $dao->contact_id
= $contactID;
803 $dao->membership_type_id
= $memType;
805 //fetch proper membership record.
807 $dao->is_test
= $isTest;
810 $dao->whereAdd('is_test IS NULL OR is_test = 0');
813 //avoid pending membership as current membership: CRM-3027
814 $statusIds = [array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus())];
815 if (!$membershipId) {
817 $statusIds[] = array_search(
819 CRM_Member_PseudoConstant
::membershipStatus(
821 " name = 'Cancelled' ",
828 $dao->whereAdd('status_id NOT IN ( ' . implode(',', $statusIds) . ')');
830 // order by start date to find most recent membership first, CRM-4545
831 $dao->orderBy('start_date DESC');
834 if ($onlySameParentOrg && $memType) {
835 // require the same parent org as the $memType
836 $params = ['id' => $memType];
837 $membershipType = [];
838 if (CRM_Member_BAO_MembershipType
::retrieve($params, $membershipType)) {
839 $memberTypesSameParentOrg = civicrm_api3('MembershipType', 'get', [
840 'member_of_contact_id' => $membershipType['member_of_contact_id'],
845 $memberTypesSameParentOrgList = implode(',', array_keys(CRM_Utils_Array
::value('values', $memberTypesSameParentOrg, [])));
846 $dao->whereAdd('membership_type_id IN (' . $memberTypesSameParentOrgList . ')');
850 if ($dao->find(TRUE)) {
852 CRM_Core_DAO
::storeValues($dao, $membership);
853 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
854 $membership['status_id'],
855 'is_current_member', 'id'
857 $ownerMemberId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
859 'owner_membership_id', 'id'
861 if ($ownerMemberId) {
862 $membership['id'] = $membership['membership_id'] = $ownerMemberId;
863 $membership['membership_contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
872 if ($onlySameParentOrg && $memType) {
873 // see if there is a membership that has same parent as $memType but different parent than $membershipID
874 if ($dao->id
&& CRM_Core_Permission
::check('edit memberships')) {
875 // CRM-10016, This is probably a backend renewal, and make sure we return the same membership thats being renewed.
882 unset($dao->membership_type_id
);
883 if ($dao->find(TRUE)) {
885 CRM_Core_DAO
::storeValues($dao, $membership);
886 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
887 $membership['status_id'],
888 'is_current_member', 'id'
897 * Combine all the importable fields from the lower levels object.
899 * @param string $contactType
901 * @param bool $status
904 * array of importable Fields
906 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
907 if (!self
::$_importableFields) {
908 if (!self
::$_importableFields) {
909 self
::$_importableFields = [];
913 $fields = ['' => ['title' => '- ' . ts('do not import') . ' -']];
916 $fields = ['' => ['title' => '- ' . ts('Membership Fields') . ' -']];
919 $tmpFields = CRM_Member_DAO_Membership
::import();
920 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
922 // Using new Dedupe rule.
924 'contact_type' => $contactType,
925 'used' => 'Unsupervised',
927 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
929 $tmpContactField = [];
930 if (is_array($fieldsArray)) {
931 foreach ($fieldsArray as $value) {
932 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
937 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
938 $tmpContactField[trim($value)] = CRM_Utils_Array
::value(trim($value), $contactFields);
940 $title = $tmpContactField[trim($value)]['title'] . " " . ts('(match to contact)');
943 $title = $tmpContactField[trim($value)]['title'];
945 $tmpContactField[trim($value)]['title'] = $title;
948 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
949 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " " . ts('(match to contact)');
951 $tmpFields['membership_contact_id']['title'] = $tmpFields['membership_contact_id']['title'] . " " . ts('(match to contact)');
953 $fields = array_merge($fields, $tmpContactField);
954 $fields = array_merge($fields, $tmpFields);
955 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
956 self
::$_importableFields = $fields;
958 return self
::$_importableFields;
962 * Get all exportable fields.
964 * @return array return array of all exportable fields
966 public static function &exportableFields() {
967 $expFieldMembership = CRM_Member_DAO_Membership
::export();
969 $expFieldsMemType = CRM_Member_DAO_MembershipType
::export();
970 $fields = array_merge($expFieldMembership, $expFieldsMemType);
971 $fields = array_merge($fields, $expFieldMembership);
972 $membershipStatus = [
973 'membership_status' => [
974 'title' => ts('Membership Status'),
975 'name' => 'membership_status',
976 'type' => CRM_Utils_Type
::T_STRING
,
977 'where' => 'civicrm_membership_status.name',
980 //CRM-6161 fix for customdata export
981 $fields = array_merge($fields, $membershipStatus, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
986 * Get membership joins/renewals for a specified membership type.
988 * Specifically, retrieves a count of memberships whose "Membership
989 * Signup" or "Membership Renewal" activity falls in the given date range.
990 * Dates match the pattern "yyyy-mm-dd".
992 * @param int $membershipTypeId
993 * Membership type id.
994 * @param int $startDate
995 * Date on which to start counting.
996 * @param int $endDate
997 * Date on which to end counting.
998 * @param bool|int $isTest if true, membership is for a test site
999 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1002 * the number of members of type $membershipTypeId whose
1003 * start_date is between $startDate and $endDate
1005 public static function getMembershipStarts($membershipTypeId, $startDate, $endDate, $isTest = 0, $isOwner = 0) {
1007 $testClause = 'membership.is_test = 1';
1009 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1012 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1013 self
::_getActTypes();
1016 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1021 SELECT COUNT(DISTINCT membership.id) as member_count
1022 FROM civicrm_membership membership
1023 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id in (%1, %2))
1024 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1025 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1026 WHERE membership.membership_type_id = %3
1027 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1030 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1033 1 => [self
::$_signupActType, 'Integer'],
1034 2 => [self
::$_renewalActType, 'Integer'],
1035 3 => [$membershipTypeId, 'Integer'],
1038 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1039 return (int) $memberCount;
1043 * Get a count of membership for a specified membership type, optionally for a specified date.
1045 * The date must have the form yyyy-mm-dd.
1047 * If $date is omitted, this function counts as a member anyone whose
1048 * membership status_id indicates they're a current member.
1049 * If $date is given, this function counts as a member anyone who:
1050 * -- Has a start_date before $date and end_date after $date, or
1051 * -- Has a start_date before $date and is currently a member, as indicated
1052 * by the the membership's status_id.
1053 * The second condition takes care of records that have no end_date. These
1054 * are assumed to be lifetime memberships.
1056 * @param int $membershipTypeId
1057 * Membership type id.
1058 * @param string $date
1059 * The date for which to retrieve the count.
1060 * @param bool|int $isTest if true, membership is for a test site
1061 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1064 * the number of members of type $membershipTypeId as of $date.
1066 public static function getMembershipCount($membershipTypeId, $date = NULL, $isTest = 0, $isOwner = 0) {
1067 if (!CRM_Utils_Rule
::date($date)) {
1068 CRM_Core_Error
::fatal(ts('Invalid date "%1" (must have form yyyy-mm-dd).', [1 => $date]));
1072 1 => [$membershipTypeId, 'Integer'],
1073 2 => [$isTest, 'Boolean'],
1075 $query = "SELECT count(civicrm_membership.id ) as member_count
1076 FROM civicrm_membership left join civicrm_membership_status on ( civicrm_membership.status_id = civicrm_membership_status.id )
1077 WHERE civicrm_membership.membership_type_id = %1
1078 AND civicrm_membership.contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)
1079 AND civicrm_membership.is_test = %2";
1081 $query .= " AND civicrm_membership_status.is_current_member = 1";
1084 $query .= " AND civicrm_membership.start_date <= '$date' AND civicrm_membership_status.is_current_member = 1";
1087 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1088 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1089 return (int) $memberCount;
1093 * Function check the status of the membership before adding membership for a contact.
1097 public static function statusAvailabilty() {
1098 $membership = new CRM_Member_DAO_MembershipStatus();
1099 $membership->whereAdd('is_active=1');
1100 return $membership->count();
1104 * @deprecated This is not used anywhere and should be removed soon!
1105 * Function for updating a membership record's contribution_recur_id.
1107 * @param CRM_Member_DAO_Membership $membership
1108 * @param \CRM_Contribute_BAO_Contribution|\CRM_Contribute_DAO_Contribution $contribution
1110 public static function updateRecurMembership(CRM_Member_DAO_Membership
$membership, CRM_Contribute_BAO_Contribution
$contribution) {
1111 CRM_Core_Error
::deprecatedFunctionWarning('Use the API instead');
1113 if (empty($contribution->contribution_recur_id
)) {
1118 1 => [$contribution->contribution_recur_id
, 'Integer'],
1119 2 => [$membership->id
, 'Integer'],
1122 $sql = "UPDATE civicrm_membership SET contribution_recur_id = %1 WHERE id = %2";
1123 CRM_Core_DAO
::executeQuery($sql, $params);
1127 * Method to fix membership status of stale membership.
1129 * This method first checks if the membership is stale. If it is,
1130 * then status will be updated based on existing start and end
1131 * dates and log will be added for the status change.
1133 * @param array $currentMembership
1134 * Reference to the array.
1135 * containing all values of
1136 * the current membership
1137 * @param string $changeToday
1138 * In case today needs
1139 * to be customised, null otherwise
1141 * @throws \CRM_Core_Exception
1143 public static function fixMembershipStatusBeforeRenew(&$currentMembership, $changeToday) {
1146 $today = CRM_Utils_Date
::processDate($changeToday, NULL, FALSE, 'Y-m-d');
1149 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
1150 CRM_Utils_Array
::value('start_date', $currentMembership),
1151 CRM_Utils_Array
::value('end_date', $currentMembership),
1152 CRM_Utils_Array
::value('join_date', $currentMembership),
1155 $currentMembership['membership_type_id'],
1159 if (empty($status) ||
empty($status['id'])) {
1160 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.'));
1163 $currentMembership['today_date'] = $today;
1165 if ($status['id'] !== $currentMembership['status_id']) {
1166 $oldStatus = $currentMembership['status_id'];
1167 $memberDAO = new CRM_Member_DAO_Membership();
1168 $memberDAO->id
= $currentMembership['id'];
1169 $memberDAO->find(TRUE);
1171 $memberDAO->status_id
= $status['id'];
1172 $memberDAO->join_date
= CRM_Utils_Date
::isoToMysql($memberDAO->join_date
);
1173 $memberDAO->start_date
= CRM_Utils_Date
::isoToMysql($memberDAO->start_date
);
1174 $memberDAO->end_date
= CRM_Utils_Date
::isoToMysql($memberDAO->end_date
);
1176 CRM_Core_DAO
::storeValues($memberDAO, $currentMembership);
1178 $currentMembership['is_current_member'] = CRM_Core_DAO
::getFieldValue(
1179 'CRM_Member_DAO_MembershipStatus',
1180 $currentMembership['status_id'],
1186 'membership_id' => $currentMembership['id'],
1187 'status_id' => $status['id'],
1188 'start_date' => CRM_Utils_Date
::customFormat(
1189 $currentMembership['start_date'],
1192 'end_date' => CRM_Utils_Date
::customFormat(
1193 $currentMembership['end_date'],
1196 'modified_date' => CRM_Utils_Date
::customFormat(
1197 $currentMembership['today_date'],
1200 'membership_type_id' => $currentMembership['membership_type_id'],
1201 'max_related' => CRM_Utils_Array
::value('max_related', $currentMembership, 0),
1204 $session = CRM_Core_Session
::singleton();
1205 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
1206 if ($session->get('userID')) {
1207 $logParams['modified_id'] = $session->get('userID');
1210 $logParams['modified_id'] = $currentMembership['contact_id'];
1213 //Create activity for status change.
1214 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
1215 CRM_Activity_BAO_Activity
::addActivity($memberDAO,
1216 'Change Membership Status',
1219 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$status['id']]}",
1220 'source_contact_id' => $logParams['modified_id'],
1221 'priority_id' => 'Normal',
1225 CRM_Member_BAO_MembershipLog
::add($logParams);
1230 * Get the contribution page id from the membership record.
1232 * @param int $membershipID
1235 * contribution page id
1237 public static function getContributionPageId($membershipID) {
1239 SELECT c.contribution_page_id as pageID
1240 FROM civicrm_membership_payment mp, civicrm_contribution c
1241 WHERE mp.contribution_id = c.id
1242 AND c.contribution_page_id IS NOT NULL
1243 AND mp.membership_id = " . CRM_Utils_Type
::escape($membershipID, 'Integer')
1244 . " ORDER BY mp.id DESC";
1246 return CRM_Core_DAO
::singleValueQuery($query);
1250 * Updated related memberships.
1252 * @param int $ownerMembershipId
1253 * Owner Membership Id.
1254 * @param array $params
1255 * Formatted array of key => value.
1257 public static function updateRelatedMemberships($ownerMembershipId, $params) {
1258 $membership = new CRM_Member_DAO_Membership();
1259 $membership->owner_membership_id
= $ownerMembershipId;
1260 $membership->find();
1262 while ($membership->fetch()) {
1263 $relatedMembership = new CRM_Member_DAO_Membership();
1264 $relatedMembership->id
= $membership->id
;
1265 $relatedMembership->copyValues($params);
1266 $relatedMembership->save();
1272 * Get list of membership fields for profile.
1274 * For now we only allow custom membership fields to be in
1278 * FIXME: This param is ignored
1281 * the list of membership fields
1283 public static function getMembershipFields($mode = NULL) {
1284 $fields = CRM_Member_DAO_Membership
::export();
1286 unset($fields['membership_contact_id']);
1287 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1289 $membershipType = CRM_Member_DAO_MembershipType
::export();
1291 $membershipStatus = CRM_Member_DAO_MembershipStatus
::export();
1293 $fields = array_merge($fields, $membershipType, $membershipStatus);
1299 * Get the sort name of a contact for a particular membership.
1302 * Id of the membership.
1304 * @return null|string
1305 * sort name of the contact if found
1307 public static function sortName($id) {
1308 $id = CRM_Utils_Type
::escape($id, 'Integer');
1311 SELECT civicrm_contact.sort_name
1312 FROM civicrm_membership, civicrm_contact
1313 WHERE civicrm_membership.contact_id = civicrm_contact.id
1314 AND civicrm_membership.id = {$id}
1316 return CRM_Core_DAO
::singleValueQuery($query);
1320 * Create memberships for related contacts, taking into account the maximum related memberships.
1322 * @param array $params
1323 * Array of key - value pairs.
1324 * @param CRM_Core_DAO $dao
1325 * Membership object.
1327 * @param bool $reset
1329 * @return array|null
1330 * Membership details, if created.
1332 * @throws \CRM_Core_Exception
1333 * @throws \CiviCRM_API3_Exception
1335 public static function createRelatedMemberships(&$params, &$dao, $reset = FALSE) {
1336 // CRM-4213 check for loops, using static variable to record contacts already processed.
1337 if (!isset(\Civi
::$statics[__CLASS__
]['related_contacts'])) {
1338 \Civi
::$statics[__CLASS__
]['related_contacts'] = [];
1342 unset(\Civi
::$statics[__CLASS__
]['related_contacts']);
1345 $relatedContactIds = &\Civi
::$statics[__CLASS__
]['related_contacts'];
1347 $membership = new CRM_Member_DAO_Membership();
1348 $membership->id
= $dao->id
;
1350 // required since create method doesn't return all the
1351 // parameters in the returned membership object
1352 if (!$membership->find(TRUE)) {
1355 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1356 // FIXME : While updating/ renewing the
1357 // membership, if the relationship is PAST then
1358 // the membership of the related contact must be
1360 // For that, getting Membership Status for which
1361 // is_current_member is 0. It works for the
1362 // generated data as there is only one membership
1363 // status having is_current_member = 0.
1364 // But this wont work exactly if there will be
1365 // more than one status having is_current_member = 0.
1366 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
1367 $membershipStatus->is_current_member
= 0;
1368 if ($membershipStatus->find(TRUE)) {
1369 $expiredStatusId = $membershipStatus->id
;
1372 $expiredStatusId = array_search('Expired', CRM_Member_PseudoConstant
::membershipStatus());
1375 $allRelatedContacts = [];
1376 $relatedContacts = [];
1377 if (!is_a($membership, 'CRM_Core_Error')) {
1378 $allRelatedContacts = CRM_Member_BAO_Membership
::checkMembershipRelationship($membership->membership_type_id
,
1379 $membership->contact_id
,
1380 CRM_Utils_Array
::value('action', $params)
1384 // CRM-4213, CRM-19735 check for loops, using static variable to record contacts already processed.
1385 // Remove repeated related contacts, which already inherited membership of this type.
1386 $relatedContactIds[$membership->contact_id
][$membership->membership_type_id
] = TRUE;
1387 foreach ($allRelatedContacts as $cid => $status) {
1388 if (empty($relatedContactIds[$cid]) ||
empty($relatedContactIds[$cid][$membership->membership_type_id
])) {
1389 $relatedContactIds[$cid][$membership->membership_type_id
] = TRUE;
1391 //don't create membership again for owner contact.
1392 $nestedRelationship = FALSE;
1393 if ($membership->owner_membership_id
) {
1394 $nestedRelMembership = new CRM_Member_DAO_Membership();
1395 $nestedRelMembership->id
= $membership->owner_membership_id
;
1396 $nestedRelMembership->contact_id
= $cid;
1397 $nestedRelationship = $nestedRelMembership->find(TRUE);
1399 if (!$nestedRelationship) {
1400 $relatedContacts[$cid] = $status;
1405 //lets cleanup related membership if any.
1406 if (empty($relatedContacts)) {
1407 self
::deleteRelatedMemberships($membership->id
);
1410 // Edit the params array
1411 unset($params['id']);
1412 // Reminder should be sent only to the direct membership
1413 unset($params['reminder_date']);
1414 // unset the custom value ids
1415 if (is_array(CRM_Utils_Array
::value('custom', $params))) {
1416 foreach ($params['custom'] as $k => $v) {
1417 unset($params['custom'][$k]['id']);
1420 if (!isset($params['membership_type_id'])) {
1421 $params['membership_type_id'] = $membership->membership_type_id
;
1424 // max_related should be set in the parent membership
1425 unset($params['max_related']);
1426 // Number of inherited memberships available - NULL is interpreted as unlimited, '0' as none
1427 $numRelatedAvailable = ($membership->max_related
== NULL ? PHP_INT_MAX
: $membership->max_related
);
1428 // will be used to queue potential memberships to be created.
1431 foreach ($relatedContacts as $contactId => $relationshipStatus) {
1432 //use existing membership record.
1433 $relMembership = new CRM_Member_DAO_Membership();
1434 $relMembership->contact_id
= $contactId;
1435 $relMembership->owner_membership_id
= $membership->id
;
1436 if ($relMembership->find(TRUE)) {
1437 $params['id'] = $relMembership->id
;
1439 $params['contact_id'] = $contactId;
1440 $params['owner_membership_id'] = $membership->id
;
1442 // set status_id as it might have been changed for
1443 // past relationship
1444 $params['status_id'] = $membership->status_id
;
1446 if ($deceasedStatusId &&
1447 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'is_deceased')
1449 $params['status_id'] = $deceasedStatusId;
1451 elseif ((CRM_Utils_Array
::value('action', $params) & CRM_Core_Action
::UPDATE
) &&
1452 ($relationshipStatus == CRM_Contact_BAO_Relationship
::PAST
)
1454 $params['status_id'] = $expiredStatusId;
1457 //don't calculate status again in create( );
1458 $params['skipStatusCal'] = TRUE;
1460 //do create activity if we changed status.
1461 if ($params['status_id'] != $relMembership->status_id
) {
1462 $params['createActivity'] = TRUE;
1465 //CRM-20707 - include start/end date
1466 $params['start_date'] = $membership->start_date
;
1467 $params['end_date'] = $membership->end_date
;
1469 // we should not created contribution record for related contacts, CRM-3371
1470 unset($params['contribution_status_id']);
1472 //CRM-16857: Do not create multiple line-items for inherited membership through priceset.
1473 unset($params['lineItems']);
1474 unset($params['line_item']);
1476 // CRM-20966: Do not create membership_payment record for inherited membership.
1477 unset($params['relate_contribution_id']);
1480 if (($params['status_id'] == $deceasedStatusId) ||
($params['status_id'] == $expiredStatusId)) {
1481 // related membership is not active so does not count towards maximum
1482 // @todo stop passing empty $ids
1483 CRM_Member_BAO_Membership
::create($params, $ids);
1486 // related membership already exists, so this is just an update
1487 if (isset($params['id'])) {
1488 if ($numRelatedAvailable > 0) {
1489 // @todo stop passing empty $ids
1490 CRM_Member_BAO_Membership
::create($params, $ids);
1491 $numRelatedAvailable--;
1494 // we have run out of inherited memberships, so delete extras
1495 self
::deleteMembership($params['id']);
1497 // we need to first check if there will remain inherited memberships, so queue it up
1504 // now go over the queue and create any available related memberships
1505 foreach ($queue as $params) {
1506 if ($numRelatedAvailable <= 0) {
1509 // @todo stop passing $ids - at this point it may be set by reference from earlier calls to CRM_Member_BAO_Membership::create
1510 CRM_Member_BAO_Membership
::create($params, $ids);
1511 $numRelatedAvailable--;
1517 * Delete the record that are associated with this Membership Payment.
1519 * @param int $membershipId
1520 * @param bool $preserveContrib
1523 * $membershipPayment deleted membership payment object
1525 public static function deleteMembershipPayment($membershipId, $preserveContrib = FALSE) {
1527 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
1528 $membershipPayment->membership_id
= $membershipId;
1529 $membershipPayment->find();
1531 while ($membershipPayment->fetch()) {
1532 if (!$preserveContrib) {
1533 CRM_Contribute_BAO_Contribution
::deleteContribution($membershipPayment->contribution_id
);
1535 CRM_Utils_Hook
::pre('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1536 $membershipPayment->delete();
1537 CRM_Utils_Hook
::post('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1539 return $membershipPayment;
1543 * Build an array of available membership types.
1545 * @param CRM_Core_Form $form
1546 * @param array $membershipTypeID
1547 * @param bool $activeOnly
1548 * Do we only want active ones?
1549 * (probably this should default to TRUE but as a newly added parameter we are leaving default b
1550 * behaviour unchanged).
1554 public static function buildMembershipTypeValues(&$form, $membershipTypeID = [], $activeOnly = FALSE) {
1555 $whereClause = " WHERE domain_id = " . CRM_Core_Config
::domainID();
1556 $membershipTypeIDS = (array) $membershipTypeID;
1559 $whereClause .= " AND is_active = 1 ";
1561 if (!empty($membershipTypeIDS)) {
1562 $allIDs = implode(',', $membershipTypeIDS);
1563 $whereClause .= " AND id IN ( $allIDs )";
1565 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes, CRM_Core_Action
::ADD
);
1567 if ($financialTypes) {
1568 $whereClause .= " AND financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1571 $whereClause .= " AND financial_type_id IN (0)";
1576 FROM civicrm_membership_type
1579 $dao = CRM_Core_DAO
::executeQuery($query);
1581 $membershipTypeValues = [];
1582 $membershipTypeFields = [
1588 'financial_type_id',
1590 'member_of_contact_id',
1591 'relationship_type_id',
1592 'relationship_direction',
1595 'duration_interval',
1598 while ($dao->fetch()) {
1599 $membershipTypeValues[$dao->id
] = [];
1600 foreach ($membershipTypeFields as $mtField) {
1601 $membershipTypeValues[$dao->id
][$mtField] = $dao->$mtField;
1605 CRM_Utils_Hook
::membershipTypeValues($form, $membershipTypeValues);
1607 if (is_numeric($membershipTypeID) &&
1608 $membershipTypeID > 0
1610 return $membershipTypeValues[$membershipTypeID];
1613 return $membershipTypeValues;
1618 * Get membership record count for a Contact.
1620 * @param int $contactID
1621 * @param bool $activeOnly
1623 * @return null|string
1625 public static function getContactMembershipCount($contactID, $activeOnly = FALSE) {
1626 CRM_Financial_BAO_FinancialType
::getAvailableMembershipTypes($membershipTypes);
1627 $addWhere = " AND membership_type_id IN (0)";
1628 if (!empty($membershipTypes)) {
1629 $addWhere = " AND membership_type_id IN (" . implode(',', array_keys($membershipTypes)) . ")";
1631 $select = "SELECT count(*) FROM civicrm_membership ";
1632 $where = "WHERE civicrm_membership.contact_id = {$contactID} AND civicrm_membership.is_test = 0 ";
1634 // CRM-6627, all status below 3 (active, pending, grace) are considered active
1636 $select .= " INNER JOIN civicrm_membership_status ON civicrm_membership.status_id = civicrm_membership_status.id ";
1637 $where .= " and civicrm_membership_status.is_current_member = 1";
1640 $query = $select . $where . $addWhere;
1641 return CRM_Core_DAO
::singleValueQuery($query);
1645 * Check whether payment processor supports cancellation of membership subscription.
1650 * @param bool $isNotCancelled
1654 public static function isCancelSubscriptionSupported($mid, $isNotCancelled = TRUE) {
1655 $cacheKeyString = "$mid";
1656 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
1658 static $supportsCancel = [];
1660 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
1661 $supportsCancel[$cacheKeyString] = FALSE;
1662 $isCancelled = FALSE;
1664 if ($isNotCancelled) {
1665 $isCancelled = self
::isSubscriptionCancelled($mid);
1668 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($mid, 'membership', 'obj');
1669 if (!empty($paymentObject)) {
1670 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
1673 return $supportsCancel[$cacheKeyString];
1677 * Check whether subscription is already cancelled.
1683 * contribution status
1685 public static function isSubscriptionCancelled($mid) {
1687 SELECT cr.contribution_status_id
1688 FROM civicrm_contribution_recur cr
1689 LEFT JOIN civicrm_membership mem ON ( cr.id = mem.contribution_recur_id )
1690 WHERE mem.id = %1 LIMIT 1";
1691 $params = [1 => [$mid, 'Integer']];
1692 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
1693 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
1694 if ($status == 'Cancelled') {
1701 * Get membership joins for a specified membership type.
1703 * Specifically, retrieves a count of still current memberships whose
1704 * join_date and start_date are within a specified date range. Dates match
1705 * the pattern "yyyy-mm-dd".
1707 * @param int $membershipTypeId
1708 * Membership type id.
1709 * @param int $startDate
1710 * Date on which to start counting.
1711 * @param int $endDate
1712 * Date on which to end counting.
1713 * @param bool|int $isTest if true, membership is for a test site
1716 * the number of members of type $membershipTypeId
1717 * whose join_date is between $startDate and $endDate and
1718 * whose start_date is between $startDate and $endDate
1720 public static function getMembershipJoins($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1721 $testClause = 'membership.is_test = 1';
1723 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1725 if (!self
::$_signupActType) {
1726 self
::_getActTypes();
1729 if (!self
::$_signupActType) {
1734 SELECT COUNT(DISTINCT membership.id) as member_count
1735 FROM civicrm_membership membership
1736 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1737 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1738 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1739 WHERE membership.membership_type_id = %2
1740 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1744 1 => [self
::$_signupActType, 'Integer'],
1745 2 => [$membershipTypeId, 'Integer'],
1748 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1750 return (int) $memberCount;
1754 * Get membership renewals for a specified membership type.
1756 * Specifically, retrieves a count of still current memberships
1757 * whose join_date is before and start_date is within a specified date
1758 * range. Dates match the pattern "yyyy-mm-dd".
1760 * @param int $membershipTypeId
1761 * Membership type id.
1762 * @param int $startDate
1763 * Date on which to start counting.
1764 * @param int $endDate
1765 * Date on which to end counting.
1766 * @param bool|int $isTest if true, membership is for a test site
1769 * returns the number of members of type $membershipTypeId
1770 * whose join_date is before $startDate and
1771 * whose start_date is between $startDate and $endDate
1773 public static function getMembershipRenewals($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1774 $testClause = 'membership.is_test = 1';
1776 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1778 if (!self
::$_renewalActType) {
1779 self
::_getActTypes();
1782 if (!self
::$_renewalActType) {
1787 SELECT COUNT(DISTINCT membership.id) as member_count
1788 FROM civicrm_membership membership
1789 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1790 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1791 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1792 WHERE membership.membership_type_id = %2
1793 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1797 1 => [self
::$_renewalActType, 'Integer'],
1798 2 => [$membershipTypeId, 'Integer'],
1800 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1802 return (int) $memberCount;
1806 * @param int $contactID
1807 * @param int $membershipTypeID
1808 * @param bool $is_test
1809 * @param string $changeToday
1810 * @param int $modifiedID
1811 * @param $customFieldsFormatted
1812 * @param $numRenewTerms
1813 * @param int $membershipID
1815 * @param int $contributionRecurID
1816 * @param $membershipSource
1817 * @param $isPayLater
1818 * @param int $campaignId
1819 * @param array $formDates
1820 * @param null|CRM_Contribute_BAO_Contribution $contribution
1821 * @param array $lineItems
1824 * @throws \CRM_Core_Exception
1825 * @throws \CiviCRM_API3_Exception
1827 public static function processMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $contributionRecurID, $membershipSource, $isPayLater, $campaignId, $formDates = [], $contribution = NULL, $lineItems = []) {
1828 $renewalMode = $updateStatusId = FALSE;
1829 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1831 $statusFormat = '%Y-%m-%d';
1832 $membershipTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipTypeID);
1836 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
1837 // is the same as the parent org of an existing membership of the contact
1838 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($contactID, $membershipTypeID,
1839 $is_test, $membershipID, TRUE
1841 if ($currentMembership) {
1842 $renewalMode = TRUE;
1844 // Do NOT do anything.
1845 //1. membership with status : PENDING/CANCELLED (CRM-2395)
1846 //2. Paylater/IPN renew. CRM-4556.
1847 if ($pending ||
in_array($currentMembership['status_id'], [
1848 array_search('Pending', $allStatus),
1850 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1854 'id' => $currentMembership['id'],
1855 'contribution' => $contribution,
1856 'status_id' => $currentMembership['status_id'],
1857 'start_date' => $currentMembership['start_date'],
1858 'end_date' => $currentMembership['end_date'],
1859 'line_item' => $lineItems,
1860 'join_date' => $currentMembership['join_date'],
1861 'membership_type_id' => $membershipTypeID,
1862 'max_related' => !empty($membershipTypeDetails['max_related']) ?
$membershipTypeDetails['max_related'] : NULL,
1863 'membership_activity_status' => ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed',
1865 if ($contributionRecurID) {
1866 $memParams['contribution_recur_id'] = $contributionRecurID;
1868 // @todo stop passing $ids - it is empty
1869 $membership = self
::create($memParams, $ids);
1870 return [$membership, $renewalMode, $dates];
1873 // Check and fix the membership if it is STALE
1874 self
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
1876 // Now Renew the membership
1877 if (!$currentMembership['is_current_member']) {
1878 // membership is not CURRENT
1880 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1881 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($currentMembership['id'],
1887 $currentMembership['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1888 foreach (['start_date', 'end_date'] as $dateType) {
1889 $currentMembership[$dateType] = CRM_Utils_Array
::value($dateType, $formDates);
1890 if (empty($currentMembership[$dateType])) {
1891 $currentMembership[$dateType] = CRM_Utils_Array
::value($dateType, $dates);
1894 $currentMembership['is_test'] = $is_test;
1896 if (!empty($membershipSource)) {
1897 $currentMembership['source'] = $membershipSource;
1900 $currentMembership['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
1901 $currentMembership['id'],
1906 if (!empty($currentMembership['id'])) {
1907 $ids['membership'] = $currentMembership['id'];
1909 $memParams = $currentMembership;
1910 $memParams['membership_type_id'] = $membershipTypeID;
1912 //set the log start date.
1913 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1917 // CURRENT Membership
1918 $membership = new CRM_Member_DAO_Membership();
1919 $membership->id
= $currentMembership['id'];
1920 $membership->find(TRUE);
1921 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1922 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
1928 // Insert renewed dates for CURRENT membership
1930 $memParams['join_date'] = CRM_Utils_Date
::isoToMysql($membership->join_date
);
1931 $memParams['start_date'] = CRM_Utils_Array
::value('start_date', $formDates, CRM_Utils_Date
::isoToMysql($membership->start_date
));
1932 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $formDates);
1933 if (empty($memParams['end_date'])) {
1934 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $dates);
1936 $memParams['membership_type_id'] = $membershipTypeID;
1938 //set the log start date.
1939 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1942 if (!empty($membershipSource)) {
1943 $memParams['source'] = $membershipSource;
1945 elseif (empty($membership->source
)) {
1946 $memParams['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
1947 $currentMembership['id'],
1952 if (!empty($currentMembership['id'])) {
1953 $ids['membership'] = $currentMembership['id'];
1955 $memParams['membership_activity_status'] = ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed';
1959 $updateStatusId = array_search('Pending', $allStatus);
1965 'contact_id' => $contactID,
1966 'membership_type_id' => $membershipTypeID,
1970 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
1972 foreach (['join_date', 'start_date', 'end_date'] as $dateType) {
1973 $memParams[$dateType] = CRM_Utils_Array
::value($dateType, $formDates);
1974 if (empty($memParams[$dateType])) {
1975 $memParams[$dateType] = CRM_Utils_Array
::value($dateType, $dates);
1979 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(CRM_Utils_Date
::customFormat($dates['start_date'],
1982 CRM_Utils_Date
::customFormat($dates['end_date'],
1985 CRM_Utils_Date
::customFormat($dates['join_date'],
1993 $updateStatusId = CRM_Utils_Array
::value('id', $status);
1996 // if IPN/Pay-Later set status to: PENDING
1997 $updateStatusId = array_search('Pending', $allStatus);
2000 if (!empty($membershipSource)) {
2001 $memParams['source'] = $membershipSource;
2003 $memParams['is_test'] = $is_test;
2004 $memParams['is_pay_later'] = $isPayLater;
2006 // Putting this in an IF is precautionary as it seems likely that it would be ignored if empty, but
2007 // perhaps shouldn't be?
2008 if ($contributionRecurID) {
2009 $memParams['contribution_recur_id'] = $contributionRecurID;
2012 //if we decided status here and want to skip status
2013 //calculation in create( ); then need to pass 'skipStatusCal'.
2014 if ($updateStatusId) {
2015 $memParams['status_id'] = $updateStatusId;
2016 $memParams['skipStatusCal'] = TRUE;
2019 //since we are renewing,
2020 //make status override false.
2021 $memParams['is_override'] = FALSE;
2023 //CRM-4027, create log w/ individual contact.
2025 $ids['userId'] = $modifiedID;
2026 $memParams['is_for_organization'] = TRUE;
2029 $ids['userId'] = $contactID;
2032 //inherit campaign from contrib page.
2033 if (isset($campaignId)) {
2034 $memParams['campaign_id'] = $campaignId;
2037 $memParams['contribution'] = $contribution;
2038 $memParams['custom'] = $customFieldsFormatted;
2039 // Load all line items & process all in membership. Don't do in contribution.
2040 // Relevant tests in api_v3_ContributionPageTest.
2041 $memParams['line_item'] = $lineItems;
2042 // @todo stop passing $ids (membership and userId may be set by this point)
2043 $membership = self
::create($memParams, $ids);
2045 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
2046 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
2047 $membership->find(TRUE);
2049 return [$membership, $renewalMode, $dates];
2053 * Get line items representing the default price set.
2055 * @param int $membershipOrg
2056 * @param int $membershipTypeID
2057 * @param float $total_amount
2058 * @param int $priceSetId
2062 public static function setQuickConfigMembershipParameters($membershipOrg, $membershipTypeID, $total_amount, $priceSetId) {
2063 $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
2065 // The name of the price field corresponds to the membership_type organization contact.
2067 'price_set_id' => $priceSetId,
2068 'name' => $membershipOrg,
2071 CRM_Price_BAO_PriceField
::retrieve($params, $results);
2073 if (!empty($results)) {
2074 $fields[$results['id']] = $priceSets['fields'][$results['id']];
2075 $fid = $results['id'];
2076 $editedFieldParams = [
2077 'price_field_id' => $results['id'],
2078 'membership_type_id' => $membershipTypeID,
2081 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $results);
2082 $fields[$fid]['options'][$results['id']] = $priceSets['fields'][$fid]['options'][$results['id']];
2083 if (!empty($total_amount)) {
2084 $fields[$fid]['options'][$results['id']]['amount'] = $total_amount;
2088 $fieldID = key($fields);
2090 'price_set_id' => $priceSetId,
2091 'price_sets' => $priceSets,
2092 'fields' => $fields,
2094 'price_' . $fieldID => CRM_Utils_Array
::value('id', $results),
2097 return $returnParams;
2101 * Update the status of all deceased members to deceased.
2104 * Count of updated contacts.
2106 * @throws \CiviCRM_API3_Exception
2107 * @throws \CRM_Core_Exception
2109 protected static function updateDeceasedMembersStatuses() {
2112 $deceasedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Deceased');
2114 // 'create' context for buildOptions returns only if enabled.
2115 $allStatus = self
::buildOptions('status_id', 'create');
2116 if (array_key_exists($deceasedStatusId, $allStatus) === FALSE) {
2117 // Deceased status is an admin status & is required. We want to fail early if
2118 // it is not present or active.
2119 // We could make the case 'some databases just don't use deceased so we will check
2120 // for the presence of a deceased contact in the DB before rejecting.
2121 if (CRM_Core_DAO
::singleValueQuery('
2122 SELECT count(*) FROM civicrm_contact WHERE is_deceased = 0'
2124 throw new CRM_Core_Exception(
2125 ts("Deceased Membership status is missing or not active. <a href='%1'>Click here to check</a>.",
2126 [1 => CRM_Utils_System
::url('civicrm/admin/member/membershipStatus', 'reset=1')]
2130 $deceasedDAO = CRM_Core_DAO
::executeQuery(
2132 SELECT membership.id as membership_id
2133 FROM civicrm_membership membership
2134 INNER JOIN civicrm_contact ON membership.contact_id = civicrm_contact.id
2135 INNER JOIN civicrm_membership_type ON membership.membership_type_id = civicrm_membership_type.id
2136 AND civicrm_membership_type.is_active = 1
2137 WHERE membership.is_test = 0
2138 AND civicrm_contact.is_deceased = 1
2139 AND membership.status_id <> %1
2141 [1 => [$deceasedStatusId, 'Integer']]
2143 while ($deceasedDAO->fetch()) {
2144 civicrm_api3('membership', 'create', [
2145 'id' => $deceasedDAO->membership_id
,
2146 'status_id' => $deceasedStatusId,
2147 'createActivity' => TRUE,
2148 'skipStatusCal' => TRUE,
2149 'skipRecentView' => TRUE,
2157 * Process price set and line items.
2159 * @param int $membershipId
2160 * @param array $lineItem
2162 * @throws \CiviCRM_API3_Exception
2164 public function processPriceSet($membershipId, $lineItem) {
2165 //FIXME : need to move this too
2166 if (!$membershipId ||
!is_array($lineItem)
2167 || CRM_Utils_System
::isNull($lineItem)
2172 foreach ($lineItem as $priceSetId => $values) {
2176 foreach ($values as $line) {
2177 $line['entity_table'] = 'civicrm_membership';
2178 $line['entity_id'] = $membershipId;
2179 CRM_Price_BAO_LineItem
::create($line);
2185 * Retrieve the contribution id for the associated Membership id.
2186 * @todo we should get this off the line item
2188 * @param int $membershipId
2191 * if more than one payment associated with membership id need to be returned.
2195 * @todo we should get this off the line item
2198 public static function getMembershipContributionId($membershipId, $all = FALSE) {
2200 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
2201 $membershipPayment->membership_id
= $membershipId;
2202 if ($all && $membershipPayment->find()) {
2203 $contributionIds = [];
2204 while ($membershipPayment->fetch()) {
2205 $contributionIds[] = $membershipPayment->contribution_id
;
2207 return $contributionIds;
2210 if ($membershipPayment->find(TRUE)) {
2211 return $membershipPayment->contribution_id
;
2217 * The function checks and updates the status of all membership records for a given domain using the
2218 * calc_membership_status and update_contact_membership APIs.
2221 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
2225 * @throws \CiviCRM_API3_Exception
2226 * @throws \CRM_Core_Exception
2228 public static function updateAllMembershipStatus() {
2229 // Tests for this function are in api_v3_JobTest. Please add tests for all updates.
2231 $updateCount = $processCount = self
::updateDeceasedMembersStatuses();
2233 // We want all of the statuses as id => name, even the disabled ones (cf.
2234 // CRM-15475), to identify which are Pending, Deceased, Cancelled, and
2236 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'validate');
2237 $allTypes = CRM_Member_PseudoConstant
::membershipType();
2239 // This query retrieves ALL memberships of active types.
2241 SELECT civicrm_membership.id as membership_id,
2242 civicrm_membership.is_override as is_override,
2243 civicrm_membership.status_override_end_date as status_override_end_date,
2244 civicrm_membership.membership_type_id as membership_type_id,
2245 civicrm_membership.status_id as status_id,
2246 civicrm_membership.join_date as join_date,
2247 civicrm_membership.start_date as start_date,
2248 civicrm_membership.end_date as end_date,
2249 civicrm_membership.source as source,
2250 civicrm_contact.id as contact_id,
2251 civicrm_membership.owner_membership_id as owner_membership_id,
2252 civicrm_membership.contribution_recur_id as recur_id
2253 FROM civicrm_membership
2254 INNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )
2255 INNER JOIN civicrm_membership_type ON
2256 (civicrm_membership.membership_type_id = civicrm_membership_type.id AND civicrm_membership_type.is_active = 1)
2257 WHERE civicrm_membership.is_test = 0
2258 AND civicrm_contact.is_deceased = 0 ";
2260 $deceaseStatusId = array_search('Deceased', $allStatus);
2261 $pendingStatusId = array_search('Pending', $allStatus);
2262 $cancelledStatusId = array_search('Cancelled', $allStatus);
2263 // Expired is not reserved so might not exist. A value of `0` won't break.
2264 $expiredStatusId = array_search('Expired', $allStatus) ?
: 0;
2266 $query = $baseQuery . " AND civicrm_membership.is_override IS NOT NULL AND civicrm_membership.status_override_end_date IS NOT NULL";
2267 $dao1 = CRM_Core_DAO
::executeQuery($query);
2268 while ($dao1->fetch()) {
2269 self
::processOverriddenUntilDateMembership($dao1);
2272 $query = $baseQuery . " AND (civicrm_membership.is_override = 0 OR civicrm_membership.is_override IS NULL)
2273 AND civicrm_membership.status_id NOT IN (%1, %2, %3, %4)
2274 AND civicrm_membership.owner_membership_id IS NULL ";
2276 1 => [$pendingStatusId, 'Integer'],
2277 2 => [$cancelledStatusId, 'Integer'],
2278 3 => [$expiredStatusId, 'Integer'],
2279 4 => [$deceaseStatusId, 'Integer'],
2281 $dao2 = CRM_Core_DAO
::executeQuery($query, $params);
2283 while ($dao2->fetch()) {
2287 // Put common parameters into array for easy access
2289 'id' => $dao2->membership_id
,
2290 'status_id' => $dao2->status_id
,
2291 'contact_id' => $dao2->contact_id
,
2292 'membership_type_id' => $dao2->membership_type_id
,
2293 'membership_type' => $allTypes[$dao2->membership_type_id
],
2294 'join_date' => $dao2->join_date
,
2295 'start_date' => $dao2->start_date
,
2296 'end_date' => $dao2->end_date
,
2297 'source' => $dao2->source
,
2298 'skipStatusCal' => TRUE,
2299 'skipRecentView' => TRUE,
2302 // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses
2303 //get the membership status as per id.
2304 $newStatus = civicrm_api('membership_status', 'calc',
2306 'membership_id' => $dao2->membership_id
,
2308 'ignore_admin_only' => TRUE,
2311 $statusId = CRM_Utils_Array
::value('id', $newStatus);
2313 //process only when status change.
2315 $statusId != $dao2->status_id
2317 //take all params that need to save.
2318 $memParams = $memberParams;
2319 $memParams['status_id'] = $statusId;
2320 $memParams['createActivity'] = TRUE;
2321 $memParams['version'] = 3;
2323 // Unset columns which should remain unchanged from their current saved
2324 // values. This avoids race condition in which these values may have
2325 // been changed by other processes.
2327 $memParams['contact_id'],
2328 $memParams['membership_type_id'],
2329 $memParams['membership_type'],
2330 $memParams['join_date'],
2331 $memParams['start_date'],
2332 $memParams['end_date'],
2333 $memParams['source']
2335 //since there is change in status.
2337 //process member record.
2338 civicrm_api('membership', 'create', $memParams);
2342 $result['is_error'] = 0;
2343 $result['messages'] = ts('Processed %1 membership records. Updated %2 records.', [
2351 * Set is_override for the 'overridden until date' membership to
2352 * False and clears the 'until date' field in case the 'until date'
2353 * is equal or after today date.
2355 * @param CRM_Core_DAO $membership
2356 * The membership to be processed
2358 * @throws \CiviCRM_API3_Exception
2360 private static function processOverriddenUntilDateMembership($membership) {
2361 $isOverriddenUntilDate = !empty($membership->is_override
) && !empty($membership->status_override_end_date
);
2362 if (!$isOverriddenUntilDate) {
2366 $todayDate = new DateTime();
2367 $todayDate->setTime(0, 0);
2369 $overrideEndDate = new DateTime($membership->status_override_end_date
);
2370 $overrideEndDate->setTime(0, 0);
2372 $datesDifference = $todayDate->diff($overrideEndDate);
2373 $daysDifference = (int) $datesDifference->format('%R%a');
2374 if ($daysDifference <= 0) {
2376 'id' => $membership->membership_id
,
2377 'is_override' => FALSE,
2378 'status_override_end_date' => 'null',
2380 civicrm_api3('membership', 'create', $params);
2385 * Returns the membership types for a particular contact
2386 * who has lifetime membership without end date.
2388 * @param int $contactID
2389 * @param bool $isTest
2390 * @param bool $onlyLifeTime
2394 public static function getAllContactMembership($contactID, $isTest = FALSE, $onlyLifeTime = FALSE) {
2395 $contactMembershipType = [];
2397 return $contactMembershipType;
2400 $dao = new CRM_Member_DAO_Membership();
2401 $dao->contact_id
= $contactID;
2402 $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
2403 $dao->whereAdd("status_id != $pendingStatusId");
2406 $dao->is_test
= $isTest;
2409 $dao->whereAdd('is_test IS NULL OR is_test = 0');
2412 if ($onlyLifeTime) {
2413 $dao->whereAdd('end_date IS NULL');
2417 while ($dao->fetch()) {
2419 CRM_Core_DAO
::storeValues($dao, $membership);
2420 $contactMembershipType[$dao->membership_type_id
] = $membership;
2422 return $contactMembershipType;
2426 * Record contribution record associated with membership.
2427 * This will update an existing contribution if $params['contribution_id'] is passed in.
2428 * This will create a MembershipPayment to link the contribution and membership
2430 * @param array $params
2431 * Array of submitted params.
2433 * (@return CRM_Contribute_BAO_Contribution
2435 * @return CRM_Contribute_BAO_Contribution
2436 * @throws \CRM_Core_Exception
2437 * @throws \CiviCRM_API3_Exception
2439 public static function recordMembershipContribution(&$params, $ids = []) {
2441 CRM_Core_Error
::deprecatedFunctionWarning('no $ids array');
2443 $membershipId = $params['membership_id'];
2444 $contributionParams = [];
2445 $config = CRM_Core_Config
::singleton();
2446 $contributionParams['currency'] = $config->defaultCurrency
;
2447 $contributionParams['receipt_date'] = (CRM_Utils_Array
::value('receipt_date', $params)) ?
$params['receipt_date'] : 'null';
2448 $contributionParams['source'] = CRM_Utils_Array
::value('contribution_source', $params);
2449 $contributionParams['non_deductible_amount'] = 'null';
2450 $contributionParams['skipCleanMoney'] = TRUE;
2451 $contributionParams['payment_processor'] = CRM_Utils_Array
::value('payment_processor_id', $params);
2452 $contributionSoftParams = CRM_Utils_Array
::value('soft_credit', $params);
2453 $recordContribution = [
2458 'financial_type_id',
2459 'payment_instrument_id',
2463 'contribution_status_id',
2470 'contribution_recur_id',
2474 foreach ($recordContribution as $f) {
2475 $contributionParams[$f] = CRM_Utils_Array
::value($f, $params);
2478 if (!empty($params['contribution_id'])) {
2479 $contributionParams['id'] = $params['contribution_id'];
2481 // make entry in batch entity batch table
2482 if (!empty($params['batch_id'])) {
2483 $contributionParams['batch_id'] = $params['batch_id'];
2486 if (!empty($params['contribution_contact_id'])) {
2487 // deal with possibility of a different person paying for contribution
2488 $contributionParams['contact_id'] = $params['contribution_contact_id'];
2491 if (!empty($params['processPriceSet']) &&
2492 !empty($params['lineItems'])
2494 $contributionParams['line_item'] = CRM_Utils_Array
::value('lineItems', $params, NULL);
2497 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams);
2499 //CRM-13981, create new soft-credit record as to record payment from different person for this membership
2500 if (!empty($contributionSoftParams)) {
2501 if (!empty($params['batch_id'])) {
2502 foreach ($contributionSoftParams as $contributionSoft) {
2503 $contributionSoft['contribution_id'] = $contribution->id
;
2504 $contributionSoft['currency'] = $contribution->currency
;
2505 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoft);
2509 $contributionSoftParams['contribution_id'] = $contribution->id
;
2510 $contributionSoftParams['currency'] = $contribution->currency
;
2511 $contributionSoftParams['amount'] = $contribution->total_amount
;
2512 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoftParams);
2516 // store contribution id
2517 $params['contribution_id'] = $contribution->id
;
2519 // Create membership payment if it does not already exist
2520 $membershipPayment = civicrm_api3('MembershipPayment', 'get', [
2521 'contribution_id' => $contribution->id
,
2523 if (empty($membershipPayment['count'])) {
2524 civicrm_api3('MembershipPayment', 'create', [
2525 'membership_id' => $membershipId,
2526 'contribution_id' => $contribution->id
,
2530 return $contribution;
2534 * @todo document me - I seem a bit out of date....
2536 public static function _getActTypes() {
2537 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2538 self
::$_renewalActType = CRM_Utils_Array
::key('Membership Renewal', $activityTypes);
2539 self
::$_signupActType = CRM_Utils_Array
::key('Membership Signup', $activityTypes);
2543 * Get all Cancelled Membership(s) for a contact
2545 * @param int $contactID
2547 * @param bool $isTest
2551 * Array of membership type
2553 public static function getContactsCancelledMembership($contactID, $isTest = FALSE) {
2557 $query = 'SELECT membership_type_id FROM civicrm_membership WHERE contact_id = %1 AND status_id = %2 AND is_test = %3';
2559 1 => [$contactID, 'Integer'],
2564 CRM_Member_PseudoConstant
::membershipStatus(
2566 " name = 'Cancelled' ",
2574 3 => [$isTest, 'Boolean'],
2577 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
2578 $cancelledMembershipIds = [];
2579 while ($dao->fetch()) {
2580 $cancelledMembershipIds[] = $dao->membership_type_id
;
2582 return $cancelledMembershipIds;
2586 * Merges the memberships from otherContactID to mainContactID.
2588 * General idea is to merge memberships in regards to their type. We
2589 * move the other contact’s contributions to the main contact’s
2590 * membership which has the same type (if any) and then we update
2591 * membership to avoid loosing `join_date`, `end_date`, and
2592 * `status_id`. In this function, we don’t touch the contributions
2593 * directly (CRM_Dedupe_Merger::moveContactBelongings() takes care
2596 * This function adds new SQL queries to the $sqlQueries parameter.
2598 * @param int $mainContactID
2599 * Contact id of main contact record.
2600 * @param int $otherContactID
2601 * Contact id of record which is going to merge.
2602 * @param array $sqlQueries
2603 * (reference) array of SQL queries to be executed.
2604 * @param array $tables
2605 * List of tables that have to be merged.
2606 * @param array $tableOperations
2607 * Special options/params for some tables to be merged.
2609 * @see CRM_Dedupe_Merger::cpTables()
2611 public static function mergeMemberships($mainContactID, $otherContactID, &$sqlQueries, $tables, $tableOperations) {
2613 * If the user requests not to merge memberships but to add them,
2614 * just attribute the `civicrm_membership` to the
2615 * `$mainContactID`. We have to do this here since the general
2616 * merge process is bypassed by this function.
2618 if (array_key_exists("civicrm_membership", $tableOperations) && $tableOperations['civicrm_membership']['add']) {
2619 $sqlQueries[] = "UPDATE IGNORE civicrm_membership SET contact_id = $mainContactID WHERE contact_id = $otherContactID";
2624 * Retrieve all memberships that belongs to each contacts and
2625 * keep track of each membership type.
2627 $mainContactMemberships = [];
2628 $otherContactMemberships = [];
2630 $sql = "SELECT id, membership_type_id FROM civicrm_membership membership WHERE contact_id = %1";
2631 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$mainContactID, "Integer"]]);
2632 while ($dao->fetch()) {
2633 $mainContactMemberships[$dao->id
] = $dao->membership_type_id
;
2636 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$otherContactID, "Integer"]]);
2637 while ($dao->fetch()) {
2638 $otherContactMemberships[$dao->id
] = $dao->membership_type_id
;
2642 * For each membership, move related contributions to the main
2643 * contact’s membership (by updating `membership_payments`). Then,
2644 * update membership’s `join_date` (if the other membership’s
2645 * join_date is older) and `end_date` (if the other membership’s
2646 * `end_date` is newer) and `status_id` (if the newly calculated
2647 * status is different).
2649 * FIXME: what should we do if we have multiple memberships with
2650 * the same type (currently we only take the first one)?
2653 foreach ($otherContactMemberships as $otherMembershipId => $otherMembershipTypeId) {
2654 if ($newMembershipId = array_search($otherMembershipTypeId, $mainContactMemberships)) {
2657 * Move other membership’s contributions to the main one only
2658 * if user requested to merge contributions.
2660 if (!empty($tables) && in_array('civicrm_contribution', $tables)) {
2661 $newSql[] = "UPDATE civicrm_membership_payment SET membership_id=$newMembershipId WHERE membership_id=$otherMembershipId";
2664 $sql = "SELECT * FROM civicrm_membership membership WHERE id = %1";
2666 $newMembership = CRM_Member_DAO_Membership
::findById($newMembershipId);
2667 $otherMembership = CRM_Member_DAO_Membership
::findById($otherMembershipId);
2670 if (new DateTime($otherMembership->join_date
) < new DateTime($newMembership->join_date
)) {
2671 $updates["join_date"] = $otherMembership->join_date
;
2674 if (new DateTime($otherMembership->end_date
) > new DateTime($newMembership->end_date
)) {
2675 $updates["end_date"] = $otherMembership->end_date
;
2678 if (count($updates)) {
2683 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
2684 isset($updates["start_date"]) ?
$updates["start_date"] : $newMembership->start_date
,
2685 isset($updates["end_date"]) ?
$updates["end_date"] : $newMembership->end_date
,
2686 isset($updates["join_date"]) ?
$updates["join_date"] : $newMembership->join_date
,
2693 if (!empty($status['id']) and $status['id'] != $newMembership->status_id
) {
2694 $updates['status_id'] = $status['id'];
2698 foreach ($updates as $k => $v) {
2699 $updates_sql[] = "$k = '{$v}'";
2702 $newSql[] = sprintf("UPDATE civicrm_membership SET %s WHERE id=%s", implode(", ", $updates_sql), $newMembershipId);
2703 $newSql[] = sprintf("DELETE FROM civicrm_membership WHERE id=%s", $otherMembershipId);
2709 $sqlQueries = array_merge($sqlQueries, $newSql);