3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
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 static $_importableFields = NULL;
42 static $_renewalActType = NULL;
44 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;
99 if (empty($membership->contact_id
) ||
empty($membership->status_id
)) {
100 // this means we are in renewal mode and are just updating the membership
101 // record or this is an API update call and all fields are not present in the update record
102 // however the hooks don't care and want all data CRM-7784
103 $tempMembership = new CRM_Member_DAO_Membership();
104 $tempMembership->id
= $membership->id
;
105 $tempMembership->find(TRUE);
106 $membership = $tempMembership;
109 //get the log start date.
110 //it is set during renewal of membership.
111 $logStartDate = CRM_Utils_Array
::value('log_start_date', $params);
112 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : CRM_Utils_Date
::isoToMysql($membership->start_date
);
113 $values = self
::getStatusANDTypeValues($membership->id
);
115 $membershipLog = array(
116 'membership_id' => $membership->id
,
117 'status_id' => $membership->status_id
,
118 'start_date' => $logStartDate,
119 'end_date' => CRM_Utils_Date
::isoToMysql($membership->end_date
),
120 'modified_date' => date('Ymd'),
121 'membership_type_id' => $values[$membership->id
]['membership_type_id'],
122 'max_related' => $membership->max_related
,
125 $session = CRM_Core_Session
::singleton();
126 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
127 if ($session->get('userID')) {
128 $membershipLog['modified_id'] = $session->get('userID');
130 elseif (!empty($ids['userId'])) {
131 $membershipLog['modified_id'] = $ids['userId'];
134 $membershipLog['modified_id'] = $membership->contact_id
;
137 CRM_Member_BAO_MembershipLog
::add($membershipLog);
139 // reset the group contact cache since smart groups might be affected due to this
140 CRM_Contact_BAO_GroupContactCache
::opportunisticCacheFlush();
142 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
143 $activityParams = array(
144 'status_id' => CRM_Utils_Array
::value('membership_activity_status', $params, 'Completed'),
146 if (in_array($allStatus[$membership->status_id
], array('Pending', 'Grace'))) {
147 $activityParams['status_id'] = 'Scheduled';
149 $activityParams['status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_status_id', $activityParams['status_id']);
151 $targetContactID = $membership->contact_id
;
152 if (!empty($params['is_for_organization'])) {
153 $targetContactID = CRM_Utils_Array
::value('userId', $ids);
156 if ($membership->status_id
!= $oldStatus) {
157 CRM_Activity_BAO_Activity
::addActivity($membership,
158 'Change Membership Status',
161 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
162 'source_contact_id' => $membershipLog['modified_id'],
163 'priority_id' => 'Normal',
167 if (isset($membership->membership_type_id
) && $membership->membership_type_id
!= $oldType) {
168 $membershipTypes = CRM_Member_BAO_Membership
::buildOptions('membership_type_id', 'get');
169 CRM_Activity_BAO_Activity
::addActivity($membership,
170 'Change Membership Type',
173 'subject' => "Type changed from {$membershipTypes[$oldType]} to {$membershipTypes[$membership->membership_type_id]}",
174 'source_contact_id' => $membershipLog['modified_id'],
175 'priority_id' => 'Normal',
180 foreach (array('Membership Signup', 'Membership Renewal') as $activityType) {
181 $activityParams['id'] = CRM_Utils_Array
::value('id',
182 civicrm_api3('Activity', 'Get',
184 'source_record_id' => $membership->id
,
185 'activity_type_id' => $activityType,
186 'status_id' => 'Scheduled',
190 // 1. Update Schedule Membership Signup/Renwal activity to completed on successful payment of pending membership
191 // 2. OR Create renewal activity scheduled if its membership renewal will be paid later
192 if (!empty($params['membership_activity_status']) && (!empty($activityParams['id']) ||
$activityType == 'Membership Renewal')) {
193 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $targetContactID, $activityParams);
198 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
201 CRM_Activity_BAO_Activity
::addActivity($membership, 'Membership Signup', $targetContactID, $activityParams);
202 CRM_Utils_Hook
::post('create', 'Membership', $membership->id
, $membership);
209 * Fetch the object and store the values in the values array.
211 * @param array $params
212 * Input parameters to find object.
213 * @param array $values
214 * Output values of the object.
215 * @param bool $active
216 * Do you want only active memberships to.
218 * @param bool $relatedMemberships
220 * @return CRM_Member_BAO_Membership|null
221 * The found object or null
223 public static function &getValues(&$params, &$values, $active = FALSE, $relatedMemberships = FALSE) {
224 if (empty($params)) {
227 $membership = new CRM_Member_BAO_Membership();
229 $membership->copyValues($params);
231 $memberships = array();
232 while ($membership->fetch()) {
234 (!CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
235 $membership->status_id
,
242 CRM_Core_DAO
::storeValues($membership, $values[$membership->id
]);
243 $memberships[$membership->id
] = $membership;
244 if ($relatedMemberships && !empty($membership->owner_membership_id
)) {
245 $values['owner_membership_ids'][] = $membership->owner_membership_id
;
253 * Takes an associative array and creates a membership object.
255 * @param array $params
256 * (reference ) an assoc array of name/value pairs.
258 * Deprecated parameter The array that holds all the db ids.
259 * @param bool $skipRedirect
261 * @throws CRM_Core_Exception
263 * @return CRM_Member_BAO_Membership|CRM_Core_Error
265 public static function create(&$params, &$ids, $skipRedirect = FALSE) {
266 // always calculate status if is_override/skipStatusCal is not true.
267 // giving respect to is_override during import. CRM-4012
269 // To skip status calculation we should use 'skipStatusCal'.
270 // eg pay later membership, membership update cron CRM-3984
272 if (empty($params['is_override']) && empty($params['skipStatusCal'])) {
273 $dates = array('start_date', 'end_date', 'join_date');
274 // Declare these out of courtesy as IDEs don't pick up the setting of them below.
275 $start_date = $end_date = $join_date = NULL;
276 foreach ($dates as $date) {
277 $
$date = $params[$date] = CRM_Utils_Date
::processDate(CRM_Utils_Array
::value($date, $params), NULL, TRUE, 'Ymd');
280 //fix for CRM-3570, during import exclude the statuses those having is_admin = 1
281 $excludeIsAdmin = CRM_Utils_Array
::value('exclude_is_admin', $params, FALSE);
283 //CRM-3724 always skip is_admin if is_override != true.
284 if (!$excludeIsAdmin && empty($params['is_override'])) {
285 $excludeIsAdmin = TRUE;
288 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($start_date, $end_date, $join_date,
289 'today', $excludeIsAdmin, CRM_Utils_Array
::value('membership_type_id', $params), $params
291 if (empty($calcStatus)) {
292 // Redirect the form in case of error
293 // @todo this redirect in the BAO layer is really bad & should be moved to the form layer
294 // however since we have no idea how (if) this is triggered we can't safely move / remove it
295 // NB I tried really hard to trigger this error from backoffice membership form in order to test it
296 // and am convinced form validation is complete on that form WRT this error.
297 $errorParams = array(
298 'message_title' => ts('No valid membership status for given dates.'),
299 'legacy_redirect_path' => 'civicrm/contact/view',
300 'legacy_redirect_query' => "reset=1&force=1&cid={$params['contact_id']}&selectedChild=member",
302 throw new CRM_Core_Exception(ts(
303 "The membership cannot be saved because the status cannot be calculated for start_date: $start_date end_date $end_date join_date $join_date as at " . date('Y-m-d H:i:s')),
308 $params['status_id'] = $calcStatus['id'];
311 // data cleanup only: all verifications on number of related memberships are done upstream in:
312 // CRM_Member_BAO_Membership::createRelatedMemberships()
313 // CRM_Contact_BAO_Relationship::relatedMemberships()
314 if (!empty($params['owner_membership_id'])) {
315 unset($params['max_related']);
318 // if membership allows related, default max_related to value in membership_type
319 if (!array_key_exists('max_related', $params) && !empty($params['membership_type_id'])) {
320 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($params['membership_type_id']);
321 if (isset($membershipType['relationship_type_id'])) {
322 $params['max_related'] = CRM_Utils_Array
::value('max_related', $membershipType);
327 $transaction = new CRM_Core_Transaction();
329 $membership = self
::add($params, $ids);
331 if (is_a($membership, 'CRM_Core_Error')) {
332 $transaction->rollback();
336 // add custom field values
337 if (!empty($params['custom']) && is_array($params['custom'])
339 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_membership', $membership->id
);
342 $params['membership_id'] = $membership->id
;
343 if (isset($ids['membership'])) {
344 $ids['contribution'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment',
351 // This code ensures a line item is created but it is recomended you pass in 'skipLineItem' or 'line_item'
352 if (empty($params['line_item']) && !empty($params['membership_type_id']) && empty($params['skipLineItem'])) {
353 CRM_Price_BAO_LineItem
::getLineItemArray($params, NULL, 'membership', $params['membership_type_id']);
355 $params['skipLineItem'] = TRUE;
357 //record contribution for this membership
358 if (!empty($params['contribution_status_id']) && empty($params['relate_contribution_id'])) {
359 $memInfo = array_merge($params, array('membership_id' => $membership->id
));
360 $params['contribution'] = self
::recordMembershipContribution($memInfo, $ids);
363 if (!empty($params['lineItems'])) {
364 $params['line_item'] = $params['lineItems'];
367 //do cleanup line items if membership edit the Membership type.
368 if (empty($ids['contribution']) && !empty($ids['membership'])) {
369 CRM_Price_BAO_LineItem
::deleteLineItems($ids['membership'], 'civicrm_membership');
372 // This could happen if there is no contribution or we are in one of many
373 // weird and wonderful flows. This is scary code. Keep adding tests.
374 if (!empty($params['line_item']) && empty($ids['contribution'])) {
376 foreach ($params['line_item'] as $priceSetId => $lineItems) {
377 foreach ($lineItems as $lineIndex => $lineItem) {
378 $lineMembershipType = CRM_Utils_Array
::value('membership_type_id', $lineItem);
379 if (CRM_Utils_Array
::value('contribution', $params)) {
380 $params['line_item'][$priceSetId][$lineIndex]['contribution_id'] = $params['contribution']->id
;
382 if ($lineMembershipType && $lineMembershipType == CRM_Utils_Array
::value('membership_type_id', $params)) {
383 $params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $membership->id
;
384 $params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_membership';
386 elseif (!$lineMembershipType && CRM_Utils_Array
::value('contribution', $params)) {
387 $params['line_item'][$priceSetId][$lineIndex]['entity_id'] = $params['contribution']->id
;
388 $params['line_item'][$priceSetId][$lineIndex]['entity_table'] = 'civicrm_contribution';
392 CRM_Price_BAO_LineItem
::processPriceSet(
394 $params['line_item'],
395 CRM_Utils_Array
::value('contribution', $params)
399 //insert payment record for this membership
400 if (!empty($params['relate_contribution_id'])) {
401 CRM_Member_BAO_MembershipPayment
::create(array(
402 'membership_id' => $membership->id
,
403 'membership_type_id' => $membership->membership_type_id
,
404 'contribution_id' => $params['relate_contribution_id'],
408 $transaction->commit();
410 self
::createRelatedMemberships($params, $membership);
412 // do not add to recent items for import, CRM-4399
413 if (empty($params['skipRecentView'])) {
414 $url = CRM_Utils_System
::url('civicrm/contact/view/membership',
415 "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
417 if (empty($membership->membership_type_id
)) {
418 // ie in an update situation.
419 $membership->find(TRUE);
421 $membershipTypes = CRM_Member_PseudoConstant
::membershipType();
422 $title = CRM_Contact_BAO_Contact
::displayName($membership->contact_id
) . ' - ' . ts('Membership Type:') . ' ' . $membershipTypes[$membership->membership_type_id
];
424 $recentOther = array();
425 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::UPDATE
)) {
426 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
427 "action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
430 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::DELETE
)) {
431 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
432 "action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
436 // add the recently created Membership
437 CRM_Utils_Recent
::add($title,
441 $membership->contact_id
,
451 * Check the membership extended through relationship.
453 * @param int $membershipTypeID
454 * Membership type id.
455 * @param int $contactId
461 * array of contact_id of all related contacts.
463 public static function checkMembershipRelationship($membershipTypeID, $contactId, $action = CRM_Core_Action
::ADD
) {
466 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipTypeID);
467 $relationships = array();
468 if (isset($membershipType['relationship_type_id'])) {
469 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
470 CRM_Contact_BAO_Relationship
::CURRENT
472 if ($action & CRM_Core_Action
::UPDATE
) {
473 $pastRelationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
474 CRM_Contact_BAO_Relationship
::PAST
476 $relationships = array_merge($relationships, $pastRelationships);
480 if (!empty($relationships)) {
481 // check for each contact relationships
482 foreach ($relationships as $values) {
483 //get details of the relationship type
484 $relType = array('id' => $values['civicrm_relationship_type_id']);
485 $relValues = array();
486 CRM_Contact_BAO_RelationshipType
::retrieve($relType, $relValues);
487 // Check if contact's relationship type exists in membership type
488 $relTypeDirs = array();
489 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_type_id']);
490 $relDirections = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_direction']);
491 $bidirectional = FALSE;
492 foreach ($relTypeIds as $key => $value) {
493 $relTypeDirs[] = $value . '_' . $relDirections[$key];
494 if (in_array($value, $relType) &&
495 $relValues['name_a_b'] == $relValues['name_b_a']
497 $bidirectional = TRUE;
501 $relTypeDir = $values['civicrm_relationship_type_id'] . '_' . $values['rtype'];
502 if ($bidirectional ||
in_array($relTypeDir, $relTypeDirs)) {
503 // $values['status'] is going to have value for
504 // current or past relationships.
505 $contacts[$values['cid']] = $values['status'];
510 // Sort by contact_id ascending
516 * Retrieve DB object based on input parameters.
518 * It also stores all the retrieved values in the default array.
520 * @param array $params
521 * (reference ) an assoc array of name/value pairs.
522 * @param array $defaults
523 * (reference ) an assoc array to hold the name / value pairs.
524 * in a hierarchical manner
526 * @return CRM_Member_BAO_Membership
528 public static function retrieve(&$params, &$defaults) {
529 $membership = new CRM_Member_DAO_Membership();
531 $membership->copyValues($params);
533 if ($membership->find(TRUE)) {
534 CRM_Core_DAO
::storeValues($membership, $defaults);
536 //get the membership status and type values.
537 $statusANDType = self
::getStatusANDTypeValues($membership->id
);
542 $defaults[$fld] = CRM_Utils_Array
::value($fld, $statusANDType[$membership->id
]);
544 if (!empty($statusANDType[$membership->id
]['is_current_member'])) {
545 $defaults['active'] = TRUE;
557 * Get membership status and membership type values.
559 * @param int $membershipId
560 * Membership id of values to return.
563 * Array of key value pairs
565 public static function getStatusANDTypeValues($membershipId) {
567 if (!$membershipId) {
571 SELECT membership.id as id,
572 status.id as status_id,
573 status.label as status,
574 status.is_current_member as is_current_member,
575 type.id as membership_type_id,
576 type.name as membership_type,
577 type.relationship_type_id as relationship_type_id
578 FROM civicrm_membership membership
579 INNER JOIN civicrm_membership_status status ON ( status.id = membership.status_id )
580 INNER JOIN civicrm_membership_type type ON ( type.id = membership.membership_type_id )
581 WHERE membership.id = %1';
582 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($membershipId, 'Positive')));
587 'membership_type_id',
589 'relationship_type_id',
591 while ($dao->fetch()) {
592 foreach ($properties as $property) {
593 $values[$dao->id
][$property] = $dao->$property;
603 * Wrapper for most delete calls. Use this unless you JUST want to delete related memberships w/o deleting the parent.
605 * @param int $membershipId
606 * Membership id that needs to be deleted.
609 * Id of deleted Membership on success, false otherwise.
611 public static function del($membershipId, $preserveContrib = FALSE) {
612 //delete related first and then delete parent.
613 self
::deleteRelatedMemberships($membershipId);
614 return self
::deleteMembership($membershipId, $preserveContrib);
620 * @param int $membershipId
621 * Membership id that needs to be deleted.
624 * Id of deleted Membership on success, false otherwise.
626 public static function deleteMembership($membershipId, $preserveContrib = FALSE) {
627 // CRM-12147, retrieve membership data before we delete it for hooks
628 $params = array('id' => $membershipId);
629 $memValues = array();
630 $memberships = self
::getValues($params, $memValues);
632 $membership = $memberships[$membershipId];
634 CRM_Utils_Hook
::pre('delete', 'Membership', $membershipId, $memValues);
636 $transaction = new CRM_Core_Transaction();
639 //delete activity record
640 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
643 $deleteActivity = FALSE;
644 $membershipActivities = array(
646 'Membership Renewal',
647 'Change Membership Status',
648 'Change Membership Type',
649 'Membership Renewal Reminder',
651 foreach ($membershipActivities as $membershipActivity) {
652 $activityId = array_search($membershipActivity, $activityTypes);
654 $params['activity_type_id'][] = $activityId;
655 $deleteActivity = TRUE;
658 if ($deleteActivity) {
659 $params['source_record_id'] = $membershipId;
660 CRM_Activity_BAO_Activity
::deleteActivity($params);
662 self
::deleteMembershipPayment($membershipId, $preserveContrib);
664 $results = $membership->delete();
665 $transaction->commit();
667 CRM_Utils_Hook
::post('delete', 'Membership', $membership->id
, $membership);
669 // delete the recently created Membership
670 $membershipRecent = array(
671 'id' => $membershipId,
672 'type' => 'Membership',
674 CRM_Utils_Recent
::del($membershipRecent);
680 * Delete related memberships.
682 * @param int $ownerMembershipId
683 * @param int $contactId
687 public static function deleteRelatedMemberships($ownerMembershipId, $contactId = NULL) {
688 if (!$ownerMembershipId && !$contactId) {
692 $membership = new CRM_Member_DAO_Membership();
693 $membership->owner_membership_id
= $ownerMembershipId;
696 $membership->contact_id
= $contactId;
700 while ($membership->fetch()) {
701 //delete related first and then delete parent.
702 self
::deleteRelatedMemberships($membership->id
);
703 self
::deleteMembership($membership->id
);
709 * Obtain active/inactive memberships from the list of memberships passed to it.
711 * @param array $memberships
712 * Membership records.
713 * @param string $status
714 * Active or inactive.
717 * array of memberships based on status
719 public static function activeMembers($memberships, $status = 'active') {
721 if ($status == 'active') {
722 foreach ($memberships as $f => $v) {
723 if (!empty($v['active'])) {
729 elseif ($status == 'inactive') {
730 foreach ($memberships as $f => $v) {
731 if (empty($v['active'])) {
741 * Return Membership Block info in Contribution Pages.
744 * Contribution page id.
748 public static function getMembershipBlock($pageID) {
749 $membershipBlock = array();
750 $dao = new CRM_Member_DAO_MembershipBlock();
751 $dao->entity_table
= 'civicrm_contribution_page';
753 $dao->entity_id
= $pageID;
755 if ($dao->find(TRUE)) {
756 CRM_Core_DAO
::storeValues($dao, $membershipBlock);
757 if (!empty($membershipBlock['membership_types'])) {
758 $membershipTypes = unserialize($membershipBlock['membership_types']);
759 if (!is_array($membershipTypes)) {
760 return $membershipBlock;
763 foreach ($membershipTypes as $key => $value) {
764 $membershipBlock['auto_renew'][$key] = $value;
765 $memTypes[$key] = $key;
767 $membershipBlock['membership_types'] = implode(',', $memTypes);
774 return $membershipBlock;
778 * Return a current membership of given contact.
780 * NB: if more than one membership meets criteria, a randomly selected one is returned.
782 * @param int $contactID
784 * @param int $memType
785 * Membership type, null to retrieve all types.
787 * @param int $membershipId
788 * If provided, then determine if it is current.
789 * @param bool $onlySameParentOrg
790 * True if only Memberships with same parent org as the $memType wanted, false otherwise.
794 public static function getContactMembership($contactID, $memType, $isTest, $membershipId = NULL, $onlySameParentOrg = FALSE) {
795 //check for owner membership id, if it exists update that membership instead: CRM-15992
797 $ownerMemberId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
799 'owner_membership_id', 'id'
801 if ($ownerMemberId) {
802 $membershipId = $ownerMemberId;
803 $contactID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
810 $dao = new CRM_Member_DAO_Membership();
812 $dao->id
= $membershipId;
814 $dao->contact_id
= $contactID;
815 $dao->membership_type_id
= $memType;
817 //fetch proper membership record.
819 $dao->is_test
= $isTest;
822 $dao->whereAdd('is_test IS NULL OR is_test = 0');
825 //avoid pending membership as current membership: CRM-3027
826 $statusIds = array(array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus()));
827 if (!$membershipId) {
829 $statusIds[] = array_search(
831 CRM_Member_PseudoConstant
::membershipStatus(
833 " name = 'Cancelled' ",
840 $dao->whereAdd('status_id NOT IN ( ' . implode(',', $statusIds) . ')');
842 // order by start date to find most recent membership first, CRM-4545
843 $dao->orderBy('start_date DESC');
846 if ($onlySameParentOrg && $memType) {
847 // require the same parent org as the $memType
848 $params = array('id' => $memType);
849 $membershipType = array();
850 if (CRM_Member_BAO_MembershipType
::retrieve($params, $membershipType)) {
851 $memberTypesSameParentOrg = civicrm_api3('MembershipType', 'get', array(
852 'member_of_contact_id' => $membershipType['member_of_contact_id'],
857 $memberTypesSameParentOrgList = implode(',', array_keys(CRM_Utils_Array
::value('values', $memberTypesSameParentOrg, array())));
858 $dao->whereAdd('membership_type_id IN (' . $memberTypesSameParentOrgList . ')');
862 if ($dao->find(TRUE)) {
863 $membership = array();
864 CRM_Core_DAO
::storeValues($dao, $membership);
865 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
866 $membership['status_id'],
867 'is_current_member', 'id'
869 $ownerMemberId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
871 'owner_membership_id', 'id'
873 if ($ownerMemberId) {
874 $membership['id'] = $membership['membership_id'] = $ownerMemberId;
875 $membership['membership_contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
884 if ($onlySameParentOrg && $memType) {
885 // see if there is a membership that has same parent as $memType but different parent than $membershipID
886 if ($dao->id
&& CRM_Core_Permission
::check('edit memberships')) {
887 // CRM-10016, This is probably a backend renewal, and make sure we return the same membership thats being renewed.
894 unset($dao->membership_type_id
);
895 if ($dao->find(TRUE)) {
896 $membership = array();
897 CRM_Core_DAO
::storeValues($dao, $membership);
898 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
899 $membership['status_id'],
900 'is_current_member', 'id'
909 * Combine all the importable fields from the lower levels object.
911 * @param string $contactType
913 * @param bool $status
916 * array of importable Fields
918 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
919 if (!self
::$_importableFields) {
920 if (!self
::$_importableFields) {
921 self
::$_importableFields = array();
925 $fields = array('' => array('title' => '- ' . ts('do not import') . ' -'));
928 $fields = array('' => array('title' => '- ' . ts('Membership Fields') . ' -'));
931 $tmpFields = CRM_Member_DAO_Membership
::import();
932 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
934 // Using new Dedupe rule.
936 'contact_type' => $contactType,
937 'used' => 'Unsupervised',
939 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
941 $tmpContactField = array();
942 if (is_array($fieldsArray)) {
943 foreach ($fieldsArray as $value) {
944 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
949 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
950 $tmpContactField[trim($value)] = CRM_Utils_Array
::value(trim($value), $contactFields);
952 $title = $tmpContactField[trim($value)]['title'] . " " . ts('(match to contact)');
955 $title = $tmpContactField[trim($value)]['title'];
957 $tmpContactField[trim($value)]['title'] = $title;
960 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
961 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " " . ts('(match to contact)');
963 $tmpFields['membership_contact_id']['title'] = $tmpFields['membership_contact_id']['title'] . " " . ts('(match to contact)');;
965 $fields = array_merge($fields, $tmpContactField);
966 $fields = array_merge($fields, $tmpFields);
967 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
968 self
::$_importableFields = $fields;
970 return self
::$_importableFields;
974 * Get all exportable fields.
976 * @return array return array of all exportable fields
978 public static function &exportableFields() {
979 $expFieldMembership = CRM_Member_DAO_Membership
::export();
981 $expFieldsMemType = CRM_Member_DAO_MembershipType
::export();
982 $fields = array_merge($expFieldMembership, $expFieldsMemType);
983 $fields = array_merge($fields, $expFieldMembership);
984 $membershipStatus = array(
985 'membership_status' => array(
986 'title' => ts('Membership Status'),
987 'name' => 'membership_status',
988 'type' => CRM_Utils_Type
::T_STRING
,
989 'where' => 'civicrm_membership_status.name',
992 //CRM-6161 fix for customdata export
993 $fields = array_merge($fields, $membershipStatus, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
998 * Get membership joins/renewals for a specified membership type.
1000 * Specifically, retrieves a count of memberships whose "Membership
1001 * Signup" or "Membership Renewal" activity falls in the given date range.
1002 * Dates match the pattern "yyyy-mm-dd".
1004 * @param int $membershipTypeId
1005 * Membership type id.
1006 * @param int $startDate
1007 * Date on which to start counting.
1008 * @param int $endDate
1009 * Date on which to end counting.
1010 * @param bool|int $isTest if true, membership is for a test site
1011 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1014 * the number of members of type $membershipTypeId whose
1015 * start_date is between $startDate and $endDate
1017 public static function getMembershipStarts($membershipTypeId, $startDate, $endDate, $isTest = 0, $isOwner = 0) {
1019 $testClause = 'membership.is_test = 1';
1021 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1024 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1025 self
::_getActTypes();
1028 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1033 SELECT COUNT(DISTINCT membership.id) as member_count
1034 FROM civicrm_membership membership
1035 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id in (%1, %2))
1036 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1037 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1038 WHERE membership.membership_type_id = %3
1039 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1042 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1045 1 => array(self
::$_signupActType, 'Integer'),
1046 2 => array(self
::$_renewalActType, 'Integer'),
1047 3 => array($membershipTypeId, 'Integer'),
1050 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1051 return (int) $memberCount;
1055 * Get a count of membership for a specified membership type, optionally for a specified date.
1057 * The date must have the form yyyy-mm-dd.
1059 * If $date is omitted, this function counts as a member anyone whose
1060 * membership status_id indicates they're a current member.
1061 * If $date is given, this function counts as a member anyone who:
1062 * -- Has a start_date before $date and end_date after $date, or
1063 * -- Has a start_date before $date and is currently a member, as indicated
1064 * by the the membership's status_id.
1065 * The second condition takes care of records that have no end_date. These
1066 * are assumed to be lifetime memberships.
1068 * @param int $membershipTypeId
1069 * Membership type id.
1070 * @param string $date
1071 * The date for which to retrieve the count.
1072 * @param bool|int $isTest if true, membership is for a test site
1073 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1076 * the number of members of type $membershipTypeId as of $date.
1078 public static function getMembershipCount($membershipTypeId, $date = NULL, $isTest = 0, $isOwner = 0) {
1079 if (!CRM_Utils_Rule
::date($date)) {
1080 CRM_Core_Error
::fatal(ts('Invalid date "%1" (must have form yyyy-mm-dd).', array(1 => $date)));
1084 1 => array($membershipTypeId, 'Integer'),
1085 2 => array($isTest, 'Boolean'),
1087 $query = "SELECT count(civicrm_membership.id ) as member_count
1088 FROM civicrm_membership left join civicrm_membership_status on ( civicrm_membership.status_id = civicrm_membership_status.id )
1089 WHERE civicrm_membership.membership_type_id = %1
1090 AND civicrm_membership.contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)
1091 AND civicrm_membership.is_test = %2";
1093 $query .= " AND civicrm_membership_status.is_current_member = 1";
1096 $query .= " AND civicrm_membership.start_date <= '$date' AND civicrm_membership_status.is_current_member = 1";
1099 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1100 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1101 return (int) $memberCount;
1105 * Function check the status of the membership before adding membership for a contact.
1109 public static function statusAvailabilty() {
1110 $membership = new CRM_Member_DAO_MembershipStatus();
1111 $membership->whereAdd('is_active=1');
1112 return $membership->count();
1116 * Function for updating a membership record's contribution_recur_id.
1118 * @param CRM_Member_DAO_Membership $membership
1119 * @param \CRM_Contribute_BAO_Contribution|\CRM_Contribute_DAO_Contribution $contribution
1121 static public function updateRecurMembership(CRM_Member_DAO_Membership
$membership, CRM_Contribute_BAO_Contribution
$contribution) {
1123 if (empty($contribution->contribution_recur_id
)) {
1128 1 => array($contribution->contribution_recur_id
, 'Integer'),
1129 2 => array($membership->id
, 'Integer'),
1132 $sql = "UPDATE civicrm_membership SET contribution_recur_id = %1 WHERE id = %2";
1133 CRM_Core_DAO
::executeQuery($sql, $params);
1137 * Method to fix membership status of stale membership.
1139 * This method first checks if the membership is stale. If it is,
1140 * then status will be updated based on existing start and end
1141 * dates and log will be added for the status change.
1143 * @param array $currentMembership
1144 * Reference to the array.
1145 * containing all values of
1146 * the current membership
1147 * @param string $changeToday
1148 * In case today needs
1149 * to be customised, null otherwise
1151 public static function fixMembershipStatusBeforeRenew(&$currentMembership, $changeToday) {
1154 $today = CRM_Utils_Date
::processDate($changeToday, NULL, FALSE, 'Y-m-d');
1157 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
1158 CRM_Utils_Array
::value('start_date', $currentMembership),
1159 CRM_Utils_Array
::value('end_date', $currentMembership),
1160 CRM_Utils_Array
::value('join_date', $currentMembership),
1163 $currentMembership['membership_type_id'],
1167 if (empty($status) ||
1168 empty($status['id'])
1170 CRM_Core_Error
::fatal(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.'));
1173 $currentMembership['today_date'] = $today;
1175 if ($status['id'] !== $currentMembership['status_id']) {
1176 $oldStatus = $currentMembership['status_id'];
1177 $memberDAO = new CRM_Member_DAO_Membership();
1178 $memberDAO->id
= $currentMembership['id'];
1179 $memberDAO->find(TRUE);
1181 $memberDAO->status_id
= $status['id'];
1182 $memberDAO->join_date
= CRM_Utils_Date
::isoToMysql($memberDAO->join_date
);
1183 $memberDAO->start_date
= CRM_Utils_Date
::isoToMysql($memberDAO->start_date
);
1184 $memberDAO->end_date
= CRM_Utils_Date
::isoToMysql($memberDAO->end_date
);
1186 CRM_Core_DAO
::storeValues($memberDAO, $currentMembership);
1189 $currentMembership['is_current_member'] = CRM_Core_DAO
::getFieldValue(
1190 'CRM_Member_DAO_MembershipStatus',
1191 $currentMembership['status_id'],
1197 'membership_id' => $currentMembership['id'],
1198 'status_id' => $status['id'],
1199 'start_date' => CRM_Utils_Date
::customFormat(
1200 $currentMembership['start_date'],
1203 'end_date' => CRM_Utils_Date
::customFormat(
1204 $currentMembership['end_date'],
1207 'modified_date' => CRM_Utils_Date
::customFormat(
1208 $currentMembership['today_date'],
1211 'membership_type_id' => $currentMembership['membership_type_id'],
1212 'max_related' => CRM_Utils_Array
::value('max_related', $currentMembership, 0),
1215 $session = CRM_Core_Session
::singleton();
1216 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
1217 if ($session->get('userID')) {
1218 $logParams['modified_id'] = $session->get('userID');
1221 $logParams['modified_id'] = $currentMembership['contact_id'];
1224 //Create activity for status change.
1225 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
1226 CRM_Activity_BAO_Activity
::addActivity($memberDAO,
1227 'Change Membership Status',
1230 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$status['id']]}",
1231 'source_contact_id' => $logParams['modified_id'],
1232 'priority_id' => 'Normal',
1236 CRM_Member_BAO_MembershipLog
::add($logParams);
1241 * Get the contribution page id from the membership record.
1243 * @param int $membershipID
1246 * contribution page id
1248 public static function getContributionPageId($membershipID) {
1250 SELECT c.contribution_page_id as pageID
1251 FROM civicrm_membership_payment mp, civicrm_contribution c
1252 WHERE mp.contribution_id = c.id
1253 AND c.contribution_page_id IS NOT NULL
1254 AND mp.membership_id = " . CRM_Utils_Type
::escape($membershipID, 'Integer')
1255 . " ORDER BY mp.id DESC";
1257 return CRM_Core_DAO
::singleValueQuery($query,
1258 CRM_Core_DAO
::$_nullArray
1263 * Updated related memberships.
1265 * @param int $ownerMembershipId
1266 * Owner Membership Id.
1267 * @param array $params
1268 * Formatted array of key => value.
1270 public static function updateRelatedMemberships($ownerMembershipId, $params) {
1271 $membership = new CRM_Member_DAO_Membership();
1272 $membership->owner_membership_id
= $ownerMembershipId;
1273 $membership->find();
1275 while ($membership->fetch()) {
1276 $relatedMembership = new CRM_Member_DAO_Membership();
1277 $relatedMembership->id
= $membership->id
;
1278 $relatedMembership->copyValues($params);
1279 $relatedMembership->save();
1280 $relatedMembership->free();
1283 $membership->free();
1287 * Get list of membership fields for profile.
1289 * For now we only allow custom membership fields to be in
1293 * FIXME: This param is ignored
1296 * the list of membership fields
1298 public static function getMembershipFields($mode = NULL) {
1299 $fields = CRM_Member_DAO_Membership
::export();
1301 unset($fields['membership_contact_id']);
1302 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1304 $membershipType = CRM_Member_DAO_MembershipType
::export();
1306 $membershipStatus = CRM_Member_DAO_MembershipStatus
::export();
1308 $fields = array_merge($fields, $membershipType, $membershipStatus);
1314 * Get the sort name of a contact for a particular membership.
1317 * Id of the membership.
1319 * @return null|string
1320 * sort name of the contact if found
1322 public static function sortName($id) {
1323 $id = CRM_Utils_Type
::escape($id, 'Integer');
1326 SELECT civicrm_contact.sort_name
1327 FROM civicrm_membership, civicrm_contact
1328 WHERE civicrm_membership.contact_id = civicrm_contact.id
1329 AND civicrm_membership.id = {$id}
1331 return CRM_Core_DAO
::singleValueQuery($query);
1335 * Create memberships for related contacts, taking into account the maximum related memberships.
1337 * @param array $params
1338 * Array of key - value pairs.
1339 * @param CRM_Core_DAO $dao
1340 * Membership object.
1342 * @param bool $reset
1344 * @return array|null
1345 * Membership details, if created.
1347 * @throws \CRM_Core_Exception
1349 public static function createRelatedMemberships(&$params, &$dao, $reset = FALSE) {
1350 // CRM-4213 check for loops, using static variable to record contacts already processed.
1351 static $relatedContactIds = array();
1353 // We need a way to reset this static variable from the test suite.
1354 // @todo consider replacing with Civi::$statics but note reset now used elsewhere: CRM-17723.
1355 $relatedContactIds = array();
1359 $membership = new CRM_Member_DAO_Membership();
1360 $membership->id
= $dao->id
;
1362 // required since create method doesn't return all the
1363 // parameters in the returned membership object
1364 if (!$membership->find(TRUE)) {
1367 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1368 // FIXME : While updating/ renewing the
1369 // membership, if the relationship is PAST then
1370 // the membership of the related contact must be
1372 // For that, getting Membership Status for which
1373 // is_current_member is 0. It works for the
1374 // generated data as there is only one membership
1375 // status having is_current_member = 0.
1376 // But this wont work exactly if there will be
1377 // more than one status having is_current_member = 0.
1378 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
1379 $membershipStatus->is_current_member
= 0;
1380 if ($membershipStatus->find(TRUE)) {
1381 $expiredStatusId = $membershipStatus->id
;
1384 $expiredStatusId = array_search('Expired', CRM_Member_PseudoConstant
::membershipStatus());
1387 $allRelatedContacts = array();
1388 $relatedContacts = array();
1389 if (!is_a($membership, 'CRM_Core_Error')) {
1390 $allRelatedContacts = CRM_Member_BAO_Membership
::checkMembershipRelationship($membership->membership_type_id
,
1391 $membership->contact_id
,
1392 CRM_Utils_Array
::value('action', $params)
1396 // CRM-4213, CRM-19735 check for loops, using static variable to record contacts already processed.
1397 // Remove repeated related contacts, which already inherited membership of this type.
1398 $relatedContactIds[$membership->contact_id
][$membership->membership_type_id
] = TRUE;
1399 foreach ($allRelatedContacts as $cid => $status) {
1400 if (empty($relatedContactIds[$cid]) ||
empty($relatedContactIds[$cid][$membership->membership_type_id
])) {
1401 $relatedContactIds[$cid][$membership->membership_type_id
] = TRUE;
1403 //don't create membership again for owner contact.
1404 $nestedRelationship = FALSE;
1405 if ($membership->owner_membership_id
) {
1406 $nestedRelMembership = new CRM_Member_DAO_Membership();
1407 $nestedRelMembership->id
= $membership->owner_membership_id
;
1408 $nestedRelMembership->contact_id
= $cid;
1409 $nestedRelationship = $nestedRelMembership->find(TRUE);
1410 $nestedRelMembership->free();
1412 if (!$nestedRelationship) {
1413 $relatedContacts[$cid] = $status;
1418 //lets cleanup related membership if any.
1419 if (empty($relatedContacts)) {
1420 self
::deleteRelatedMemberships($membership->id
);
1423 // Edit the params array
1424 unset($params['id']);
1425 // Reminder should be sent only to the direct membership
1426 unset($params['reminder_date']);
1427 // unset the custom value ids
1428 if (is_array(CRM_Utils_Array
::value('custom', $params))) {
1429 foreach ($params['custom'] as $k => $v) {
1430 unset($params['custom'][$k]['id']);
1433 if (!isset($params['membership_type_id'])) {
1434 $params['membership_type_id'] = $membership->membership_type_id
;
1437 // max_related should be set in the parent membership
1438 unset($params['max_related']);
1439 // Number of inherited memberships available - NULL is interpreted as unlimited, '0' as none
1440 $numRelatedAvailable = ($membership->max_related
== NULL ? PHP_INT_MAX
: $membership->max_related
);
1441 // will be used to queue potential memberships to be created.
1444 foreach ($relatedContacts as $contactId => $relationshipStatus) {
1445 //use existing membership record.
1446 $relMembership = new CRM_Member_DAO_Membership();
1447 $relMembership->contact_id
= $contactId;
1448 $relMembership->owner_membership_id
= $membership->id
;
1449 $relMemIds = array();
1450 if ($relMembership->find(TRUE)) {
1451 $params['id'] = $relMemIds['membership'] = $relMembership->id
;
1453 $params['contact_id'] = $contactId;
1454 $params['owner_membership_id'] = $membership->id
;
1456 // set status_id as it might have been changed for
1457 // past relationship
1458 $params['status_id'] = $membership->status_id
;
1460 if ($deceasedStatusId &&
1461 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'is_deceased')
1463 $params['status_id'] = $deceasedStatusId;
1465 elseif ((CRM_Utils_Array
::value('action', $params) & CRM_Core_Action
::UPDATE
) &&
1466 ($relationshipStatus == CRM_Contact_BAO_Relationship
::PAST
)
1468 $params['status_id'] = $expiredStatusId;
1471 //don't calculate status again in create( );
1472 $params['skipStatusCal'] = TRUE;
1474 //do create activity if we changed status.
1475 if ($params['status_id'] != $relMembership->status_id
) {
1476 $params['createActivity'] = TRUE;
1479 //CRM-20707 - include start/end date
1480 $params['start_date'] = $membership->start_date
;
1481 $params['end_date'] = $membership->end_date
;
1483 // we should not created contribution record for related contacts, CRM-3371
1484 unset($params['contribution_status_id']);
1486 //CRM-16857: Do not create multiple line-items for inherited membership through priceset.
1487 unset($params['lineItems']);
1488 unset($params['line_item']);
1490 // CRM-20966: Do not create membership_payment record for inherited membership.
1491 unset($params['relate_contribution_id']);
1493 if (($params['status_id'] == $deceasedStatusId) ||
($params['status_id'] == $expiredStatusId)) {
1494 // related membership is not active so does not count towards maximum
1495 CRM_Member_BAO_Membership
::create($params, $relMemIds);
1498 // related membership already exists, so this is just an update
1499 if (isset($params['id'])) {
1500 if ($numRelatedAvailable > 0) {
1501 CRM_Member_BAO_Membership
::create($params, $relMemIds);
1502 $numRelatedAvailable--;
1505 // we have run out of inherited memberships, so delete extras
1506 self
::deleteMembership($params['id']);
1508 // we need to first check if there will remain inherited memberships, so queue it up
1515 // now go over the queue and create any available related memberships
1516 foreach ($queue as $params) {
1517 if ($numRelatedAvailable <= 0) {
1520 CRM_Member_BAO_Membership
::create($params, $relMemIds);
1521 $numRelatedAvailable--;
1527 * Delete the record that are associated with this Membership Payment.
1529 * @param int $membershipId
1532 * $membershipPayment deleted membership payment object
1534 public static function deleteMembershipPayment($membershipId, $preserveContrib = FALSE) {
1536 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
1537 $membershipPayment->membership_id
= $membershipId;
1538 $membershipPayment->find();
1540 while ($membershipPayment->fetch()) {
1541 if (!$preserveContrib) {
1542 CRM_Contribute_BAO_Contribution
::deleteContribution($membershipPayment->contribution_id
);
1544 CRM_Utils_Hook
::pre('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1545 $membershipPayment->delete();
1546 CRM_Utils_Hook
::post('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1548 return $membershipPayment;
1552 * Build an array of available membership types.
1554 * @param CRM_Core_Form $form
1555 * @param array $membershipTypeID
1556 * @param bool $activeOnly
1557 * Do we only want active ones?
1558 * (probably this should default to TRUE but as a newly added parameter we are leaving default b
1559 * behaviour unchanged).
1563 public static function buildMembershipTypeValues(&$form, $membershipTypeID = array(), $activeOnly = FALSE) {
1564 $whereClause = " WHERE domain_id = " . CRM_Core_Config
::domainID();
1565 $membershipTypeIDS = (array) $membershipTypeID;
1568 $whereClause .= " AND is_active = 1 ";
1570 if (!empty($membershipTypeIDS)) {
1571 $allIDs = implode(',', $membershipTypeIDS);
1572 $whereClause .= " AND id IN ( $allIDs )";
1574 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes, CRM_Core_Action
::ADD
);
1576 if ($financialTypes) {
1577 $whereClause .= " AND financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1580 $whereClause .= " AND financial_type_id IN (0)";
1585 FROM civicrm_membership_type
1588 $dao = CRM_Core_DAO
::executeQuery($query);
1590 $membershipTypeValues = array();
1591 $membershipTypeFields = array(
1597 'financial_type_id',
1599 'member_of_contact_id',
1600 'relationship_type_id',
1601 'relationship_direction',
1604 'duration_interval',
1607 while ($dao->fetch()) {
1608 $membershipTypeValues[$dao->id
] = array();
1609 foreach ($membershipTypeFields as $mtField) {
1610 $membershipTypeValues[$dao->id
][$mtField] = $dao->$mtField;
1615 CRM_Utils_Hook
::membershipTypeValues($form, $membershipTypeValues);
1617 if (is_numeric($membershipTypeID) &&
1618 $membershipTypeID > 0
1620 return $membershipTypeValues[$membershipTypeID];
1623 return $membershipTypeValues;
1628 * Get membership record count for a Contact.
1630 * @param int $contactID
1631 * @param bool $activeOnly
1633 * @return null|string
1635 public static function getContactMembershipCount($contactID, $activeOnly = FALSE) {
1636 CRM_Financial_BAO_FinancialType
::getAvailableMembershipTypes($membershipTypes);
1637 $addWhere = " AND membership_type_id IN (0)";
1638 if (!empty($membershipTypes)) {
1639 $addWhere = " AND membership_type_id IN (" . implode(',', array_keys($membershipTypes)) . ")";
1641 $select = "SELECT count(*) FROM civicrm_membership ";
1642 $where = "WHERE civicrm_membership.contact_id = {$contactID} AND civicrm_membership.is_test = 0 ";
1644 // CRM-6627, all status below 3 (active, pending, grace) are considered active
1646 $select .= " INNER JOIN civicrm_membership_status ON civicrm_membership.status_id = civicrm_membership_status.id ";
1647 $where .= " and civicrm_membership_status.is_current_member = 1";
1650 $query = $select . $where . $addWhere;
1651 return CRM_Core_DAO
::singleValueQuery($query);
1655 * Check whether payment processor supports cancellation of membership subscription.
1660 * @param bool $isNotCancelled
1664 public static function isCancelSubscriptionSupported($mid, $isNotCancelled = TRUE) {
1665 $cacheKeyString = "$mid";
1666 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
1668 static $supportsCancel = array();
1670 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
1671 $supportsCancel[$cacheKeyString] = FALSE;
1672 $isCancelled = FALSE;
1674 if ($isNotCancelled) {
1675 $isCancelled = self
::isSubscriptionCancelled($mid);
1678 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($mid, 'membership', 'obj');
1679 if (!empty($paymentObject)) {
1680 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
1683 return $supportsCancel[$cacheKeyString];
1687 * Check whether subscription is already cancelled.
1693 * contribution status
1695 public static function isSubscriptionCancelled($mid) {
1697 SELECT cr.contribution_status_id
1698 FROM civicrm_contribution_recur cr
1699 LEFT JOIN civicrm_membership mem ON ( cr.id = mem.contribution_recur_id )
1700 WHERE mem.id = %1 LIMIT 1";
1701 $params = array(1 => array($mid, 'Integer'));
1702 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
1703 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
1704 if ($status == 'Cancelled') {
1711 * Get membership joins for a specified membership type.
1713 * Specifically, retrieves a count of still current memberships whose
1714 * join_date and start_date are within a specified date range. Dates match
1715 * the pattern "yyyy-mm-dd".
1717 * @param int $membershipTypeId
1718 * Membership type id.
1719 * @param int $startDate
1720 * Date on which to start counting.
1721 * @param int $endDate
1722 * Date on which to end counting.
1723 * @param bool|int $isTest if true, membership is for a test site
1726 * the number of members of type $membershipTypeId
1727 * whose join_date is between $startDate and $endDate and
1728 * whose start_date is between $startDate and $endDate
1730 public static function getMembershipJoins($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1731 $testClause = 'membership.is_test = 1';
1733 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1735 if (!self
::$_signupActType) {
1736 self
::_getActTypes();
1739 if (!self
::$_signupActType) {
1744 SELECT COUNT(DISTINCT membership.id) as member_count
1745 FROM civicrm_membership membership
1746 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1747 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1748 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1749 WHERE membership.membership_type_id = %2
1750 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1754 1 => array(self
::$_signupActType, 'Integer'),
1755 2 => array($membershipTypeId, 'Integer'),
1758 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1760 return (int) $memberCount;
1764 * Get membership renewals for a specified membership type.
1766 * Specifically, retrieves a count of still current memberships
1767 * whose join_date is before and start_date is within a specified date
1768 * range. Dates match the pattern "yyyy-mm-dd".
1770 * @param int $membershipTypeId
1771 * Membership type id.
1772 * @param int $startDate
1773 * Date on which to start counting.
1774 * @param int $endDate
1775 * Date on which to end counting.
1776 * @param bool|int $isTest if true, membership is for a test site
1779 * returns the number of members of type $membershipTypeId
1780 * whose join_date is before $startDate and
1781 * whose start_date is between $startDate and $endDate
1783 public static function getMembershipRenewals($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1784 $testClause = 'membership.is_test = 1';
1786 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1788 if (!self
::$_renewalActType) {
1789 self
::_getActTypes();
1792 if (!self
::$_renewalActType) {
1797 SELECT COUNT(DISTINCT membership.id) as member_count
1798 FROM civicrm_membership membership
1799 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1800 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1801 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1802 WHERE membership.membership_type_id = %2
1803 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1807 1 => array(self
::$_renewalActType, 'Integer'),
1808 2 => array($membershipTypeId, 'Integer'),
1810 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1812 return (int) $memberCount;
1816 * Create linkages between membership & contribution - note this is the wrong place for this code but this is a
1817 * refactoring step. This should be BAO functionality
1818 * @param $membership
1819 * @param $membershipContribution
1821 public static function linkMembershipPayment($membership, $membershipContribution) {
1822 CRM_Member_BAO_MembershipPayment
::create(array(
1823 'membership_id' => $membership->id
,
1824 'membership_type_id' => $membership->membership_type_id
,
1825 'contribution_id' => $membershipContribution->id
,
1830 * @param int $contactID
1831 * @param int $membershipTypeID
1832 * @param bool $is_test
1833 * @param string $changeToday
1834 * @param int $modifiedID
1835 * @param $customFieldsFormatted
1836 * @param $numRenewTerms
1837 * @param int $membershipID
1839 * @param int $contributionRecurID
1840 * @param $membershipSource
1841 * @param $isPayLater
1842 * @param int $campaignId
1843 * @param array $formDates
1844 * @param null|CRM_Contribute_BAO_Contribution $contribution
1845 * @param array $lineItems
1848 * @throws \CRM_Core_Exception
1850 public static function processMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $contributionRecurID, $membershipSource, $isPayLater, $campaignId, $formDates = array(), $contribution = NULL, $lineItems = array()) {
1851 $renewalMode = $updateStatusId = FALSE;
1852 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1854 $statusFormat = '%Y-%m-%d';
1855 $membershipTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipTypeID);
1858 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
1859 // is the same as the parent org of an existing membership of the contact
1860 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($contactID, $membershipTypeID,
1861 $is_test, $membershipID, TRUE
1863 if ($currentMembership) {
1864 $renewalMode = TRUE;
1866 // Do NOT do anything.
1867 //1. membership with status : PENDING/CANCELLED (CRM-2395)
1868 //2. Paylater/IPN renew. CRM-4556.
1869 if ($pending ||
in_array($currentMembership['status_id'], array(
1870 array_search('Pending', $allStatus),
1872 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1876 'id' => $currentMembership['id'],
1877 'contribution' => $contribution,
1878 'status_id' => $currentMembership['status_id'],
1879 'start_date' => $currentMembership['start_date'],
1880 'end_date' => $currentMembership['end_date'],
1881 'line_item' => $lineItems,
1882 'join_date' => $currentMembership['join_date'],
1883 'membership_type_id' => $membershipTypeID,
1884 'max_related' => !empty($membershipTypeDetails['max_related']) ?
$membershipTypeDetails['max_related'] : NULL,
1885 'membership_activity_status' => ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed',
1887 if ($contributionRecurID) {
1888 $memParams['contribution_recur_id'] = $contributionRecurID;
1891 $membership = self
::create($memParams, $ids, FALSE);
1892 return array($membership, $renewalMode, $dates);
1895 // Check and fix the membership if it is STALE
1896 self
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
1898 // Now Renew the membership
1899 if (!$currentMembership['is_current_member']) {
1900 // membership is not CURRENT
1902 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1903 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($currentMembership['id'],
1909 $currentMembership['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1910 foreach (array('start_date', 'end_date') as $dateType) {
1911 $currentMembership[$dateType] = CRM_Utils_Array
::value($dateType, $formDates);
1912 if (empty($currentMembership[$dateType])) {
1913 $currentMembership[$dateType] = CRM_Utils_Array
::value($dateType, $dates);
1916 $currentMembership['is_test'] = $is_test;
1918 if (!empty($membershipSource)) {
1919 $currentMembership['source'] = $membershipSource;
1922 $currentMembership['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
1923 $currentMembership['id'],
1928 if (!empty($currentMembership['id'])) {
1929 $ids['membership'] = $currentMembership['id'];
1931 $memParams = $currentMembership;
1932 $memParams['membership_type_id'] = $membershipTypeID;
1934 //set the log start date.
1935 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1939 // CURRENT Membership
1940 $membership = new CRM_Member_DAO_Membership();
1941 $membership->id
= $currentMembership['id'];
1942 $membership->find(TRUE);
1943 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1944 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
1950 // Insert renewed dates for CURRENT membership
1951 $memParams = array();
1952 $memParams['join_date'] = CRM_Utils_Date
::isoToMysql($membership->join_date
);
1953 $memParams['start_date'] = CRM_Utils_Array
::value('start_date', $formDates, CRM_Utils_Date
::isoToMysql($membership->start_date
));
1954 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $formDates);
1955 if (empty($memParams['end_date'])) {
1956 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $dates);
1958 $memParams['membership_type_id'] = $membershipTypeID;
1960 //set the log start date.
1961 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1964 if (!empty($membershipSource)) {
1965 $memParams['source'] = $membershipSource;
1967 elseif (empty($membership->source
)) {
1968 $memParams['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
1969 $currentMembership['id'],
1974 if (!empty($currentMembership['id'])) {
1975 $ids['membership'] = $currentMembership['id'];
1977 $memParams['membership_activity_status'] = ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed';
1981 $updateStatusId = array_search('Pending', $allStatus);
1987 'contact_id' => $contactID,
1988 'membership_type_id' => $membershipTypeID,
1992 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
1994 foreach (array('join_date', 'start_date', 'end_date') as $dateType) {
1995 $memParams[$dateType] = CRM_Utils_Array
::value($dateType, $formDates);
1996 if (empty($memParams[$dateType])) {
1997 $memParams[$dateType] = CRM_Utils_Array
::value($dateType, $dates);
2001 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(CRM_Utils_Date
::customFormat($dates['start_date'],
2004 CRM_Utils_Date
::customFormat($dates['end_date'],
2007 CRM_Utils_Date
::customFormat($dates['join_date'],
2015 $updateStatusId = CRM_Utils_Array
::value('id', $status);
2018 // if IPN/Pay-Later set status to: PENDING
2019 $updateStatusId = array_search('Pending', $allStatus);
2022 if (!empty($membershipSource)) {
2023 $memParams['source'] = $membershipSource;
2025 $memParams['is_test'] = $is_test;
2026 $memParams['is_pay_later'] = $isPayLater;
2028 // Putting this in an IF is precautionary as it seems likely that it would be ignored if empty, but
2029 // perhaps shouldn't be?
2030 if ($contributionRecurID) {
2031 $memParams['contribution_recur_id'] = $contributionRecurID;
2034 //if we decided status here and want to skip status
2035 //calculation in create( ); then need to pass 'skipStatusCal'.
2036 if ($updateStatusId) {
2037 $memParams['status_id'] = $updateStatusId;
2038 $memParams['skipStatusCal'] = TRUE;
2041 //since we are renewing,
2042 //make status override false.
2043 $memParams['is_override'] = FALSE;
2045 //CRM-4027, create log w/ individual contact.
2047 $ids['userId'] = $modifiedID;
2048 $memParams['is_for_organization'] = TRUE;
2051 $ids['userId'] = $contactID;
2054 //inherit campaign from contrib page.
2055 if (isset($campaignId)) {
2056 $memParams['campaign_id'] = $campaignId;
2059 $memParams['contribution'] = $contribution;
2060 $memParams['custom'] = $customFieldsFormatted;
2061 // Load all line items & process all in membership. Don't do in contribution.
2062 // Relevant tests in api_v3_ContributionPageTest.
2063 $memParams['line_item'] = $lineItems;
2064 $membership = self
::create($memParams, $ids, FALSE);
2066 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
2067 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
2068 $membership->find(TRUE);
2070 return array($membership, $renewalMode, $dates);
2074 * Get line items representing the default price set.
2076 * @param int $membershipOrg
2077 * @param int $membershipTypeID
2078 * @param float $total_amount
2079 * @param int $priceSetId
2083 public static function setQuickConfigMembershipParameters($membershipOrg, $membershipTypeID, $total_amount, $priceSetId) {
2084 $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
2086 // The name of the price field corresponds to the membership_type organization contact.
2088 'price_set_id' => $priceSetId,
2089 'name' => $membershipOrg,
2092 CRM_Price_BAO_PriceField
::retrieve($params, $results);
2094 if (!empty($results)) {
2095 $fields[$results['id']] = $priceSets['fields'][$results['id']];
2096 $fid = $results['id'];
2097 $editedFieldParams = array(
2098 'price_field_id' => $results['id'],
2099 'membership_type_id' => $membershipTypeID,
2102 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $results);
2103 $fields[$fid]['options'][$results['id']] = $priceSets['fields'][$fid]['options'][$results['id']];
2104 if (!empty($total_amount)) {
2105 $fields[$fid]['options'][$results['id']]['amount'] = $total_amount;
2109 $fieldID = key($fields);
2110 $returnParams = array(
2111 'price_set_id' => $priceSetId,
2112 'price_sets' => $priceSets,
2113 'fields' => $fields,
2114 'price_fields' => array(
2115 'price_' . $fieldID => CRM_Utils_Array
::value('id', $results),
2118 return $returnParams;
2122 * Update the status of all deceased members to deceased.
2125 * Count of updated contacts.
2127 protected static function updateDeceasedMembersStatuses() {
2130 $deceasedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Deceased');
2132 // 'create' context for buildOptions returns only if enabled.
2133 $allStatus = self
::buildOptions('status_id', 'create');
2134 if (array_key_exists($deceasedStatusId, $allStatus) === FALSE) {
2135 // Deceased status is an admin status & is required. We want to fail early if
2136 // it is not present or active.
2137 // We could make the case 'some databases just don't use deceased so we will check
2138 // for the presence of a deceased contact in the DB before rejecting.
2139 if (CRM_Core_DAO
::singleValueQuery('
2140 SELECT count(*) FROM civicrm_contact WHERE is_deceased = 0'
2142 throw new CRM_Core_Exception(
2143 ts("Deceased Membership status is missing or not active. <a href='%1'>Click here to check</a>.",
2144 [1 => CRM_Utils_System
::url('civicrm/admin/member/membershipStatus', 'reset=1')]
2148 $deceasedDAO = CRM_Core_DAO
::executeQuery(
2150 SELECT membership.id as membership_id
2151 FROM civicrm_membership membership
2152 INNER JOIN civicrm_contact ON membership.contact_id = civicrm_contact.id
2153 INNER JOIN civicrm_membership_type ON membership.membership_type_id = civicrm_membership_type.id
2154 AND civicrm_membership_type.is_active = 1
2155 WHERE membership.is_test = 0
2156 AND civicrm_contact.is_deceased = 1
2157 AND membership.status_id <> %1
2159 [1 => [$deceasedStatusId, 'Integer']]
2161 while ($deceasedDAO->fetch()) {
2162 civicrm_api3('membership', 'create', [
2163 'id' => $deceasedDAO->membership_id
,
2164 'status_id' => $deceasedStatusId,
2165 'createActivity' => TRUE,
2166 'skipStatusCal' => TRUE,
2167 'skipRecentView' => TRUE,
2171 $deceasedDAO->free();
2176 * Process price set and line items.
2178 * @param int $membershipId
2179 * @param array $lineItem
2181 public function processPriceSet($membershipId, $lineItem) {
2182 //FIXME : need to move this too
2183 if (!$membershipId ||
!is_array($lineItem)
2184 || CRM_Utils_System
::isNull($lineItem)
2189 foreach ($lineItem as $priceSetId => $values) {
2193 foreach ($values as $line) {
2194 $line['entity_table'] = 'civicrm_membership';
2195 $line['entity_id'] = $membershipId;
2196 CRM_Price_BAO_LineItem
::create($line);
2202 * Retrieve the contribution id for the associated Membership id.
2203 * @todo we should get this off the line item
2205 * @param int $membershipId
2208 * if more than one payment associated with membership id need to be returned.
2213 public static function getMembershipContributionId($membershipId, $all = FALSE) {
2215 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
2216 $membershipPayment->membership_id
= $membershipId;
2217 if ($all && $membershipPayment->find()) {
2218 $contributionIds = array();
2219 while ($membershipPayment->fetch()) {
2220 $contributionIds[] = $membershipPayment->contribution_id
;
2222 return $contributionIds;
2225 if ($membershipPayment->find(TRUE)) {
2226 return $membershipPayment->contribution_id
;
2232 * The function checks and updates the status of all membership records for a given domain using the
2233 * calc_membership_status and update_contact_membership APIs.
2236 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
2240 public static function updateAllMembershipStatus() {
2241 // Tests for this function are in api_v3_JobTest. Please add tests for all updates.
2243 $updateCount = $processCount = self
::updateDeceasedMembersStatuses();
2244 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2245 $allTypes = CRM_Member_PseudoConstant
::membershipType();
2247 // This query retrieves ALL memberships of active types.
2249 SELECT civicrm_membership.id as membership_id,
2250 civicrm_membership.is_override as is_override,
2251 civicrm_membership.status_override_end_date as status_override_end_date,
2252 civicrm_membership.membership_type_id as membership_type_id,
2253 civicrm_membership.status_id as status_id,
2254 civicrm_membership.join_date as join_date,
2255 civicrm_membership.start_date as start_date,
2256 civicrm_membership.end_date as end_date,
2257 civicrm_membership.source as source,
2258 civicrm_contact.id as contact_id,
2259 civicrm_membership.owner_membership_id as owner_membership_id,
2260 civicrm_membership.contribution_recur_id as recur_id
2261 FROM civicrm_membership
2262 INNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )
2263 INNER JOIN civicrm_membership_type ON
2264 (civicrm_membership.membership_type_id = civicrm_membership_type.id AND civicrm_membership_type.is_active = 1)
2265 WHERE civicrm_membership.is_test = 0
2266 AND civicrm_contact.is_deceased = 0 ";
2268 $deceaseStatusId = array_search('Deceased', $allStatus);
2269 $pendingStatusId = array_search('Pending', $allStatus);
2271 $cancelledStatusId = array_search(
2273 CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)
2275 $expiredStatusId = array_search('Expired', $allStatus);
2277 $query = $baseQuery . " AND civicrm_membership.is_override IS NOT NULL AND civicrm_membership.status_override_end_date IS NOT NULL";
2278 $dao1 = CRM_Core_DAO
::executeQuery($query);
2279 while ($dao1->fetch()) {
2280 self
::processOverriddenUntilDateMembership($dao1);
2284 $query = $baseQuery . " AND civicrm_membership.is_override IS NULL
2285 AND civicrm_membership.status_id NOT IN (%1, %2, %3, %4)
2286 AND civicrm_membership.owner_membership_id IS NULL ";
2288 1 => array($pendingStatusId, 'Integer'),
2289 2 => array($cancelledStatusId, 'Integer'),
2290 3 => array($expiredStatusId, 'Integer'),
2291 4 => array($deceaseStatusId, 'Integer'),
2293 $dao2 = CRM_Core_DAO
::executeQuery($query, $params);
2295 while ($dao2->fetch()) {
2299 // Put common parameters into array for easy access
2300 $memberParams = array(
2301 'id' => $dao2->membership_id
,
2302 'status_id' => $dao2->status_id
,
2303 'contact_id' => $dao2->contact_id
,
2304 'membership_type_id' => $dao2->membership_type_id
,
2305 'membership_type' => $allTypes[$dao2->membership_type_id
],
2306 'join_date' => $dao2->join_date
,
2307 'start_date' => $dao2->start_date
,
2308 'end_date' => $dao2->end_date
,
2309 'source' => $dao2->source
,
2310 'skipStatusCal' => TRUE,
2311 'skipRecentView' => TRUE,
2314 // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses
2315 //get the membership status as per id.
2316 $newStatus = civicrm_api('membership_status', 'calc',
2318 'membership_id' => $dao2->membership_id
,
2320 'ignore_admin_only' => TRUE,
2323 $statusId = CRM_Utils_Array
::value('id', $newStatus);
2325 //process only when status change.
2327 $statusId != $dao2->status_id
2329 //take all params that need to save.
2330 $memParams = $memberParams;
2331 $memParams['status_id'] = $statusId;
2332 $memParams['createActivity'] = TRUE;
2333 $memParams['version'] = 3;
2335 // Unset columns which should remain unchanged from their current saved
2336 // values. This avoids race condition in which these values may have
2337 // been changed by other processes.
2339 $memParams['contact_id'],
2340 $memParams['membership_type_id'],
2341 $memParams['membership_type'],
2342 $memParams['join_date'],
2343 $memParams['start_date'],
2344 $memParams['end_date'],
2345 $memParams['source']
2347 //since there is change in status.
2349 //process member record.
2350 civicrm_api('membership', 'create', $memParams);
2355 $result['is_error'] = 0;
2356 $result['messages'] = ts('Processed %1 membership records. Updated %2 records.', array(
2364 * Set is_override for the 'overridden until date' membership to
2365 * False and clears the 'until date' field in case the 'until date'
2366 * is equal or after today date.
2368 * @param CRM_Core_DAO $membership
2369 * The membership to be processed
2371 private static function processOverriddenUntilDateMembership($membership) {
2372 $isOverriddenUntilDate = !empty($membership->is_override
) && !empty($membership->status_override_end_date
);
2373 if (!$isOverriddenUntilDate) {
2377 $todayDate = new DateTime();
2378 $todayDate->setTime(0, 0);
2380 $overrideEndDate = new DateTime($membership->status_override_end_date
);
2381 $overrideEndDate->setTime(0, 0);
2383 $datesDifference = $todayDate->diff($overrideEndDate);
2384 $daysDifference = (int) $datesDifference->format('%R%a');
2385 if ($daysDifference <= 0) {
2387 'id' => $membership->membership_id
,
2388 'is_override' => FALSE,
2389 'status_override_end_date' => 'null',
2391 civicrm_api3('membership', 'create', $params);
2396 * Returns the membership types for a particular contact
2397 * who has lifetime membership without end date.
2399 * @param int $contactID
2400 * @param bool $isTest
2401 * @param bool $onlyLifeTime
2405 public static function getAllContactMembership($contactID, $isTest = FALSE, $onlyLifeTime = FALSE) {
2406 $contactMembershipType = array();
2408 return $contactMembershipType;
2411 $dao = new CRM_Member_DAO_Membership();
2412 $dao->contact_id
= $contactID;
2413 $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
2414 $dao->whereAdd("status_id != $pendingStatusId");
2417 $dao->is_test
= $isTest;
2420 $dao->whereAdd('is_test IS NULL OR is_test = 0');
2423 if ($onlyLifeTime) {
2424 $dao->whereAdd('end_date IS NULL');
2428 while ($dao->fetch()) {
2429 $membership = array();
2430 CRM_Core_DAO
::storeValues($dao, $membership);
2431 $contactMembershipType[$dao->membership_type_id
] = $membership;
2433 return $contactMembershipType;
2437 * Record contribution record associated with membership.
2439 * @param array $params
2440 * Array of submitted params.
2442 * (param in process of being removed - try to use params) array of ids.
2444 * @return CRM_Contribute_BAO_Contribution
2446 public static function recordMembershipContribution(&$params, $ids = array()) {
2447 $membershipId = $params['membership_id'];
2448 $contributionParams = array();
2449 $config = CRM_Core_Config
::singleton();
2450 $contributionParams['currency'] = $config->defaultCurrency
;
2451 $contributionParams['receipt_date'] = (CRM_Utils_Array
::value('receipt_date', $params)) ?
$params['receipt_date'] : 'null';
2452 $contributionParams['source'] = CRM_Utils_Array
::value('contribution_source', $params);
2453 $contributionParams['non_deductible_amount'] = 'null';
2454 $contributionParams['skipCleanMoney'] = TRUE;
2455 $contributionParams['payment_processor'] = CRM_Utils_Array
::value('payment_processor_id', $params);
2456 $contributionSoftParams = CRM_Utils_Array
::value('soft_credit', $params);
2457 $recordContribution = array(
2462 'financial_type_id',
2463 'payment_instrument_id',
2467 'contribution_status_id',
2474 'contribution_recur_id',
2478 foreach ($recordContribution as $f) {
2479 $contributionParams[$f] = CRM_Utils_Array
::value($f, $params);
2482 // make entry in batch entity batch table
2483 if (!empty($params['batch_id'])) {
2484 $contributionParams['batch_id'] = $params['batch_id'];
2487 if (!empty($params['contribution_contact_id'])) {
2488 // deal with possibility of a different person paying for contribution
2489 $contributionParams['contact_id'] = $params['contribution_contact_id'];
2492 if (!empty($params['processPriceSet']) &&
2493 !empty($params['lineItems'])
2495 $contributionParams['line_item'] = CRM_Utils_Array
::value('lineItems', $params, NULL);
2498 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
2500 //CRM-13981, create new soft-credit record as to record payment from different person for this membership
2501 if (!empty($contributionSoftParams)) {
2502 if (!empty($params['batch_id'])) {
2503 foreach ($contributionSoftParams as $contributionSoft) {
2504 $contributionSoft['contribution_id'] = $contribution->id
;
2505 $contributionSoft['currency'] = $contribution->currency
;
2506 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoft);
2510 $contributionSoftParams['contribution_id'] = $contribution->id
;
2511 $contributionSoftParams['currency'] = $contribution->currency
;
2512 $contributionSoftParams['amount'] = $contribution->total_amount
;
2513 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoftParams);
2517 // store contribution id
2518 $params['contribution_id'] = $contribution->id
;
2520 //insert payment record for this membership
2521 if (empty($ids['contribution']) ||
!empty($params['is_recur'])) {
2522 CRM_Member_BAO_MembershipPayment
::create(array(
2523 'membership_id' => $membershipId,
2524 'contribution_id' => $contribution->id
,
2527 return $contribution;
2531 * @todo document me - I seem a bit out of date....
2533 public static function _getActTypes() {
2534 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2535 self
::$_renewalActType = CRM_Utils_Array
::key('Membership Renewal', $activityTypes);
2536 self
::$_signupActType = CRM_Utils_Array
::key('Membership Signup', $activityTypes);
2540 * Get all Cancelled Membership(s) for a contact
2542 * @param int $contactID
2544 * @param bool $isTest
2548 * Array of membership type
2550 public static function getContactsCancelledMembership($contactID, $isTest = FALSE) {
2554 $query = 'SELECT membership_type_id FROM civicrm_membership WHERE contact_id = %1 AND status_id = %2 AND is_test = %3';
2555 $queryParams = array(
2556 1 => array($contactID, 'Integer'),
2561 CRM_Member_PseudoConstant
::membershipStatus(
2563 " name = 'Cancelled' ",
2571 3 => array($isTest, 'Boolean'),
2574 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
2575 $cancelledMembershipIds = array();
2576 while ($dao->fetch()) {
2577 $cancelledMembershipIds[] = $dao->membership_type_id
;
2579 return $cancelledMembershipIds;
2583 * Merges the memberships from otherContactID to mainContactID.
2585 * General idea is to merge memberships in regards to their type. We
2586 * move the other contact’s contributions to the main contact’s
2587 * membership which has the same type (if any) and then we update
2588 * membership to avoid loosing `join_date`, `end_date`, and
2589 * `status_id`. In this function, we don’t touch the contributions
2590 * directly (CRM_Dedupe_Merger::moveContactBelongings() takes care
2593 * This function adds new SQL queries to the $sqlQueries parameter.
2595 * @param int $mainContactID
2596 * Contact id of main contact record.
2597 * @param int $otherContactID
2598 * Contact id of record which is going to merge.
2599 * @param array $sqlQueries
2600 * (reference) array of SQL queries to be executed.
2601 * @param array $tables
2602 * List of tables that have to be merged.
2603 * @param array $tableOperations
2604 * Special options/params for some tables to be merged.
2606 * @see CRM_Dedupe_Merger::cpTables()
2608 public static function mergeMemberships($mainContactID, $otherContactID, &$sqlQueries, $tables, $tableOperations) {
2610 * If the user requests not to merge memberships but to add them,
2611 * just attribute the `civicrm_membership` to the
2612 * `$mainContactID`. We have to do this here since the general
2613 * merge process is bypassed by this function.
2615 if (array_key_exists("civicrm_membership", $tableOperations) && $tableOperations['civicrm_membership']['add']) {
2616 $sqlQueries[] = "UPDATE IGNORE civicrm_membership SET contact_id = $mainContactID WHERE contact_id = $otherContactID";
2621 * Retrieve all memberships that belongs to each contacts and
2622 * keep track of each membership type.
2624 $mainContactMemberships = array();
2625 $otherContactMemberships = array();
2627 $sql = "SELECT id, membership_type_id FROM civicrm_membership membership WHERE contact_id = %1";
2628 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($mainContactID, "Integer")));
2629 while ($dao->fetch()) {
2630 $mainContactMemberships[$dao->id
] = $dao->membership_type_id
;
2633 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($otherContactID, "Integer")));
2634 while ($dao->fetch()) {
2635 $otherContactMemberships[$dao->id
] = $dao->membership_type_id
;
2639 * For each membership, move related contributions to the main
2640 * contact’s membership (by updating `membership_payments`). Then,
2641 * update membership’s `join_date` (if the other membership’s
2642 * join_date is older) and `end_date` (if the other membership’s
2643 * `end_date` is newer) and `status_id` (if the newly calculated
2644 * status is different).
2646 * FIXME: what should we do if we have multiple memberships with
2647 * the same type (currently we only take the first one)?
2650 foreach ($otherContactMemberships as $otherMembershipId => $otherMembershipTypeId) {
2651 if ($newMembershipId = array_search($otherMembershipTypeId, $mainContactMemberships)) {
2654 * Move other membership’s contributions to the main one only
2655 * if user requested to merge contributions.
2657 if (!empty($tables) && in_array('civicrm_contribution', $tables)) {
2658 $newSql[] = "UPDATE civicrm_membership_payment SET membership_id=$newMembershipId WHERE membership_id=$otherMembershipId";
2661 $sql = "SELECT * FROM civicrm_membership membership WHERE id = %1";
2663 $newMembership = CRM_Member_DAO_Membership
::findById($newMembershipId);
2664 $otherMembership = CRM_Member_DAO_Membership
::findById($otherMembershipId);
2667 if (new DateTime($otherMembership->join_date
) < new DateTime($newMembership->join_date
)) {
2668 $updates["join_date"] = $otherMembership->join_date
;
2671 if (new DateTime($otherMembership->end_date
) > new DateTime($newMembership->end_date
)) {
2672 $updates["end_date"] = $otherMembership->end_date
;
2675 if (count($updates)) {
2680 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
2681 isset($updates["start_date"]) ?
$updates["start_date"] : $newMembership->start_date
,
2682 isset($updates["end_date"]) ?
$updates["end_date"] : $newMembership->end_date
,
2683 isset($updates["join_date"]) ?
$updates["join_date"] : $newMembership->join_date
,
2690 if (!empty($status['id']) and $status['id'] != $newMembership->status_id
) {
2691 $updates['status_id'] = $status['id'];
2695 foreach ($updates as $k => $v) {
2696 $updates_sql[] = "$k = '{$v}'";
2699 $newSql[] = sprintf("UPDATE civicrm_membership SET %s WHERE id=%s", implode(", ", $updates_sql), $newMembershipId);
2700 $newSql[] = sprintf("DELETE FROM civicrm_membership WHERE id=%s", $otherMembershipId);
2706 $sqlQueries = array_merge($sqlQueries, $newSql);