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,
1253 CRM_Core_DAO
::$_nullArray
1258 * Updated related memberships.
1260 * @param int $ownerMembershipId
1261 * Owner Membership Id.
1262 * @param array $params
1263 * Formatted array of key => value.
1265 public static function updateRelatedMemberships($ownerMembershipId, $params) {
1266 $membership = new CRM_Member_DAO_Membership();
1267 $membership->owner_membership_id
= $ownerMembershipId;
1268 $membership->find();
1270 while ($membership->fetch()) {
1271 $relatedMembership = new CRM_Member_DAO_Membership();
1272 $relatedMembership->id
= $membership->id
;
1273 $relatedMembership->copyValues($params);
1274 $relatedMembership->save();
1280 * Get list of membership fields for profile.
1282 * For now we only allow custom membership fields to be in
1286 * FIXME: This param is ignored
1289 * the list of membership fields
1291 public static function getMembershipFields($mode = NULL) {
1292 $fields = CRM_Member_DAO_Membership
::export();
1294 unset($fields['membership_contact_id']);
1295 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1297 $membershipType = CRM_Member_DAO_MembershipType
::export();
1299 $membershipStatus = CRM_Member_DAO_MembershipStatus
::export();
1301 $fields = array_merge($fields, $membershipType, $membershipStatus);
1307 * Get the sort name of a contact for a particular membership.
1310 * Id of the membership.
1312 * @return null|string
1313 * sort name of the contact if found
1315 public static function sortName($id) {
1316 $id = CRM_Utils_Type
::escape($id, 'Integer');
1319 SELECT civicrm_contact.sort_name
1320 FROM civicrm_membership, civicrm_contact
1321 WHERE civicrm_membership.contact_id = civicrm_contact.id
1322 AND civicrm_membership.id = {$id}
1324 return CRM_Core_DAO
::singleValueQuery($query);
1328 * Create memberships for related contacts, taking into account the maximum related memberships.
1330 * @param array $params
1331 * Array of key - value pairs.
1332 * @param CRM_Core_DAO $dao
1333 * Membership object.
1335 * @param bool $reset
1337 * @return array|null
1338 * Membership details, if created.
1340 * @throws \CRM_Core_Exception
1342 public static function createRelatedMemberships(&$params, &$dao, $reset = FALSE) {
1343 // CRM-4213 check for loops, using static variable to record contacts already processed.
1344 static $relatedContactIds = array();
1346 // We need a way to reset this static variable from the test suite.
1347 // @todo consider replacing with Civi::$statics but note reset now used elsewhere: CRM-17723.
1348 $relatedContactIds = array();
1352 $membership = new CRM_Member_DAO_Membership();
1353 $membership->id
= $dao->id
;
1355 // required since create method doesn't return all the
1356 // parameters in the returned membership object
1357 if (!$membership->find(TRUE)) {
1360 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1361 // FIXME : While updating/ renewing the
1362 // membership, if the relationship is PAST then
1363 // the membership of the related contact must be
1365 // For that, getting Membership Status for which
1366 // is_current_member is 0. It works for the
1367 // generated data as there is only one membership
1368 // status having is_current_member = 0.
1369 // But this wont work exactly if there will be
1370 // more than one status having is_current_member = 0.
1371 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
1372 $membershipStatus->is_current_member
= 0;
1373 if ($membershipStatus->find(TRUE)) {
1374 $expiredStatusId = $membershipStatus->id
;
1377 $expiredStatusId = array_search('Expired', CRM_Member_PseudoConstant
::membershipStatus());
1380 $allRelatedContacts = array();
1381 $relatedContacts = array();
1382 if (!is_a($membership, 'CRM_Core_Error')) {
1383 $allRelatedContacts = CRM_Member_BAO_Membership
::checkMembershipRelationship($membership->membership_type_id
,
1384 $membership->contact_id
,
1385 CRM_Utils_Array
::value('action', $params)
1389 // CRM-4213, CRM-19735 check for loops, using static variable to record contacts already processed.
1390 // Remove repeated related contacts, which already inherited membership of this type.
1391 $relatedContactIds[$membership->contact_id
][$membership->membership_type_id
] = TRUE;
1392 foreach ($allRelatedContacts as $cid => $status) {
1393 if (empty($relatedContactIds[$cid]) ||
empty($relatedContactIds[$cid][$membership->membership_type_id
])) {
1394 $relatedContactIds[$cid][$membership->membership_type_id
] = TRUE;
1396 //don't create membership again for owner contact.
1397 $nestedRelationship = FALSE;
1398 if ($membership->owner_membership_id
) {
1399 $nestedRelMembership = new CRM_Member_DAO_Membership();
1400 $nestedRelMembership->id
= $membership->owner_membership_id
;
1401 $nestedRelMembership->contact_id
= $cid;
1402 $nestedRelationship = $nestedRelMembership->find(TRUE);
1404 if (!$nestedRelationship) {
1405 $relatedContacts[$cid] = $status;
1410 //lets cleanup related membership if any.
1411 if (empty($relatedContacts)) {
1412 self
::deleteRelatedMemberships($membership->id
);
1415 // Edit the params array
1416 unset($params['id']);
1417 // Reminder should be sent only to the direct membership
1418 unset($params['reminder_date']);
1419 // unset the custom value ids
1420 if (is_array(CRM_Utils_Array
::value('custom', $params))) {
1421 foreach ($params['custom'] as $k => $v) {
1422 unset($params['custom'][$k]['id']);
1425 if (!isset($params['membership_type_id'])) {
1426 $params['membership_type_id'] = $membership->membership_type_id
;
1429 // max_related should be set in the parent membership
1430 unset($params['max_related']);
1431 // Number of inherited memberships available - NULL is interpreted as unlimited, '0' as none
1432 $numRelatedAvailable = ($membership->max_related
== NULL ? PHP_INT_MAX
: $membership->max_related
);
1433 // will be used to queue potential memberships to be created.
1436 foreach ($relatedContacts as $contactId => $relationshipStatus) {
1437 //use existing membership record.
1438 $relMembership = new CRM_Member_DAO_Membership();
1439 $relMembership->contact_id
= $contactId;
1440 $relMembership->owner_membership_id
= $membership->id
;
1441 $relMemIds = array();
1442 if ($relMembership->find(TRUE)) {
1443 $params['id'] = $relMemIds['membership'] = $relMembership->id
;
1445 $params['contact_id'] = $contactId;
1446 $params['owner_membership_id'] = $membership->id
;
1448 // set status_id as it might have been changed for
1449 // past relationship
1450 $params['status_id'] = $membership->status_id
;
1452 if ($deceasedStatusId &&
1453 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'is_deceased')
1455 $params['status_id'] = $deceasedStatusId;
1457 elseif ((CRM_Utils_Array
::value('action', $params) & CRM_Core_Action
::UPDATE
) &&
1458 ($relationshipStatus == CRM_Contact_BAO_Relationship
::PAST
)
1460 $params['status_id'] = $expiredStatusId;
1463 //don't calculate status again in create( );
1464 $params['skipStatusCal'] = TRUE;
1466 //do create activity if we changed status.
1467 if ($params['status_id'] != $relMembership->status_id
) {
1468 $params['createActivity'] = TRUE;
1471 //CRM-20707 - include start/end date
1472 $params['start_date'] = $membership->start_date
;
1473 $params['end_date'] = $membership->end_date
;
1475 // we should not created contribution record for related contacts, CRM-3371
1476 unset($params['contribution_status_id']);
1478 //CRM-16857: Do not create multiple line-items for inherited membership through priceset.
1479 unset($params['lineItems']);
1480 unset($params['line_item']);
1482 // CRM-20966: Do not create membership_payment record for inherited membership.
1483 unset($params['relate_contribution_id']);
1485 if (($params['status_id'] == $deceasedStatusId) ||
($params['status_id'] == $expiredStatusId)) {
1486 // related membership is not active so does not count towards maximum
1487 CRM_Member_BAO_Membership
::create($params, $relMemIds);
1490 // related membership already exists, so this is just an update
1491 if (isset($params['id'])) {
1492 if ($numRelatedAvailable > 0) {
1493 CRM_Member_BAO_Membership
::create($params, $relMemIds);
1494 $numRelatedAvailable--;
1497 // we have run out of inherited memberships, so delete extras
1498 self
::deleteMembership($params['id']);
1500 // we need to first check if there will remain inherited memberships, so queue it up
1507 // now go over the queue and create any available related memberships
1508 foreach ($queue as $params) {
1509 if ($numRelatedAvailable <= 0) {
1512 CRM_Member_BAO_Membership
::create($params, $relMemIds);
1513 $numRelatedAvailable--;
1519 * Delete the record that are associated with this Membership Payment.
1521 * @param int $membershipId
1522 * @param bool $preserveContrib
1525 * $membershipPayment deleted membership payment object
1527 public static function deleteMembershipPayment($membershipId, $preserveContrib = FALSE) {
1529 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
1530 $membershipPayment->membership_id
= $membershipId;
1531 $membershipPayment->find();
1533 while ($membershipPayment->fetch()) {
1534 if (!$preserveContrib) {
1535 CRM_Contribute_BAO_Contribution
::deleteContribution($membershipPayment->contribution_id
);
1537 CRM_Utils_Hook
::pre('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1538 $membershipPayment->delete();
1539 CRM_Utils_Hook
::post('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1541 return $membershipPayment;
1545 * Build an array of available membership types.
1547 * @param CRM_Core_Form $form
1548 * @param array $membershipTypeID
1549 * @param bool $activeOnly
1550 * Do we only want active ones?
1551 * (probably this should default to TRUE but as a newly added parameter we are leaving default b
1552 * behaviour unchanged).
1556 public static function buildMembershipTypeValues(&$form, $membershipTypeID = array(), $activeOnly = FALSE) {
1557 $whereClause = " WHERE domain_id = " . CRM_Core_Config
::domainID();
1558 $membershipTypeIDS = (array) $membershipTypeID;
1561 $whereClause .= " AND is_active = 1 ";
1563 if (!empty($membershipTypeIDS)) {
1564 $allIDs = implode(',', $membershipTypeIDS);
1565 $whereClause .= " AND id IN ( $allIDs )";
1567 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes, CRM_Core_Action
::ADD
);
1569 if ($financialTypes) {
1570 $whereClause .= " AND financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1573 $whereClause .= " AND financial_type_id IN (0)";
1578 FROM civicrm_membership_type
1581 $dao = CRM_Core_DAO
::executeQuery($query);
1583 $membershipTypeValues = array();
1584 $membershipTypeFields = array(
1590 'financial_type_id',
1592 'member_of_contact_id',
1593 'relationship_type_id',
1594 'relationship_direction',
1597 'duration_interval',
1600 while ($dao->fetch()) {
1601 $membershipTypeValues[$dao->id
] = array();
1602 foreach ($membershipTypeFields as $mtField) {
1603 $membershipTypeValues[$dao->id
][$mtField] = $dao->$mtField;
1607 CRM_Utils_Hook
::membershipTypeValues($form, $membershipTypeValues);
1609 if (is_numeric($membershipTypeID) &&
1610 $membershipTypeID > 0
1612 return $membershipTypeValues[$membershipTypeID];
1615 return $membershipTypeValues;
1620 * Get membership record count for a Contact.
1622 * @param int $contactID
1623 * @param bool $activeOnly
1625 * @return null|string
1627 public static function getContactMembershipCount($contactID, $activeOnly = FALSE) {
1628 CRM_Financial_BAO_FinancialType
::getAvailableMembershipTypes($membershipTypes);
1629 $addWhere = " AND membership_type_id IN (0)";
1630 if (!empty($membershipTypes)) {
1631 $addWhere = " AND membership_type_id IN (" . implode(',', array_keys($membershipTypes)) . ")";
1633 $select = "SELECT count(*) FROM civicrm_membership ";
1634 $where = "WHERE civicrm_membership.contact_id = {$contactID} AND civicrm_membership.is_test = 0 ";
1636 // CRM-6627, all status below 3 (active, pending, grace) are considered active
1638 $select .= " INNER JOIN civicrm_membership_status ON civicrm_membership.status_id = civicrm_membership_status.id ";
1639 $where .= " and civicrm_membership_status.is_current_member = 1";
1642 $query = $select . $where . $addWhere;
1643 return CRM_Core_DAO
::singleValueQuery($query);
1647 * Check whether payment processor supports cancellation of membership subscription.
1652 * @param bool $isNotCancelled
1656 public static function isCancelSubscriptionSupported($mid, $isNotCancelled = TRUE) {
1657 $cacheKeyString = "$mid";
1658 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
1660 static $supportsCancel = array();
1662 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
1663 $supportsCancel[$cacheKeyString] = FALSE;
1664 $isCancelled = FALSE;
1666 if ($isNotCancelled) {
1667 $isCancelled = self
::isSubscriptionCancelled($mid);
1670 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($mid, 'membership', 'obj');
1671 if (!empty($paymentObject)) {
1672 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
1675 return $supportsCancel[$cacheKeyString];
1679 * Check whether subscription is already cancelled.
1685 * contribution status
1687 public static function isSubscriptionCancelled($mid) {
1689 SELECT cr.contribution_status_id
1690 FROM civicrm_contribution_recur cr
1691 LEFT JOIN civicrm_membership mem ON ( cr.id = mem.contribution_recur_id )
1692 WHERE mem.id = %1 LIMIT 1";
1693 $params = array(1 => array($mid, 'Integer'));
1694 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
1695 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
1696 if ($status == 'Cancelled') {
1703 * Get membership joins for a specified membership type.
1705 * Specifically, retrieves a count of still current memberships whose
1706 * join_date and start_date are within a specified date range. Dates match
1707 * the pattern "yyyy-mm-dd".
1709 * @param int $membershipTypeId
1710 * Membership type id.
1711 * @param int $startDate
1712 * Date on which to start counting.
1713 * @param int $endDate
1714 * Date on which to end counting.
1715 * @param bool|int $isTest if true, membership is for a test site
1718 * the number of members of type $membershipTypeId
1719 * whose join_date is between $startDate and $endDate and
1720 * whose start_date is between $startDate and $endDate
1722 public static function getMembershipJoins($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1723 $testClause = 'membership.is_test = 1';
1725 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1727 if (!self
::$_signupActType) {
1728 self
::_getActTypes();
1731 if (!self
::$_signupActType) {
1736 SELECT COUNT(DISTINCT membership.id) as member_count
1737 FROM civicrm_membership membership
1738 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1739 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1740 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1741 WHERE membership.membership_type_id = %2
1742 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1746 1 => array(self
::$_signupActType, 'Integer'),
1747 2 => array($membershipTypeId, 'Integer'),
1750 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1752 return (int) $memberCount;
1756 * Get membership renewals for a specified membership type.
1758 * Specifically, retrieves a count of still current memberships
1759 * whose join_date is before and start_date is within a specified date
1760 * range. Dates match the pattern "yyyy-mm-dd".
1762 * @param int $membershipTypeId
1763 * Membership type id.
1764 * @param int $startDate
1765 * Date on which to start counting.
1766 * @param int $endDate
1767 * Date on which to end counting.
1768 * @param bool|int $isTest if true, membership is for a test site
1771 * returns the number of members of type $membershipTypeId
1772 * whose join_date is before $startDate and
1773 * whose start_date is between $startDate and $endDate
1775 public static function getMembershipRenewals($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1776 $testClause = 'membership.is_test = 1';
1778 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1780 if (!self
::$_renewalActType) {
1781 self
::_getActTypes();
1784 if (!self
::$_renewalActType) {
1789 SELECT COUNT(DISTINCT membership.id) as member_count
1790 FROM civicrm_membership membership
1791 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1792 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1793 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1794 WHERE membership.membership_type_id = %2
1795 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1799 1 => array(self
::$_renewalActType, 'Integer'),
1800 2 => array($membershipTypeId, 'Integer'),
1802 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1804 return (int) $memberCount;
1808 * Create linkages between membership & contribution - note this is the wrong place for this code but this is a
1809 * refactoring step. This should be BAO functionality
1810 * @param $membership
1811 * @param $membershipContribution
1813 public static function linkMembershipPayment($membership, $membershipContribution) {
1814 CRM_Member_BAO_MembershipPayment
::create(array(
1815 'membership_id' => $membership->id
,
1816 'membership_type_id' => $membership->membership_type_id
,
1817 'contribution_id' => $membershipContribution->id
,
1822 * @param int $contactID
1823 * @param int $membershipTypeID
1824 * @param bool $is_test
1825 * @param string $changeToday
1826 * @param int $modifiedID
1827 * @param $customFieldsFormatted
1828 * @param $numRenewTerms
1829 * @param int $membershipID
1831 * @param int $contributionRecurID
1832 * @param $membershipSource
1833 * @param $isPayLater
1834 * @param int $campaignId
1835 * @param array $formDates
1836 * @param null|CRM_Contribute_BAO_Contribution $contribution
1837 * @param array $lineItems
1840 * @throws \CRM_Core_Exception
1842 public static function processMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $contributionRecurID, $membershipSource, $isPayLater, $campaignId, $formDates = array(), $contribution = NULL, $lineItems = array()) {
1843 $renewalMode = $updateStatusId = FALSE;
1844 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1846 $statusFormat = '%Y-%m-%d';
1847 $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'], array(
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;
1883 $membership = self
::create($memParams, $ids, FALSE);
1884 return array($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 (array('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
1943 $memParams = array();
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 (array('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 $membership = self
::create($memParams, $ids, FALSE);
2058 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
2059 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
2060 $membership->find(TRUE);
2062 return array($membership, $renewalMode, $dates);
2066 * Get line items representing the default price set.
2068 * @param int $membershipOrg
2069 * @param int $membershipTypeID
2070 * @param float $total_amount
2071 * @param int $priceSetId
2075 public static function setQuickConfigMembershipParameters($membershipOrg, $membershipTypeID, $total_amount, $priceSetId) {
2076 $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
2078 // The name of the price field corresponds to the membership_type organization contact.
2080 'price_set_id' => $priceSetId,
2081 'name' => $membershipOrg,
2084 CRM_Price_BAO_PriceField
::retrieve($params, $results);
2086 if (!empty($results)) {
2087 $fields[$results['id']] = $priceSets['fields'][$results['id']];
2088 $fid = $results['id'];
2089 $editedFieldParams = array(
2090 'price_field_id' => $results['id'],
2091 'membership_type_id' => $membershipTypeID,
2094 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $results);
2095 $fields[$fid]['options'][$results['id']] = $priceSets['fields'][$fid]['options'][$results['id']];
2096 if (!empty($total_amount)) {
2097 $fields[$fid]['options'][$results['id']]['amount'] = $total_amount;
2101 $fieldID = key($fields);
2102 $returnParams = array(
2103 'price_set_id' => $priceSetId,
2104 'price_sets' => $priceSets,
2105 'fields' => $fields,
2106 'price_fields' => array(
2107 'price_' . $fieldID => CRM_Utils_Array
::value('id', $results),
2110 return $returnParams;
2114 * Update the status of all deceased members to deceased.
2117 * Count of updated contacts.
2119 protected static function updateDeceasedMembersStatuses() {
2122 $deceasedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Deceased');
2124 // 'create' context for buildOptions returns only if enabled.
2125 $allStatus = self
::buildOptions('status_id', 'create');
2126 if (array_key_exists($deceasedStatusId, $allStatus) === FALSE) {
2127 // Deceased status is an admin status & is required. We want to fail early if
2128 // it is not present or active.
2129 // We could make the case 'some databases just don't use deceased so we will check
2130 // for the presence of a deceased contact in the DB before rejecting.
2131 if (CRM_Core_DAO
::singleValueQuery('
2132 SELECT count(*) FROM civicrm_contact WHERE is_deceased = 0'
2134 throw new CRM_Core_Exception(
2135 ts("Deceased Membership status is missing or not active. <a href='%1'>Click here to check</a>.",
2136 [1 => CRM_Utils_System
::url('civicrm/admin/member/membershipStatus', 'reset=1')]
2140 $deceasedDAO = CRM_Core_DAO
::executeQuery(
2142 SELECT membership.id as membership_id
2143 FROM civicrm_membership membership
2144 INNER JOIN civicrm_contact ON membership.contact_id = civicrm_contact.id
2145 INNER JOIN civicrm_membership_type ON membership.membership_type_id = civicrm_membership_type.id
2146 AND civicrm_membership_type.is_active = 1
2147 WHERE membership.is_test = 0
2148 AND civicrm_contact.is_deceased = 1
2149 AND membership.status_id <> %1
2151 [1 => [$deceasedStatusId, 'Integer']]
2153 while ($deceasedDAO->fetch()) {
2154 civicrm_api3('membership', 'create', [
2155 'id' => $deceasedDAO->membership_id
,
2156 'status_id' => $deceasedStatusId,
2157 'createActivity' => TRUE,
2158 'skipStatusCal' => TRUE,
2159 'skipRecentView' => TRUE,
2167 * Process price set and line items.
2169 * @param int $membershipId
2170 * @param array $lineItem
2172 public function processPriceSet($membershipId, $lineItem) {
2173 //FIXME : need to move this too
2174 if (!$membershipId ||
!is_array($lineItem)
2175 || CRM_Utils_System
::isNull($lineItem)
2180 foreach ($lineItem as $priceSetId => $values) {
2184 foreach ($values as $line) {
2185 $line['entity_table'] = 'civicrm_membership';
2186 $line['entity_id'] = $membershipId;
2187 CRM_Price_BAO_LineItem
::create($line);
2193 * Retrieve the contribution id for the associated Membership id.
2194 * @todo we should get this off the line item
2196 * @param int $membershipId
2199 * if more than one payment associated with membership id need to be returned.
2204 public static function getMembershipContributionId($membershipId, $all = FALSE) {
2206 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
2207 $membershipPayment->membership_id
= $membershipId;
2208 if ($all && $membershipPayment->find()) {
2209 $contributionIds = array();
2210 while ($membershipPayment->fetch()) {
2211 $contributionIds[] = $membershipPayment->contribution_id
;
2213 return $contributionIds;
2216 if ($membershipPayment->find(TRUE)) {
2217 return $membershipPayment->contribution_id
;
2223 * The function checks and updates the status of all membership records for a given domain using the
2224 * calc_membership_status and update_contact_membership APIs.
2227 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
2231 public static function updateAllMembershipStatus() {
2232 // Tests for this function are in api_v3_JobTest. Please add tests for all updates.
2234 $updateCount = $processCount = self
::updateDeceasedMembersStatuses();
2236 // We want all of the statuses as id => name, even the disabled ones (cf.
2237 // CRM-15475), to identify which are Pending, Deceased, Cancelled, and
2239 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'validate');
2240 $allTypes = CRM_Member_PseudoConstant
::membershipType();
2242 // This query retrieves ALL memberships of active types.
2244 SELECT civicrm_membership.id as membership_id,
2245 civicrm_membership.is_override as is_override,
2246 civicrm_membership.status_override_end_date as status_override_end_date,
2247 civicrm_membership.membership_type_id as membership_type_id,
2248 civicrm_membership.status_id as status_id,
2249 civicrm_membership.join_date as join_date,
2250 civicrm_membership.start_date as start_date,
2251 civicrm_membership.end_date as end_date,
2252 civicrm_membership.source as source,
2253 civicrm_contact.id as contact_id,
2254 civicrm_membership.owner_membership_id as owner_membership_id,
2255 civicrm_membership.contribution_recur_id as recur_id
2256 FROM civicrm_membership
2257 INNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )
2258 INNER JOIN civicrm_membership_type ON
2259 (civicrm_membership.membership_type_id = civicrm_membership_type.id AND civicrm_membership_type.is_active = 1)
2260 WHERE civicrm_membership.is_test = 0
2261 AND civicrm_contact.is_deceased = 0 ";
2263 $deceaseStatusId = array_search('Deceased', $allStatus);
2264 $pendingStatusId = array_search('Pending', $allStatus);
2265 $cancelledStatusId = array_search('Cancelled', $allStatus);
2266 // Expired is not reserved so might not exist. A value of `0` won't break.
2267 $expiredStatusId = array_search('Expired', $allStatus) ?
: 0;
2269 $query = $baseQuery . " AND civicrm_membership.is_override IS NOT NULL AND civicrm_membership.status_override_end_date IS NOT NULL";
2270 $dao1 = CRM_Core_DAO
::executeQuery($query);
2271 while ($dao1->fetch()) {
2272 self
::processOverriddenUntilDateMembership($dao1);
2275 $query = $baseQuery . " AND (civicrm_membership.is_override = 0 OR civicrm_membership.is_override IS NULL)
2276 AND civicrm_membership.status_id NOT IN (%1, %2, %3, %4)
2277 AND civicrm_membership.owner_membership_id IS NULL ";
2279 1 => array($pendingStatusId, 'Integer'),
2280 2 => array($cancelledStatusId, 'Integer'),
2281 3 => array($expiredStatusId, 'Integer'),
2282 4 => array($deceaseStatusId, 'Integer'),
2284 $dao2 = CRM_Core_DAO
::executeQuery($query, $params);
2286 while ($dao2->fetch()) {
2290 // Put common parameters into array for easy access
2291 $memberParams = array(
2292 'id' => $dao2->membership_id
,
2293 'status_id' => $dao2->status_id
,
2294 'contact_id' => $dao2->contact_id
,
2295 'membership_type_id' => $dao2->membership_type_id
,
2296 'membership_type' => $allTypes[$dao2->membership_type_id
],
2297 'join_date' => $dao2->join_date
,
2298 'start_date' => $dao2->start_date
,
2299 'end_date' => $dao2->end_date
,
2300 'source' => $dao2->source
,
2301 'skipStatusCal' => TRUE,
2302 'skipRecentView' => TRUE,
2305 // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses
2306 //get the membership status as per id.
2307 $newStatus = civicrm_api('membership_status', 'calc',
2309 'membership_id' => $dao2->membership_id
,
2311 'ignore_admin_only' => TRUE,
2314 $statusId = CRM_Utils_Array
::value('id', $newStatus);
2316 //process only when status change.
2318 $statusId != $dao2->status_id
2320 //take all params that need to save.
2321 $memParams = $memberParams;
2322 $memParams['status_id'] = $statusId;
2323 $memParams['createActivity'] = TRUE;
2324 $memParams['version'] = 3;
2326 // Unset columns which should remain unchanged from their current saved
2327 // values. This avoids race condition in which these values may have
2328 // been changed by other processes.
2330 $memParams['contact_id'],
2331 $memParams['membership_type_id'],
2332 $memParams['membership_type'],
2333 $memParams['join_date'],
2334 $memParams['start_date'],
2335 $memParams['end_date'],
2336 $memParams['source']
2338 //since there is change in status.
2340 //process member record.
2341 civicrm_api('membership', 'create', $memParams);
2345 $result['is_error'] = 0;
2346 $result['messages'] = ts('Processed %1 membership records. Updated %2 records.', array(
2354 * Set is_override for the 'overridden until date' membership to
2355 * False and clears the 'until date' field in case the 'until date'
2356 * is equal or after today date.
2358 * @param CRM_Core_DAO $membership
2359 * The membership to be processed
2361 private static function processOverriddenUntilDateMembership($membership) {
2362 $isOverriddenUntilDate = !empty($membership->is_override
) && !empty($membership->status_override_end_date
);
2363 if (!$isOverriddenUntilDate) {
2367 $todayDate = new DateTime();
2368 $todayDate->setTime(0, 0);
2370 $overrideEndDate = new DateTime($membership->status_override_end_date
);
2371 $overrideEndDate->setTime(0, 0);
2373 $datesDifference = $todayDate->diff($overrideEndDate);
2374 $daysDifference = (int) $datesDifference->format('%R%a');
2375 if ($daysDifference <= 0) {
2377 'id' => $membership->membership_id
,
2378 'is_override' => FALSE,
2379 'status_override_end_date' => 'null',
2381 civicrm_api3('membership', 'create', $params);
2386 * Returns the membership types for a particular contact
2387 * who has lifetime membership without end date.
2389 * @param int $contactID
2390 * @param bool $isTest
2391 * @param bool $onlyLifeTime
2395 public static function getAllContactMembership($contactID, $isTest = FALSE, $onlyLifeTime = FALSE) {
2396 $contactMembershipType = array();
2398 return $contactMembershipType;
2401 $dao = new CRM_Member_DAO_Membership();
2402 $dao->contact_id
= $contactID;
2403 $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
2404 $dao->whereAdd("status_id != $pendingStatusId");
2407 $dao->is_test
= $isTest;
2410 $dao->whereAdd('is_test IS NULL OR is_test = 0');
2413 if ($onlyLifeTime) {
2414 $dao->whereAdd('end_date IS NULL');
2418 while ($dao->fetch()) {
2419 $membership = array();
2420 CRM_Core_DAO
::storeValues($dao, $membership);
2421 $contactMembershipType[$dao->membership_type_id
] = $membership;
2423 return $contactMembershipType;
2427 * Record contribution record associated with membership.
2429 * @param array $params
2430 * Array of submitted params.
2432 * (param in process of being removed - try to use params) array of ids.
2434 * @return CRM_Contribute_BAO_Contribution
2436 public static function recordMembershipContribution(&$params, $ids = array()) {
2437 $membershipId = $params['membership_id'];
2438 $contributionParams = array();
2439 $config = CRM_Core_Config
::singleton();
2440 $contributionParams['currency'] = $config->defaultCurrency
;
2441 $contributionParams['receipt_date'] = (CRM_Utils_Array
::value('receipt_date', $params)) ?
$params['receipt_date'] : 'null';
2442 $contributionParams['source'] = CRM_Utils_Array
::value('contribution_source', $params);
2443 $contributionParams['non_deductible_amount'] = 'null';
2444 $contributionParams['skipCleanMoney'] = TRUE;
2445 $contributionParams['payment_processor'] = CRM_Utils_Array
::value('payment_processor_id', $params);
2446 $contributionSoftParams = CRM_Utils_Array
::value('soft_credit', $params);
2447 $recordContribution = array(
2452 'financial_type_id',
2453 'payment_instrument_id',
2457 'contribution_status_id',
2464 'contribution_recur_id',
2468 foreach ($recordContribution as $f) {
2469 $contributionParams[$f] = CRM_Utils_Array
::value($f, $params);
2472 // make entry in batch entity batch table
2473 if (!empty($params['batch_id'])) {
2474 $contributionParams['batch_id'] = $params['batch_id'];
2477 if (!empty($params['contribution_contact_id'])) {
2478 // deal with possibility of a different person paying for contribution
2479 $contributionParams['contact_id'] = $params['contribution_contact_id'];
2482 if (!empty($params['processPriceSet']) &&
2483 !empty($params['lineItems'])
2485 $contributionParams['line_item'] = CRM_Utils_Array
::value('lineItems', $params, NULL);
2488 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
2490 //CRM-13981, create new soft-credit record as to record payment from different person for this membership
2491 if (!empty($contributionSoftParams)) {
2492 if (!empty($params['batch_id'])) {
2493 foreach ($contributionSoftParams as $contributionSoft) {
2494 $contributionSoft['contribution_id'] = $contribution->id
;
2495 $contributionSoft['currency'] = $contribution->currency
;
2496 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoft);
2500 $contributionSoftParams['contribution_id'] = $contribution->id
;
2501 $contributionSoftParams['currency'] = $contribution->currency
;
2502 $contributionSoftParams['amount'] = $contribution->total_amount
;
2503 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoftParams);
2507 // store contribution id
2508 $params['contribution_id'] = $contribution->id
;
2510 //insert payment record for this membership
2511 if (empty($ids['contribution']) ||
!empty($params['is_recur'])) {
2512 CRM_Member_BAO_MembershipPayment
::create(array(
2513 'membership_id' => $membershipId,
2514 'contribution_id' => $contribution->id
,
2517 return $contribution;
2521 * @todo document me - I seem a bit out of date....
2523 public static function _getActTypes() {
2524 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2525 self
::$_renewalActType = CRM_Utils_Array
::key('Membership Renewal', $activityTypes);
2526 self
::$_signupActType = CRM_Utils_Array
::key('Membership Signup', $activityTypes);
2530 * Get all Cancelled Membership(s) for a contact
2532 * @param int $contactID
2534 * @param bool $isTest
2538 * Array of membership type
2540 public static function getContactsCancelledMembership($contactID, $isTest = FALSE) {
2544 $query = 'SELECT membership_type_id FROM civicrm_membership WHERE contact_id = %1 AND status_id = %2 AND is_test = %3';
2545 $queryParams = array(
2546 1 => array($contactID, 'Integer'),
2551 CRM_Member_PseudoConstant
::membershipStatus(
2553 " name = 'Cancelled' ",
2561 3 => array($isTest, 'Boolean'),
2564 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
2565 $cancelledMembershipIds = array();
2566 while ($dao->fetch()) {
2567 $cancelledMembershipIds[] = $dao->membership_type_id
;
2569 return $cancelledMembershipIds;
2573 * Merges the memberships from otherContactID to mainContactID.
2575 * General idea is to merge memberships in regards to their type. We
2576 * move the other contact’s contributions to the main contact’s
2577 * membership which has the same type (if any) and then we update
2578 * membership to avoid loosing `join_date`, `end_date`, and
2579 * `status_id`. In this function, we don’t touch the contributions
2580 * directly (CRM_Dedupe_Merger::moveContactBelongings() takes care
2583 * This function adds new SQL queries to the $sqlQueries parameter.
2585 * @param int $mainContactID
2586 * Contact id of main contact record.
2587 * @param int $otherContactID
2588 * Contact id of record which is going to merge.
2589 * @param array $sqlQueries
2590 * (reference) array of SQL queries to be executed.
2591 * @param array $tables
2592 * List of tables that have to be merged.
2593 * @param array $tableOperations
2594 * Special options/params for some tables to be merged.
2596 * @see CRM_Dedupe_Merger::cpTables()
2598 public static function mergeMemberships($mainContactID, $otherContactID, &$sqlQueries, $tables, $tableOperations) {
2600 * If the user requests not to merge memberships but to add them,
2601 * just attribute the `civicrm_membership` to the
2602 * `$mainContactID`. We have to do this here since the general
2603 * merge process is bypassed by this function.
2605 if (array_key_exists("civicrm_membership", $tableOperations) && $tableOperations['civicrm_membership']['add']) {
2606 $sqlQueries[] = "UPDATE IGNORE civicrm_membership SET contact_id = $mainContactID WHERE contact_id = $otherContactID";
2611 * Retrieve all memberships that belongs to each contacts and
2612 * keep track of each membership type.
2614 $mainContactMemberships = array();
2615 $otherContactMemberships = array();
2617 $sql = "SELECT id, membership_type_id FROM civicrm_membership membership WHERE contact_id = %1";
2618 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($mainContactID, "Integer")));
2619 while ($dao->fetch()) {
2620 $mainContactMemberships[$dao->id
] = $dao->membership_type_id
;
2623 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($otherContactID, "Integer")));
2624 while ($dao->fetch()) {
2625 $otherContactMemberships[$dao->id
] = $dao->membership_type_id
;
2629 * For each membership, move related contributions to the main
2630 * contact’s membership (by updating `membership_payments`). Then,
2631 * update membership’s `join_date` (if the other membership’s
2632 * join_date is older) and `end_date` (if the other membership’s
2633 * `end_date` is newer) and `status_id` (if the newly calculated
2634 * status is different).
2636 * FIXME: what should we do if we have multiple memberships with
2637 * the same type (currently we only take the first one)?
2640 foreach ($otherContactMemberships as $otherMembershipId => $otherMembershipTypeId) {
2641 if ($newMembershipId = array_search($otherMembershipTypeId, $mainContactMemberships)) {
2644 * Move other membership’s contributions to the main one only
2645 * if user requested to merge contributions.
2647 if (!empty($tables) && in_array('civicrm_contribution', $tables)) {
2648 $newSql[] = "UPDATE civicrm_membership_payment SET membership_id=$newMembershipId WHERE membership_id=$otherMembershipId";
2651 $sql = "SELECT * FROM civicrm_membership membership WHERE id = %1";
2653 $newMembership = CRM_Member_DAO_Membership
::findById($newMembershipId);
2654 $otherMembership = CRM_Member_DAO_Membership
::findById($otherMembershipId);
2657 if (new DateTime($otherMembership->join_date
) < new DateTime($newMembership->join_date
)) {
2658 $updates["join_date"] = $otherMembership->join_date
;
2661 if (new DateTime($otherMembership->end_date
) > new DateTime($newMembership->end_date
)) {
2662 $updates["end_date"] = $otherMembership->end_date
;
2665 if (count($updates)) {
2670 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
2671 isset($updates["start_date"]) ?
$updates["start_date"] : $newMembership->start_date
,
2672 isset($updates["end_date"]) ?
$updates["end_date"] : $newMembership->end_date
,
2673 isset($updates["join_date"]) ?
$updates["join_date"] : $newMembership->join_date
,
2680 if (!empty($status['id']) and $status['id'] != $newMembership->status_id
) {
2681 $updates['status_id'] = $status['id'];
2685 foreach ($updates as $k => $v) {
2686 $updates_sql[] = "$k = '{$v}'";
2689 $newSql[] = sprintf("UPDATE civicrm_membership SET %s WHERE id=%s", implode(", ", $updates_sql), $newMembershipId);
2690 $newSql[] = sprintf("DELETE FROM civicrm_membership WHERE id=%s", $otherMembershipId);
2696 $sqlQueries = array_merge($sqlQueries, $newSql);