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, CRM_Core_DAO
::$_nullArray);
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 $membershipId
455 * @param int $contactId
461 * array of contact_id of all related contacts.
463 public static function checkMembershipRelationship($membershipId, $contactId, $action = CRM_Core_Action
::ADD
) {
465 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $membershipId, 'membership_type_id');
467 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipTypeID);
468 $relationships = array();
469 if (isset($membershipType['relationship_type_id'])) {
470 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
471 CRM_Contact_BAO_Relationship
::CURRENT
473 if ($action & CRM_Core_Action
::UPDATE
) {
474 $pastRelationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
475 CRM_Contact_BAO_Relationship
::PAST
477 $relationships = array_merge($relationships, $pastRelationships);
481 if (!empty($relationships)) {
482 // check for each contact relationships
483 foreach ($relationships as $values) {
484 //get details of the relationship type
485 $relType = array('id' => $values['civicrm_relationship_type_id']);
486 $relValues = array();
487 CRM_Contact_BAO_RelationshipType
::retrieve($relType, $relValues);
488 // Check if contact's relationship type exists in membership type
489 $relTypeDirs = array();
490 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_type_id']);
491 $relDirections = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_direction']);
492 $bidirectional = FALSE;
493 foreach ($relTypeIds as $key => $value) {
494 $relTypeDirs[] = $value . '_' . $relDirections[$key];
495 if (in_array($value, $relType) &&
496 $relValues['name_a_b'] == $relValues['name_b_a']
498 $bidirectional = TRUE;
502 $relTypeDir = $values['civicrm_relationship_type_id'] . '_' . $values['rtype'];
503 if ($bidirectional ||
in_array($relTypeDir, $relTypeDirs)) {
504 // $values['status'] is going to have value for
505 // current or past relationships.
506 $contacts[$values['cid']] = $values['status'];
511 // Sort by contact_id ascending
517 * Retrieve DB object based on input parameters.
519 * It also stores all the retrieved values in the default array.
521 * @param array $params
522 * (reference ) an assoc array of name/value pairs.
523 * @param array $defaults
524 * (reference ) an assoc array to hold the name / value pairs.
525 * in a hierarchical manner
527 * @return CRM_Member_BAO_Membership
529 public static function retrieve(&$params, &$defaults) {
530 $membership = new CRM_Member_DAO_Membership();
532 $membership->copyValues($params);
534 if ($membership->find(TRUE)) {
535 CRM_Core_DAO
::storeValues($membership, $defaults);
537 //get the membership status and type values.
538 $statusANDType = self
::getStatusANDTypeValues($membership->id
);
543 $defaults[$fld] = CRM_Utils_Array
::value($fld, $statusANDType[$membership->id
]);
545 if (!empty($statusANDType[$membership->id
]['is_current_member'])) {
546 $defaults['active'] = TRUE;
558 * Get membership status and membership type values.
560 * @param int $membershipId
561 * Membership id of values to return.
564 * Array of key value pairs
566 public static function getStatusANDTypeValues($membershipId) {
568 if (!$membershipId) {
572 SELECT membership.id as id,
573 status.id as status_id,
574 status.label as status,
575 status.is_current_member as is_current_member,
576 type.id as membership_type_id,
577 type.name as membership_type,
578 type.relationship_type_id as relationship_type_id
579 FROM civicrm_membership membership
580 INNER JOIN civicrm_membership_status status ON ( status.id = membership.status_id )
581 INNER JOIN civicrm_membership_type type ON ( type.id = membership.membership_type_id )
582 WHERE membership.id = %1';
583 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($membershipId, 'Positive')));
588 'membership_type_id',
590 'relationship_type_id',
592 while ($dao->fetch()) {
593 foreach ($properties as $property) {
594 $values[$dao->id
][$property] = $dao->$property;
604 * Wrapper for most delete calls. Use this unless you JUST want to delete related memberships w/o deleting the parent.
606 * @param int $membershipId
607 * Membership id that needs to be deleted.
610 * Id of deleted Membership on success, false otherwise.
612 public static function del($membershipId, $preserveContrib = FALSE) {
613 //delete related first and then delete parent.
614 self
::deleteRelatedMemberships($membershipId);
615 return self
::deleteMembership($membershipId, $preserveContrib);
621 * @param int $membershipId
622 * Membership id that needs to be deleted.
625 * Id of deleted Membership on success, false otherwise.
627 public static function deleteMembership($membershipId, $preserveContrib = FALSE) {
628 // CRM-12147, retrieve membership data before we delete it for hooks
629 $params = array('id' => $membershipId);
630 $memValues = array();
631 $memberships = self
::getValues($params, $memValues);
633 $membership = $memberships[$membershipId];
635 CRM_Utils_Hook
::pre('delete', 'Membership', $membershipId, $memValues);
637 $transaction = new CRM_Core_Transaction();
640 //delete activity record
641 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
644 $deleteActivity = FALSE;
645 $membershipActivities = array(
647 'Membership Renewal',
648 'Change Membership Status',
649 'Change Membership Type',
650 'Membership Renewal Reminder',
652 foreach ($membershipActivities as $membershipActivity) {
653 $activityId = array_search($membershipActivity, $activityTypes);
655 $params['activity_type_id'][] = $activityId;
656 $deleteActivity = TRUE;
659 if ($deleteActivity) {
660 $params['source_record_id'] = $membershipId;
661 CRM_Activity_BAO_Activity
::deleteActivity($params);
663 self
::deleteMembershipPayment($membershipId, $preserveContrib);
665 $results = $membership->delete();
666 $transaction->commit();
668 CRM_Utils_Hook
::post('delete', 'Membership', $membership->id
, $membership);
670 // delete the recently created Membership
671 $membershipRecent = array(
672 'id' => $membershipId,
673 'type' => 'Membership',
675 CRM_Utils_Recent
::del($membershipRecent);
681 * Delete related memberships.
683 * @param int $ownerMembershipId
684 * @param int $contactId
688 public static function deleteRelatedMemberships($ownerMembershipId, $contactId = NULL) {
689 if (!$ownerMembershipId && !$contactId) {
693 $membership = new CRM_Member_DAO_Membership();
694 $membership->owner_membership_id
= $ownerMembershipId;
697 $membership->contact_id
= $contactId;
701 while ($membership->fetch()) {
702 //delete related first and then delete parent.
703 self
::deleteRelatedMemberships($membership->id
);
704 self
::deleteMembership($membership->id
);
710 * Obtain active/inactive memberships from the list of memberships passed to it.
712 * @param array $memberships
713 * Membership records.
714 * @param string $status
715 * Active or inactive.
718 * array of memberships based on status
720 public static function activeMembers($memberships, $status = 'active') {
722 if ($status == 'active') {
723 foreach ($memberships as $f => $v) {
724 if (!empty($v['active'])) {
730 elseif ($status == 'inactive') {
731 foreach ($memberships as $f => $v) {
732 if (empty($v['active'])) {
742 * Return Membership Block info in Contribution Pages.
745 * Contribution page id.
749 public static function getMembershipBlock($pageID) {
750 $membershipBlock = array();
751 $dao = new CRM_Member_DAO_MembershipBlock();
752 $dao->entity_table
= 'civicrm_contribution_page';
754 $dao->entity_id
= $pageID;
756 if ($dao->find(TRUE)) {
757 CRM_Core_DAO
::storeValues($dao, $membershipBlock);
758 if (!empty($membershipBlock['membership_types'])) {
759 $membershipTypes = unserialize($membershipBlock['membership_types']);
760 if (!is_array($membershipTypes)) {
761 return $membershipBlock;
764 foreach ($membershipTypes as $key => $value) {
765 $membershipBlock['auto_renew'][$key] = $value;
766 $memTypes[$key] = $key;
768 $membershipBlock['membership_types'] = implode(',', $memTypes);
775 return $membershipBlock;
779 * Return a current membership of given contact.
781 * NB: if more than one membership meets criteria, a randomly selected one is returned.
783 * @param int $contactID
785 * @param int $memType
786 * Membership type, null to retrieve all types.
788 * @param int $membershipId
789 * If provided, then determine if it is current.
790 * @param bool $onlySameParentOrg
791 * True if only Memberships with same parent org as the $memType wanted, false otherwise.
795 public static function getContactMembership($contactID, $memType, $isTest, $membershipId = NULL, $onlySameParentOrg = FALSE) {
796 //check for owner membership id, if it exists update that membership instead: CRM-15992
798 $ownerMemberId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
800 'owner_membership_id', 'id'
802 if ($ownerMemberId) {
803 $membershipId = $ownerMemberId;
804 $contactID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
811 $dao = new CRM_Member_DAO_Membership();
813 $dao->id
= $membershipId;
815 $dao->contact_id
= $contactID;
816 $dao->membership_type_id
= $memType;
818 //fetch proper membership record.
820 $dao->is_test
= $isTest;
823 $dao->whereAdd('is_test IS NULL OR is_test = 0');
826 //avoid pending membership as current membership: CRM-3027
827 $statusIds = array(array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus()));
828 if (!$membershipId) {
830 $statusIds[] = array_search(
832 CRM_Member_PseudoConstant
::membershipStatus(
834 " name = 'Cancelled' ",
841 $dao->whereAdd('status_id NOT IN ( ' . implode(',', $statusIds) . ')');
843 // order by start date to find most recent membership first, CRM-4545
844 $dao->orderBy('start_date DESC');
847 if ($onlySameParentOrg && $memType) {
848 // require the same parent org as the $memType
849 $params = array('id' => $memType);
850 $membershipType = array();
851 if (CRM_Member_BAO_MembershipType
::retrieve($params, $membershipType)) {
852 $memberTypesSameParentOrg = civicrm_api3('MembershipType', 'get', array(
853 'member_of_contact_id' => $membershipType['member_of_contact_id'],
858 $memberTypesSameParentOrgList = implode(',', array_keys(CRM_Utils_Array
::value('values', $memberTypesSameParentOrg, array())));
859 $dao->whereAdd('membership_type_id IN (' . $memberTypesSameParentOrgList . ')');
863 if ($dao->find(TRUE)) {
864 $membership = array();
865 CRM_Core_DAO
::storeValues($dao, $membership);
866 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
867 $membership['status_id'],
868 'is_current_member', 'id'
870 $ownerMemberId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
872 'owner_membership_id', 'id'
874 if ($ownerMemberId) {
875 $membership['id'] = $membership['membership_id'] = $ownerMemberId;
876 $membership['membership_contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
885 if ($onlySameParentOrg && $memType) {
886 // see if there is a membership that has same parent as $memType but different parent than $membershipID
887 if ($dao->id
&& CRM_Core_Permission
::check('edit memberships')) {
888 // CRM-10016, This is probably a backend renewal, and make sure we return the same membership thats being renewed.
895 unset($dao->membership_type_id
);
896 if ($dao->find(TRUE)) {
897 $membership = array();
898 CRM_Core_DAO
::storeValues($dao, $membership);
899 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
900 $membership['status_id'],
901 'is_current_member', 'id'
910 * Combine all the importable fields from the lower levels object.
912 * @param string $contactType
914 * @param bool $status
917 * array of importable Fields
919 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
920 if (!self
::$_importableFields) {
921 if (!self
::$_importableFields) {
922 self
::$_importableFields = array();
926 $fields = array('' => array('title' => '- ' . ts('do not import') . ' -'));
929 $fields = array('' => array('title' => '- ' . ts('Membership Fields') . ' -'));
932 $tmpFields = CRM_Member_DAO_Membership
::import();
933 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
935 // Using new Dedupe rule.
937 'contact_type' => $contactType,
938 'used' => 'Unsupervised',
940 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
942 $tmpContactField = array();
943 if (is_array($fieldsArray)) {
944 foreach ($fieldsArray as $value) {
945 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
950 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
951 $tmpContactField[trim($value)] = CRM_Utils_Array
::value(trim($value), $contactFields);
953 $title = $tmpContactField[trim($value)]['title'] . " " . ts('(match to contact)');
956 $title = $tmpContactField[trim($value)]['title'];
958 $tmpContactField[trim($value)]['title'] = $title;
961 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
962 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " " . ts('(match to contact)');
964 $tmpFields['membership_contact_id']['title'] = $tmpFields['membership_contact_id']['title'] . " " . ts('(match to contact)');;
966 $fields = array_merge($fields, $tmpContactField);
967 $fields = array_merge($fields, $tmpFields);
968 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
969 self
::$_importableFields = $fields;
971 return self
::$_importableFields;
975 * Get all exportable fields.
977 * @return array return array of all exportable fields
979 public static function &exportableFields() {
980 $expFieldMembership = CRM_Member_DAO_Membership
::export();
982 $expFieldsMemType = CRM_Member_DAO_MembershipType
::export();
983 $fields = array_merge($expFieldMembership, $expFieldsMemType);
984 $fields = array_merge($fields, $expFieldMembership);
985 $membershipStatus = array(
986 'membership_status' => array(
987 'title' => ts('Membership Status'),
988 'name' => 'membership_status',
989 'type' => CRM_Utils_Type
::T_STRING
,
990 'where' => 'civicrm_membership_status.name',
993 //CRM-6161 fix for customdata export
994 $fields = array_merge($fields, $membershipStatus, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
999 * Get membership joins/renewals for a specified membership type.
1001 * Specifically, retrieves a count of memberships whose "Membership
1002 * Signup" or "Membership Renewal" activity falls in the given date range.
1003 * Dates match the pattern "yyyy-mm-dd".
1005 * @param int $membershipTypeId
1006 * Membership type id.
1007 * @param int $startDate
1008 * Date on which to start counting.
1009 * @param int $endDate
1010 * Date on which to end counting.
1011 * @param bool|int $isTest if true, membership is for a test site
1012 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1015 * the number of members of type $membershipTypeId whose
1016 * start_date is between $startDate and $endDate
1018 public static function getMembershipStarts($membershipTypeId, $startDate, $endDate, $isTest = 0, $isOwner = 0) {
1020 $testClause = 'membership.is_test = 1';
1022 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1025 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1026 self
::_getActTypes();
1029 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1034 SELECT COUNT(DISTINCT membership.id) as member_count
1035 FROM civicrm_membership membership
1036 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id in (%1, %2))
1037 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1038 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1039 WHERE membership.membership_type_id = %3
1040 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1043 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1046 1 => array(self
::$_signupActType, 'Integer'),
1047 2 => array(self
::$_renewalActType, 'Integer'),
1048 3 => array($membershipTypeId, 'Integer'),
1051 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1052 return (int) $memberCount;
1056 * Get a count of membership for a specified membership type, optionally for a specified date.
1058 * The date must have the form yyyy-mm-dd.
1060 * If $date is omitted, this function counts as a member anyone whose
1061 * membership status_id indicates they're a current member.
1062 * If $date is given, this function counts as a member anyone who:
1063 * -- Has a start_date before $date and end_date after $date, or
1064 * -- Has a start_date before $date and is currently a member, as indicated
1065 * by the the membership's status_id.
1066 * The second condition takes care of records that have no end_date. These
1067 * are assumed to be lifetime memberships.
1069 * @param int $membershipTypeId
1070 * Membership type id.
1071 * @param string $date
1072 * The date for which to retrieve the count.
1073 * @param bool|int $isTest if true, membership is for a test site
1074 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1077 * the number of members of type $membershipTypeId as of $date.
1079 public static function getMembershipCount($membershipTypeId, $date = NULL, $isTest = 0, $isOwner = 0) {
1080 if (!CRM_Utils_Rule
::date($date)) {
1081 CRM_Core_Error
::fatal(ts('Invalid date "%1" (must have form yyyy-mm-dd).', array(1 => $date)));
1085 1 => array($membershipTypeId, 'Integer'),
1086 2 => array($isTest, 'Boolean'),
1088 $query = "SELECT count(civicrm_membership.id ) as member_count
1089 FROM civicrm_membership left join civicrm_membership_status on ( civicrm_membership.status_id = civicrm_membership_status.id )
1090 WHERE civicrm_membership.membership_type_id = %1
1091 AND civicrm_membership.contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)
1092 AND civicrm_membership.is_test = %2";
1094 $query .= " AND civicrm_membership_status.is_current_member = 1";
1097 $query .= " AND civicrm_membership.start_date <= '$date' AND civicrm_membership_status.is_current_member = 1";
1100 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1101 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1102 return (int) $memberCount;
1106 * Function check the status of the membership before adding membership for a contact.
1110 public static function statusAvailabilty() {
1111 $membership = new CRM_Member_DAO_MembershipStatus();
1112 $membership->whereAdd('is_active=1');
1113 return $membership->count();
1117 * Function for updating a membership record's contribution_recur_id.
1119 * @param CRM_Member_DAO_Membership $membership
1120 * @param \CRM_Contribute_BAO_Contribution|\CRM_Contribute_DAO_Contribution $contribution
1122 static public function updateRecurMembership(CRM_Member_DAO_Membership
$membership, CRM_Contribute_BAO_Contribution
$contribution) {
1124 if (empty($contribution->contribution_recur_id
)) {
1129 1 => array($contribution->contribution_recur_id
, 'Integer'),
1130 2 => array($membership->id
, 'Integer'),
1133 $sql = "UPDATE civicrm_membership SET contribution_recur_id = %1 WHERE id = %2";
1134 CRM_Core_DAO
::executeQuery($sql, $params);
1138 * Method to fix membership status of stale membership.
1140 * This method first checks if the membership is stale. If it is,
1141 * then status will be updated based on existing start and end
1142 * dates and log will be added for the status change.
1144 * @param array $currentMembership
1145 * Reference to the array.
1146 * containing all values of
1147 * the current membership
1148 * @param string $changeToday
1149 * In case today needs
1150 * to be customised, null otherwise
1152 public static function fixMembershipStatusBeforeRenew(&$currentMembership, $changeToday) {
1155 $today = CRM_Utils_Date
::processDate($changeToday, NULL, FALSE, 'Y-m-d');
1158 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
1159 CRM_Utils_Array
::value('start_date', $currentMembership),
1160 CRM_Utils_Array
::value('end_date', $currentMembership),
1161 CRM_Utils_Array
::value('join_date', $currentMembership),
1164 $currentMembership['membership_type_id'],
1168 if (empty($status) ||
1169 empty($status['id'])
1171 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.'));
1174 $currentMembership['today_date'] = $today;
1176 if ($status['id'] !== $currentMembership['status_id']) {
1177 $oldStatus = $currentMembership['status_id'];
1178 $memberDAO = new CRM_Member_DAO_Membership();
1179 $memberDAO->id
= $currentMembership['id'];
1180 $memberDAO->find(TRUE);
1182 $memberDAO->status_id
= $status['id'];
1183 $memberDAO->join_date
= CRM_Utils_Date
::isoToMysql($memberDAO->join_date
);
1184 $memberDAO->start_date
= CRM_Utils_Date
::isoToMysql($memberDAO->start_date
);
1185 $memberDAO->end_date
= CRM_Utils_Date
::isoToMysql($memberDAO->end_date
);
1187 CRM_Core_DAO
::storeValues($memberDAO, $currentMembership);
1190 $currentMembership['is_current_member'] = CRM_Core_DAO
::getFieldValue(
1191 'CRM_Member_DAO_MembershipStatus',
1192 $currentMembership['status_id'],
1198 'membership_id' => $currentMembership['id'],
1199 'status_id' => $status['id'],
1200 'start_date' => CRM_Utils_Date
::customFormat(
1201 $currentMembership['start_date'],
1204 'end_date' => CRM_Utils_Date
::customFormat(
1205 $currentMembership['end_date'],
1208 'modified_date' => CRM_Utils_Date
::customFormat(
1209 $currentMembership['today_date'],
1212 'membership_type_id' => $currentMembership['membership_type_id'],
1213 'max_related' => CRM_Utils_Array
::value('max_related', $currentMembership, 0),
1216 $session = CRM_Core_Session
::singleton();
1217 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
1218 if ($session->get('userID')) {
1219 $logParams['modified_id'] = $session->get('userID');
1222 $logParams['modified_id'] = $currentMembership['contact_id'];
1225 //Create activity for status change.
1226 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
1227 CRM_Activity_BAO_Activity
::addActivity($memberDAO,
1228 'Change Membership Status',
1231 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$status['id']]}",
1232 'source_contact_id' => $logParams['modified_id'],
1233 'priority_id' => 'Normal',
1237 CRM_Member_BAO_MembershipLog
::add($logParams, CRM_Core_DAO
::$_nullArray);
1242 * Get the contribution page id from the membership record.
1244 * @param int $membershipID
1247 * contribution page id
1249 public static function getContributionPageId($membershipID) {
1251 SELECT c.contribution_page_id as pageID
1252 FROM civicrm_membership_payment mp, civicrm_contribution c
1253 WHERE mp.contribution_id = c.id
1254 AND c.contribution_page_id IS NOT NULL
1255 AND mp.membership_id = " . CRM_Utils_Type
::escape($membershipID, 'Integer')
1256 . " ORDER BY mp.id DESC";
1258 return CRM_Core_DAO
::singleValueQuery($query,
1259 CRM_Core_DAO
::$_nullArray
1264 * Updated related memberships.
1266 * @param int $ownerMembershipId
1267 * Owner Membership Id.
1268 * @param array $params
1269 * Formatted array of key => value.
1271 public static function updateRelatedMemberships($ownerMembershipId, $params) {
1272 $membership = new CRM_Member_DAO_Membership();
1273 $membership->owner_membership_id
= $ownerMembershipId;
1274 $membership->find();
1276 while ($membership->fetch()) {
1277 $relatedMembership = new CRM_Member_DAO_Membership();
1278 $relatedMembership->id
= $membership->id
;
1279 $relatedMembership->copyValues($params);
1280 $relatedMembership->save();
1281 $relatedMembership->free();
1284 $membership->free();
1288 * Get list of membership fields for profile.
1290 * For now we only allow custom membership fields to be in
1294 * FIXME: This param is ignored
1297 * the list of membership fields
1299 public static function getMembershipFields($mode = NULL) {
1300 $fields = CRM_Member_DAO_Membership
::export();
1302 unset($fields['membership_contact_id']);
1303 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1305 $membershipType = CRM_Member_DAO_MembershipType
::export();
1307 $membershipStatus = CRM_Member_DAO_MembershipStatus
::export();
1309 $fields = array_merge($fields, $membershipType, $membershipStatus);
1315 * Get the sort name of a contact for a particular membership.
1318 * Id of the membership.
1320 * @return null|string
1321 * sort name of the contact if found
1323 public static function sortName($id) {
1324 $id = CRM_Utils_Type
::escape($id, 'Integer');
1327 SELECT civicrm_contact.sort_name
1328 FROM civicrm_membership, civicrm_contact
1329 WHERE civicrm_membership.contact_id = civicrm_contact.id
1330 AND civicrm_membership.id = {$id}
1332 return CRM_Core_DAO
::singleValueQuery($query);
1336 * Create memberships for related contacts, taking into account the maximum related memberships.
1338 * @param array $params
1339 * Array of key - value pairs.
1340 * @param CRM_Core_DAO $dao
1341 * Membership object.
1343 * @param bool $reset
1345 * @return array|null
1346 * Membership details, if created.
1348 * @throws \CRM_Core_Exception
1350 public static function createRelatedMemberships(&$params, &$dao, $reset = FALSE) {
1351 // CRM-4213 check for loops, using static variable to record contacts already processed.
1352 static $relatedContactIds = array();
1354 // We need a way to reset this static variable from the test suite.
1355 // @todo consider replacing with Civi::$statics but note reset now used elsewhere: CRM-17723.
1356 $relatedContactIds = array();
1360 $membership = new CRM_Member_DAO_Membership();
1361 $membership->id
= $dao->id
;
1363 // required since create method doesn't return all the
1364 // parameters in the returned membership object
1365 if (!$membership->find(TRUE)) {
1368 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1369 // FIXME : While updating/ renewing the
1370 // membership, if the relationship is PAST then
1371 // the membership of the related contact must be
1373 // For that, getting Membership Status for which
1374 // is_current_member is 0. It works for the
1375 // generated data as there is only one membership
1376 // status having is_current_member = 0.
1377 // But this wont work exactly if there will be
1378 // more than one status having is_current_member = 0.
1379 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
1380 $membershipStatus->is_current_member
= 0;
1381 if ($membershipStatus->find(TRUE)) {
1382 $expiredStatusId = $membershipStatus->id
;
1385 $expiredStatusId = array_search('Expired', CRM_Member_PseudoConstant
::membershipStatus());
1388 $allRelatedContacts = array();
1389 $relatedContacts = array();
1390 if (!is_a($membership, 'CRM_Core_Error')) {
1391 $allRelatedContacts = CRM_Member_BAO_Membership
::checkMembershipRelationship($membership->id
,
1392 $membership->contact_id
,
1393 CRM_Utils_Array
::value('action', $params)
1397 // CRM-4213, CRM-19735 check for loops, using static variable to record contacts already processed.
1398 // Remove repeated related contacts, which already inherited membership of this type.
1399 $relatedContactIds[$membership->contact_id
][$membership->membership_type_id
] = TRUE;
1400 foreach ($allRelatedContacts as $cid => $status) {
1401 if (empty($relatedContactIds[$cid]) ||
empty($relatedContactIds[$cid][$membership->membership_type_id
])) {
1402 $relatedContactIds[$cid][$membership->membership_type_id
] = TRUE;
1404 //don't create membership again for owner contact.
1405 $nestedRelationship = FALSE;
1406 if ($membership->owner_membership_id
) {
1407 $nestedRelMembership = new CRM_Member_DAO_Membership();
1408 $nestedRelMembership->id
= $membership->owner_membership_id
;
1409 $nestedRelMembership->contact_id
= $cid;
1410 $nestedRelationship = $nestedRelMembership->find(TRUE);
1411 $nestedRelMembership->free();
1413 if (!$nestedRelationship) {
1414 $relatedContacts[$cid] = $status;
1419 //lets cleanup related membership if any.
1420 if (empty($relatedContacts)) {
1421 self
::deleteRelatedMemberships($membership->id
);
1424 // Edit the params array
1425 unset($params['id']);
1426 // Reminder should be sent only to the direct membership
1427 unset($params['reminder_date']);
1428 // unset the custom value ids
1429 if (is_array(CRM_Utils_Array
::value('custom', $params))) {
1430 foreach ($params['custom'] as $k => $v) {
1431 unset($params['custom'][$k]['id']);
1434 if (!isset($params['membership_type_id'])) {
1435 $params['membership_type_id'] = $membership->membership_type_id
;
1438 // max_related should be set in the parent membership
1439 unset($params['max_related']);
1440 // Number of inherited memberships available - NULL is interpreted as unlimited, '0' as none
1441 $numRelatedAvailable = ($membership->max_related
== NULL ? PHP_INT_MAX
: $membership->max_related
);
1442 // will be used to queue potential memberships to be created.
1445 foreach ($relatedContacts as $contactId => $relationshipStatus) {
1446 //use existing membership record.
1447 $relMembership = new CRM_Member_DAO_Membership();
1448 $relMembership->contact_id
= $contactId;
1449 $relMembership->owner_membership_id
= $membership->id
;
1450 $relMemIds = array();
1451 if ($relMembership->find(TRUE)) {
1452 $params['id'] = $relMemIds['membership'] = $relMembership->id
;
1454 $params['contact_id'] = $contactId;
1455 $params['owner_membership_id'] = $membership->id
;
1457 // set status_id as it might have been changed for
1458 // past relationship
1459 $params['status_id'] = $membership->status_id
;
1461 if ($deceasedStatusId &&
1462 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'is_deceased')
1464 $params['status_id'] = $deceasedStatusId;
1466 elseif ((CRM_Utils_Array
::value('action', $params) & CRM_Core_Action
::UPDATE
) &&
1467 ($relationshipStatus == CRM_Contact_BAO_Relationship
::PAST
)
1469 $params['status_id'] = $expiredStatusId;
1472 //don't calculate status again in create( );
1473 $params['skipStatusCal'] = TRUE;
1475 //do create activity if we changed status.
1476 if ($params['status_id'] != $relMembership->status_id
) {
1477 $params['createActivity'] = TRUE;
1480 //CRM-20707 - include start/end date
1481 $params['start_date'] = $membership->start_date
;
1482 $params['end_date'] = $membership->end_date
;
1484 // we should not created contribution record for related contacts, CRM-3371
1485 unset($params['contribution_status_id']);
1487 //CRM-16857: Do not create multiple line-items for inherited membership through priceset.
1488 unset($params['lineItems']);
1489 unset($params['line_item']);
1491 // CRM-20966: Do not create membership_payment record for inherited membership.
1492 unset($params['relate_contribution_id']);
1494 if (($params['status_id'] == $deceasedStatusId) ||
($params['status_id'] == $expiredStatusId)) {
1495 // related membership is not active so does not count towards maximum
1496 CRM_Member_BAO_Membership
::create($params, $relMemIds);
1499 // related membership already exists, so this is just an update
1500 if (isset($params['id'])) {
1501 if ($numRelatedAvailable > 0) {
1502 CRM_Member_BAO_Membership
::create($params, $relMemIds);
1503 $numRelatedAvailable--;
1506 // we have run out of inherited memberships, so delete extras
1507 self
::deleteMembership($params['id']);
1509 // we need to first check if there will remain inherited memberships, so queue it up
1516 // now go over the queue and create any available related memberships
1517 foreach ($queue as $params) {
1518 if ($numRelatedAvailable <= 0) {
1521 CRM_Member_BAO_Membership
::create($params, $relMemIds);
1522 $numRelatedAvailable--;
1528 * Delete the record that are associated with this Membership Payment.
1530 * @param int $membershipId
1533 * $membershipPayment deleted membership payment object
1535 public static function deleteMembershipPayment($membershipId, $preserveContrib = FALSE) {
1537 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
1538 $membershipPayment->membership_id
= $membershipId;
1539 $membershipPayment->find();
1541 while ($membershipPayment->fetch()) {
1542 if (!$preserveContrib) {
1543 CRM_Contribute_BAO_Contribution
::deleteContribution($membershipPayment->contribution_id
);
1545 CRM_Utils_Hook
::pre('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1546 $membershipPayment->delete();
1547 CRM_Utils_Hook
::post('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1549 return $membershipPayment;
1553 * Build an array of available membership types.
1555 * @param CRM_Core_Form $form
1556 * @param array $membershipTypeID
1557 * @param bool $activeOnly
1558 * Do we only want active ones?
1559 * (probably this should default to TRUE but as a newly added parameter we are leaving default b
1560 * behaviour unchanged).
1564 public static function buildMembershipTypeValues(&$form, $membershipTypeID = array(), $activeOnly = FALSE) {
1565 $whereClause = " WHERE domain_id = " . CRM_Core_Config
::domainID();
1566 $membershipTypeIDS = (array) $membershipTypeID;
1569 $whereClause .= " AND is_active = 1 ";
1571 if (!empty($membershipTypeIDS)) {
1572 $allIDs = implode(',', $membershipTypeIDS);
1573 $whereClause .= " AND id IN ( $allIDs )";
1575 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes, CRM_Core_Action
::ADD
);
1577 if ($financialTypes) {
1578 $whereClause .= " AND financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1581 $whereClause .= " AND financial_type_id IN (0)";
1586 FROM civicrm_membership_type
1589 $dao = CRM_Core_DAO
::executeQuery($query);
1591 $membershipTypeValues = array();
1592 $membershipTypeFields = array(
1598 'financial_type_id',
1600 'member_of_contact_id',
1601 'relationship_type_id',
1602 'relationship_direction',
1605 'duration_interval',
1608 while ($dao->fetch()) {
1609 $membershipTypeValues[$dao->id
] = array();
1610 foreach ($membershipTypeFields as $mtField) {
1611 $membershipTypeValues[$dao->id
][$mtField] = $dao->$mtField;
1616 CRM_Utils_Hook
::membershipTypeValues($form, $membershipTypeValues);
1618 if (is_numeric($membershipTypeID) &&
1619 $membershipTypeID > 0
1621 return $membershipTypeValues[$membershipTypeID];
1624 return $membershipTypeValues;
1629 * Get membership record count for a Contact.
1631 * @param int $contactID
1632 * @param bool $activeOnly
1634 * @return null|string
1636 public static function getContactMembershipCount($contactID, $activeOnly = FALSE) {
1637 CRM_Financial_BAO_FinancialType
::getAvailableMembershipTypes($membershipTypes);
1638 $addWhere = " AND membership_type_id IN (0)";
1639 if (!empty($membershipTypes)) {
1640 $addWhere = " AND membership_type_id IN (" . implode(',', array_keys($membershipTypes)) . ")";
1642 $select = "SELECT count(*) FROM civicrm_membership ";
1643 $where = "WHERE civicrm_membership.contact_id = {$contactID} AND civicrm_membership.is_test = 0 ";
1645 // CRM-6627, all status below 3 (active, pending, grace) are considered active
1647 $select .= " INNER JOIN civicrm_membership_status ON civicrm_membership.status_id = civicrm_membership_status.id ";
1648 $where .= " and civicrm_membership_status.is_current_member = 1";
1651 $query = $select . $where . $addWhere;
1652 return CRM_Core_DAO
::singleValueQuery($query);
1656 * Check whether payment processor supports cancellation of membership subscription.
1661 * @param bool $isNotCancelled
1665 public static function isCancelSubscriptionSupported($mid, $isNotCancelled = TRUE) {
1666 $cacheKeyString = "$mid";
1667 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
1669 static $supportsCancel = array();
1671 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
1672 $supportsCancel[$cacheKeyString] = FALSE;
1673 $isCancelled = FALSE;
1675 if ($isNotCancelled) {
1676 $isCancelled = self
::isSubscriptionCancelled($mid);
1679 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($mid, 'membership', 'obj');
1680 if (!empty($paymentObject)) {
1681 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
1684 return $supportsCancel[$cacheKeyString];
1688 * Check whether subscription is already cancelled.
1694 * contribution status
1696 public static function isSubscriptionCancelled($mid) {
1698 SELECT cr.contribution_status_id
1699 FROM civicrm_contribution_recur cr
1700 LEFT JOIN civicrm_membership mem ON ( cr.id = mem.contribution_recur_id )
1701 WHERE mem.id = %1 LIMIT 1";
1702 $params = array(1 => array($mid, 'Integer'));
1703 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
1704 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
1705 if ($status == 'Cancelled') {
1712 * Get membership joins for a specified membership type.
1714 * Specifically, retrieves a count of still current memberships whose
1715 * join_date and start_date are within a specified date range. Dates match
1716 * the pattern "yyyy-mm-dd".
1718 * @param int $membershipTypeId
1719 * Membership type id.
1720 * @param int $startDate
1721 * Date on which to start counting.
1722 * @param int $endDate
1723 * Date on which to end counting.
1724 * @param bool|int $isTest if true, membership is for a test site
1727 * the number of members of type $membershipTypeId
1728 * whose join_date is between $startDate and $endDate and
1729 * whose start_date is between $startDate and $endDate
1731 public static function getMembershipJoins($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1732 $testClause = 'membership.is_test = 1';
1734 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1736 if (!self
::$_signupActType) {
1737 self
::_getActTypes();
1740 if (!self
::$_signupActType) {
1745 SELECT COUNT(DISTINCT membership.id) as member_count
1746 FROM civicrm_membership membership
1747 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1748 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1749 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1750 WHERE membership.membership_type_id = %2
1751 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1755 1 => array(self
::$_signupActType, 'Integer'),
1756 2 => array($membershipTypeId, 'Integer'),
1759 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1761 return (int) $memberCount;
1765 * Get membership renewals for a specified membership type.
1767 * Specifically, retrieves a count of still current memberships
1768 * whose join_date is before and start_date is within a specified date
1769 * range. Dates match the pattern "yyyy-mm-dd".
1771 * @param int $membershipTypeId
1772 * Membership type id.
1773 * @param int $startDate
1774 * Date on which to start counting.
1775 * @param int $endDate
1776 * Date on which to end counting.
1777 * @param bool|int $isTest if true, membership is for a test site
1780 * returns the number of members of type $membershipTypeId
1781 * whose join_date is before $startDate and
1782 * whose start_date is between $startDate and $endDate
1784 public static function getMembershipRenewals($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1785 $testClause = 'membership.is_test = 1';
1787 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1789 if (!self
::$_renewalActType) {
1790 self
::_getActTypes();
1793 if (!self
::$_renewalActType) {
1798 SELECT COUNT(DISTINCT membership.id) as member_count
1799 FROM civicrm_membership membership
1800 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1801 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1802 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1803 WHERE membership.membership_type_id = %2
1804 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1808 1 => array(self
::$_renewalActType, 'Integer'),
1809 2 => array($membershipTypeId, 'Integer'),
1811 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1813 return (int) $memberCount;
1817 * Create linkages between membership & contribution - note this is the wrong place for this code but this is a
1818 * refactoring step. This should be BAO functionality
1819 * @param $membership
1820 * @param $membershipContribution
1822 public static function linkMembershipPayment($membership, $membershipContribution) {
1823 CRM_Member_BAO_MembershipPayment
::create(array(
1824 'membership_id' => $membership->id
,
1825 'membership_type_id' => $membership->membership_type_id
,
1826 'contribution_id' => $membershipContribution->id
,
1831 * @param int $contactID
1832 * @param int $membershipTypeID
1833 * @param bool $is_test
1834 * @param string $changeToday
1835 * @param int $modifiedID
1836 * @param $customFieldsFormatted
1837 * @param $numRenewTerms
1838 * @param int $membershipID
1840 * @param int $contributionRecurID
1841 * @param $membershipSource
1842 * @param $isPayLater
1843 * @param int $campaignId
1844 * @param array $formDates
1845 * @param null|CRM_Contribute_BAO_Contribution $contribution
1846 * @param array $lineItems
1849 * @throws \CRM_Core_Exception
1851 public static function processMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $contributionRecurID, $membershipSource, $isPayLater, $campaignId, $formDates = array(), $contribution = NULL, $lineItems = array()) {
1852 $renewalMode = $updateStatusId = FALSE;
1853 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1855 $statusFormat = '%Y-%m-%d';
1856 $membershipTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipTypeID);
1859 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
1860 // is the same as the parent org of an existing membership of the contact
1861 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($contactID, $membershipTypeID,
1862 $is_test, $membershipID, TRUE
1864 if ($currentMembership) {
1865 $renewalMode = TRUE;
1867 // Do NOT do anything.
1868 //1. membership with status : PENDING/CANCELLED (CRM-2395)
1869 //2. Paylater/IPN renew. CRM-4556.
1870 if ($pending ||
in_array($currentMembership['status_id'], array(
1871 array_search('Pending', $allStatus),
1873 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1877 'id' => $currentMembership['id'],
1878 'contribution' => $contribution,
1879 'status_id' => $currentMembership['status_id'],
1880 'start_date' => $currentMembership['start_date'],
1881 'end_date' => $currentMembership['end_date'],
1882 'line_item' => $lineItems,
1883 'join_date' => $currentMembership['join_date'],
1884 'membership_type_id' => $membershipTypeID,
1885 'max_related' => !empty($membershipTypeDetails['max_related']) ?
$membershipTypeDetails['max_related'] : NULL,
1886 'membership_activity_status' => ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed',
1888 if ($contributionRecurID) {
1889 $memParams['contribution_recur_id'] = $contributionRecurID;
1892 $membership = self
::create($memParams, $ids, FALSE);
1893 return array($membership, $renewalMode, $dates);
1896 // Check and fix the membership if it is STALE
1897 self
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
1899 // Now Renew the membership
1900 if (!$currentMembership['is_current_member']) {
1901 // membership is not CURRENT
1903 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1904 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($currentMembership['id'],
1910 $currentMembership['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1911 foreach (array('start_date', 'end_date') as $dateType) {
1912 $currentMembership[$dateType] = CRM_Utils_Array
::value($dateType, $formDates);
1913 if (empty($currentMembership[$dateType])) {
1914 $currentMembership[$dateType] = CRM_Utils_Array
::value($dateType, $dates);
1917 $currentMembership['is_test'] = $is_test;
1919 if (!empty($membershipSource)) {
1920 $currentMembership['source'] = $membershipSource;
1923 $currentMembership['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
1924 $currentMembership['id'],
1929 if (!empty($currentMembership['id'])) {
1930 $ids['membership'] = $currentMembership['id'];
1932 $memParams = $currentMembership;
1933 $memParams['membership_type_id'] = $membershipTypeID;
1935 //set the log start date.
1936 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1940 // CURRENT Membership
1941 $membership = new CRM_Member_DAO_Membership();
1942 $membership->id
= $currentMembership['id'];
1943 $membership->find(TRUE);
1944 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1945 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
1951 // Insert renewed dates for CURRENT membership
1952 $memParams = array();
1953 $memParams['join_date'] = CRM_Utils_Date
::isoToMysql($membership->join_date
);
1954 $memParams['start_date'] = CRM_Utils_Array
::value('start_date', $formDates, CRM_Utils_Date
::isoToMysql($membership->start_date
));
1955 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $formDates);
1956 if (empty($memParams['end_date'])) {
1957 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $dates);
1959 $memParams['membership_type_id'] = $membershipTypeID;
1961 //set the log start date.
1962 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1965 if (!empty($membershipSource)) {
1966 $memParams['source'] = $membershipSource;
1968 elseif (empty($membership->source
)) {
1969 $memParams['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
1970 $currentMembership['id'],
1975 if (!empty($currentMembership['id'])) {
1976 $ids['membership'] = $currentMembership['id'];
1978 $memParams['membership_activity_status'] = ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed';
1982 $updateStatusId = array_search('Pending', $allStatus);
1988 'contact_id' => $contactID,
1989 'membership_type_id' => $membershipTypeID,
1993 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
1995 foreach (array('join_date', 'start_date', 'end_date') as $dateType) {
1996 $memParams[$dateType] = CRM_Utils_Array
::value($dateType, $formDates);
1997 if (empty($memParams[$dateType])) {
1998 $memParams[$dateType] = CRM_Utils_Array
::value($dateType, $dates);
2002 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(CRM_Utils_Date
::customFormat($dates['start_date'],
2005 CRM_Utils_Date
::customFormat($dates['end_date'],
2008 CRM_Utils_Date
::customFormat($dates['join_date'],
2016 $updateStatusId = CRM_Utils_Array
::value('id', $status);
2019 // if IPN/Pay-Later set status to: PENDING
2020 $updateStatusId = array_search('Pending', $allStatus);
2023 if (!empty($membershipSource)) {
2024 $memParams['source'] = $membershipSource;
2026 $memParams['is_test'] = $is_test;
2027 $memParams['is_pay_later'] = $isPayLater;
2029 // Putting this in an IF is precautionary as it seems likely that it would be ignored if empty, but
2030 // perhaps shouldn't be?
2031 if ($contributionRecurID) {
2032 $memParams['contribution_recur_id'] = $contributionRecurID;
2035 //if we decided status here and want to skip status
2036 //calculation in create( ); then need to pass 'skipStatusCal'.
2037 if ($updateStatusId) {
2038 $memParams['status_id'] = $updateStatusId;
2039 $memParams['skipStatusCal'] = TRUE;
2042 //since we are renewing,
2043 //make status override false.
2044 $memParams['is_override'] = FALSE;
2046 //CRM-4027, create log w/ individual contact.
2048 $ids['userId'] = $modifiedID;
2049 $memParams['is_for_organization'] = TRUE;
2052 $ids['userId'] = $contactID;
2055 //inherit campaign from contrib page.
2056 if (isset($campaignId)) {
2057 $memParams['campaign_id'] = $campaignId;
2060 $memParams['contribution'] = $contribution;
2061 $memParams['custom'] = $customFieldsFormatted;
2062 // Load all line items & process all in membership. Don't do in contribution.
2063 // Relevant tests in api_v3_ContributionPageTest.
2064 $memParams['line_item'] = $lineItems;
2065 $membership = self
::create($memParams, $ids, FALSE);
2067 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
2068 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
2069 $membership->find(TRUE);
2071 return array($membership, $renewalMode, $dates);
2075 * Get line items representing the default price set.
2077 * @param int $membershipOrg
2078 * @param int $membershipTypeID
2079 * @param float $total_amount
2080 * @param int $priceSetId
2084 public static function setQuickConfigMembershipParameters($membershipOrg, $membershipTypeID, $total_amount, $priceSetId) {
2085 $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
2087 // The name of the price field corresponds to the membership_type organization contact.
2089 'price_set_id' => $priceSetId,
2090 'name' => $membershipOrg,
2093 CRM_Price_BAO_PriceField
::retrieve($params, $results);
2095 if (!empty($results)) {
2096 $fields[$results['id']] = $priceSets['fields'][$results['id']];
2097 $fid = $results['id'];
2098 $editedFieldParams = array(
2099 'price_field_id' => $results['id'],
2100 'membership_type_id' => $membershipTypeID,
2103 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $results);
2104 $fields[$fid]['options'][$results['id']] = $priceSets['fields'][$fid]['options'][$results['id']];
2105 if (!empty($total_amount)) {
2106 $fields[$fid]['options'][$results['id']]['amount'] = $total_amount;
2110 $fieldID = key($fields);
2111 $returnParams = array(
2112 'price_set_id' => $priceSetId,
2113 'price_sets' => $priceSets,
2114 'fields' => $fields,
2115 'price_fields' => array(
2116 'price_' . $fieldID => CRM_Utils_Array
::value('id', $results),
2119 return $returnParams;
2123 * Update the status of all deceased members to deceased.
2126 * Count of updated contacts.
2128 protected static function updateDeceasedMembersStatuses() {
2131 $deceasedStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Deceased');
2133 // 'create' context for buildOptions returns only if enabled.
2134 $allStatus = self
::buildOptions('status_id', 'create');
2135 if (array_key_exists($deceasedStatusId, $allStatus) === FALSE) {
2136 // Deceased status is an admin status & is required. We want to fail early if
2137 // it is not present or active.
2138 // We could make the case 'some databases just don't use deceased so we will check
2139 // for the presence of a deceased contact in the DB before rejecting.
2140 if (CRM_Core_DAO
::singleValueQuery('
2141 SELECT count(*) FROM civicrm_contact WHERE is_deceased = 0'
2143 throw new CRM_Core_Exception(
2144 ts("Deceased Membership status is missing or not active. <a href='%1'>Click here to check</a>.",
2145 [1 => CRM_Utils_System
::url('civicrm/admin/member/membershipStatus', 'reset=1')]
2149 $deceasedDAO = CRM_Core_DAO
::executeQuery(
2151 SELECT membership.id as membership_id
2152 FROM civicrm_membership membership
2153 INNER JOIN civicrm_contact ON membership.contact_id = civicrm_contact.id
2154 INNER JOIN civicrm_membership_type ON membership.membership_type_id = civicrm_membership_type.id
2155 AND civicrm_membership_type.is_active = 1
2156 WHERE membership.is_test = 0
2157 AND civicrm_contact.is_deceased = 1
2158 AND membership.status_id <> %1
2160 [1 => [$deceasedStatusId, 'Integer']]
2162 while ($deceasedDAO->fetch()) {
2163 civicrm_api3('membership', 'create', [
2164 'id' => $deceasedDAO->membership_id
,
2165 'status_id' => $deceasedStatusId,
2166 'createActivity' => TRUE,
2167 'skipStatusCal' => TRUE,
2168 'skipRecentView' => TRUE,
2172 $deceasedDAO->free();
2177 * Process price set and line items.
2179 * @param int $membershipId
2180 * @param array $lineItem
2182 public function processPriceSet($membershipId, $lineItem) {
2183 //FIXME : need to move this too
2184 if (!$membershipId ||
!is_array($lineItem)
2185 || CRM_Utils_System
::isNull($lineItem)
2190 foreach ($lineItem as $priceSetId => $values) {
2194 foreach ($values as $line) {
2195 $line['entity_table'] = 'civicrm_membership';
2196 $line['entity_id'] = $membershipId;
2197 CRM_Price_BAO_LineItem
::create($line);
2203 * Retrieve the contribution id for the associated Membership id.
2204 * @todo we should get this off the line item
2206 * @param int $membershipId
2209 * if more than one payment associated with membership id need to be returned.
2214 public static function getMembershipContributionId($membershipId, $all = FALSE) {
2216 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
2217 $membershipPayment->membership_id
= $membershipId;
2218 if ($all && $membershipPayment->find()) {
2219 $contributionIds = array();
2220 while ($membershipPayment->fetch()) {
2221 $contributionIds[] = $membershipPayment->contribution_id
;
2223 return $contributionIds;
2226 if ($membershipPayment->find(TRUE)) {
2227 return $membershipPayment->contribution_id
;
2233 * The function checks and updates the status of all membership records for a given domain using the
2234 * calc_membership_status and update_contact_membership APIs.
2237 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
2241 public static function updateAllMembershipStatus() {
2242 // Tests for this function are in api_v3_JobTest. Please add tests for all updates.
2244 $updateCount = $processCount = self
::updateDeceasedMembersStatuses();
2246 $allTypes = CRM_Member_PseudoConstant
::membershipType();
2248 // This query retrieves ALL memberships of active types.
2250 SELECT civicrm_membership.id as membership_id,
2251 civicrm_membership.is_override as is_override,
2252 civicrm_membership.status_override_end_date as status_override_end_date,
2253 civicrm_membership.membership_type_id as membership_type_id,
2254 civicrm_membership.status_id as status_id,
2255 civicrm_membership.join_date as join_date,
2256 civicrm_membership.start_date as start_date,
2257 civicrm_membership.end_date as end_date,
2258 civicrm_membership.source as source,
2259 civicrm_contact.id as contact_id,
2260 civicrm_membership.owner_membership_id as owner_membership_id,
2261 civicrm_membership.contribution_recur_id as recur_id
2262 FROM civicrm_membership
2263 INNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )
2264 INNER JOIN civicrm_membership_type ON
2265 (civicrm_membership.membership_type_id = civicrm_membership_type.id AND civicrm_membership_type.is_active = 1)
2266 WHERE civicrm_membership.is_test = 0";
2268 $dao = CRM_Core_DAO
::executeQuery($baseQuery . " AND civicrm_contact.is_deceased = 0");
2270 $allStatus = self
::buildOptions('status_id', 'create');
2271 while ($dao->fetch()) {
2274 $memberParams = array(
2275 'id' => $dao->membership_id
,
2276 'status_id' => $dao->status_id
,
2277 'contact_id' => $dao->contact_id
,
2278 'membership_type_id' => $dao->membership_type_id
,
2279 'membership_type' => $allTypes[$dao->membership_type_id
],
2280 'join_date' => $dao->join_date
,
2281 'start_date' => $dao->start_date
,
2282 'end_date' => $dao->end_date
,
2283 'source' => $dao->source
,
2284 'skipStatusCal' => TRUE,
2285 'skipRecentView' => TRUE,
2288 //we fetch related, since we need to check for deceased
2289 //now further processing is handle w/ main membership record.
2290 if ($dao->owner_membership_id
) {
2294 self
::processOverriddenUntilDateMembership($dao);
2296 //update membership records where status is NOT - Pending OR Cancelled.
2297 //as well as membership is not override.
2298 //skipping Expired membership records -> reduced extra processing( kiran )
2299 if (!$dao->is_override
&&
2300 !in_array($dao->status_id
, array(
2301 array_search('Pending', $allStatus),
2305 CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)
2307 array_search('Expired', $allStatus),
2311 // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses
2312 //get the membership status as per id.
2313 $newStatus = civicrm_api('membership_status', 'calc',
2315 'membership_id' => $dao->membership_id
,
2317 'ignore_admin_only' => TRUE,
2320 $statusId = CRM_Utils_Array
::value('id', $newStatus);
2322 //process only when status change.
2324 $statusId != $dao->status_id
2326 //take all params that need to save.
2327 $memParams = $memberParams;
2328 $memParams['status_id'] = $statusId;
2329 $memParams['createActivity'] = TRUE;
2330 $memParams['version'] = 3;
2332 // Unset columns which should remain unchanged from their current saved
2333 // values. This avoids race condition in which these values may have
2334 // been changed by other processes.
2336 $memParams['contact_id'],
2337 $memParams['membership_type_id'],
2338 $memParams['membership_type'],
2339 $memParams['join_date'],
2340 $memParams['start_date'],
2341 $memParams['end_date'],
2342 $memParams['source']
2345 //process member record.
2346 civicrm_api('membership', 'create', $memParams);
2351 $result['is_error'] = 0;
2352 $result['messages'] = ts('Processed %1 membership records. Updated %2 records.', array(
2360 * Set is_override for the 'overridden until date' membership to
2361 * False and clears the 'until date' field in case the 'until date'
2362 * is equal or after today date.
2364 * @param CRM_Core_DAO $membership
2365 * The membership to be processed
2367 private static function processOverriddenUntilDateMembership($membership) {
2368 $isOverriddenUntilDate = !empty($membership->is_override
) && !empty($membership->status_override_end_date
);
2369 if (!$isOverriddenUntilDate) {
2373 $todayDate = new DateTime();
2374 $todayDate->setTime(0, 0);
2376 $overrideEndDate = new DateTime($membership->status_override_end_date
);
2377 $overrideEndDate->setTime(0, 0);
2379 $datesDifference = $todayDate->diff($overrideEndDate);
2380 $daysDifference = (int) $datesDifference->format('%R%a');
2381 if ($daysDifference <= 0) {
2383 'id' => $membership->membership_id
,
2384 'is_override' => FALSE,
2385 'status_override_end_date' => 'null',
2387 civicrm_api3('membership', 'create', $params);
2392 * Returns the membership types for a particular contact
2393 * who has lifetime membership without end date.
2395 * @param int $contactID
2396 * @param bool $isTest
2397 * @param bool $onlyLifeTime
2401 public static function getAllContactMembership($contactID, $isTest = FALSE, $onlyLifeTime = FALSE) {
2402 $contactMembershipType = array();
2404 return $contactMembershipType;
2407 $dao = new CRM_Member_DAO_Membership();
2408 $dao->contact_id
= $contactID;
2409 $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
2410 $dao->whereAdd("status_id != $pendingStatusId");
2413 $dao->is_test
= $isTest;
2416 $dao->whereAdd('is_test IS NULL OR is_test = 0');
2419 if ($onlyLifeTime) {
2420 $dao->whereAdd('end_date IS NULL');
2424 while ($dao->fetch()) {
2425 $membership = array();
2426 CRM_Core_DAO
::storeValues($dao, $membership);
2427 $contactMembershipType[$dao->membership_type_id
] = $membership;
2429 return $contactMembershipType;
2433 * Record contribution record associated with membership.
2435 * @param array $params
2436 * Array of submitted params.
2438 * (param in process of being removed - try to use params) array of ids.
2440 * @return CRM_Contribute_BAO_Contribution
2442 public static function recordMembershipContribution(&$params, $ids = array()) {
2443 $membershipId = $params['membership_id'];
2444 $contributionParams = array();
2445 $config = CRM_Core_Config
::singleton();
2446 $contributionParams['currency'] = $config->defaultCurrency
;
2447 $contributionParams['receipt_date'] = (CRM_Utils_Array
::value('receipt_date', $params)) ?
$params['receipt_date'] : 'null';
2448 $contributionParams['source'] = CRM_Utils_Array
::value('contribution_source', $params);
2449 $contributionParams['non_deductible_amount'] = 'null';
2450 $contributionParams['skipCleanMoney'] = TRUE;
2451 $contributionParams['payment_processor'] = CRM_Utils_Array
::value('payment_processor_id', $params);
2452 $contributionSoftParams = CRM_Utils_Array
::value('soft_credit', $params);
2453 $recordContribution = array(
2458 'financial_type_id',
2459 'payment_instrument_id',
2463 'contribution_status_id',
2470 'contribution_recur_id',
2474 foreach ($recordContribution as $f) {
2475 $contributionParams[$f] = CRM_Utils_Array
::value($f, $params);
2478 // make entry in batch entity batch table
2479 if (!empty($params['batch_id'])) {
2480 $contributionParams['batch_id'] = $params['batch_id'];
2483 if (!empty($params['contribution_contact_id'])) {
2484 // deal with possibility of a different person paying for contribution
2485 $contributionParams['contact_id'] = $params['contribution_contact_id'];
2488 if (!empty($params['processPriceSet']) &&
2489 !empty($params['lineItems'])
2491 $contributionParams['line_item'] = CRM_Utils_Array
::value('lineItems', $params, NULL);
2494 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
2496 //CRM-13981, create new soft-credit record as to record payment from different person for this membership
2497 if (!empty($contributionSoftParams)) {
2498 if (!empty($params['batch_id'])) {
2499 foreach ($contributionSoftParams as $contributionSoft) {
2500 $contributionSoft['contribution_id'] = $contribution->id
;
2501 $contributionSoft['currency'] = $contribution->currency
;
2502 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoft);
2506 $contributionSoftParams['contribution_id'] = $contribution->id
;
2507 $contributionSoftParams['currency'] = $contribution->currency
;
2508 $contributionSoftParams['amount'] = $contribution->total_amount
;
2509 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoftParams);
2513 // store contribution id
2514 $params['contribution_id'] = $contribution->id
;
2516 //insert payment record for this membership
2517 if (empty($ids['contribution']) ||
!empty($params['is_recur'])) {
2518 CRM_Member_BAO_MembershipPayment
::create(array(
2519 'membership_id' => $membershipId,
2520 'contribution_id' => $contribution->id
,
2523 return $contribution;
2527 * @todo document me - I seem a bit out of date....
2529 public static function _getActTypes() {
2530 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2531 self
::$_renewalActType = CRM_Utils_Array
::key('Membership Renewal', $activityTypes);
2532 self
::$_signupActType = CRM_Utils_Array
::key('Membership Signup', $activityTypes);
2536 * Get all Cancelled Membership(s) for a contact
2538 * @param int $contactID
2540 * @param bool $isTest
2544 * Array of membership type
2546 public static function getContactsCancelledMembership($contactID, $isTest = FALSE) {
2550 $query = 'SELECT membership_type_id FROM civicrm_membership WHERE contact_id = %1 AND status_id = %2 AND is_test = %3';
2551 $queryParams = array(
2552 1 => array($contactID, 'Integer'),
2557 CRM_Member_PseudoConstant
::membershipStatus(
2559 " name = 'Cancelled' ",
2567 3 => array($isTest, 'Boolean'),
2570 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
2571 $cancelledMembershipIds = array();
2572 while ($dao->fetch()) {
2573 $cancelledMembershipIds[] = $dao->membership_type_id
;
2575 return $cancelledMembershipIds;
2579 * Merges the memberships from otherContactID to mainContactID.
2581 * General idea is to merge memberships in regards to their type. We
2582 * move the other contact’s contributions to the main contact’s
2583 * membership which has the same type (if any) and then we update
2584 * membership to avoid loosing `join_date`, `end_date`, and
2585 * `status_id`. In this function, we don’t touch the contributions
2586 * directly (CRM_Dedupe_Merger::moveContactBelongings() takes care
2589 * This function adds new SQL queries to the $sqlQueries parameter.
2591 * @param int $mainContactID
2592 * Contact id of main contact record.
2593 * @param int $otherContactID
2594 * Contact id of record which is going to merge.
2595 * @param array $sqlQueries
2596 * (reference) array of SQL queries to be executed.
2597 * @param array $tables
2598 * List of tables that have to be merged.
2599 * @param array $tableOperations
2600 * Special options/params for some tables to be merged.
2602 * @see CRM_Dedupe_Merger::cpTables()
2604 public static function mergeMemberships($mainContactID, $otherContactID, &$sqlQueries, $tables, $tableOperations) {
2606 * If the user requests not to merge memberships but to add them,
2607 * just attribute the `civicrm_membership` to the
2608 * `$mainContactID`. We have to do this here since the general
2609 * merge process is bypassed by this function.
2611 if (array_key_exists("civicrm_membership", $tableOperations) && $tableOperations['civicrm_membership']['add']) {
2612 $sqlQueries[] = "UPDATE IGNORE civicrm_membership SET contact_id = $mainContactID WHERE contact_id = $otherContactID";
2617 * Retrieve all memberships that belongs to each contacts and
2618 * keep track of each membership type.
2620 $mainContactMemberships = array();
2621 $otherContactMemberships = array();
2623 $sql = "SELECT id, membership_type_id FROM civicrm_membership membership WHERE contact_id = %1";
2624 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($mainContactID, "Integer")));
2625 while ($dao->fetch()) {
2626 $mainContactMemberships[$dao->id
] = $dao->membership_type_id
;
2629 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($otherContactID, "Integer")));
2630 while ($dao->fetch()) {
2631 $otherContactMemberships[$dao->id
] = $dao->membership_type_id
;
2635 * For each membership, move related contributions to the main
2636 * contact’s membership (by updating `membership_payments`). Then,
2637 * update membership’s `join_date` (if the other membership’s
2638 * join_date is older) and `end_date` (if the other membership’s
2639 * `end_date` is newer) and `status_id` (if the newly calculated
2640 * status is different).
2642 * FIXME: what should we do if we have multiple memberships with
2643 * the same type (currently we only take the first one)?
2646 foreach ($otherContactMemberships as $otherMembershipId => $otherMembershipTypeId) {
2647 if ($newMembershipId = array_search($otherMembershipTypeId, $mainContactMemberships)) {
2650 * Move other membership’s contributions to the main one only
2651 * if user requested to merge contributions.
2653 if (!empty($tables) && in_array('civicrm_contribution', $tables)) {
2654 $newSql[] = "UPDATE civicrm_membership_payment SET membership_id=$newMembershipId WHERE membership_id=$otherMembershipId";
2657 $sql = "SELECT * FROM civicrm_membership membership WHERE id = %1";
2659 $newMembership = CRM_Member_DAO_Membership
::findById($newMembershipId);
2660 $otherMembership = CRM_Member_DAO_Membership
::findById($otherMembershipId);
2663 if (new DateTime($otherMembership->join_date
) < new DateTime($newMembership->join_date
)) {
2664 $updates["join_date"] = $otherMembership->join_date
;
2667 if (new DateTime($otherMembership->end_date
) > new DateTime($newMembership->end_date
)) {
2668 $updates["end_date"] = $otherMembership->end_date
;
2671 if (count($updates)) {
2676 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
2677 isset($updates["start_date"]) ?
$updates["start_date"] : $newMembership->start_date
,
2678 isset($updates["end_date"]) ?
$updates["end_date"] : $newMembership->end_date
,
2679 isset($updates["join_date"]) ?
$updates["join_date"] : $newMembership->join_date
,
2686 if (!empty($status['id']) and $status['id'] != $newMembership->status_id
) {
2687 $updates['status_id'] = $status['id'];
2691 foreach ($updates as $k => $v) {
2692 $updates_sql[] = "$k = '{$v}'";
2695 $newSql[] = sprintf("UPDATE civicrm_membership SET %s WHERE id=%s", implode(", ", $updates_sql), $newMembershipId);
2696 $newSql[] = sprintf("DELETE FROM civicrm_membership WHERE id=%s", $otherMembershipId);
2702 $sqlQueries = array_merge($sqlQueries, $newSql);