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
67 public static function add(&$params, $ids = array()) {
68 $oldStatus = $oldType = NULL;
69 $params['id'] = CRM_Utils_Array
::value('id', $params, CRM_Utils_Array
::value('membership', $ids));
71 CRM_Utils_Hook
::pre('edit', 'Membership', $params['id'], $params);
74 CRM_Utils_Hook
::pre('create', 'Membership', NULL, $params);
77 // we do this after the hooks are called in case it has been altered
79 $membershipObj = new CRM_Member_DAO_Membership();
80 $membershipObj->id
= $id;
81 $membershipObj->find();
82 while ($membershipObj->fetch()) {
83 $oldStatus = $membershipObj->status_id
;
84 $oldType = $membershipObj->membership_type_id
;
88 if (array_key_exists('is_override', $params) && !$params['is_override']) {
89 $params['is_override'] = 'null';
92 $membership = new CRM_Member_BAO_Membership();
93 $membership->copyValues($params);
94 $membership->id
= $id;
98 if (empty($membership->contact_id
) ||
empty($membership->status_id
)) {
99 // this means we are in renewal mode and are just updating the membership
100 // record or this is an API update call and all fields are not present in the update record
101 // however the hooks don't care and want all data CRM-7784
102 $tempMembership = new CRM_Member_DAO_Membership();
103 $tempMembership->id
= $membership->id
;
104 $tempMembership->find(TRUE);
105 $membership = $tempMembership;
108 //get the log start date.
109 //it is set during renewal of membership.
110 $logStartDate = CRM_Utils_Array
::value('log_start_date', $params);
111 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : CRM_Utils_Date
::isoToMysql($membership->start_date
);
112 $values = self
::getStatusANDTypeValues($membership->id
);
114 $membershipLog = array(
115 'membership_id' => $membership->id
,
116 'status_id' => $membership->status_id
,
117 'start_date' => $logStartDate,
118 'end_date' => CRM_Utils_Date
::isoToMysql($membership->end_date
),
119 'modified_date' => date('Ymd'),
120 'membership_type_id' => $values[$membership->id
]['membership_type_id'],
121 'max_related' => $membership->max_related
,
124 $session = CRM_Core_Session
::singleton();
125 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
126 if ($session->get('userID')) {
127 $membershipLog['modified_id'] = $session->get('userID');
129 elseif (!empty($ids['userId'])) {
130 $membershipLog['modified_id'] = $ids['userId'];
133 $membershipLog['modified_id'] = $membership->contact_id
;
136 CRM_Member_BAO_MembershipLog
::add($membershipLog);
138 // reset the group contact cache since smart groups might be affected due to this
139 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
141 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
142 $activityParams = array(
143 'status_id' => CRM_Utils_Array
::value('membership_activity_status', $params, 'Completed'),
145 if (in_array($allStatus[$membership->status_id
], array('Pending', 'Grace'))) {
146 $activityParams['status_id'] = 'Scheduled';
148 $activityParams['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', $activityParams['status_id']);
150 $targetContactID = $membership->contact_id
;
151 if (!empty($params['is_for_organization'])) {
152 $targetContactID = CRM_Utils_Array
::value('userId', $ids);
155 if ($membership->status_id
!= $oldStatus) {
156 CRM_Activity_BAO_Activity
::addActivity($membership,
157 'Change Membership Status',
160 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
161 'source_contact_id' => $membershipLog['modified_id'],
162 'priority_id' => 'Normal',
166 if (isset($membership->membership_type_id
) && $membership->membership_type_id
!= $oldType) {
167 $membershipTypes = CRM_Member_BAO_Membership
::buildOptions('membership_type_id', 'get');
168 CRM_Activity_BAO_Activity
::addActivity($membership,
169 'Change Membership Type',
172 'subject' => "Type changed from {$membershipTypes[$oldType]} to {$membershipTypes[$membership->membership_type_id]}",
173 'source_contact_id' => $membershipLog['modified_id'],
174 'priority_id' => 'Normal',
179 foreach (array('Membership Signup', 'Membership Renewal') as $activityType) {
180 $activityParams['id'] = CRM_Utils_Array
::value('id',
181 civicrm_api3('Activity', 'Get',
183 'source_record_id' => $membership->id
,
184 'activity_type_id' => $activityType,
185 'status_id' => 'Scheduled',
189 // 1. Update Schedule Membership Signup/Renwal activity to completed on successful payment of pending membership
190 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
191 if (!empty($params['membership_activity_status']) && (!empty($activityParams['id']) ||
$activityType == 'Membership Renewal')) {
192 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $targetContactID, $activityParams);
197 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
200 CRM_Activity_BAO_Activity
::addActivity($membership, 'Membership Signup', $targetContactID, $activityParams);
201 CRM_Utils_Hook
::post('create', 'Membership', $membership->id
, $membership);
208 * Fetch the object and store the values in the values array.
210 * @param array $params
211 * Input parameters to find object.
212 * @param array $values
213 * Output values of the object.
214 * @param bool $active
215 * Do you want only active memberships to.
217 * @param bool $relatedMemberships
219 * @return CRM_Member_BAO_Membership|null
220 * The found object or null
222 public static function &getValues(&$params, &$values, $active = FALSE, $relatedMemberships = FALSE) {
223 if (empty($params)) {
226 $membership = new CRM_Member_BAO_Membership();
228 $membership->copyValues($params);
230 $memberships = array();
231 while ($membership->fetch()) {
233 (!CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
234 $membership->status_id
,
241 CRM_Core_DAO
::storeValues($membership, $values[$membership->id
]);
242 $memberships[$membership->id
] = $membership;
243 if ($relatedMemberships && !empty($membership->owner_membership_id
)) {
244 $values['owner_membership_ids'][] = $membership->owner_membership_id
;
252 * Takes an associative array and creates a membership object.
254 * @param array $params
255 * (reference ) an assoc array of name/value pairs.
257 * Deprecated parameter The array that holds all the db ids.
258 * @param bool $skipRedirect
260 * @throws CRM_Core_Exception
262 * @return CRM_Member_BAO_Membership|CRM_Core_Error
264 public static function create(&$params, &$ids = [], $skipRedirect = FALSE) {
265 // always calculate status if is_override/skipStatusCal is not true.
266 // giving respect to is_override during import. CRM-4012
268 // To skip status calculation we should use 'skipStatusCal'.
269 // eg pay later membership, membership update cron CRM-3984
271 if (empty($params['is_override']) && empty($params['skipStatusCal'])) {
272 $dates = array('start_date', 'end_date', 'join_date');
273 // Declare these out of courtesy as IDEs don't pick up the setting of them below.
274 $start_date = $end_date = $join_date = NULL;
275 foreach ($dates as $date) {
276 $
$date = $params[$date] = CRM_Utils_Date
::processDate(CRM_Utils_Array
::value($date, $params), NULL, TRUE, 'Ymd');
279 //fix for CRM-3570, during import exclude the statuses those having is_admin = 1
280 $excludeIsAdmin = CRM_Utils_Array
::value('exclude_is_admin', $params, FALSE);
282 //CRM-3724 always skip is_admin if is_override != true.
283 if (!$excludeIsAdmin && empty($params['is_override'])) {
284 $excludeIsAdmin = TRUE;
287 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($start_date, $end_date, $join_date,
288 'today', $excludeIsAdmin, CRM_Utils_Array
::value('membership_type_id', $params), $params
290 if (empty($calcStatus)) {
291 // Redirect the form in case of error
292 // @todo this redirect in the BAO layer is really bad & should be moved to the form layer
293 // however since we have no idea how (if) this is triggered we can't safely move / remove it
294 // NB I tried really hard to trigger this error from backoffice membership form in order to test it
295 // and am convinced form validation is complete on that form WRT this error.
296 $errorParams = array(
297 'message_title' => ts('No valid membership status for given dates.'),
298 'legacy_redirect_path' => 'civicrm/contact/view',
299 'legacy_redirect_query' => "reset=1&force=1&cid={$params['contact_id']}&selectedChild=member",
301 throw new CRM_Core_Exception(ts(
302 "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')),
307 $params['status_id'] = $calcStatus['id'];
310 // data cleanup only: all verifications on number of related memberships are done upstream in:
311 // CRM_Member_BAO_Membership::createRelatedMemberships()
312 // CRM_Contact_BAO_Relationship::relatedMemberships()
313 if (!empty($params['owner_membership_id'])) {
314 unset($params['max_related']);
317 // if membership allows related, default max_related to value in membership_type
318 if (!array_key_exists('max_related', $params) && !empty($params['membership_type_id'])) {
319 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($params['membership_type_id']);
320 if (isset($membershipType['relationship_type_id'])) {
321 $params['max_related'] = CRM_Utils_Array
::value('max_related', $membershipType);
326 $transaction = new CRM_Core_Transaction();
328 $membership = self
::add($params, $ids);
330 if (is_a($membership, 'CRM_Core_Error')) {
331 $transaction->rollback();
335 // add custom field values
336 if (!empty($params['custom']) && is_array($params['custom'])
338 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_membership', $membership->id
);
341 $params['membership_id'] = $membership->id
;
342 if (isset($ids['membership'])) {
343 $ids['contribution'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment',
350 // This code ensures a line item is created but it is recomended you pass in 'skipLineItem' or 'line_item'
351 if (empty($params['line_item']) && !empty($params['membership_type_id']) && empty($params['skipLineItem'])) {
352 CRM_Price_BAO_LineItem
::getLineItemArray($params, NULL, 'membership', $params['membership_type_id']);
354 $params['skipLineItem'] = TRUE;
356 //record contribution for this membership
357 if (!empty($params['contribution_status_id']) && empty($params['relate_contribution_id'])) {
358 $memInfo = array_merge($params, array('membership_id' => $membership->id
));
359 $params['contribution'] = self
::recordMembershipContribution($memInfo, $ids);
362 if (!empty($params['lineItems'])) {
363 $params['line_item'] = $params['lineItems'];
366 //do cleanup line items if membership edit the Membership type.
367 if (empty($ids['contribution']) && !empty($ids['membership'])) {
368 CRM_Price_BAO_LineItem
::deleteLineItems($ids['membership'], 'civicrm_membership');
371 // This could happen if there is no contribution or we are in one of many
372 // weird and wonderful flows. This is scary code. Keep adding tests.
373 if (!empty($params['line_item']) && empty($ids['contribution'])) {
375 foreach ($params['line_item'] as $priceSetId => $lineItems) {
376 foreach ($lineItems as $lineIndex => $lineItem) {
377 $lineMembershipType = CRM_Utils_Array
::value('membership_type_id', $lineItem);
378 if (CRM_Utils_Array
::value('contribution', $params)) {
379 $params['line_item'][$priceSetId][$lineIndex]['contribution_id'] = $params['contribution']->id
;
381 if ($lineMembershipType && $lineMembershipType == CRM_Utils_Array
::value('membership_type_id', $params)) {
382 $params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $membership->id
;
383 $params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_membership';
385 elseif (!$lineMembershipType && CRM_Utils_Array
::value('contribution', $params)) {
386 $params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $params['contribution']->id
;
387 $params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_contribution';
391 CRM_Price_BAO_LineItem
::processPriceSet(
393 $params['line_item'],
394 CRM_Utils_Array
::value('contribution', $params)
398 //insert payment record for this membership
399 if (!empty($params['relate_contribution_id'])) {
400 CRM_Member_BAO_MembershipPayment
::create(array(
401 'membership_id' => $membership->id
,
402 'membership_type_id' => $membership->membership_type_id
,
403 'contribution_id' => $params['relate_contribution_id'],
407 $transaction->commit();
409 self
::createRelatedMemberships($params, $membership);
411 // do not add to recent items for import, CRM-4399
412 if (empty($params['skipRecentView'])) {
413 $url = CRM_Utils_System
::url('civicrm/contact/view/membership',
414 "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
416 if (empty($membership->membership_type_id
)) {
417 // ie in an update situation.
418 $membership->find(TRUE);
420 $membershipTypes = CRM_Member_PseudoConstant
::membershipType();
421 $title = CRM_Contact_BAO_Contact
::displayName($membership->contact_id
) . ' - ' . ts('Membership Type:') . ' ' . $membershipTypes[$membership->membership_type_id
];
423 $recentOther = array();
424 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::UPDATE
)) {
425 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
426 "action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
429 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::DELETE
)) {
430 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
431 "action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
435 // add the recently created Membership
436 CRM_Utils_Recent
::add($title,
440 $membership->contact_id
,
450 * Check the membership extended through relationship.
452 * @param int $membershipTypeID
453 * Membership type id.
454 * @param int $contactId
460 * array of contact_id of all related contacts.
462 public static function checkMembershipRelationship($membershipTypeID, $contactId, $action = CRM_Core_Action
::ADD
) {
465 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipTypeID);
466 $relationships = array();
467 if (isset($membershipType['relationship_type_id'])) {
468 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
469 CRM_Contact_BAO_Relationship
::CURRENT
471 if ($action & CRM_Core_Action
::UPDATE
) {
472 $pastRelationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
473 CRM_Contact_BAO_Relationship
::PAST
475 $relationships = array_merge($relationships, $pastRelationships);
479 if (!empty($relationships)) {
480 // check for each contact relationships
481 foreach ($relationships as $values) {
482 //get details of the relationship type
483 $relType = array('id' => $values['civicrm_relationship_type_id']);
484 $relValues = array();
485 CRM_Contact_BAO_RelationshipType
::retrieve($relType, $relValues);
486 // Check if contact's relationship type exists in membership type
487 $relTypeDirs = array();
488 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_type_id']);
489 $relDirections = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_direction']);
490 $bidirectional = FALSE;
491 foreach ($relTypeIds as $key => $value) {
492 $relTypeDirs[] = $value . '_' . $relDirections[$key];
493 if (in_array($value, $relType) &&
494 $relValues['name_a_b'] == $relValues['name_b_a']
496 $bidirectional = TRUE;
500 $relTypeDir = $values['civicrm_relationship_type_id'] . '_' . $values['rtype'];
501 if ($bidirectional ||
in_array($relTypeDir, $relTypeDirs)) {
502 // $values['status'] is going to have value for
503 // current or past relationships.
504 $contacts[$values['cid']] = $values['status'];
509 // Sort by contact_id ascending
515 * Retrieve DB object based on input parameters.
517 * It also stores all the retrieved values in the default array.
519 * @param array $params
520 * (reference ) an assoc array of name/value pairs.
521 * @param array $defaults
522 * (reference ) an assoc array to hold the name / value pairs.
523 * in a hierarchical manner
525 * @return CRM_Member_BAO_Membership
527 public static function retrieve(&$params, &$defaults) {
528 $membership = new CRM_Member_DAO_Membership();
530 $membership->copyValues($params);
532 if ($membership->find(TRUE)) {
533 CRM_Core_DAO
::storeValues($membership, $defaults);
535 //get the membership status and type values.
536 $statusANDType = self
::getStatusANDTypeValues($membership->id
);
541 $defaults[$fld] = CRM_Utils_Array
::value($fld, $statusANDType[$membership->id
]);
543 if (!empty($statusANDType[$membership->id
]['is_current_member'])) {
544 $defaults['active'] = TRUE;
554 * Get membership status and membership type values.
556 * @param int $membershipId
557 * Membership id of values to return.
560 * Array of key value pairs
562 public static function getStatusANDTypeValues($membershipId) {
564 if (!$membershipId) {
568 SELECT membership.id as id,
569 status.id as status_id,
570 status.label as status,
571 status.is_current_member as is_current_member,
572 type.id as membership_type_id,
573 type.name as membership_type,
574 type.relationship_type_id as relationship_type_id
575 FROM civicrm_membership membership
576 INNER JOIN civicrm_membership_status status ON ( status.id = membership.status_id )
577 INNER JOIN civicrm_membership_type type ON ( type.id = membership.membership_type_id )
578 WHERE membership.id = %1';
579 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($membershipId, 'Positive')));
584 'membership_type_id',
586 'relationship_type_id',
588 while ($dao->fetch()) {
589 foreach ($properties as $property) {
590 $values[$dao->id
][$property] = $dao->$property;
600 * Wrapper for most delete calls. Use this unless you JUST want to delete related memberships w/o deleting the parent.
602 * @param int $membershipId
603 * Membership id that needs to be deleted.
604 * @param bool $preserveContrib
607 * Id of deleted Membership on success, false otherwise.
609 public static function del($membershipId, $preserveContrib = FALSE) {
610 //delete related first and then delete parent.
611 self
::deleteRelatedMemberships($membershipId);
612 return self
::deleteMembership($membershipId, $preserveContrib);
618 * @param int $membershipId
619 * Membership id that needs to be deleted.
620 * @param bool $preserveContrib
623 * Id of deleted Membership on success, false otherwise.
625 public static function deleteMembership($membershipId, $preserveContrib = FALSE) {
626 // CRM-12147, retrieve membership data before we delete it for hooks
627 $params = array('id' => $membershipId);
628 $memValues = array();
629 $memberships = self
::getValues($params, $memValues);
631 $membership = $memberships[$membershipId];
633 CRM_Utils_Hook
::pre('delete', 'Membership', $membershipId, $memValues);
635 $transaction = new CRM_Core_Transaction();
638 //delete activity record
639 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
642 $deleteActivity = FALSE;
643 $membershipActivities = array(
645 'Membership Renewal',
646 'Change Membership Status',
647 'Change Membership Type',
648 'Membership Renewal Reminder',
650 foreach ($membershipActivities as $membershipActivity) {
651 $activityId = array_search($membershipActivity, $activityTypes);
653 $params['activity_type_id'][] = $activityId;
654 $deleteActivity = TRUE;
657 if ($deleteActivity) {
658 $params['source_record_id'] = $membershipId;
659 CRM_Activity_BAO_Activity
::deleteActivity($params);
661 self
::deleteMembershipPayment($membershipId, $preserveContrib);
663 $results = $membership->delete();
664 $transaction->commit();
666 CRM_Utils_Hook
::post('delete', 'Membership', $membership->id
, $membership);
668 // delete the recently created Membership
669 $membershipRecent = array(
670 'id' => $membershipId,
671 'type' => 'Membership',
673 CRM_Utils_Recent
::del($membershipRecent);
679 * Delete related memberships.
681 * @param int $ownerMembershipId
682 * @param int $contactId
686 public static function deleteRelatedMemberships($ownerMembershipId, $contactId = NULL) {
687 if (!$ownerMembershipId && !$contactId) {
691 $membership = new CRM_Member_DAO_Membership();
692 $membership->owner_membership_id
= $ownerMembershipId;
695 $membership->contact_id
= $contactId;
699 while ($membership->fetch()) {
700 //delete related first and then delete parent.
701 self
::deleteRelatedMemberships($membership->id
);
702 self
::deleteMembership($membership->id
);
707 * Obtain active/inactive memberships from the list of memberships passed to it.
709 * @param array $memberships
710 * Membership records.
711 * @param string $status
712 * Active or inactive.
715 * array of memberships based on status
717 public static function activeMembers($memberships, $status = 'active') {
719 if ($status == 'active') {
720 foreach ($memberships as $f => $v) {
721 if (!empty($v['active'])) {
727 elseif ($status == 'inactive') {
728 foreach ($memberships as $f => $v) {
729 if (empty($v['active'])) {
739 * Return Membership Block info in Contribution Pages.
742 * Contribution page id.
746 public static function getMembershipBlock($pageID) {
747 $membershipBlock = array();
748 $dao = new CRM_Member_DAO_MembershipBlock();
749 $dao->entity_table
= 'civicrm_contribution_page';
751 $dao->entity_id
= $pageID;
753 if ($dao->find(TRUE)) {
754 CRM_Core_DAO
::storeValues($dao, $membershipBlock);
755 if (!empty($membershipBlock['membership_types'])) {
756 $membershipTypes = unserialize($membershipBlock['membership_types']);
757 if (!is_array($membershipTypes)) {
758 return $membershipBlock;
761 foreach ($membershipTypes as $key => $value) {
762 $membershipBlock['auto_renew'][$key] = $value;
763 $memTypes[$key] = $key;
765 $membershipBlock['membership_types'] = implode(',', $memTypes);
772 return $membershipBlock;
776 * Return a current membership of given contact.
778 * NB: if more than one membership meets criteria, a randomly selected one is returned.
780 * @param int $contactID
782 * @param int $memType
783 * Membership type, null to retrieve all types.
785 * @param int $membershipId
786 * If provided, then determine if it is current.
787 * @param bool $onlySameParentOrg
788 * True if only Memberships with same parent org as the $memType wanted, false otherwise.
792 public static function getContactMembership($contactID, $memType, $isTest, $membershipId = NULL, $onlySameParentOrg = FALSE) {
793 //check for owner membership id, if it exists update that membership instead: CRM-15992
795 $ownerMemberId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
797 'owner_membership_id', 'id'
799 if ($ownerMemberId) {
800 $membershipId = $ownerMemberId;
801 $contactID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
808 $dao = new CRM_Member_DAO_Membership();
810 $dao->id
= $membershipId;
812 $dao->contact_id
= $contactID;
813 $dao->membership_type_id
= $memType;
815 //fetch proper membership record.
817 $dao->is_test
= $isTest;
820 $dao->whereAdd('is_test IS NULL OR is_test = 0');
823 //avoid pending membership as current membership: CRM-3027
824 $statusIds = array(array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus()));
825 if (!$membershipId) {
827 $statusIds[] = array_search(
829 CRM_Member_PseudoConstant
::membershipStatus(
831 " name = 'Cancelled' ",
838 $dao->whereAdd('status_id NOT IN ( ' . implode(',', $statusIds) . ')');
840 // order by start date to find most recent membership first, CRM-4545
841 $dao->orderBy('start_date DESC');
844 if ($onlySameParentOrg && $memType) {
845 // require the same parent org as the $memType
846 $params = array('id' => $memType);
847 $membershipType = array();
848 if (CRM_Member_BAO_MembershipType
::retrieve($params, $membershipType)) {
849 $memberTypesSameParentOrg = civicrm_api3('MembershipType', 'get', array(
850 'member_of_contact_id' => $membershipType['member_of_contact_id'],
855 $memberTypesSameParentOrgList = implode(',', array_keys(CRM_Utils_Array
::value('values', $memberTypesSameParentOrg, array())));
856 $dao->whereAdd('membership_type_id IN (' . $memberTypesSameParentOrgList . ')');
860 if ($dao->find(TRUE)) {
861 $membership = array();
862 CRM_Core_DAO
::storeValues($dao, $membership);
863 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
864 $membership['status_id'],
865 'is_current_member', 'id'
867 $ownerMemberId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
869 'owner_membership_id', 'id'
871 if ($ownerMemberId) {
872 $membership['id'] = $membership['membership_id'] = $ownerMemberId;
873 $membership['membership_contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
882 if ($onlySameParentOrg && $memType) {
883 // see if there is a membership that has same parent as $memType but different parent than $membershipID
884 if ($dao->id
&& CRM_Core_Permission
::check('edit memberships')) {
885 // CRM-10016, This is probably a backend renewal, and make sure we return the same membership thats being renewed.
892 unset($dao->membership_type_id
);
893 if ($dao->find(TRUE)) {
894 $membership = array();
895 CRM_Core_DAO
::storeValues($dao, $membership);
896 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
897 $membership['status_id'],
898 'is_current_member', 'id'
907 * Combine all the importable fields from the lower levels object.
909 * @param string $contactType
911 * @param bool $status
914 * array of importable Fields
916 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
917 if (!self
::$_importableFields) {
918 if (!self
::$_importableFields) {
919 self
::$_importableFields = array();
923 $fields = array('' => array('title' => '- ' . ts('do not import') . ' -'));
926 $fields = array('' => array('title' => '- ' . ts('Membership Fields') . ' -'));
929 $tmpFields = CRM_Member_DAO_Membership
::import();
930 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
932 // Using new Dedupe rule.
934 'contact_type' => $contactType,
935 'used' => 'Unsupervised',
937 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
939 $tmpContactField = array();
940 if (is_array($fieldsArray)) {
941 foreach ($fieldsArray as $value) {
942 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
947 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
948 $tmpContactField[trim($value)] = CRM_Utils_Array
::value(trim($value), $contactFields);
950 $title = $tmpContactField[trim($value)]['title'] . " " . ts('(match to contact)');
953 $title = $tmpContactField[trim($value)]['title'];
955 $tmpContactField[trim($value)]['title'] = $title;
958 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
959 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " " . ts('(match to contact)');
961 $tmpFields['membership_contact_id']['title'] = $tmpFields['membership_contact_id']['title'] . " " . ts('(match to contact)');;
963 $fields = array_merge($fields, $tmpContactField);
964 $fields = array_merge($fields, $tmpFields);
965 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
966 self
::$_importableFields = $fields;
968 return self
::$_importableFields;
972 * Get all exportable fields.
974 * @return array return array of all exportable fields
976 public static function &exportableFields() {
977 $expFieldMembership = CRM_Member_DAO_Membership
::export();
979 $expFieldsMemType = CRM_Member_DAO_MembershipType
::export();
980 $fields = array_merge($expFieldMembership, $expFieldsMemType);
981 $fields = array_merge($fields, $expFieldMembership);
982 $membershipStatus = array(
983 'membership_status' => array(
984 'title' => ts('Membership Status'),
985 'name' => 'membership_status',
986 'type' => CRM_Utils_Type
::T_STRING
,
987 'where' => 'civicrm_membership_status.name',
990 //CRM-6161 fix for customdata export
991 $fields = array_merge($fields, $membershipStatus, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
996 * Get membership joins/renewals for a specified membership type.
998 * Specifically, retrieves a count of memberships whose "Membership
999 * Signup" or "Membership Renewal" activity falls in the given date range.
1000 * Dates match the pattern "yyyy-mm-dd".
1002 * @param int $membershipTypeId
1003 * Membership type id.
1004 * @param int $startDate
1005 * Date on which to start counting.
1006 * @param int $endDate
1007 * Date on which to end counting.
1008 * @param bool|int $isTest if true, membership is for a test site
1009 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1012 * the number of members of type $membershipTypeId whose
1013 * start_date is between $startDate and $endDate
1015 public static function getMembershipStarts($membershipTypeId, $startDate, $endDate, $isTest = 0, $isOwner = 0) {
1017 $testClause = 'membership.is_test = 1';
1019 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1022 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1023 self
::_getActTypes();
1026 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1031 SELECT COUNT(DISTINCT membership.id) as member_count
1032 FROM civicrm_membership membership
1033 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id in (%1, %2))
1034 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1035 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1036 WHERE membership.membership_type_id = %3
1037 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1040 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1043 1 => array(self
::$_signupActType, 'Integer'),
1044 2 => array(self
::$_renewalActType, 'Integer'),
1045 3 => array($membershipTypeId, 'Integer'),
1048 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1049 return (int) $memberCount;
1053 * Get a count of membership for a specified membership type, optionally for a specified date.
1055 * The date must have the form yyyy-mm-dd.
1057 * If $date is omitted, this function counts as a member anyone whose
1058 * membership status_id indicates they're a current member.
1059 * If $date is given, this function counts as a member anyone who:
1060 * -- Has a start_date before $date and end_date after $date, or
1061 * -- Has a start_date before $date and is currently a member, as indicated
1062 * by the the membership's status_id.
1063 * The second condition takes care of records that have no end_date. These
1064 * are assumed to be lifetime memberships.
1066 * @param int $membershipTypeId
1067 * Membership type id.
1068 * @param string $date
1069 * The date for which to retrieve the count.
1070 * @param bool|int $isTest if true, membership is for a test site
1071 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1074 * the number of members of type $membershipTypeId as of $date.
1076 public static function getMembershipCount($membershipTypeId, $date = NULL, $isTest = 0, $isOwner = 0) {
1077 if (!CRM_Utils_Rule
::date($date)) {
1078 CRM_Core_Error
::fatal(ts('Invalid date "%1" (must have form yyyy-mm-dd).', array(1 => $date)));
1082 1 => array($membershipTypeId, 'Integer'),
1083 2 => array($isTest, 'Boolean'),
1085 $query = "SELECT count(civicrm_membership.id ) as member_count
1086 FROM civicrm_membership left join civicrm_membership_status on ( civicrm_membership.status_id = civicrm_membership_status.id )
1087 WHERE civicrm_membership.membership_type_id = %1
1088 AND civicrm_membership.contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)
1089 AND civicrm_membership.is_test = %2";
1091 $query .= " AND civicrm_membership_status.is_current_member = 1";
1094 $query .= " AND civicrm_membership.start_date <= '$date' AND civicrm_membership_status.is_current_member = 1";
1097 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1098 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1099 return (int) $memberCount;
1103 * Function check the status of the membership before adding membership for a contact.
1107 public static function statusAvailabilty() {
1108 $membership = new CRM_Member_DAO_MembershipStatus();
1109 $membership->whereAdd('is_active=1');
1110 return $membership->count();
1114 * Function for updating a membership record's contribution_recur_id.
1116 * @param CRM_Member_DAO_Membership $membership
1117 * @param \CRM_Contribute_BAO_Contribution|\CRM_Contribute_DAO_Contribution $contribution
1119 public static function updateRecurMembership(CRM_Member_DAO_Membership
$membership, CRM_Contribute_BAO_Contribution
$contribution) {
1121 if (empty($contribution->contribution_recur_id
)) {
1126 1 => array($contribution->contribution_recur_id
, 'Integer'),
1127 2 => array($membership->id
, 'Integer'),
1130 $sql = "UPDATE civicrm_membership SET contribution_recur_id = %1 WHERE id = %2";
1131 CRM_Core_DAO
::executeQuery($sql, $params);
1135 * Method to fix membership status of stale membership.
1137 * This method first checks if the membership is stale. If it is,
1138 * then status will be updated based on existing start and end
1139 * dates and log will be added for the status change.
1141 * @param array $currentMembership
1142 * Reference to the array.
1143 * containing all values of
1144 * the current membership
1145 * @param string $changeToday
1146 * In case today needs
1147 * to be customised, null otherwise
1149 public static function fixMembershipStatusBeforeRenew(&$currentMembership, $changeToday) {
1152 $today = CRM_Utils_Date
::processDate($changeToday, NULL, FALSE, 'Y-m-d');
1155 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
1156 CRM_Utils_Array
::value('start_date', $currentMembership),
1157 CRM_Utils_Array
::value('end_date', $currentMembership),
1158 CRM_Utils_Array
::value('join_date', $currentMembership),
1161 $currentMembership['membership_type_id'],
1165 if (empty($status) ||
empty($status['id'])) {
1166 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.'));
1169 $currentMembership['today_date'] = $today;
1171 if ($status['id'] !== $currentMembership['status_id']) {
1172 $oldStatus = $currentMembership['status_id'];
1173 $memberDAO = new CRM_Member_DAO_Membership();
1174 $memberDAO->id
= $currentMembership['id'];
1175 $memberDAO->find(TRUE);
1177 $memberDAO->status_id
= $status['id'];
1178 $memberDAO->join_date
= CRM_Utils_Date
::isoToMysql($memberDAO->join_date
);
1179 $memberDAO->start_date
= CRM_Utils_Date
::isoToMysql($memberDAO->start_date
);
1180 $memberDAO->end_date
= CRM_Utils_Date
::isoToMysql($memberDAO->end_date
);
1182 CRM_Core_DAO
::storeValues($memberDAO, $currentMembership);
1184 $currentMembership['is_current_member'] = CRM_Core_DAO
::getFieldValue(
1185 'CRM_Member_DAO_MembershipStatus',
1186 $currentMembership['status_id'],
1192 'membership_id' => $currentMembership['id'],
1193 'status_id' => $status['id'],
1194 'start_date' => CRM_Utils_Date
::customFormat(
1195 $currentMembership['start_date'],
1198 'end_date' => CRM_Utils_Date
::customFormat(
1199 $currentMembership['end_date'],
1202 'modified_date' => CRM_Utils_Date
::customFormat(
1203 $currentMembership['today_date'],
1206 'membership_type_id' => $currentMembership['membership_type_id'],
1207 'max_related' => CRM_Utils_Array
::value('max_related', $currentMembership, 0),
1210 $session = CRM_Core_Session
::singleton();
1211 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
1212 if ($session->get('userID')) {
1213 $logParams['modified_id'] = $session->get('userID');
1216 $logParams['modified_id'] = $currentMembership['contact_id'];
1219 //Create activity for status change.
1220 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
1221 CRM_Activity_BAO_Activity
::addActivity($memberDAO,
1222 'Change Membership Status',
1225 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$status['id']]}",
1226 'source_contact_id' => $logParams['modified_id'],
1227 'priority_id' => 'Normal',
1231 CRM_Member_BAO_MembershipLog
::add($logParams);
1236 * Get the contribution page id from the membership record.
1238 * @param int $membershipID
1241 * contribution page id
1243 public static function getContributionPageId($membershipID) {
1245 SELECT c.contribution_page_id as pageID
1246 FROM civicrm_membership_payment mp, civicrm_contribution c
1247 WHERE mp.contribution_id = c.id
1248 AND c.contribution_page_id IS NOT NULL
1249 AND mp.membership_id = " . CRM_Utils_Type
::escape($membershipID, 'Integer')
1250 . " ORDER BY mp.id DESC";
1252 return CRM_Core_DAO
::singleValueQuery($query);
1256 * Updated related memberships.
1258 * @param int $ownerMembershipId
1259 * Owner Membership Id.
1260 * @param array $params
1261 * Formatted array of key => value.
1263 public static function updateRelatedMemberships($ownerMembershipId, $params) {
1264 $membership = new CRM_Member_DAO_Membership();
1265 $membership->owner_membership_id
= $ownerMembershipId;
1266 $membership->find();
1268 while ($membership->fetch()) {
1269 $relatedMembership = new CRM_Member_DAO_Membership();
1270 $relatedMembership->id
= $membership->id
;
1271 $relatedMembership->copyValues($params);
1272 $relatedMembership->save();
1278 * Get list of membership fields for profile.
1280 * For now we only allow custom membership fields to be in
1284 * FIXME: This param is ignored
1287 * the list of membership fields
1289 public static function getMembershipFields($mode = NULL) {
1290 $fields = CRM_Member_DAO_Membership
::export();
1292 unset($fields['membership_contact_id']);
1293 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1295 $membershipType = CRM_Member_DAO_MembershipType
::export();
1297 $membershipStatus = CRM_Member_DAO_MembershipStatus
::export();
1299 $fields = array_merge($fields, $membershipType, $membershipStatus);
1305 * Get the sort name of a contact for a particular membership.
1308 * Id of the membership.
1310 * @return null|string
1311 * sort name of the contact if found
1313 public static function sortName($id) {
1314 $id = CRM_Utils_Type
::escape($id, 'Integer');
1317 SELECT civicrm_contact.sort_name
1318 FROM civicrm_membership, civicrm_contact
1319 WHERE civicrm_membership.contact_id = civicrm_contact.id
1320 AND civicrm_membership.id = {$id}
1322 return CRM_Core_DAO
::singleValueQuery($query);
1326 * Create memberships for related contacts, taking into account the maximum related memberships.
1328 * @param array $params
1329 * Array of key - value pairs.
1330 * @param CRM_Core_DAO $dao
1331 * Membership object.
1333 * @param bool $reset
1335 * @return array|null
1336 * Membership details, if created.
1338 * @throws \CRM_Core_Exception
1340 public static function createRelatedMemberships(&$params, &$dao, $reset = FALSE) {
1341 // CRM-4213 check for loops, using static variable to record contacts already processed.
1342 static $relatedContactIds = array();
1344 // We need a way to reset this static variable from the test suite.
1345 // @todo consider replacing with Civi::$statics but note reset now used elsewhere: CRM-17723.
1346 $relatedContactIds = array();
1350 $membership = new CRM_Member_DAO_Membership();
1351 $membership->id
= $dao->id
;
1353 // required since create method doesn't return all the
1354 // parameters in the returned membership object
1355 if (!$membership->find(TRUE)) {
1358 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1359 // FIXME : While updating/ renewing the
1360 // membership, if the relationship is PAST then
1361 // the membership of the related contact must be
1363 // For that, getting Membership Status for which
1364 // is_current_member is 0. It works for the
1365 // generated data as there is only one membership
1366 // status having is_current_member = 0.
1367 // But this wont work exactly if there will be
1368 // more than one status having is_current_member = 0.
1369 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
1370 $membershipStatus->is_current_member
= 0;
1371 if ($membershipStatus->find(TRUE)) {
1372 $expiredStatusId = $membershipStatus->id
;
1375 $expiredStatusId = array_search('Expired', CRM_Member_PseudoConstant
::membershipStatus());
1378 $allRelatedContacts = array();
1379 $relatedContacts = array();
1380 if (!is_a($membership, 'CRM_Core_Error')) {
1381 $allRelatedContacts = CRM_Member_BAO_Membership
::checkMembershipRelationship($membership->membership_type_id
,
1382 $membership->contact_id
,
1383 CRM_Utils_Array
::value('action', $params)
1387 // CRM-4213, CRM-19735 check for loops, using static variable to record contacts already processed.
1388 // Remove repeated related contacts, which already inherited membership of this type.
1389 $relatedContactIds[$membership->contact_id
][$membership->membership_type_id
] = TRUE;
1390 foreach ($allRelatedContacts as $cid => $status) {
1391 if (empty($relatedContactIds[$cid]) ||
empty($relatedContactIds[$cid][$membership->membership_type_id
])) {
1392 $relatedContactIds[$cid][$membership->membership_type_id
] = TRUE;
1394 //don't create membership again for owner contact.
1395 $nestedRelationship = FALSE;
1396 if ($membership->owner_membership_id
) {
1397 $nestedRelMembership = new CRM_Member_DAO_Membership();
1398 $nestedRelMembership->id
= $membership->owner_membership_id
;
1399 $nestedRelMembership->contact_id
= $cid;
1400 $nestedRelationship = $nestedRelMembership->find(TRUE);
1402 if (!$nestedRelationship) {
1403 $relatedContacts[$cid] = $status;
1408 //lets cleanup related membership if any.
1409 if (empty($relatedContacts)) {
1410 self
::deleteRelatedMemberships($membership->id
);
1413 // Edit the params array
1414 unset($params['id']);
1415 // Reminder should be sent only to the direct membership
1416 unset($params['reminder_date']);
1417 // unset the custom value ids
1418 if (is_array(CRM_Utils_Array
::value('custom', $params))) {
1419 foreach ($params['custom'] as $k => $v) {
1420 unset($params['custom'][$k]['id']);
1423 if (!isset($params['membership_type_id'])) {
1424 $params['membership_type_id'] = $membership->membership_type_id
;
1427 // max_related should be set in the parent membership
1428 unset($params['max_related']);
1429 // Number of inherited memberships available - NULL is interpreted as unlimited, '0' as none
1430 $numRelatedAvailable = ($membership->max_related
== NULL ? PHP_INT_MAX
: $membership->max_related
);
1431 // will be used to queue potential memberships to be created.
1434 foreach ($relatedContacts as $contactId => $relationshipStatus) {
1435 //use existing membership record.
1436 $relMembership = new CRM_Member_DAO_Membership();
1437 $relMembership->contact_id
= $contactId;
1438 $relMembership->owner_membership_id
= $membership->id
;
1439 $relMemIds = array();
1440 if ($relMembership->find(TRUE)) {
1441 $params['id'] = $relMemIds['membership'] = $relMembership->id
;
1443 $params['contact_id'] = $contactId;
1444 $params['owner_membership_id'] = $membership->id
;
1446 // set status_id as it might have been changed for
1447 // past relationship
1448 $params['status_id'] = $membership->status_id
;
1450 if ($deceasedStatusId &&
1451 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'is_deceased')
1453 $params['status_id'] = $deceasedStatusId;
1455 elseif ((CRM_Utils_Array
::value('action', $params) & CRM_Core_Action
::UPDATE
) &&
1456 ($relationshipStatus == CRM_Contact_BAO_Relationship
::PAST
)
1458 $params['status_id'] = $expiredStatusId;
1461 //don't calculate status again in create( );
1462 $params['skipStatusCal'] = TRUE;
1464 //do create activity if we changed status.
1465 if ($params['status_id'] != $relMembership->status_id
) {
1466 $params['createActivity'] = TRUE;
1469 //CRM-20707 - include start/end date
1470 $params['start_date'] = $membership->start_date
;
1471 $params['end_date'] = $membership->end_date
;
1473 // we should not created contribution record for related contacts, CRM-3371
1474 unset($params['contribution_status_id']);
1476 //CRM-16857: Do not create multiple line-items for inherited membership through priceset.
1477 unset($params['lineItems']);
1478 unset($params['line_item']);
1480 // CRM-20966: Do not create membership_payment record for inherited membership.
1481 unset($params['relate_contribution_id']);
1483 if (($params['status_id'] == $deceasedStatusId) ||
($params['status_id'] == $expiredStatusId)) {
1484 // related membership is not active so does not count towards maximum
1485 CRM_Member_BAO_Membership
::create($params, $relMemIds);
1488 // related membership already exists, so this is just an update
1489 if (isset($params['id'])) {
1490 if ($numRelatedAvailable > 0) {
1491 CRM_Member_BAO_Membership
::create($params, $relMemIds);
1492 $numRelatedAvailable--;
1495 // we have run out of inherited memberships, so delete extras
1496 self
::deleteMembership($params['id']);
1498 // we need to first check if there will remain inherited memberships, so queue it up
1505 // now go over the queue and create any available related memberships
1506 foreach ($queue as $params) {
1507 if ($numRelatedAvailable <= 0) {
1510 CRM_Member_BAO_Membership
::create($params, $relMemIds);
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 = array(), $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 = array();
1582 $membershipTypeFields = array(
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
] = array();
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 = array();
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 = array(1 => array($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 => array(self
::$_signupActType, 'Integer'),
1745 2 => array($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 => array(self
::$_renewalActType, 'Integer'),
1798 2 => array($membershipTypeId, 'Integer'),
1800 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1802 return (int) $memberCount;
1806 * Create linkages between membership & contribution - note this is the wrong place for this code but this is a
1807 * refactoring step. This should be BAO functionality
1808 * @param $membership
1809 * @param $membershipContribution
1811 public static function linkMembershipPayment($membership, $membershipContribution) {
1812 CRM_Member_BAO_MembershipPayment
::create(array(
1813 'membership_id' => $membership->id
,
1814 'membership_type_id' => $membership->membership_type_id
,
1815 'contribution_id' => $membershipContribution->id
,
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
1840 public static function processMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $contributionRecurID, $membershipSource, $isPayLater, $campaignId, $formDates = array(), $contribution = NULL, $lineItems = array()) {
1841 $renewalMode = $updateStatusId = FALSE;
1842 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1844 $statusFormat = '%Y-%m-%d';
1845 $membershipTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipTypeID);
1848 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
1849 // is the same as the parent org of an existing membership of the contact
1850 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($contactID, $membershipTypeID,
1851 $is_test, $membershipID, TRUE
1853 if ($currentMembership) {
1854 $renewalMode = TRUE;
1856 // Do NOT do anything.
1857 //1. membership with status : PENDING/CANCELLED (CRM-2395)
1858 //2. Paylater/IPN renew. CRM-4556.
1859 if ($pending ||
in_array($currentMembership['status_id'], array(
1860 array_search('Pending', $allStatus),
1862 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1866 'id' => $currentMembership['id'],
1867 'contribution' => $contribution,
1868 'status_id' => $currentMembership['status_id'],
1869 'start_date' => $currentMembership['start_date'],
1870 'end_date' => $currentMembership['end_date'],
1871 'line_item' => $lineItems,
1872 'join_date' => $currentMembership['join_date'],
1873 'membership_type_id' => $membershipTypeID,
1874 'max_related' => !empty($membershipTypeDetails['max_related']) ?
$membershipTypeDetails['max_related'] : NULL,
1875 'membership_activity_status' => ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed',
1877 if ($contributionRecurID) {
1878 $memParams['contribution_recur_id'] = $contributionRecurID;
1881 $membership = self
::create($memParams, $ids, FALSE);
1882 return array($membership, $renewalMode, $dates);
1885 // Check and fix the membership if it is STALE
1886 self
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
1888 // Now Renew the membership
1889 if (!$currentMembership['is_current_member']) {
1890 // membership is not CURRENT
1892 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1893 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($currentMembership['id'],
1899 $currentMembership['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1900 foreach (array('start_date', 'end_date') as $dateType) {
1901 $currentMembership[$dateType] = CRM_Utils_Array
::value($dateType, $formDates);
1902 if (empty($currentMembership[$dateType])) {
1903 $currentMembership[$dateType] = CRM_Utils_Array
::value($dateType, $dates);
1906 $currentMembership['is_test'] = $is_test;
1908 if (!empty($membershipSource)) {
1909 $currentMembership['source'] = $membershipSource;
1912 $currentMembership['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
1913 $currentMembership['id'],
1918 if (!empty($currentMembership['id'])) {
1919 $ids['membership'] = $currentMembership['id'];
1921 $memParams = $currentMembership;
1922 $memParams['membership_type_id'] = $membershipTypeID;
1924 //set the log start date.
1925 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1929 // CURRENT Membership
1930 $membership = new CRM_Member_DAO_Membership();
1931 $membership->id
= $currentMembership['id'];
1932 $membership->find(TRUE);
1933 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1934 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
1940 // Insert renewed dates for CURRENT membership
1941 $memParams = array();
1942 $memParams['join_date'] = CRM_Utils_Date
::isoToMysql($membership->join_date
);
1943 $memParams['start_date'] = CRM_Utils_Array
::value('start_date', $formDates, CRM_Utils_Date
::isoToMysql($membership->start_date
));
1944 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $formDates);
1945 if (empty($memParams['end_date'])) {
1946 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $dates);
1948 $memParams['membership_type_id'] = $membershipTypeID;
1950 //set the log start date.
1951 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1954 if (!empty($membershipSource)) {
1955 $memParams['source'] = $membershipSource;
1957 elseif (empty($membership->source
)) {
1958 $memParams['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
1959 $currentMembership['id'],
1964 if (!empty($currentMembership['id'])) {
1965 $ids['membership'] = $currentMembership['id'];
1967 $memParams['membership_activity_status'] = ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed';
1971 $updateStatusId = array_search('Pending', $allStatus);
1977 'contact_id' => $contactID,
1978 'membership_type_id' => $membershipTypeID,
1982 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
1984 foreach (array('join_date', 'start_date', 'end_date') as $dateType) {
1985 $memParams[$dateType] = CRM_Utils_Array
::value($dateType, $formDates);
1986 if (empty($memParams[$dateType])) {
1987 $memParams[$dateType] = CRM_Utils_Array
::value($dateType, $dates);
1991 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(CRM_Utils_Date
::customFormat($dates['start_date'],
1994 CRM_Utils_Date
::customFormat($dates['end_date'],
1997 CRM_Utils_Date
::customFormat($dates['join_date'],
2005 $updateStatusId = CRM_Utils_Array
::value('id', $status);
2008 // if IPN/Pay-Later set status to: PENDING
2009 $updateStatusId = array_search('Pending', $allStatus);
2012 if (!empty($membershipSource)) {
2013 $memParams['source'] = $membershipSource;
2015 $memParams['is_test'] = $is_test;
2016 $memParams['is_pay_later'] = $isPayLater;
2018 // Putting this in an IF is precautionary as it seems likely that it would be ignored if empty, but
2019 // perhaps shouldn't be?
2020 if ($contributionRecurID) {
2021 $memParams['contribution_recur_id'] = $contributionRecurID;
2024 //if we decided status here and want to skip status
2025 //calculation in create( ); then need to pass 'skipStatusCal'.
2026 if ($updateStatusId) {
2027 $memParams['status_id'] = $updateStatusId;
2028 $memParams['skipStatusCal'] = TRUE;
2031 //since we are renewing,
2032 //make status override false.
2033 $memParams['is_override'] = FALSE;
2035 //CRM-4027, create log w/ individual contact.
2037 $ids['userId'] = $modifiedID;
2038 $memParams['is_for_organization'] = TRUE;
2041 $ids['userId'] = $contactID;
2044 //inherit campaign from contrib page.
2045 if (isset($campaignId)) {
2046 $memParams['campaign_id'] = $campaignId;
2049 $memParams['contribution'] = $contribution;
2050 $memParams['custom'] = $customFieldsFormatted;
2051 // Load all line items & process all in membership. Don't do in contribution.
2052 // Relevant tests in api_v3_ContributionPageTest.
2053 $memParams['line_item'] = $lineItems;
2054 $membership = self
::create($memParams, $ids, FALSE);
2056 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
2057 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
2058 $membership->find(TRUE);
2060 return array($membership, $renewalMode, $dates);
2064 * Get line items representing the default price set.
2066 * @param int $membershipOrg
2067 * @param int $membershipTypeID
2068 * @param float $total_amount
2069 * @param int $priceSetId
2073 public static function setQuickConfigMembershipParameters($membershipOrg, $membershipTypeID, $total_amount, $priceSetId) {
2074 $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
2076 // The name of the price field corresponds to the membership_type organization contact.
2078 'price_set_id' => $priceSetId,
2079 'name' => $membershipOrg,
2082 CRM_Price_BAO_PriceField
::retrieve($params, $results);
2084 if (!empty($results)) {
2085 $fields[$results['id']] = $priceSets['fields'][$results['id']];
2086 $fid = $results['id'];
2087 $editedFieldParams = array(
2088 'price_field_id' => $results['id'],
2089 'membership_type_id' => $membershipTypeID,
2092 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $results);
2093 $fields[$fid]['options'][$results['id']] = $priceSets['fields'][$fid]['options'][$results['id']];
2094 if (!empty($total_amount)) {
2095 $fields[$fid]['options'][$results['id']]['amount'] = $total_amount;
2099 $fieldID = key($fields);
2100 $returnParams = array(
2101 'price_set_id' => $priceSetId,
2102 'price_sets' => $priceSets,
2103 'fields' => $fields,
2104 'price_fields' => array(
2105 'price_' . $fieldID => CRM_Utils_Array
::value('id', $results),
2108 return $returnParams;
2112 * Update the status of all deceased members to deceased.
2115 * Count of updated contacts.
2117 protected static function updateDeceasedMembersStatuses() {
2120 $deceasedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Deceased');
2122 // 'create' context for buildOptions returns only if enabled.
2123 $allStatus = self
::buildOptions('status_id', 'create');
2124 if (array_key_exists($deceasedStatusId, $allStatus) === FALSE) {
2125 // Deceased status is an admin status & is required. We want to fail early if
2126 // it is not present or active.
2127 // We could make the case 'some databases just don't use deceased so we will check
2128 // for the presence of a deceased contact in the DB before rejecting.
2129 if (CRM_Core_DAO
::singleValueQuery('
2130 SELECT count(*) FROM civicrm_contact WHERE is_deceased = 0'
2132 throw new CRM_Core_Exception(
2133 ts("Deceased Membership status is missing or not active. <a href='%1'>Click here to check</a>.",
2134 [1 => CRM_Utils_System
::url('civicrm/admin/member/membershipStatus', 'reset=1')]
2138 $deceasedDAO = CRM_Core_DAO
::executeQuery(
2140 SELECT membership.id as membership_id
2141 FROM civicrm_membership membership
2142 INNER JOIN civicrm_contact ON membership.contact_id = civicrm_contact.id
2143 INNER JOIN civicrm_membership_type ON membership.membership_type_id = civicrm_membership_type.id
2144 AND civicrm_membership_type.is_active = 1
2145 WHERE membership.is_test = 0
2146 AND civicrm_contact.is_deceased = 1
2147 AND membership.status_id <> %1
2149 [1 => [$deceasedStatusId, 'Integer']]
2151 while ($deceasedDAO->fetch()) {
2152 civicrm_api3('membership', 'create', [
2153 'id' => $deceasedDAO->membership_id
,
2154 'status_id' => $deceasedStatusId,
2155 'createActivity' => TRUE,
2156 'skipStatusCal' => TRUE,
2157 'skipRecentView' => TRUE,
2165 * Process price set and line items.
2167 * @param int $membershipId
2168 * @param array $lineItem
2170 public function processPriceSet($membershipId, $lineItem) {
2171 //FIXME : need to move this too
2172 if (!$membershipId ||
!is_array($lineItem)
2173 || CRM_Utils_System
::isNull($lineItem)
2178 foreach ($lineItem as $priceSetId => $values) {
2182 foreach ($values as $line) {
2183 $line['entity_table'] = 'civicrm_membership';
2184 $line['entity_id'] = $membershipId;
2185 CRM_Price_BAO_LineItem
::create($line);
2191 * Retrieve the contribution id for the associated Membership id.
2192 * @todo we should get this off the line item
2194 * @param int $membershipId
2197 * if more than one payment associated with membership id need to be returned.
2202 public static function getMembershipContributionId($membershipId, $all = FALSE) {
2204 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
2205 $membershipPayment->membership_id
= $membershipId;
2206 if ($all && $membershipPayment->find()) {
2207 $contributionIds = array();
2208 while ($membershipPayment->fetch()) {
2209 $contributionIds[] = $membershipPayment->contribution_id
;
2211 return $contributionIds;
2214 if ($membershipPayment->find(TRUE)) {
2215 return $membershipPayment->contribution_id
;
2221 * The function checks and updates the status of all membership records for a given domain using the
2222 * calc_membership_status and update_contact_membership APIs.
2225 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
2229 public static function updateAllMembershipStatus() {
2230 // Tests for this function are in api_v3_JobTest. Please add tests for all updates.
2232 $updateCount = $processCount = self
::updateDeceasedMembersStatuses();
2234 // We want all of the statuses as id => name, even the disabled ones (cf.
2235 // CRM-15475), to identify which are Pending, Deceased, Cancelled, and
2237 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'validate');
2238 $allTypes = CRM_Member_PseudoConstant
::membershipType();
2240 // This query retrieves ALL memberships of active types.
2242 SELECT civicrm_membership.id as membership_id,
2243 civicrm_membership.is_override as is_override,
2244 civicrm_membership.status_override_end_date as status_override_end_date,
2245 civicrm_membership.membership_type_id as membership_type_id,
2246 civicrm_membership.status_id as status_id,
2247 civicrm_membership.join_date as join_date,
2248 civicrm_membership.start_date as start_date,
2249 civicrm_membership.end_date as end_date,
2250 civicrm_membership.source as source,
2251 civicrm_contact.id as contact_id,
2252 civicrm_membership.owner_membership_id as owner_membership_id,
2253 civicrm_membership.contribution_recur_id as recur_id
2254 FROM civicrm_membership
2255 INNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )
2256 INNER JOIN civicrm_membership_type ON
2257 (civicrm_membership.membership_type_id = civicrm_membership_type.id AND civicrm_membership_type.is_active = 1)
2258 WHERE civicrm_membership.is_test = 0
2259 AND civicrm_contact.is_deceased = 0 ";
2261 $deceaseStatusId = array_search('Deceased', $allStatus);
2262 $pendingStatusId = array_search('Pending', $allStatus);
2263 $cancelledStatusId = array_search('Cancelled', $allStatus);
2264 // Expired is not reserved so might not exist. A value of `0` won't break.
2265 $expiredStatusId = array_search('Expired', $allStatus) ?
: 0;
2267 $query = $baseQuery . " AND civicrm_membership.is_override IS NOT NULL AND civicrm_membership.status_override_end_date IS NOT NULL";
2268 $dao1 = CRM_Core_DAO
::executeQuery($query);
2269 while ($dao1->fetch()) {
2270 self
::processOverriddenUntilDateMembership($dao1);
2273 $query = $baseQuery . " AND (civicrm_membership.is_override = 0 OR civicrm_membership.is_override IS NULL)
2274 AND civicrm_membership.status_id NOT IN (%1, %2, %3, %4)
2275 AND civicrm_membership.owner_membership_id IS NULL ";
2277 1 => array($pendingStatusId, 'Integer'),
2278 2 => array($cancelledStatusId, 'Integer'),
2279 3 => array($expiredStatusId, 'Integer'),
2280 4 => array($deceaseStatusId, 'Integer'),
2282 $dao2 = CRM_Core_DAO
::executeQuery($query, $params);
2284 while ($dao2->fetch()) {
2288 // Put common parameters into array for easy access
2289 $memberParams = array(
2290 'id' => $dao2->membership_id
,
2291 'status_id' => $dao2->status_id
,
2292 'contact_id' => $dao2->contact_id
,
2293 'membership_type_id' => $dao2->membership_type_id
,
2294 'membership_type' => $allTypes[$dao2->membership_type_id
],
2295 'join_date' => $dao2->join_date
,
2296 'start_date' => $dao2->start_date
,
2297 'end_date' => $dao2->end_date
,
2298 'source' => $dao2->source
,
2299 'skipStatusCal' => TRUE,
2300 'skipRecentView' => TRUE,
2303 // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses
2304 //get the membership status as per id.
2305 $newStatus = civicrm_api('membership_status', 'calc',
2307 'membership_id' => $dao2->membership_id
,
2309 'ignore_admin_only' => TRUE,
2312 $statusId = CRM_Utils_Array
::value('id', $newStatus);
2314 //process only when status change.
2316 $statusId != $dao2->status_id
2318 //take all params that need to save.
2319 $memParams = $memberParams;
2320 $memParams['status_id'] = $statusId;
2321 $memParams['createActivity'] = TRUE;
2322 $memParams['version'] = 3;
2324 // Unset columns which should remain unchanged from their current saved
2325 // values. This avoids race condition in which these values may have
2326 // been changed by other processes.
2328 $memParams['contact_id'],
2329 $memParams['membership_type_id'],
2330 $memParams['membership_type'],
2331 $memParams['join_date'],
2332 $memParams['start_date'],
2333 $memParams['end_date'],
2334 $memParams['source']
2336 //since there is change in status.
2338 //process member record.
2339 civicrm_api('membership', 'create', $memParams);
2343 $result['is_error'] = 0;
2344 $result['messages'] = ts('Processed %1 membership records. Updated %2 records.', array(
2352 * Set is_override for the 'overridden until date' membership to
2353 * False and clears the 'until date' field in case the 'until date'
2354 * is equal or after today date.
2356 * @param CRM_Core_DAO $membership
2357 * The membership to be processed
2359 private static function processOverriddenUntilDateMembership($membership) {
2360 $isOverriddenUntilDate = !empty($membership->is_override
) && !empty($membership->status_override_end_date
);
2361 if (!$isOverriddenUntilDate) {
2365 $todayDate = new DateTime();
2366 $todayDate->setTime(0, 0);
2368 $overrideEndDate = new DateTime($membership->status_override_end_date
);
2369 $overrideEndDate->setTime(0, 0);
2371 $datesDifference = $todayDate->diff($overrideEndDate);
2372 $daysDifference = (int) $datesDifference->format('%R%a');
2373 if ($daysDifference <= 0) {
2375 'id' => $membership->membership_id
,
2376 'is_override' => FALSE,
2377 'status_override_end_date' => 'null',
2379 civicrm_api3('membership', 'create', $params);
2384 * Returns the membership types for a particular contact
2385 * who has lifetime membership without end date.
2387 * @param int $contactID
2388 * @param bool $isTest
2389 * @param bool $onlyLifeTime
2393 public static function getAllContactMembership($contactID, $isTest = FALSE, $onlyLifeTime = FALSE) {
2394 $contactMembershipType = array();
2396 return $contactMembershipType;
2399 $dao = new CRM_Member_DAO_Membership();
2400 $dao->contact_id
= $contactID;
2401 $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
2402 $dao->whereAdd("status_id != $pendingStatusId");
2405 $dao->is_test
= $isTest;
2408 $dao->whereAdd('is_test IS NULL OR is_test = 0');
2411 if ($onlyLifeTime) {
2412 $dao->whereAdd('end_date IS NULL');
2416 while ($dao->fetch()) {
2417 $membership = array();
2418 CRM_Core_DAO
::storeValues($dao, $membership);
2419 $contactMembershipType[$dao->membership_type_id
] = $membership;
2421 return $contactMembershipType;
2425 * Record contribution record associated with membership.
2427 * @param array $params
2428 * Array of submitted params.
2430 * (param in process of being removed - try to use params) array of ids.
2432 * @return CRM_Contribute_BAO_Contribution
2434 public static function recordMembershipContribution(&$params, $ids = array()) {
2435 $membershipId = $params['membership_id'];
2436 $contributionParams = array();
2437 $config = CRM_Core_Config
::singleton();
2438 $contributionParams['currency'] = $config->defaultCurrency
;
2439 $contributionParams['receipt_date'] = (CRM_Utils_Array
::value('receipt_date', $params)) ?
$params['receipt_date'] : 'null';
2440 $contributionParams['source'] = CRM_Utils_Array
::value('contribution_source', $params);
2441 $contributionParams['non_deductible_amount'] = 'null';
2442 $contributionParams['skipCleanMoney'] = TRUE;
2443 $contributionParams['payment_processor'] = CRM_Utils_Array
::value('payment_processor_id', $params);
2444 $contributionSoftParams = CRM_Utils_Array
::value('soft_credit', $params);
2445 $recordContribution = array(
2450 'financial_type_id',
2451 'payment_instrument_id',
2455 'contribution_status_id',
2462 'contribution_recur_id',
2466 foreach ($recordContribution as $f) {
2467 $contributionParams[$f] = CRM_Utils_Array
::value($f, $params);
2470 // make entry in batch entity batch table
2471 if (!empty($params['batch_id'])) {
2472 $contributionParams['batch_id'] = $params['batch_id'];
2475 if (!empty($params['contribution_contact_id'])) {
2476 // deal with possibility of a different person paying for contribution
2477 $contributionParams['contact_id'] = $params['contribution_contact_id'];
2480 if (!empty($params['processPriceSet']) &&
2481 !empty($params['lineItems'])
2483 $contributionParams['line_item'] = CRM_Utils_Array
::value('lineItems', $params, NULL);
2486 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
2488 //CRM-13981, create new soft-credit record as to record payment from different person for this membership
2489 if (!empty($contributionSoftParams)) {
2490 if (!empty($params['batch_id'])) {
2491 foreach ($contributionSoftParams as $contributionSoft) {
2492 $contributionSoft['contribution_id'] = $contribution->id
;
2493 $contributionSoft['currency'] = $contribution->currency
;
2494 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoft);
2498 $contributionSoftParams['contribution_id'] = $contribution->id
;
2499 $contributionSoftParams['currency'] = $contribution->currency
;
2500 $contributionSoftParams['amount'] = $contribution->total_amount
;
2501 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoftParams);
2505 // store contribution id
2506 $params['contribution_id'] = $contribution->id
;
2508 //insert payment record for this membership
2509 if (empty($ids['contribution']) ||
!empty($params['is_recur'])) {
2510 CRM_Member_BAO_MembershipPayment
::create(array(
2511 'membership_id' => $membershipId,
2512 'contribution_id' => $contribution->id
,
2515 return $contribution;
2519 * @todo document me - I seem a bit out of date....
2521 public static function _getActTypes() {
2522 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2523 self
::$_renewalActType = CRM_Utils_Array
::key('Membership Renewal', $activityTypes);
2524 self
::$_signupActType = CRM_Utils_Array
::key('Membership Signup', $activityTypes);
2528 * Get all Cancelled Membership(s) for a contact
2530 * @param int $contactID
2532 * @param bool $isTest
2536 * Array of membership type
2538 public static function getContactsCancelledMembership($contactID, $isTest = FALSE) {
2542 $query = 'SELECT membership_type_id FROM civicrm_membership WHERE contact_id = %1 AND status_id = %2 AND is_test = %3';
2543 $queryParams = array(
2544 1 => array($contactID, 'Integer'),
2549 CRM_Member_PseudoConstant
::membershipStatus(
2551 " name = 'Cancelled' ",
2559 3 => array($isTest, 'Boolean'),
2562 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
2563 $cancelledMembershipIds = array();
2564 while ($dao->fetch()) {
2565 $cancelledMembershipIds[] = $dao->membership_type_id
;
2567 return $cancelledMembershipIds;
2571 * Merges the memberships from otherContactID to mainContactID.
2573 * General idea is to merge memberships in regards to their type. We
2574 * move the other contact’s contributions to the main contact’s
2575 * membership which has the same type (if any) and then we update
2576 * membership to avoid loosing `join_date`, `end_date`, and
2577 * `status_id`. In this function, we don’t touch the contributions
2578 * directly (CRM_Dedupe_Merger::moveContactBelongings() takes care
2581 * This function adds new SQL queries to the $sqlQueries parameter.
2583 * @param int $mainContactID
2584 * Contact id of main contact record.
2585 * @param int $otherContactID
2586 * Contact id of record which is going to merge.
2587 * @param array $sqlQueries
2588 * (reference) array of SQL queries to be executed.
2589 * @param array $tables
2590 * List of tables that have to be merged.
2591 * @param array $tableOperations
2592 * Special options/params for some tables to be merged.
2594 * @see CRM_Dedupe_Merger::cpTables()
2596 public static function mergeMemberships($mainContactID, $otherContactID, &$sqlQueries, $tables, $tableOperations) {
2598 * If the user requests not to merge memberships but to add them,
2599 * just attribute the `civicrm_membership` to the
2600 * `$mainContactID`. We have to do this here since the general
2601 * merge process is bypassed by this function.
2603 if (array_key_exists("civicrm_membership", $tableOperations) && $tableOperations['civicrm_membership']['add']) {
2604 $sqlQueries[] = "UPDATE IGNORE civicrm_membership SET contact_id = $mainContactID WHERE contact_id = $otherContactID";
2609 * Retrieve all memberships that belongs to each contacts and
2610 * keep track of each membership type.
2612 $mainContactMemberships = array();
2613 $otherContactMemberships = array();
2615 $sql = "SELECT id, membership_type_id FROM civicrm_membership membership WHERE contact_id = %1";
2616 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($mainContactID, "Integer")));
2617 while ($dao->fetch()) {
2618 $mainContactMemberships[$dao->id
] = $dao->membership_type_id
;
2621 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($otherContactID, "Integer")));
2622 while ($dao->fetch()) {
2623 $otherContactMemberships[$dao->id
] = $dao->membership_type_id
;
2627 * For each membership, move related contributions to the main
2628 * contact’s membership (by updating `membership_payments`). Then,
2629 * update membership’s `join_date` (if the other membership’s
2630 * join_date is older) and `end_date` (if the other membership’s
2631 * `end_date` is newer) and `status_id` (if the newly calculated
2632 * status is different).
2634 * FIXME: what should we do if we have multiple memberships with
2635 * the same type (currently we only take the first one)?
2638 foreach ($otherContactMemberships as $otherMembershipId => $otherMembershipTypeId) {
2639 if ($newMembershipId = array_search($otherMembershipTypeId, $mainContactMemberships)) {
2642 * Move other membership’s contributions to the main one only
2643 * if user requested to merge contributions.
2645 if (!empty($tables) && in_array('civicrm_contribution', $tables)) {
2646 $newSql[] = "UPDATE civicrm_membership_payment SET membership_id=$newMembershipId WHERE membership_id=$otherMembershipId";
2649 $sql = "SELECT * FROM civicrm_membership membership WHERE id = %1";
2651 $newMembership = CRM_Member_DAO_Membership
::findById($newMembershipId);
2652 $otherMembership = CRM_Member_DAO_Membership
::findById($otherMembershipId);
2655 if (new DateTime($otherMembership->join_date
) < new DateTime($newMembership->join_date
)) {
2656 $updates["join_date"] = $otherMembership->join_date
;
2659 if (new DateTime($otherMembership->end_date
) > new DateTime($newMembership->end_date
)) {
2660 $updates["end_date"] = $otherMembership->end_date
;
2663 if (count($updates)) {
2668 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
2669 isset($updates["start_date"]) ?
$updates["start_date"] : $newMembership->start_date
,
2670 isset($updates["end_date"]) ?
$updates["end_date"] : $newMembership->end_date
,
2671 isset($updates["join_date"]) ?
$updates["join_date"] : $newMembership->join_date
,
2678 if (!empty($status['id']) and $status['id'] != $newMembership->status_id
) {
2679 $updates['status_id'] = $status['id'];
2683 foreach ($updates as $k => $v) {
2684 $updates_sql[] = "$k = '{$v}'";
2687 $newSql[] = sprintf("UPDATE civicrm_membership SET %s WHERE id=%s", implode(", ", $updates_sql), $newMembershipId);
2688 $newSql[] = sprintf("DELETE FROM civicrm_membership WHERE id=%s", $otherMembershipId);
2694 $sqlQueries = array_merge($sqlQueries, $newSql);