3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
33 class CRM_Member_BAO_Membership
extends CRM_Member_DAO_Membership
{
36 * Static field for all the membership information that we can potentially import.
40 public static $_importableFields = NULL;
42 public static $_renewalActType = NULL;
44 public static $_signupActType = NULL;
49 public function __construct() {
50 parent
::__construct();
54 * Takes an associative array and creates a membership object.
56 * the function extracts all the params it needs to initialize the created
57 * membership object. The params array could contain additional unused name/value
60 * @param array $params
61 * (reference ) an assoc array of name/value pairs.
63 * The array that holds all the db ids.
65 * @return CRM_Member_BAO_Membership
66 * @throws \CiviCRM_API3_Exception
68 public static function add(&$params, $ids = []) {
69 $oldStatus = $oldType = NULL;
70 $params['id'] = CRM_Utils_Array
::value('id', $params, CRM_Utils_Array
::value('membership', $ids));
72 CRM_Utils_Hook
::pre('edit', 'Membership', $params['id'], $params);
75 CRM_Utils_Hook
::pre('create', 'Membership', NULL, $params);
78 // we do this after the hooks are called in case it has been altered
80 $membershipObj = new CRM_Member_DAO_Membership();
81 $membershipObj->id
= $id;
82 $membershipObj->find();
83 while ($membershipObj->fetch()) {
84 $oldStatus = $membershipObj->status_id
;
85 $oldType = $membershipObj->membership_type_id
;
89 if (array_key_exists('is_override', $params) && !$params['is_override']) {
90 $params['is_override'] = 'null';
93 $membership = new CRM_Member_BAO_Membership();
94 $membership->copyValues($params);
95 $membership->id
= $id;
99 if (empty($membership->contact_id
) ||
empty($membership->status_id
)) {
100 // this means we are in renewal mode and are just updating the membership
101 // record or this is an API update call and all fields are not present in the update record
102 // however the hooks don't care and want all data CRM-7784
103 $tempMembership = new CRM_Member_DAO_Membership();
104 $tempMembership->id
= $membership->id
;
105 $tempMembership->find(TRUE);
106 $membership = $tempMembership;
109 //get the log start date.
110 //it is set during renewal of membership.
111 $logStartDate = CRM_Utils_Array
::value('log_start_date', $params);
112 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : CRM_Utils_Date
::isoToMysql($membership->start_date
);
113 $values = self
::getStatusANDTypeValues($membership->id
);
116 'membership_id' => $membership->id
,
117 'status_id' => $membership->status_id
,
118 'start_date' => $logStartDate,
119 'end_date' => CRM_Utils_Date
::isoToMysql($membership->end_date
),
120 'modified_date' => date('Ymd'),
121 'membership_type_id' => $values[$membership->id
]['membership_type_id'],
122 'max_related' => $membership->max_related
,
125 $session = CRM_Core_Session
::singleton();
126 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
127 if ($session->get('userID')) {
128 $membershipLog['modified_id'] = $session->get('userID');
130 elseif (!empty($ids['userId'])) {
131 $membershipLog['modified_id'] = $ids['userId'];
134 $membershipLog['modified_id'] = $membership->contact_id
;
137 CRM_Member_BAO_MembershipLog
::add($membershipLog);
139 // reset the group contact cache since smart groups might be affected due to this
140 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
142 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
144 'status_id' => CRM_Utils_Array
::value('membership_activity_status', $params, 'Completed'),
146 if (in_array($allStatus[$membership->status_id
], ['Pending', 'Grace'])) {
147 $activityParams['status_id'] = 'Scheduled';
149 $activityParams['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', $activityParams['status_id']);
151 $targetContactID = $membership->contact_id
;
152 if (!empty($params['is_for_organization'])) {
153 $targetContactID = CRM_Utils_Array
::value('userId', $ids);
156 if ($membership->status_id
!= $oldStatus) {
157 CRM_Activity_BAO_Activity
::addActivity($membership,
158 'Change Membership Status',
161 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
162 'source_contact_id' => $membershipLog['modified_id'],
163 'priority_id' => 'Normal',
167 if (isset($membership->membership_type_id
) && $membership->membership_type_id
!= $oldType) {
168 $membershipTypes = CRM_Member_BAO_Membership
::buildOptions('membership_type_id', 'get');
169 CRM_Activity_BAO_Activity
::addActivity($membership,
170 'Change Membership Type',
173 'subject' => "Type changed from {$membershipTypes[$oldType]} to {$membershipTypes[$membership->membership_type_id]}",
174 'source_contact_id' => $membershipLog['modified_id'],
175 'priority_id' => 'Normal',
180 foreach (['Membership Signup', 'Membership Renewal'] as $activityType) {
181 $activityParams['id'] = CRM_Utils_Array
::value('id',
182 civicrm_api3('Activity', 'Get',
184 'source_record_id' => $membership->id
,
185 'activity_type_id' => $activityType,
186 'status_id' => 'Scheduled',
190 // 1. Update Schedule Membership Signup/Renwal activity to completed on successful payment of pending membership
191 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
192 if (!empty($params['membership_activity_status']) && (!empty($activityParams['id']) ||
$activityType == 'Membership Renewal')) {
193 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $targetContactID, $activityParams);
198 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
201 CRM_Activity_BAO_Activity
::addActivity($membership, 'Membership Signup', $targetContactID, $activityParams);
202 CRM_Utils_Hook
::post('create', 'Membership', $membership->id
, $membership);
209 * Fetch the object and store the values in the values array.
211 * @param array $params
212 * Input parameters to find object.
213 * @param array $values
214 * Output values of the object.
215 * @param bool $active
216 * Do you want only active memberships to.
218 * @param bool $relatedMemberships
220 * @return CRM_Member_BAO_Membership|null
221 * The found object or null
223 public static function &getValues(&$params, &$values, $active = FALSE, $relatedMemberships = FALSE) {
224 if (empty($params)) {
227 $membership = new CRM_Member_BAO_Membership();
229 $membership->copyValues($params);
232 while ($membership->fetch()) {
234 (!CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
235 $membership->status_id
,
242 CRM_Core_DAO
::storeValues($membership, $values[$membership->id
]);
243 $memberships[$membership->id
] = $membership;
244 if ($relatedMemberships && !empty($membership->owner_membership_id
)) {
245 $values['owner_membership_ids'][] = $membership->owner_membership_id
;
253 * Takes an associative array and creates a membership object.
255 * @param array $params
256 * (reference ) an assoc array of name/value pairs.
258 * Deprecated parameter The array that holds all the db ids.
260 * @return CRM_Member_BAO_Membership|CRM_Core_Error
261 * @throws \CiviCRM_API3_Exception
263 * @throws CRM_Core_Exception
265 public static function create(&$params, &$ids = []) {
266 // always calculate status if is_override/skipStatusCal is not true.
267 // giving respect to is_override during import. CRM-4012
269 // To skip status calculation we should use 'skipStatusCal'.
270 // eg pay later membership, membership update cron CRM-3984
272 if (empty($params['is_override']) && empty($params['skipStatusCal'])) {
273 $dates = ['start_date', 'end_date', 'join_date'];
274 // Declare these out of courtesy as IDEs don't pick up the setting of them below.
275 $start_date = $end_date = $join_date = NULL;
276 foreach ($dates as $date) {
277 $
$date = $params[$date] = CRM_Utils_Date
::processDate(CRM_Utils_Array
::value($date, $params), NULL, TRUE, 'Ymd');
280 //fix for CRM-3570, during import exclude the statuses those having is_admin = 1
281 $excludeIsAdmin = CRM_Utils_Array
::value('exclude_is_admin', $params, FALSE);
283 //CRM-3724 always skip is_admin if is_override != true.
284 if (!$excludeIsAdmin && empty($params['is_override'])) {
285 $excludeIsAdmin = TRUE;
288 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($start_date, $end_date, $join_date,
289 'today', $excludeIsAdmin, CRM_Utils_Array
::value('membership_type_id', $params), $params
291 if (empty($calcStatus)) {
292 // Redirect the form in case of error
293 // @todo this redirect in the BAO layer is really bad & should be moved to the form layer
294 // however since we have no idea how (if) this is triggered we can't safely move / remove it
295 // NB I tried really hard to trigger this error from backoffice membership form in order to test it
296 // and am convinced form validation is complete on that form WRT this error.
298 'message_title' => ts('No valid membership status for given dates.'),
299 'legacy_redirect_path' => 'civicrm/contact/view',
300 'legacy_redirect_query' => "reset=1&force=1&cid={$params['contact_id']}&selectedChild=member",
302 throw new CRM_Core_Exception(ts(
303 "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')),
308 $params['status_id'] = $calcStatus['id'];
311 // data cleanup only: all verifications on number of related memberships are done upstream in:
312 // CRM_Member_BAO_Membership::createRelatedMemberships()
313 // CRM_Contact_BAO_Relationship::relatedMemberships()
314 if (!empty($params['owner_membership_id'])) {
315 unset($params['max_related']);
318 // if membership allows related, default max_related to value in membership_type
319 if (!array_key_exists('max_related', $params) && !empty($params['membership_type_id'])) {
320 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($params['membership_type_id']);
321 if (isset($membershipType['relationship_type_id'])) {
322 $params['max_related'] = CRM_Utils_Array
::value('max_related', $membershipType);
327 $transaction = new CRM_Core_Transaction();
329 // @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
330 $membership = self
::add($params, $ids);
332 if (is_a($membership, 'CRM_Core_Error')) {
333 $transaction->rollback();
337 // add custom field values
338 if (!empty($params['custom']) && is_array($params['custom'])
340 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_membership', $membership->id
);
343 $params['membership_id'] = $membership->id
;
344 // @todo further cleanup required to remove use of $ids['contribution'] from here
345 if (isset($ids['membership'])) {
346 $ids['contribution'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment',
351 // @todo this is a temporary step to removing $ids['contribution'] completely
352 if (empty($params['contribution_id']) && !empty($ids['contribution'])) {
353 $params['contribution_id'] = $ids['contribution'];
357 // This code ensures a line item is created but it is recommended you pass in 'skipLineItem' or 'line_item'
358 if (empty($params['line_item']) && !empty($params['membership_type_id']) && empty($params['skipLineItem'])) {
359 CRM_Price_BAO_LineItem
::getLineItemArray($params, NULL, 'membership', $params['membership_type_id']);
361 $params['skipLineItem'] = TRUE;
363 //record contribution for this membership
364 if (!empty($params['contribution_status_id']) && empty($params['relate_contribution_id'])) {
365 $memInfo = array_merge($params, ['membership_id' => $membership->id
]);
366 $params['contribution'] = self
::recordMembershipContribution($memInfo);
369 if (!empty($params['lineItems'])) {
370 $params['line_item'] = $params['lineItems'];
373 // do cleanup line items if membership edit the Membership type.
374 if (empty($ids['contribution']) && !empty($ids['membership'])) {
375 CRM_Price_BAO_LineItem
::deleteLineItems($ids['membership'], 'civicrm_membership');
378 // This could happen if there is no contribution or we are in one of many
379 // weird and wonderful flows. This is scary code. Keep adding tests.
380 if (!empty($params['line_item']) && empty($ids['contribution']) && empty($params['contribution_id'])) {
382 foreach ($params['line_item'] as $priceSetId => $lineItems) {
383 foreach ($lineItems as $lineIndex => $lineItem) {
384 $lineMembershipType = CRM_Utils_Array
::value('membership_type_id', $lineItem);
385 if (!empty($params['contribution'])) {
386 $params['line_item'][$priceSetId][$lineIndex]['contribution_id'] = $params['contribution']->id
;
388 if ($lineMembershipType && $lineMembershipType == CRM_Utils_Array
::value('membership_type_id', $params)) {
389 $params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $membership->id
;
390 $params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_membership';
392 elseif (!$lineMembershipType && !empty($params['contribution'])) {
393 $params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $params['contribution']->id
;
394 $params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_contribution';
398 CRM_Price_BAO_LineItem
::processPriceSet(
400 $params['line_item'],
401 CRM_Utils_Array
::value('contribution', $params)
405 //insert payment record for this membership
406 if (!empty($params['relate_contribution_id'])) {
407 $membershipPaymentParams = [
408 'membership_id' => $membership->id
,
409 'membership_type_id' => $membership->membership_type_id
,
410 'contribution_id' => $params['relate_contribution_id'],
412 civicrm_api3('MembershipPayment', 'create', $membershipPaymentParams);
415 $transaction->commit();
417 self
::createRelatedMemberships($params, $membership);
419 // do not add to recent items for import, CRM-4399
420 if (empty($params['skipRecentView'])) {
421 $url = CRM_Utils_System
::url('civicrm/contact/view/membership',
422 "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
424 if (empty($membership->membership_type_id
)) {
425 // ie in an update situation.
426 $membership->find(TRUE);
428 $membershipTypes = CRM_Member_PseudoConstant
::membershipType();
429 $title = CRM_Contact_BAO_Contact
::displayName($membership->contact_id
) . ' - ' . ts('Membership Type:') . ' ' . $membershipTypes[$membership->membership_type_id
];
432 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::UPDATE
)) {
433 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
434 "action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
437 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::DELETE
)) {
438 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
439 "action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
443 // add the recently created Membership
444 CRM_Utils_Recent
::add($title,
448 $membership->contact_id
,
458 * Check the membership extended through relationship.
460 * @param int $membershipTypeID
461 * Membership type id.
462 * @param int $contactId
468 * array of contact_id of all related contacts.
470 public static function checkMembershipRelationship($membershipTypeID, $contactId, $action = CRM_Core_Action
::ADD
) {
473 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipTypeID);
475 if (isset($membershipType['relationship_type_id'])) {
476 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
477 CRM_Contact_BAO_Relationship
::CURRENT
479 if ($action & CRM_Core_Action
::UPDATE
) {
480 $pastRelationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
481 CRM_Contact_BAO_Relationship
::PAST
483 $relationships = array_merge($relationships, $pastRelationships);
487 if (!empty($relationships)) {
488 // check for each contact relationships
489 foreach ($relationships as $values) {
490 //get details of the relationship type
491 $relType = ['id' => $values['civicrm_relationship_type_id']];
493 CRM_Contact_BAO_RelationshipType
::retrieve($relType, $relValues);
494 // Check if contact's relationship type exists in membership type
496 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_type_id']);
497 $relDirections = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_direction']);
498 $bidirectional = FALSE;
499 foreach ($relTypeIds as $key => $value) {
500 $relTypeDirs[] = $value . '_' . $relDirections[$key];
501 if (in_array($value, $relType) &&
502 $relValues['name_a_b'] == $relValues['name_b_a']
504 $bidirectional = TRUE;
508 $relTypeDir = $values['civicrm_relationship_type_id'] . '_' . $values['rtype'];
509 if ($bidirectional ||
in_array($relTypeDir, $relTypeDirs)) {
510 // $values['status'] is going to have value for
511 // current or past relationships.
512 $contacts[$values['cid']] = $values['status'];
517 // Sort by contact_id ascending
523 * Retrieve DB object based on input parameters.
525 * It also stores all the retrieved values in the default array.
527 * @param array $params
528 * (reference ) an assoc array of name/value pairs.
529 * @param array $defaults
530 * (reference ) an assoc array to hold the name / value pairs.
531 * in a hierarchical manner
533 * @return CRM_Member_BAO_Membership
535 public static function retrieve(&$params, &$defaults) {
536 $membership = new CRM_Member_DAO_Membership();
538 $membership->copyValues($params);
540 if ($membership->find(TRUE)) {
541 CRM_Core_DAO
::storeValues($membership, $defaults);
543 //get the membership status and type values.
544 $statusANDType = self
::getStatusANDTypeValues($membership->id
);
545 foreach (['status', 'membership_type'] as $fld) {
546 $defaults[$fld] = CRM_Utils_Array
::value($fld, $statusANDType[$membership->id
]);
548 if (!empty($statusANDType[$membership->id
]['is_current_member'])) {
549 $defaults['active'] = TRUE;
559 * Get membership status and membership type values.
561 * @param int $membershipId
562 * Membership id of values to return.
565 * Array of key value pairs
567 public static function getStatusANDTypeValues($membershipId) {
569 if (!$membershipId) {
573 SELECT membership.id as id,
574 status.id as status_id,
575 status.label as status,
576 status.is_current_member as is_current_member,
577 type.id as membership_type_id,
578 type.name as membership_type,
579 type.relationship_type_id as relationship_type_id
580 FROM civicrm_membership membership
581 INNER JOIN civicrm_membership_status status ON ( status.id = membership.status_id )
582 INNER JOIN civicrm_membership_type type ON ( type.id = membership.membership_type_id )
583 WHERE membership.id = %1';
584 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$membershipId, 'Positive']]);
589 'membership_type_id',
591 'relationship_type_id',
593 while ($dao->fetch()) {
594 foreach ($properties as $property) {
595 $values[$dao->id
][$property] = $dao->$property;
605 * Wrapper for most delete calls. Use this unless you JUST want to delete related memberships w/o deleting the parent.
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 del($membershipId, $preserveContrib = FALSE) {
615 //delete related first and then delete parent.
616 self
::deleteRelatedMemberships($membershipId);
617 return self
::deleteMembership($membershipId, $preserveContrib);
623 * @param int $membershipId
624 * Membership id that needs to be deleted.
625 * @param bool $preserveContrib
628 * Id of deleted Membership on success, false otherwise.
630 public static function deleteMembership($membershipId, $preserveContrib = FALSE) {
631 // CRM-12147, retrieve membership data before we delete it for hooks
632 $params = ['id' => $membershipId];
634 $memberships = self
::getValues($params, $memValues);
636 $membership = $memberships[$membershipId];
638 CRM_Utils_Hook
::pre('delete', 'Membership', $membershipId, $memValues);
640 $transaction = new CRM_Core_Transaction();
643 //delete activity record
644 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
647 $deleteActivity = FALSE;
648 $membershipActivities = [
650 'Membership Renewal',
651 'Change Membership Status',
652 'Change Membership Type',
653 'Membership Renewal Reminder',
655 foreach ($membershipActivities as $membershipActivity) {
656 $activityId = array_search($membershipActivity, $activityTypes);
658 $params['activity_type_id'][] = $activityId;
659 $deleteActivity = TRUE;
662 if ($deleteActivity) {
663 $params['source_record_id'] = $membershipId;
664 CRM_Activity_BAO_Activity
::deleteActivity($params);
666 self
::deleteMembershipPayment($membershipId, $preserveContrib);
668 $results = $membership->delete();
669 $transaction->commit();
671 CRM_Utils_Hook
::post('delete', 'Membership', $membership->id
, $membership);
673 // delete the recently created Membership
674 $membershipRecent = [
675 'id' => $membershipId,
676 'type' => 'Membership',
678 CRM_Utils_Recent
::del($membershipRecent);
684 * Delete related memberships.
686 * @param int $ownerMembershipId
687 * @param int $contactId
691 public static function deleteRelatedMemberships($ownerMembershipId, $contactId = NULL) {
692 if (!$ownerMembershipId && !$contactId) {
696 $membership = new CRM_Member_DAO_Membership();
697 $membership->owner_membership_id
= $ownerMembershipId;
700 $membership->contact_id
= $contactId;
704 while ($membership->fetch()) {
705 //delete related first and then delete parent.
706 self
::deleteRelatedMemberships($membership->id
);
707 self
::deleteMembership($membership->id
);
712 * Obtain active/inactive memberships from the list of memberships passed to it.
714 * @param array $memberships
715 * Membership records.
716 * @param string $status
717 * Active or inactive.
720 * array of memberships based on status
722 public static function activeMembers($memberships, $status = 'active') {
724 if ($status == 'active') {
725 foreach ($memberships as $f => $v) {
726 if (!empty($v['active'])) {
732 elseif ($status == 'inactive') {
733 foreach ($memberships as $f => $v) {
734 if (empty($v['active'])) {
744 * Return Membership Block info in Contribution Pages.
747 * Contribution page id.
751 public static function getMembershipBlock($pageID) {
752 $membershipBlock = [];
753 $dao = new CRM_Member_DAO_MembershipBlock();
754 $dao->entity_table
= 'civicrm_contribution_page';
756 $dao->entity_id
= $pageID;
758 if ($dao->find(TRUE)) {
759 CRM_Core_DAO
::storeValues($dao, $membershipBlock);
760 if (!empty($membershipBlock['membership_types'])) {
761 $membershipTypes = unserialize($membershipBlock['membership_types']);
762 if (!is_array($membershipTypes)) {
763 return $membershipBlock;
766 foreach ($membershipTypes as $key => $value) {
767 $membershipBlock['auto_renew'][$key] = $value;
768 $memTypes[$key] = $key;
770 $membershipBlock['membership_types'] = implode(',', $memTypes);
777 return $membershipBlock;
781 * Return a current membership of given contact.
783 * NB: if more than one membership meets criteria, a randomly selected one is returned.
785 * @param int $contactID
787 * @param int $memType
788 * Membership type, null to retrieve all types.
790 * @param int $membershipId
791 * If provided, then determine if it is current.
792 * @param bool $onlySameParentOrg
793 * True if only Memberships with same parent org as the $memType wanted, false otherwise.
796 * @throws \CiviCRM_API3_Exception
798 public static function getContactMembership($contactID, $memType, $isTest, $membershipId = NULL, $onlySameParentOrg = FALSE) {
799 //check for owner membership id, if it exists update that membership instead: CRM-15992
801 $ownerMemberId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
803 'owner_membership_id', 'id'
805 if ($ownerMemberId) {
806 $membershipId = $ownerMemberId;
807 $contactID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
814 $dao = new CRM_Member_DAO_Membership();
816 $dao->id
= $membershipId;
818 $dao->contact_id
= $contactID;
819 $dao->membership_type_id
= $memType;
821 //fetch proper membership record.
823 $dao->is_test
= $isTest;
826 $dao->whereAdd('is_test IS NULL OR is_test = 0');
829 //avoid pending membership as current membership: CRM-3027
830 $statusIds = [array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus())];
831 if (!$membershipId) {
833 $statusIds[] = array_search(
835 CRM_Member_PseudoConstant
::membershipStatus(
837 " name = 'Cancelled' ",
844 $dao->whereAdd('status_id NOT IN ( ' . implode(',', $statusIds) . ')');
846 // order by start date to find most recent membership first, CRM-4545
847 $dao->orderBy('start_date DESC');
850 if ($onlySameParentOrg && $memType) {
851 // require the same parent org as the $memType
852 $params = ['id' => $memType];
853 $membershipType = [];
854 if (CRM_Member_BAO_MembershipType
::retrieve($params, $membershipType)) {
855 $memberTypesSameParentOrg = civicrm_api3('MembershipType', 'get', [
856 'member_of_contact_id' => $membershipType['member_of_contact_id'],
861 $memberTypesSameParentOrgList = implode(',', array_keys(CRM_Utils_Array
::value('values', $memberTypesSameParentOrg, [])));
862 $dao->whereAdd('membership_type_id IN (' . $memberTypesSameParentOrgList . ')');
866 if ($dao->find(TRUE)) {
868 CRM_Core_DAO
::storeValues($dao, $membership);
869 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
870 $membership['status_id'],
871 'is_current_member', 'id'
873 $ownerMemberId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
875 'owner_membership_id', 'id'
877 if ($ownerMemberId) {
878 $membership['id'] = $membership['membership_id'] = $ownerMemberId;
879 $membership['membership_contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
888 if ($onlySameParentOrg && $memType) {
889 // see if there is a membership that has same parent as $memType but different parent than $membershipID
890 if ($dao->id
&& CRM_Core_Permission
::check('edit memberships')) {
891 // CRM-10016, This is probably a backend renewal, and make sure we return the same membership thats being renewed.
898 unset($dao->membership_type_id
);
899 if ($dao->find(TRUE)) {
901 CRM_Core_DAO
::storeValues($dao, $membership);
902 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
903 $membership['status_id'],
904 'is_current_member', 'id'
913 * Combine all the importable fields from the lower levels object.
915 * @param string $contactType
917 * @param bool $status
920 * array of importable Fields
922 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
923 if (!self
::$_importableFields) {
924 if (!self
::$_importableFields) {
925 self
::$_importableFields = [];
929 $fields = ['' => ['title' => '- ' . ts('do not import') . ' -']];
932 $fields = ['' => ['title' => '- ' . ts('Membership Fields') . ' -']];
935 $tmpFields = CRM_Member_DAO_Membership
::import();
936 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
938 // Using new Dedupe rule.
940 'contact_type' => $contactType,
941 'used' => 'Unsupervised',
943 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
945 $tmpContactField = [];
946 if (is_array($fieldsArray)) {
947 foreach ($fieldsArray as $value) {
948 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
953 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
954 $tmpContactField[trim($value)] = CRM_Utils_Array
::value(trim($value), $contactFields);
956 $title = $tmpContactField[trim($value)]['title'] . " " . ts('(match to contact)');
959 $title = $tmpContactField[trim($value)]['title'];
961 $tmpContactField[trim($value)]['title'] = $title;
964 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
965 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " " . ts('(match to contact)');
967 $tmpFields['membership_contact_id']['title'] = $tmpFields['membership_contact_id']['title'] . " " . ts('(match to contact)');;
969 $fields = array_merge($fields, $tmpContactField);
970 $fields = array_merge($fields, $tmpFields);
971 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
972 self
::$_importableFields = $fields;
974 return self
::$_importableFields;
978 * Get all exportable fields.
980 * @return array return array of all exportable fields
982 public static function &exportableFields() {
983 $expFieldMembership = CRM_Member_DAO_Membership
::export();
985 $expFieldsMemType = CRM_Member_DAO_MembershipType
::export();
986 $fields = array_merge($expFieldMembership, $expFieldsMemType);
987 $fields = array_merge($fields, $expFieldMembership);
988 $membershipStatus = [
989 'membership_status' => [
990 'title' => ts('Membership Status'),
991 'name' => 'membership_status',
992 'type' => CRM_Utils_Type
::T_STRING
,
993 'where' => 'civicrm_membership_status.name',
996 //CRM-6161 fix for customdata export
997 $fields = array_merge($fields, $membershipStatus, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1002 * Get membership joins/renewals for a specified membership type.
1004 * Specifically, retrieves a count of memberships whose "Membership
1005 * Signup" or "Membership Renewal" activity falls in the given date range.
1006 * Dates match the pattern "yyyy-mm-dd".
1008 * @param int $membershipTypeId
1009 * Membership type id.
1010 * @param int $startDate
1011 * Date on which to start counting.
1012 * @param int $endDate
1013 * Date on which to end counting.
1014 * @param bool|int $isTest if true, membership is for a test site
1015 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1018 * the number of members of type $membershipTypeId whose
1019 * start_date is between $startDate and $endDate
1021 public static function getMembershipStarts($membershipTypeId, $startDate, $endDate, $isTest = 0, $isOwner = 0) {
1023 $testClause = 'membership.is_test = 1';
1025 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1028 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1029 self
::_getActTypes();
1032 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1037 SELECT COUNT(DISTINCT membership.id) as member_count
1038 FROM civicrm_membership membership
1039 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id in (%1, %2))
1040 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1041 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1042 WHERE membership.membership_type_id = %3
1043 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1046 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1049 1 => [self
::$_signupActType, 'Integer'],
1050 2 => [self
::$_renewalActType, 'Integer'],
1051 3 => [$membershipTypeId, 'Integer'],
1054 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1055 return (int) $memberCount;
1059 * Get a count of membership for a specified membership type, optionally for a specified date.
1061 * The date must have the form yyyy-mm-dd.
1063 * If $date is omitted, this function counts as a member anyone whose
1064 * membership status_id indicates they're a current member.
1065 * If $date is given, this function counts as a member anyone who:
1066 * -- Has a start_date before $date and end_date after $date, or
1067 * -- Has a start_date before $date and is currently a member, as indicated
1068 * by the the membership's status_id.
1069 * The second condition takes care of records that have no end_date. These
1070 * are assumed to be lifetime memberships.
1072 * @param int $membershipTypeId
1073 * Membership type id.
1074 * @param string $date
1075 * The date for which to retrieve the count.
1076 * @param bool|int $isTest if true, membership is for a test site
1077 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1080 * the number of members of type $membershipTypeId as of $date.
1082 public static function getMembershipCount($membershipTypeId, $date = NULL, $isTest = 0, $isOwner = 0) {
1083 if (!CRM_Utils_Rule
::date($date)) {
1084 CRM_Core_Error
::fatal(ts('Invalid date "%1" (must have form yyyy-mm-dd).', [1 => $date]));
1088 1 => [$membershipTypeId, 'Integer'],
1089 2 => [$isTest, 'Boolean'],
1091 $query = "SELECT count(civicrm_membership.id ) as member_count
1092 FROM civicrm_membership left join civicrm_membership_status on ( civicrm_membership.status_id = civicrm_membership_status.id )
1093 WHERE civicrm_membership.membership_type_id = %1
1094 AND civicrm_membership.contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)
1095 AND civicrm_membership.is_test = %2";
1097 $query .= " AND civicrm_membership_status.is_current_member = 1";
1100 $query .= " AND civicrm_membership.start_date <= '$date' AND civicrm_membership_status.is_current_member = 1";
1103 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1104 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1105 return (int) $memberCount;
1109 * Function check the status of the membership before adding membership for a contact.
1113 public static function statusAvailabilty() {
1114 $membership = new CRM_Member_DAO_MembershipStatus();
1115 $membership->whereAdd('is_active=1');
1116 return $membership->count();
1120 * @deprecated This is not used anywhere and should be removed soon!
1121 * Function for updating a membership record's contribution_recur_id.
1123 * @param CRM_Member_DAO_Membership $membership
1124 * @param \CRM_Contribute_BAO_Contribution|\CRM_Contribute_DAO_Contribution $contribution
1126 public static function updateRecurMembership(CRM_Member_DAO_Membership
$membership, CRM_Contribute_BAO_Contribution
$contribution) {
1127 CRM_Core_Error
::deprecatedFunctionWarning('Use the API instead');
1129 if (empty($contribution->contribution_recur_id
)) {
1134 1 => [$contribution->contribution_recur_id
, 'Integer'],
1135 2 => [$membership->id
, 'Integer'],
1138 $sql = "UPDATE civicrm_membership SET contribution_recur_id = %1 WHERE id = %2";
1139 CRM_Core_DAO
::executeQuery($sql, $params);
1143 * Method to fix membership status of stale membership.
1145 * This method first checks if the membership is stale. If it is,
1146 * then status will be updated based on existing start and end
1147 * dates and log will be added for the status change.
1149 * @param array $currentMembership
1150 * Reference to the array.
1151 * containing all values of
1152 * the current membership
1153 * @param string $changeToday
1154 * In case today needs
1155 * to be customised, null otherwise
1157 * @throws \CRM_Core_Exception
1159 public static function fixMembershipStatusBeforeRenew(&$currentMembership, $changeToday) {
1162 $today = CRM_Utils_Date
::processDate($changeToday, NULL, FALSE, 'Y-m-d');
1165 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
1166 CRM_Utils_Array
::value('start_date', $currentMembership),
1167 CRM_Utils_Array
::value('end_date', $currentMembership),
1168 CRM_Utils_Array
::value('join_date', $currentMembership),
1171 $currentMembership['membership_type_id'],
1175 if (empty($status) ||
empty($status['id'])) {
1176 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.'));
1179 $currentMembership['today_date'] = $today;
1181 if ($status['id'] !== $currentMembership['status_id']) {
1182 $oldStatus = $currentMembership['status_id'];
1183 $memberDAO = new CRM_Member_DAO_Membership();
1184 $memberDAO->id
= $currentMembership['id'];
1185 $memberDAO->find(TRUE);
1187 $memberDAO->status_id
= $status['id'];
1188 $memberDAO->join_date
= CRM_Utils_Date
::isoToMysql($memberDAO->join_date
);
1189 $memberDAO->start_date
= CRM_Utils_Date
::isoToMysql($memberDAO->start_date
);
1190 $memberDAO->end_date
= CRM_Utils_Date
::isoToMysql($memberDAO->end_date
);
1192 CRM_Core_DAO
::storeValues($memberDAO, $currentMembership);
1194 $currentMembership['is_current_member'] = CRM_Core_DAO
::getFieldValue(
1195 'CRM_Member_DAO_MembershipStatus',
1196 $currentMembership['status_id'],
1202 'membership_id' => $currentMembership['id'],
1203 'status_id' => $status['id'],
1204 'start_date' => CRM_Utils_Date
::customFormat(
1205 $currentMembership['start_date'],
1208 'end_date' => CRM_Utils_Date
::customFormat(
1209 $currentMembership['end_date'],
1212 'modified_date' => CRM_Utils_Date
::customFormat(
1213 $currentMembership['today_date'],
1216 'membership_type_id' => $currentMembership['membership_type_id'],
1217 'max_related' => CRM_Utils_Array
::value('max_related', $currentMembership, 0),
1220 $session = CRM_Core_Session
::singleton();
1221 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
1222 if ($session->get('userID')) {
1223 $logParams['modified_id'] = $session->get('userID');
1226 $logParams['modified_id'] = $currentMembership['contact_id'];
1229 //Create activity for status change.
1230 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
1231 CRM_Activity_BAO_Activity
::addActivity($memberDAO,
1232 'Change Membership Status',
1235 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$status['id']]}",
1236 'source_contact_id' => $logParams['modified_id'],
1237 'priority_id' => 'Normal',
1241 CRM_Member_BAO_MembershipLog
::add($logParams);
1246 * Get the contribution page id from the membership record.
1248 * @param int $membershipID
1251 * contribution page id
1253 public static function getContributionPageId($membershipID) {
1255 SELECT c.contribution_page_id as pageID
1256 FROM civicrm_membership_payment mp, civicrm_contribution c
1257 WHERE mp.contribution_id = c.id
1258 AND c.contribution_page_id IS NOT NULL
1259 AND mp.membership_id = " . CRM_Utils_Type
::escape($membershipID, 'Integer')
1260 . " ORDER BY mp.id DESC";
1262 return CRM_Core_DAO
::singleValueQuery($query);
1266 * Updated related memberships.
1268 * @param int $ownerMembershipId
1269 * Owner Membership Id.
1270 * @param array $params
1271 * Formatted array of key => value.
1273 public static function updateRelatedMemberships($ownerMembershipId, $params) {
1274 $membership = new CRM_Member_DAO_Membership();
1275 $membership->owner_membership_id
= $ownerMembershipId;
1276 $membership->find();
1278 while ($membership->fetch()) {
1279 $relatedMembership = new CRM_Member_DAO_Membership();
1280 $relatedMembership->id
= $membership->id
;
1281 $relatedMembership->copyValues($params);
1282 $relatedMembership->save();
1288 * Get list of membership fields for profile.
1290 * For now we only allow custom membership fields to be in
1294 * FIXME: This param is ignored
1297 * the list of membership fields
1299 public static function getMembershipFields($mode = NULL) {
1300 $fields = CRM_Member_DAO_Membership
::export();
1302 unset($fields['membership_contact_id']);
1303 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1305 $membershipType = CRM_Member_DAO_MembershipType
::export();
1307 $membershipStatus = CRM_Member_DAO_MembershipStatus
::export();
1309 $fields = array_merge($fields, $membershipType, $membershipStatus);
1315 * Get the sort name of a contact for a particular membership.
1318 * Id of the membership.
1320 * @return null|string
1321 * sort name of the contact if found
1323 public static function sortName($id) {
1324 $id = CRM_Utils_Type
::escape($id, 'Integer');
1327 SELECT civicrm_contact.sort_name
1328 FROM civicrm_membership, civicrm_contact
1329 WHERE civicrm_membership.contact_id = civicrm_contact.id
1330 AND civicrm_membership.id = {$id}
1332 return CRM_Core_DAO
::singleValueQuery($query);
1336 * Create memberships for related contacts, taking into account the maximum related memberships.
1338 * @param array $params
1339 * Array of key - value pairs.
1340 * @param CRM_Core_DAO $dao
1341 * Membership object.
1343 * @param bool $reset
1345 * @return array|null
1346 * Membership details, if created.
1348 * @throws \CRM_Core_Exception
1349 * @throws \CiviCRM_API3_Exception
1351 public static function createRelatedMemberships(&$params, &$dao, $reset = FALSE) {
1352 // CRM-4213 check for loops, using static variable to record contacts already processed.
1353 static $relatedContactIds = [];
1355 // We need a way to reset this static variable from the test suite.
1356 // @todo consider replacing with Civi::$statics but note reset now used elsewhere: CRM-17723.
1357 $relatedContactIds = [];
1361 $membership = new CRM_Member_DAO_Membership();
1362 $membership->id
= $dao->id
;
1364 // required since create method doesn't return all the
1365 // parameters in the returned membership object
1366 if (!$membership->find(TRUE)) {
1369 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1370 // FIXME : While updating/ renewing the
1371 // membership, if the relationship is PAST then
1372 // the membership of the related contact must be
1374 // For that, getting Membership Status for which
1375 // is_current_member is 0. It works for the
1376 // generated data as there is only one membership
1377 // status having is_current_member = 0.
1378 // But this wont work exactly if there will be
1379 // more than one status having is_current_member = 0.
1380 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
1381 $membershipStatus->is_current_member
= 0;
1382 if ($membershipStatus->find(TRUE)) {
1383 $expiredStatusId = $membershipStatus->id
;
1386 $expiredStatusId = array_search('Expired', CRM_Member_PseudoConstant
::membershipStatus());
1389 $allRelatedContacts = [];
1390 $relatedContacts = [];
1391 if (!is_a($membership, 'CRM_Core_Error')) {
1392 $allRelatedContacts = CRM_Member_BAO_Membership
::checkMembershipRelationship($membership->membership_type_id
,
1393 $membership->contact_id
,
1394 CRM_Utils_Array
::value('action', $params)
1398 // CRM-4213, CRM-19735 check for loops, using static variable to record contacts already processed.
1399 // Remove repeated related contacts, which already inherited membership of this type.
1400 $relatedContactIds[$membership->contact_id
][$membership->membership_type_id
] = TRUE;
1401 foreach ($allRelatedContacts as $cid => $status) {
1402 if (empty($relatedContactIds[$cid]) ||
empty($relatedContactIds[$cid][$membership->membership_type_id
])) {
1403 $relatedContactIds[$cid][$membership->membership_type_id
] = TRUE;
1405 //don't create membership again for owner contact.
1406 $nestedRelationship = FALSE;
1407 if ($membership->owner_membership_id
) {
1408 $nestedRelMembership = new CRM_Member_DAO_Membership();
1409 $nestedRelMembership->id
= $membership->owner_membership_id
;
1410 $nestedRelMembership->contact_id
= $cid;
1411 $nestedRelationship = $nestedRelMembership->find(TRUE);
1413 if (!$nestedRelationship) {
1414 $relatedContacts[$cid] = $status;
1419 //lets cleanup related membership if any.
1420 if (empty($relatedContacts)) {
1421 self
::deleteRelatedMemberships($membership->id
);
1424 // Edit the params array
1425 unset($params['id']);
1426 // Reminder should be sent only to the direct membership
1427 unset($params['reminder_date']);
1428 // unset the custom value ids
1429 if (is_array(CRM_Utils_Array
::value('custom', $params))) {
1430 foreach ($params['custom'] as $k => $v) {
1431 unset($params['custom'][$k]['id']);
1434 if (!isset($params['membership_type_id'])) {
1435 $params['membership_type_id'] = $membership->membership_type_id
;
1438 // max_related should be set in the parent membership
1439 unset($params['max_related']);
1440 // Number of inherited memberships available - NULL is interpreted as unlimited, '0' as none
1441 $numRelatedAvailable = ($membership->max_related
== NULL ? PHP_INT_MAX
: $membership->max_related
);
1442 // will be used to queue potential memberships to be created.
1445 foreach ($relatedContacts as $contactId => $relationshipStatus) {
1446 //use existing membership record.
1447 $relMembership = new CRM_Member_DAO_Membership();
1448 $relMembership->contact_id
= $contactId;
1449 $relMembership->owner_membership_id
= $membership->id
;
1450 if ($relMembership->find(TRUE)) {
1451 $params['id'] = $relMembership->id
;
1453 $params['contact_id'] = $contactId;
1454 $params['owner_membership_id'] = $membership->id
;
1456 // set status_id as it might have been changed for
1457 // past relationship
1458 $params['status_id'] = $membership->status_id
;
1460 if ($deceasedStatusId &&
1461 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'is_deceased')
1463 $params['status_id'] = $deceasedStatusId;
1465 elseif ((CRM_Utils_Array
::value('action', $params) & CRM_Core_Action
::UPDATE
) &&
1466 ($relationshipStatus == CRM_Contact_BAO_Relationship
::PAST
)
1468 $params['status_id'] = $expiredStatusId;
1471 //don't calculate status again in create( );
1472 $params['skipStatusCal'] = TRUE;
1474 //do create activity if we changed status.
1475 if ($params['status_id'] != $relMembership->status_id
) {
1476 $params['createActivity'] = TRUE;
1479 //CRM-20707 - include start/end date
1480 $params['start_date'] = $membership->start_date
;
1481 $params['end_date'] = $membership->end_date
;
1483 // we should not created contribution record for related contacts, CRM-3371
1484 unset($params['contribution_status_id']);
1486 //CRM-16857: Do not create multiple line-items for inherited membership through priceset.
1487 unset($params['lineItems']);
1488 unset($params['line_item']);
1490 // CRM-20966: Do not create membership_payment record for inherited membership.
1491 unset($params['relate_contribution_id']);
1494 if (($params['status_id'] == $deceasedStatusId) ||
($params['status_id'] == $expiredStatusId)) {
1495 // related membership is not active so does not count towards maximum
1496 // @todo stop passing empty $ids
1497 CRM_Member_BAO_Membership
::create($params, $ids);
1500 // related membership already exists, so this is just an update
1501 if (isset($params['id'])) {
1502 if ($numRelatedAvailable > 0) {
1503 // @todo stop passing empty $ids
1504 CRM_Member_BAO_Membership
::create($params, $ids);
1505 $numRelatedAvailable--;
1508 // we have run out of inherited memberships, so delete extras
1509 self
::deleteMembership($params['id']);
1511 // we need to first check if there will remain inherited memberships, so queue it up
1518 // now go over the queue and create any available related memberships
1519 foreach ($queue as $params) {
1520 if ($numRelatedAvailable <= 0) {
1523 // @todo stop passing $ids - at this point it may be set by reference from earlier calls to CRM_Member_BAO_Membership::create
1524 CRM_Member_BAO_Membership
::create($params, $ids);
1525 $numRelatedAvailable--;
1531 * Delete the record that are associated with this Membership Payment.
1533 * @param int $membershipId
1534 * @param bool $preserveContrib
1537 * $membershipPayment deleted membership payment object
1539 public static function deleteMembershipPayment($membershipId, $preserveContrib = FALSE) {
1541 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
1542 $membershipPayment->membership_id
= $membershipId;
1543 $membershipPayment->find();
1545 while ($membershipPayment->fetch()) {
1546 if (!$preserveContrib) {
1547 CRM_Contribute_BAO_Contribution
::deleteContribution($membershipPayment->contribution_id
);
1549 CRM_Utils_Hook
::pre('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1550 $membershipPayment->delete();
1551 CRM_Utils_Hook
::post('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1553 return $membershipPayment;
1557 * Build an array of available membership types.
1559 * @param CRM_Core_Form $form
1560 * @param array $membershipTypeID
1561 * @param bool $activeOnly
1562 * Do we only want active ones?
1563 * (probably this should default to TRUE but as a newly added parameter we are leaving default b
1564 * behaviour unchanged).
1568 public static function buildMembershipTypeValues(&$form, $membershipTypeID = [], $activeOnly = FALSE) {
1569 $whereClause = " WHERE domain_id = " . CRM_Core_Config
::domainID();
1570 $membershipTypeIDS = (array) $membershipTypeID;
1573 $whereClause .= " AND is_active = 1 ";
1575 if (!empty($membershipTypeIDS)) {
1576 $allIDs = implode(',', $membershipTypeIDS);
1577 $whereClause .= " AND id IN ( $allIDs )";
1579 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes, CRM_Core_Action
::ADD
);
1581 if ($financialTypes) {
1582 $whereClause .= " AND financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1585 $whereClause .= " AND financial_type_id IN (0)";
1590 FROM civicrm_membership_type
1593 $dao = CRM_Core_DAO
::executeQuery($query);
1595 $membershipTypeValues = [];
1596 $membershipTypeFields = [
1602 'financial_type_id',
1604 'member_of_contact_id',
1605 'relationship_type_id',
1606 'relationship_direction',
1609 'duration_interval',
1612 while ($dao->fetch()) {
1613 $membershipTypeValues[$dao->id
] = [];
1614 foreach ($membershipTypeFields as $mtField) {
1615 $membershipTypeValues[$dao->id
][$mtField] = $dao->$mtField;
1619 CRM_Utils_Hook
::membershipTypeValues($form, $membershipTypeValues);
1621 if (is_numeric($membershipTypeID) &&
1622 $membershipTypeID > 0
1624 return $membershipTypeValues[$membershipTypeID];
1627 return $membershipTypeValues;
1632 * Get membership record count for a Contact.
1634 * @param int $contactID
1635 * @param bool $activeOnly
1637 * @return null|string
1639 public static function getContactMembershipCount($contactID, $activeOnly = FALSE) {
1640 CRM_Financial_BAO_FinancialType
::getAvailableMembershipTypes($membershipTypes);
1641 $addWhere = " AND membership_type_id IN (0)";
1642 if (!empty($membershipTypes)) {
1643 $addWhere = " AND membership_type_id IN (" . implode(',', array_keys($membershipTypes)) . ")";
1645 $select = "SELECT count(*) FROM civicrm_membership ";
1646 $where = "WHERE civicrm_membership.contact_id = {$contactID} AND civicrm_membership.is_test = 0 ";
1648 // CRM-6627, all status below 3 (active, pending, grace) are considered active
1650 $select .= " INNER JOIN civicrm_membership_status ON civicrm_membership.status_id = civicrm_membership_status.id ";
1651 $where .= " and civicrm_membership_status.is_current_member = 1";
1654 $query = $select . $where . $addWhere;
1655 return CRM_Core_DAO
::singleValueQuery($query);
1659 * Check whether payment processor supports cancellation of membership subscription.
1664 * @param bool $isNotCancelled
1668 public static function isCancelSubscriptionSupported($mid, $isNotCancelled = TRUE) {
1669 $cacheKeyString = "$mid";
1670 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
1672 static $supportsCancel = [];
1674 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
1675 $supportsCancel[$cacheKeyString] = FALSE;
1676 $isCancelled = FALSE;
1678 if ($isNotCancelled) {
1679 $isCancelled = self
::isSubscriptionCancelled($mid);
1682 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($mid, 'membership', 'obj');
1683 if (!empty($paymentObject)) {
1684 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
1687 return $supportsCancel[$cacheKeyString];
1691 * Check whether subscription is already cancelled.
1697 * contribution status
1699 public static function isSubscriptionCancelled($mid) {
1701 SELECT cr.contribution_status_id
1702 FROM civicrm_contribution_recur cr
1703 LEFT JOIN civicrm_membership mem ON ( cr.id = mem.contribution_recur_id )
1704 WHERE mem.id = %1 LIMIT 1";
1705 $params = [1 => [$mid, 'Integer']];
1706 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
1707 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
1708 if ($status == 'Cancelled') {
1715 * Get membership joins for a specified membership type.
1717 * Specifically, retrieves a count of still current memberships whose
1718 * join_date and start_date are within a specified date range. Dates match
1719 * the pattern "yyyy-mm-dd".
1721 * @param int $membershipTypeId
1722 * Membership type id.
1723 * @param int $startDate
1724 * Date on which to start counting.
1725 * @param int $endDate
1726 * Date on which to end counting.
1727 * @param bool|int $isTest if true, membership is for a test site
1730 * the number of members of type $membershipTypeId
1731 * whose join_date is between $startDate and $endDate and
1732 * whose start_date is between $startDate and $endDate
1734 public static function getMembershipJoins($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1735 $testClause = 'membership.is_test = 1';
1737 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1739 if (!self
::$_signupActType) {
1740 self
::_getActTypes();
1743 if (!self
::$_signupActType) {
1748 SELECT COUNT(DISTINCT membership.id) as member_count
1749 FROM civicrm_membership membership
1750 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1751 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1752 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1753 WHERE membership.membership_type_id = %2
1754 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1758 1 => [self
::$_signupActType, 'Integer'],
1759 2 => [$membershipTypeId, 'Integer'],
1762 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1764 return (int) $memberCount;
1768 * Get membership renewals for a specified membership type.
1770 * Specifically, retrieves a count of still current memberships
1771 * whose join_date is before and start_date is within a specified date
1772 * range. Dates match the pattern "yyyy-mm-dd".
1774 * @param int $membershipTypeId
1775 * Membership type id.
1776 * @param int $startDate
1777 * Date on which to start counting.
1778 * @param int $endDate
1779 * Date on which to end counting.
1780 * @param bool|int $isTest if true, membership is for a test site
1783 * returns the number of members of type $membershipTypeId
1784 * whose join_date is before $startDate and
1785 * whose start_date is between $startDate and $endDate
1787 public static function getMembershipRenewals($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1788 $testClause = 'membership.is_test = 1';
1790 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1792 if (!self
::$_renewalActType) {
1793 self
::_getActTypes();
1796 if (!self
::$_renewalActType) {
1801 SELECT COUNT(DISTINCT membership.id) as member_count
1802 FROM civicrm_membership membership
1803 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1804 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1805 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1806 WHERE membership.membership_type_id = %2
1807 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1811 1 => [self
::$_renewalActType, 'Integer'],
1812 2 => [$membershipTypeId, 'Integer'],
1814 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1816 return (int) $memberCount;
1820 * @param int $contactID
1821 * @param int $membershipTypeID
1822 * @param bool $is_test
1823 * @param string $changeToday
1824 * @param int $modifiedID
1825 * @param $customFieldsFormatted
1826 * @param $numRenewTerms
1827 * @param int $membershipID
1829 * @param int $contributionRecurID
1830 * @param $membershipSource
1831 * @param $isPayLater
1832 * @param int $campaignId
1833 * @param array $formDates
1834 * @param null|CRM_Contribute_BAO_Contribution $contribution
1835 * @param array $lineItems
1838 * @throws \CRM_Core_Exception
1839 * @throws \CiviCRM_API3_Exception
1841 public static function processMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $contributionRecurID, $membershipSource, $isPayLater, $campaignId, $formDates = [], $contribution = NULL, $lineItems = []) {
1842 $renewalMode = $updateStatusId = FALSE;
1843 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1845 $statusFormat = '%Y-%m-%d';
1846 $membershipTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipTypeID);
1850 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
1851 // is the same as the parent org of an existing membership of the contact
1852 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($contactID, $membershipTypeID,
1853 $is_test, $membershipID, TRUE
1855 if ($currentMembership) {
1856 $renewalMode = TRUE;
1858 // Do NOT do anything.
1859 //1. membership with status : PENDING/CANCELLED (CRM-2395)
1860 //2. Paylater/IPN renew. CRM-4556.
1861 if ($pending ||
in_array($currentMembership['status_id'], [
1862 array_search('Pending', $allStatus),
1864 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1868 'id' => $currentMembership['id'],
1869 'contribution' => $contribution,
1870 'status_id' => $currentMembership['status_id'],
1871 'start_date' => $currentMembership['start_date'],
1872 'end_date' => $currentMembership['end_date'],
1873 'line_item' => $lineItems,
1874 'join_date' => $currentMembership['join_date'],
1875 'membership_type_id' => $membershipTypeID,
1876 'max_related' => !empty($membershipTypeDetails['max_related']) ?
$membershipTypeDetails['max_related'] : NULL,
1877 'membership_activity_status' => ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed',
1879 if ($contributionRecurID) {
1880 $memParams['contribution_recur_id'] = $contributionRecurID;
1882 // @todo stop passing $ids - it is empty
1883 $membership = self
::create($memParams, $ids);
1884 return [$membership, $renewalMode, $dates];
1887 // Check and fix the membership if it is STALE
1888 self
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
1890 // Now Renew the membership
1891 if (!$currentMembership['is_current_member']) {
1892 // membership is not CURRENT
1894 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1895 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($currentMembership['id'],
1901 $currentMembership['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1902 foreach (['start_date', 'end_date'] as $dateType) {
1903 $currentMembership[$dateType] = CRM_Utils_Array
::value($dateType, $formDates);
1904 if (empty($currentMembership[$dateType])) {
1905 $currentMembership[$dateType] = CRM_Utils_Array
::value($dateType, $dates);
1908 $currentMembership['is_test'] = $is_test;
1910 if (!empty($membershipSource)) {
1911 $currentMembership['source'] = $membershipSource;
1914 $currentMembership['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
1915 $currentMembership['id'],
1920 if (!empty($currentMembership['id'])) {
1921 $ids['membership'] = $currentMembership['id'];
1923 $memParams = $currentMembership;
1924 $memParams['membership_type_id'] = $membershipTypeID;
1926 //set the log start date.
1927 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1931 // CURRENT Membership
1932 $membership = new CRM_Member_DAO_Membership();
1933 $membership->id
= $currentMembership['id'];
1934 $membership->find(TRUE);
1935 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1936 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
1942 // Insert renewed dates for CURRENT membership
1944 $memParams['join_date'] = CRM_Utils_Date
::isoToMysql($membership->join_date
);
1945 $memParams['start_date'] = CRM_Utils_Array
::value('start_date', $formDates, CRM_Utils_Date
::isoToMysql($membership->start_date
));
1946 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $formDates);
1947 if (empty($memParams['end_date'])) {
1948 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $dates);
1950 $memParams['membership_type_id'] = $membershipTypeID;
1952 //set the log start date.
1953 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1956 if (!empty($membershipSource)) {
1957 $memParams['source'] = $membershipSource;
1959 elseif (empty($membership->source
)) {
1960 $memParams['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
1961 $currentMembership['id'],
1966 if (!empty($currentMembership['id'])) {
1967 $ids['membership'] = $currentMembership['id'];
1969 $memParams['membership_activity_status'] = ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed';
1973 $updateStatusId = array_search('Pending', $allStatus);
1979 'contact_id' => $contactID,
1980 'membership_type_id' => $membershipTypeID,
1984 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
1986 foreach (['join_date', 'start_date', 'end_date'] as $dateType) {
1987 $memParams[$dateType] = CRM_Utils_Array
::value($dateType, $formDates);
1988 if (empty($memParams[$dateType])) {
1989 $memParams[$dateType] = CRM_Utils_Array
::value($dateType, $dates);
1993 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(CRM_Utils_Date
::customFormat($dates['start_date'],
1996 CRM_Utils_Date
::customFormat($dates['end_date'],
1999 CRM_Utils_Date
::customFormat($dates['join_date'],
2007 $updateStatusId = CRM_Utils_Array
::value('id', $status);
2010 // if IPN/Pay-Later set status to: PENDING
2011 $updateStatusId = array_search('Pending', $allStatus);
2014 if (!empty($membershipSource)) {
2015 $memParams['source'] = $membershipSource;
2017 $memParams['is_test'] = $is_test;
2018 $memParams['is_pay_later'] = $isPayLater;
2020 // Putting this in an IF is precautionary as it seems likely that it would be ignored if empty, but
2021 // perhaps shouldn't be?
2022 if ($contributionRecurID) {
2023 $memParams['contribution_recur_id'] = $contributionRecurID;
2026 //if we decided status here and want to skip status
2027 //calculation in create( ); then need to pass 'skipStatusCal'.
2028 if ($updateStatusId) {
2029 $memParams['status_id'] = $updateStatusId;
2030 $memParams['skipStatusCal'] = TRUE;
2033 //since we are renewing,
2034 //make status override false.
2035 $memParams['is_override'] = FALSE;
2037 //CRM-4027, create log w/ individual contact.
2039 $ids['userId'] = $modifiedID;
2040 $memParams['is_for_organization'] = TRUE;
2043 $ids['userId'] = $contactID;
2046 //inherit campaign from contrib page.
2047 if (isset($campaignId)) {
2048 $memParams['campaign_id'] = $campaignId;
2051 $memParams['contribution'] = $contribution;
2052 $memParams['custom'] = $customFieldsFormatted;
2053 // Load all line items & process all in membership. Don't do in contribution.
2054 // Relevant tests in api_v3_ContributionPageTest.
2055 $memParams['line_item'] = $lineItems;
2056 // @todo stop passing $ids (membership and userId may be set by this point)
2057 $membership = self
::create($memParams, $ids);
2059 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
2060 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
2061 $membership->find(TRUE);
2063 return [$membership, $renewalMode, $dates];
2067 * Get line items representing the default price set.
2069 * @param int $membershipOrg
2070 * @param int $membershipTypeID
2071 * @param float $total_amount
2072 * @param int $priceSetId
2076 public static function setQuickConfigMembershipParameters($membershipOrg, $membershipTypeID, $total_amount, $priceSetId) {
2077 $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
2079 // The name of the price field corresponds to the membership_type organization contact.
2081 'price_set_id' => $priceSetId,
2082 'name' => $membershipOrg,
2085 CRM_Price_BAO_PriceField
::retrieve($params, $results);
2087 if (!empty($results)) {
2088 $fields[$results['id']] = $priceSets['fields'][$results['id']];
2089 $fid = $results['id'];
2090 $editedFieldParams = [
2091 'price_field_id' => $results['id'],
2092 'membership_type_id' => $membershipTypeID,
2095 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $results);
2096 $fields[$fid]['options'][$results['id']] = $priceSets['fields'][$fid]['options'][$results['id']];
2097 if (!empty($total_amount)) {
2098 $fields[$fid]['options'][$results['id']]['amount'] = $total_amount;
2102 $fieldID = key($fields);
2104 'price_set_id' => $priceSetId,
2105 'price_sets' => $priceSets,
2106 'fields' => $fields,
2108 'price_' . $fieldID => CRM_Utils_Array
::value('id', $results),
2111 return $returnParams;
2115 * Update the status of all deceased members to deceased.
2118 * Count of updated contacts.
2120 * @throws \CiviCRM_API3_Exception
2121 * @throws \CRM_Core_Exception
2123 protected static function updateDeceasedMembersStatuses() {
2126 $deceasedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Deceased');
2128 // 'create' context for buildOptions returns only if enabled.
2129 $allStatus = self
::buildOptions('status_id', 'create');
2130 if (array_key_exists($deceasedStatusId, $allStatus) === FALSE) {
2131 // Deceased status is an admin status & is required. We want to fail early if
2132 // it is not present or active.
2133 // We could make the case 'some databases just don't use deceased so we will check
2134 // for the presence of a deceased contact in the DB before rejecting.
2135 if (CRM_Core_DAO
::singleValueQuery('
2136 SELECT count(*) FROM civicrm_contact WHERE is_deceased = 0'
2138 throw new CRM_Core_Exception(
2139 ts("Deceased Membership status is missing or not active. <a href='%1'>Click here to check</a>.",
2140 [1 => CRM_Utils_System
::url('civicrm/admin/member/membershipStatus', 'reset=1')]
2144 $deceasedDAO = CRM_Core_DAO
::executeQuery(
2146 SELECT membership.id as membership_id
2147 FROM civicrm_membership membership
2148 INNER JOIN civicrm_contact ON membership.contact_id = civicrm_contact.id
2149 INNER JOIN civicrm_membership_type ON membership.membership_type_id = civicrm_membership_type.id
2150 AND civicrm_membership_type.is_active = 1
2151 WHERE membership.is_test = 0
2152 AND civicrm_contact.is_deceased = 1
2153 AND membership.status_id <> %1
2155 [1 => [$deceasedStatusId, 'Integer']]
2157 while ($deceasedDAO->fetch()) {
2158 civicrm_api3('membership', 'create', [
2159 'id' => $deceasedDAO->membership_id
,
2160 'status_id' => $deceasedStatusId,
2161 'createActivity' => TRUE,
2162 'skipStatusCal' => TRUE,
2163 'skipRecentView' => TRUE,
2171 * Process price set and line items.
2173 * @param int $membershipId
2174 * @param array $lineItem
2176 * @throws \CiviCRM_API3_Exception
2178 public function processPriceSet($membershipId, $lineItem) {
2179 //FIXME : need to move this too
2180 if (!$membershipId ||
!is_array($lineItem)
2181 || CRM_Utils_System
::isNull($lineItem)
2186 foreach ($lineItem as $priceSetId => $values) {
2190 foreach ($values as $line) {
2191 $line['entity_table'] = 'civicrm_membership';
2192 $line['entity_id'] = $membershipId;
2193 CRM_Price_BAO_LineItem
::create($line);
2199 * Retrieve the contribution id for the associated Membership id.
2200 * @todo we should get this off the line item
2202 * @param int $membershipId
2205 * if more than one payment associated with membership id need to be returned.
2209 * @todo we should get this off the line item
2212 public static function getMembershipContributionId($membershipId, $all = FALSE) {
2214 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
2215 $membershipPayment->membership_id
= $membershipId;
2216 if ($all && $membershipPayment->find()) {
2217 $contributionIds = [];
2218 while ($membershipPayment->fetch()) {
2219 $contributionIds[] = $membershipPayment->contribution_id
;
2221 return $contributionIds;
2224 if ($membershipPayment->find(TRUE)) {
2225 return $membershipPayment->contribution_id
;
2231 * The function checks and updates the status of all membership records for a given domain using the
2232 * calc_membership_status and update_contact_membership APIs.
2235 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
2239 * @throws \CiviCRM_API3_Exception
2240 * @throws \CRM_Core_Exception
2242 public static function updateAllMembershipStatus() {
2243 // Tests for this function are in api_v3_JobTest. Please add tests for all updates.
2245 $updateCount = $processCount = self
::updateDeceasedMembersStatuses();
2247 // We want all of the statuses as id => name, even the disabled ones (cf.
2248 // CRM-15475), to identify which are Pending, Deceased, Cancelled, and
2250 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'validate');
2251 $allTypes = CRM_Member_PseudoConstant
::membershipType();
2253 // This query retrieves ALL memberships of active types.
2255 SELECT civicrm_membership.id as membership_id,
2256 civicrm_membership.is_override as is_override,
2257 civicrm_membership.status_override_end_date as status_override_end_date,
2258 civicrm_membership.membership_type_id as membership_type_id,
2259 civicrm_membership.status_id as status_id,
2260 civicrm_membership.join_date as join_date,
2261 civicrm_membership.start_date as start_date,
2262 civicrm_membership.end_date as end_date,
2263 civicrm_membership.source as source,
2264 civicrm_contact.id as contact_id,
2265 civicrm_membership.owner_membership_id as owner_membership_id,
2266 civicrm_membership.contribution_recur_id as recur_id
2267 FROM civicrm_membership
2268 INNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )
2269 INNER JOIN civicrm_membership_type ON
2270 (civicrm_membership.membership_type_id = civicrm_membership_type.id AND civicrm_membership_type.is_active = 1)
2271 WHERE civicrm_membership.is_test = 0
2272 AND civicrm_contact.is_deceased = 0 ";
2274 $deceaseStatusId = array_search('Deceased', $allStatus);
2275 $pendingStatusId = array_search('Pending', $allStatus);
2276 $cancelledStatusId = array_search('Cancelled', $allStatus);
2277 // Expired is not reserved so might not exist. A value of `0` won't break.
2278 $expiredStatusId = array_search('Expired', $allStatus) ?
: 0;
2280 $query = $baseQuery . " AND civicrm_membership.is_override IS NOT NULL AND civicrm_membership.status_override_end_date IS NOT NULL";
2281 $dao1 = CRM_Core_DAO
::executeQuery($query);
2282 while ($dao1->fetch()) {
2283 self
::processOverriddenUntilDateMembership($dao1);
2286 $query = $baseQuery . " AND (civicrm_membership.is_override = 0 OR civicrm_membership.is_override IS NULL)
2287 AND civicrm_membership.status_id NOT IN (%1, %2, %3, %4)
2288 AND civicrm_membership.owner_membership_id IS NULL ";
2290 1 => [$pendingStatusId, 'Integer'],
2291 2 => [$cancelledStatusId, 'Integer'],
2292 3 => [$expiredStatusId, 'Integer'],
2293 4 => [$deceaseStatusId, 'Integer'],
2295 $dao2 = CRM_Core_DAO
::executeQuery($query, $params);
2297 while ($dao2->fetch()) {
2301 // Put common parameters into array for easy access
2303 'id' => $dao2->membership_id
,
2304 'status_id' => $dao2->status_id
,
2305 'contact_id' => $dao2->contact_id
,
2306 'membership_type_id' => $dao2->membership_type_id
,
2307 'membership_type' => $allTypes[$dao2->membership_type_id
],
2308 'join_date' => $dao2->join_date
,
2309 'start_date' => $dao2->start_date
,
2310 'end_date' => $dao2->end_date
,
2311 'source' => $dao2->source
,
2312 'skipStatusCal' => TRUE,
2313 'skipRecentView' => TRUE,
2316 // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses
2317 //get the membership status as per id.
2318 $newStatus = civicrm_api('membership_status', 'calc',
2320 'membership_id' => $dao2->membership_id
,
2322 'ignore_admin_only' => TRUE,
2325 $statusId = CRM_Utils_Array
::value('id', $newStatus);
2327 //process only when status change.
2329 $statusId != $dao2->status_id
2331 //take all params that need to save.
2332 $memParams = $memberParams;
2333 $memParams['status_id'] = $statusId;
2334 $memParams['createActivity'] = TRUE;
2335 $memParams['version'] = 3;
2337 // Unset columns which should remain unchanged from their current saved
2338 // values. This avoids race condition in which these values may have
2339 // been changed by other processes.
2341 $memParams['contact_id'],
2342 $memParams['membership_type_id'],
2343 $memParams['membership_type'],
2344 $memParams['join_date'],
2345 $memParams['start_date'],
2346 $memParams['end_date'],
2347 $memParams['source']
2349 //since there is change in status.
2351 //process member record.
2352 civicrm_api('membership', 'create', $memParams);
2356 $result['is_error'] = 0;
2357 $result['messages'] = ts('Processed %1 membership records. Updated %2 records.', [
2365 * Set is_override for the 'overridden until date' membership to
2366 * False and clears the 'until date' field in case the 'until date'
2367 * is equal or after today date.
2369 * @param CRM_Core_DAO $membership
2370 * The membership to be processed
2372 * @throws \CiviCRM_API3_Exception
2374 private static function processOverriddenUntilDateMembership($membership) {
2375 $isOverriddenUntilDate = !empty($membership->is_override
) && !empty($membership->status_override_end_date
);
2376 if (!$isOverriddenUntilDate) {
2380 $todayDate = new DateTime();
2381 $todayDate->setTime(0, 0);
2383 $overrideEndDate = new DateTime($membership->status_override_end_date
);
2384 $overrideEndDate->setTime(0, 0);
2386 $datesDifference = $todayDate->diff($overrideEndDate);
2387 $daysDifference = (int) $datesDifference->format('%R%a');
2388 if ($daysDifference <= 0) {
2390 'id' => $membership->membership_id
,
2391 'is_override' => FALSE,
2392 'status_override_end_date' => 'null',
2394 civicrm_api3('membership', 'create', $params);
2399 * Returns the membership types for a particular contact
2400 * who has lifetime membership without end date.
2402 * @param int $contactID
2403 * @param bool $isTest
2404 * @param bool $onlyLifeTime
2408 public static function getAllContactMembership($contactID, $isTest = FALSE, $onlyLifeTime = FALSE) {
2409 $contactMembershipType = [];
2411 return $contactMembershipType;
2414 $dao = new CRM_Member_DAO_Membership();
2415 $dao->contact_id
= $contactID;
2416 $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
2417 $dao->whereAdd("status_id != $pendingStatusId");
2420 $dao->is_test
= $isTest;
2423 $dao->whereAdd('is_test IS NULL OR is_test = 0');
2426 if ($onlyLifeTime) {
2427 $dao->whereAdd('end_date IS NULL');
2431 while ($dao->fetch()) {
2433 CRM_Core_DAO
::storeValues($dao, $membership);
2434 $contactMembershipType[$dao->membership_type_id
] = $membership;
2436 return $contactMembershipType;
2440 * Record contribution record associated with membership.
2442 * @param array $params
2443 * Array of submitted params.
2445 * (@return CRM_Contribute_BAO_Contribution
2447 * @throws \CiviCRM_API3_Exception
2448 * @throws \CRM_Core_Exception
2450 public static function recordMembershipContribution(&$params, $ids = []) {
2452 CRM_Core_Error
::deprecatedFunctionWarning('no $ids array');
2454 $membershipId = $params['membership_id'];
2455 $contributionParams = [];
2456 $config = CRM_Core_Config
::singleton();
2457 $contributionParams['currency'] = $config->defaultCurrency
;
2458 $contributionParams['receipt_date'] = (CRM_Utils_Array
::value('receipt_date', $params)) ?
$params['receipt_date'] : 'null';
2459 $contributionParams['source'] = CRM_Utils_Array
::value('contribution_source', $params);
2460 $contributionParams['non_deductible_amount'] = 'null';
2461 $contributionParams['skipCleanMoney'] = TRUE;
2462 $contributionParams['payment_processor'] = CRM_Utils_Array
::value('payment_processor_id', $params);
2463 $contributionSoftParams = CRM_Utils_Array
::value('soft_credit', $params);
2464 $recordContribution = [
2469 'financial_type_id',
2470 'payment_instrument_id',
2474 'contribution_status_id',
2481 'contribution_recur_id',
2485 foreach ($recordContribution as $f) {
2486 $contributionParams[$f] = CRM_Utils_Array
::value($f, $params);
2489 if (!empty($params['contribution_id'])) {
2490 $contributionParams['id'] = $params['contribution_id'];
2492 // make entry in batch entity batch table
2493 if (!empty($params['batch_id'])) {
2494 $contributionParams['batch_id'] = $params['batch_id'];
2497 if (!empty($params['contribution_contact_id'])) {
2498 // deal with possibility of a different person paying for contribution
2499 $contributionParams['contact_id'] = $params['contribution_contact_id'];
2502 if (!empty($params['processPriceSet']) &&
2503 !empty($params['lineItems'])
2505 $contributionParams['line_item'] = CRM_Utils_Array
::value('lineItems', $params, NULL);
2508 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams);
2510 //CRM-13981, create new soft-credit record as to record payment from different person for this membership
2511 if (!empty($contributionSoftParams)) {
2512 if (!empty($params['batch_id'])) {
2513 foreach ($contributionSoftParams as $contributionSoft) {
2514 $contributionSoft['contribution_id'] = $contribution->id
;
2515 $contributionSoft['currency'] = $contribution->currency
;
2516 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoft);
2520 $contributionSoftParams['contribution_id'] = $contribution->id
;
2521 $contributionSoftParams['currency'] = $contribution->currency
;
2522 $contributionSoftParams['amount'] = $contribution->total_amount
;
2523 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoftParams);
2527 // store contribution id
2528 $params['contribution_id'] = $contribution->id
;
2530 // Create membership payment if it does not already exist
2531 $membershipPayment = civicrm_api3('MembershipPayment', 'get', [
2532 'contribution_id' => $contribution->id
,
2534 if (empty($membershipPayment['count'])) {
2535 civicrm_api3('MembershipPayment', 'create', [
2536 'membership_id' => $membershipId,
2537 'contribution_id' => $contribution->id
,
2541 return $contribution;
2545 * @todo document me - I seem a bit out of date....
2547 public static function _getActTypes() {
2548 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2549 self
::$_renewalActType = CRM_Utils_Array
::key('Membership Renewal', $activityTypes);
2550 self
::$_signupActType = CRM_Utils_Array
::key('Membership Signup', $activityTypes);
2554 * Get all Cancelled Membership(s) for a contact
2556 * @param int $contactID
2558 * @param bool $isTest
2562 * Array of membership type
2564 public static function getContactsCancelledMembership($contactID, $isTest = FALSE) {
2568 $query = 'SELECT membership_type_id FROM civicrm_membership WHERE contact_id = %1 AND status_id = %2 AND is_test = %3';
2570 1 => [$contactID, 'Integer'],
2575 CRM_Member_PseudoConstant
::membershipStatus(
2577 " name = 'Cancelled' ",
2585 3 => [$isTest, 'Boolean'],
2588 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
2589 $cancelledMembershipIds = [];
2590 while ($dao->fetch()) {
2591 $cancelledMembershipIds[] = $dao->membership_type_id
;
2593 return $cancelledMembershipIds;
2597 * Merges the memberships from otherContactID to mainContactID.
2599 * General idea is to merge memberships in regards to their type. We
2600 * move the other contact’s contributions to the main contact’s
2601 * membership which has the same type (if any) and then we update
2602 * membership to avoid loosing `join_date`, `end_date`, and
2603 * `status_id`. In this function, we don’t touch the contributions
2604 * directly (CRM_Dedupe_Merger::moveContactBelongings() takes care
2607 * This function adds new SQL queries to the $sqlQueries parameter.
2609 * @param int $mainContactID
2610 * Contact id of main contact record.
2611 * @param int $otherContactID
2612 * Contact id of record which is going to merge.
2613 * @param array $sqlQueries
2614 * (reference) array of SQL queries to be executed.
2615 * @param array $tables
2616 * List of tables that have to be merged.
2617 * @param array $tableOperations
2618 * Special options/params for some tables to be merged.
2620 * @see CRM_Dedupe_Merger::cpTables()
2622 public static function mergeMemberships($mainContactID, $otherContactID, &$sqlQueries, $tables, $tableOperations) {
2624 * If the user requests not to merge memberships but to add them,
2625 * just attribute the `civicrm_membership` to the
2626 * `$mainContactID`. We have to do this here since the general
2627 * merge process is bypassed by this function.
2629 if (array_key_exists("civicrm_membership", $tableOperations) && $tableOperations['civicrm_membership']['add']) {
2630 $sqlQueries[] = "UPDATE IGNORE civicrm_membership SET contact_id = $mainContactID WHERE contact_id = $otherContactID";
2635 * Retrieve all memberships that belongs to each contacts and
2636 * keep track of each membership type.
2638 $mainContactMemberships = [];
2639 $otherContactMemberships = [];
2641 $sql = "SELECT id, membership_type_id FROM civicrm_membership membership WHERE contact_id = %1";
2642 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$mainContactID, "Integer"]]);
2643 while ($dao->fetch()) {
2644 $mainContactMemberships[$dao->id
] = $dao->membership_type_id
;
2647 $dao = CRM_Core_DAO
::executeQuery($sql, [1 => [$otherContactID, "Integer"]]);
2648 while ($dao->fetch()) {
2649 $otherContactMemberships[$dao->id
] = $dao->membership_type_id
;
2653 * For each membership, move related contributions to the main
2654 * contact’s membership (by updating `membership_payments`). Then,
2655 * update membership’s `join_date` (if the other membership’s
2656 * join_date is older) and `end_date` (if the other membership’s
2657 * `end_date` is newer) and `status_id` (if the newly calculated
2658 * status is different).
2660 * FIXME: what should we do if we have multiple memberships with
2661 * the same type (currently we only take the first one)?
2664 foreach ($otherContactMemberships as $otherMembershipId => $otherMembershipTypeId) {
2665 if ($newMembershipId = array_search($otherMembershipTypeId, $mainContactMemberships)) {
2668 * Move other membership’s contributions to the main one only
2669 * if user requested to merge contributions.
2671 if (!empty($tables) && in_array('civicrm_contribution', $tables)) {
2672 $newSql[] = "UPDATE civicrm_membership_payment SET membership_id=$newMembershipId WHERE membership_id=$otherMembershipId";
2675 $sql = "SELECT * FROM civicrm_membership membership WHERE id = %1";
2677 $newMembership = CRM_Member_DAO_Membership
::findById($newMembershipId);
2678 $otherMembership = CRM_Member_DAO_Membership
::findById($otherMembershipId);
2681 if (new DateTime($otherMembership->join_date
) < new DateTime($newMembership->join_date
)) {
2682 $updates["join_date"] = $otherMembership->join_date
;
2685 if (new DateTime($otherMembership->end_date
) > new DateTime($newMembership->end_date
)) {
2686 $updates["end_date"] = $otherMembership->end_date
;
2689 if (count($updates)) {
2694 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
2695 isset($updates["start_date"]) ?
$updates["start_date"] : $newMembership->start_date
,
2696 isset($updates["end_date"]) ?
$updates["end_date"] : $newMembership->end_date
,
2697 isset($updates["join_date"]) ?
$updates["join_date"] : $newMembership->join_date
,
2704 if (!empty($status['id']) and $status['id'] != $newMembership->status_id
) {
2705 $updates['status_id'] = $status['id'];
2709 foreach ($updates as $k => $v) {
2710 $updates_sql[] = "$k = '{$v}'";
2713 $newSql[] = sprintf("UPDATE civicrm_membership SET %s WHERE id=%s", implode(", ", $updates_sql), $newMembershipId);
2714 $newSql[] = sprintf("DELETE FROM civicrm_membership WHERE id=%s", $otherMembershipId);
2720 $sqlQueries = array_merge($sqlQueries, $newSql);