3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
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 = CRM_Member_BAO_MembershipType
::getMembershipTypesByOrg($membershipType['member_of_contact_id']);
853 $memberTypesSameParentOrgList = implode(',', array_keys($memberTypesSameParentOrg));
854 $dao->whereAdd('membership_type_id IN (' . $memberTypesSameParentOrgList . ')');
858 if ($dao->find(TRUE)) {
859 $membership = array();
860 CRM_Core_DAO
::storeValues($dao, $membership);
861 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
862 $membership['status_id'],
863 'is_current_member', 'id'
865 $ownerMemberId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
867 'owner_membership_id', 'id'
869 if ($ownerMemberId) {
870 $membership['id'] = $membership['membership_id'] = $ownerMemberId;
871 $membership['membership_contact_id'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
880 if ($onlySameParentOrg && $memType) {
881 // see if there is a membership that has same parent as $memType but different parent than $membershipID
882 if ($dao->id
&& CRM_Core_Permission
::check('edit memberships')) {
883 // CRM-10016, This is probably a backend renewal, and make sure we return the same membership thats being renewed.
890 unset($dao->membership_type_id
);
891 if ($dao->find(TRUE)) {
892 $membership = array();
893 CRM_Core_DAO
::storeValues($dao, $membership);
894 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
895 $membership['status_id'],
896 'is_current_member', 'id'
905 * Combine all the importable fields from the lower levels object.
907 * @param string $contactType
909 * @param bool $status
912 * array of importable Fields
914 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
915 if (!self
::$_importableFields) {
916 if (!self
::$_importableFields) {
917 self
::$_importableFields = array();
921 $fields = array('' => array('title' => '- ' . ts('do not import') . ' -'));
924 $fields = array('' => array('title' => '- ' . ts('Membership Fields') . ' -'));
927 $tmpFields = CRM_Member_DAO_Membership
::import();
928 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
930 // Using new Dedupe rule.
932 'contact_type' => $contactType,
933 'used' => 'Unsupervised',
935 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
937 $tmpContactField = array();
938 if (is_array($fieldsArray)) {
939 foreach ($fieldsArray as $value) {
940 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
945 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
946 $tmpContactField[trim($value)] = CRM_Utils_Array
::value(trim($value), $contactFields);
948 $title = $tmpContactField[trim($value)]['title'] . " " . ts('(match to contact)');
951 $title = $tmpContactField[trim($value)]['title'];
953 $tmpContactField[trim($value)]['title'] = $title;
956 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
957 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " " . ts('(match to contact)');
959 $tmpFields['membership_contact_id']['title'] = $tmpFields['membership_contact_id']['title'] . " " . ts('(match to contact)');;
961 $fields = array_merge($fields, $tmpContactField);
962 $fields = array_merge($fields, $tmpFields);
963 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
964 self
::$_importableFields = $fields;
966 return self
::$_importableFields;
970 * Get all exportable fields.
972 * @return array return array of all exportable fields
974 public static function &exportableFields() {
975 $expFieldMembership = CRM_Member_DAO_Membership
::export();
977 $expFieldsMemType = CRM_Member_DAO_MembershipType
::export();
978 $fields = array_merge($expFieldMembership, $expFieldsMemType);
979 $fields = array_merge($fields, $expFieldMembership);
980 $membershipStatus = array(
981 'membership_status' => array(
982 'title' => ts('Membership Status'),
983 'name' => 'membership_status',
984 'type' => CRM_Utils_Type
::T_STRING
,
985 'where' => 'civicrm_membership_status.name',
988 //CRM-6161 fix for customdata export
989 $fields = array_merge($fields, $membershipStatus, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
994 * Get membership joins/renewals for a specified membership type.
996 * Specifically, retrieves a count of memberships whose "Membership
997 * Signup" or "Membership Renewal" activity falls in the given date range.
998 * Dates match the pattern "yyyy-mm-dd".
1000 * @param int $membershipTypeId
1001 * Membership type id.
1002 * @param int $startDate
1003 * Date on which to start counting.
1004 * @param int $endDate
1005 * Date on which to end counting.
1006 * @param bool|int $isTest if true, membership is for a test site
1007 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1010 * the number of members of type $membershipTypeId whose
1011 * start_date is between $startDate and $endDate
1013 public static function getMembershipStarts($membershipTypeId, $startDate, $endDate, $isTest = 0, $isOwner = 0) {
1015 $testClause = 'membership.is_test = 1';
1017 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1020 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1021 self
::_getActTypes();
1024 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1029 SELECT COUNT(DISTINCT membership.id) as member_count
1030 FROM civicrm_membership membership
1031 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id in (%1, %2))
1032 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1033 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1034 WHERE membership.membership_type_id = %3
1035 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1038 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1041 1 => array(self
::$_signupActType, 'Integer'),
1042 2 => array(self
::$_renewalActType, 'Integer'),
1043 3 => array($membershipTypeId, 'Integer'),
1046 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1047 return (int) $memberCount;
1051 * Get a count of membership for a specified membership type, optionally for a specified date.
1053 * The date must have the form yyyy-mm-dd.
1055 * If $date is omitted, this function counts as a member anyone whose
1056 * membership status_id indicates they're a current member.
1057 * If $date is given, this function counts as a member anyone who:
1058 * -- Has a start_date before $date and end_date after $date, or
1059 * -- Has a start_date before $date and is currently a member, as indicated
1060 * by the the membership's status_id.
1061 * The second condition takes care of records that have no end_date. These
1062 * are assumed to be lifetime memberships.
1064 * @param int $membershipTypeId
1065 * Membership type id.
1066 * @param string $date
1067 * The date for which to retrieve the count.
1068 * @param bool|int $isTest if true, membership is for a test site
1069 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1072 * the number of members of type $membershipTypeId as of $date.
1074 public static function getMembershipCount($membershipTypeId, $date = NULL, $isTest = 0, $isOwner = 0) {
1075 if (!CRM_Utils_Rule
::date($date)) {
1076 CRM_Core_Error
::fatal(ts('Invalid date "%1" (must have form yyyy-mm-dd).', array(1 => $date)));
1080 1 => array($membershipTypeId, 'Integer'),
1081 2 => array($isTest, 'Boolean'),
1083 $query = "SELECT count(civicrm_membership.id ) as member_count
1084 FROM civicrm_membership left join civicrm_membership_status on ( civicrm_membership.status_id = civicrm_membership_status.id )
1085 WHERE civicrm_membership.membership_type_id = %1
1086 AND civicrm_membership.contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)
1087 AND civicrm_membership.is_test = %2";
1089 $query .= " AND civicrm_membership_status.is_current_member = 1";
1092 $query .= " AND civicrm_membership.start_date <= '$date' AND civicrm_membership_status.is_current_member = 1";
1095 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1096 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1097 return (int) $memberCount;
1101 * Function check the status of the membership before adding membership for a contact.
1105 public static function statusAvailabilty() {
1106 $membership = new CRM_Member_DAO_MembershipStatus();
1107 $membership->whereAdd('is_active=1');
1108 return $membership->count();
1112 * Function for updating a membership record's contribution_recur_id.
1114 * @param CRM_Member_DAO_Membership $membership
1115 * @param \CRM_Contribute_BAO_Contribution|\CRM_Contribute_DAO_Contribution $contribution
1117 static public function updateRecurMembership(CRM_Member_DAO_Membership
$membership, CRM_Contribute_BAO_Contribution
$contribution) {
1119 if (empty($contribution->contribution_recur_id
)) {
1124 1 => array($contribution->contribution_recur_id
, 'Integer'),
1125 2 => array($membership->id
, 'Integer'),
1128 $sql = "UPDATE civicrm_membership SET contribution_recur_id = %1 WHERE id = %2";
1129 CRM_Core_DAO
::executeQuery($sql, $params);
1133 * Method to fix membership status of stale membership.
1135 * This method first checks if the membership is stale. If it is,
1136 * then status will be updated based on existing start and end
1137 * dates and log will be added for the status change.
1139 * @param array $currentMembership
1140 * Reference to the array.
1141 * containing all values of
1142 * the current membership
1143 * @param array $changeToday
1144 * Array of month, day, year.
1145 * values in case today needs
1146 * to be customised, null otherwise
1148 public static function fixMembershipStatusBeforeRenew(&$currentMembership, $changeToday) {
1151 $today = CRM_Utils_Date
::processDate($changeToday, NULL, FALSE, 'Y-m-d');
1154 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
1155 CRM_Utils_Array
::value('start_date', $currentMembership),
1156 CRM_Utils_Array
::value('end_date', $currentMembership),
1157 CRM_Utils_Array
::value('join_date', $currentMembership),
1160 $currentMembership['membership_type_id'],
1164 if (empty($status) ||
1165 empty($status['id'])
1167 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.'));
1170 $currentMembership['today_date'] = $today;
1172 if ($status['id'] !== $currentMembership['status_id']) {
1173 $oldStatus = $currentMembership['status_id'];
1174 $memberDAO = new CRM_Member_DAO_Membership();
1175 $memberDAO->id
= $currentMembership['id'];
1176 $memberDAO->find(TRUE);
1178 $memberDAO->status_id
= $status['id'];
1179 $memberDAO->join_date
= CRM_Utils_Date
::isoToMysql($memberDAO->join_date
);
1180 $memberDAO->start_date
= CRM_Utils_Date
::isoToMysql($memberDAO->start_date
);
1181 $memberDAO->end_date
= CRM_Utils_Date
::isoToMysql($memberDAO->end_date
);
1183 CRM_Core_DAO
::storeValues($memberDAO, $currentMembership);
1186 $currentMembership['is_current_member'] = CRM_Core_DAO
::getFieldValue(
1187 'CRM_Member_DAO_MembershipStatus',
1188 $currentMembership['status_id'],
1194 'membership_id' => $currentMembership['id'],
1195 'status_id' => $status['id'],
1196 'start_date' => CRM_Utils_Date
::customFormat(
1197 $currentMembership['start_date'],
1200 'end_date' => CRM_Utils_Date
::customFormat(
1201 $currentMembership['end_date'],
1204 'modified_date' => CRM_Utils_Date
::customFormat(
1205 $currentMembership['today_date'],
1208 'membership_type_id' => $currentMembership['membership_type_id'],
1209 'max_related' => CRM_Utils_Array
::value('max_related', $currentMembership, 0),
1212 $session = CRM_Core_Session
::singleton();
1213 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
1214 if ($session->get('userID')) {
1215 $logParams['modified_id'] = $session->get('userID');
1218 $logParams['modified_id'] = $currentMembership['contact_id'];
1221 //Create activity for status change.
1222 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
1223 CRM_Activity_BAO_Activity
::addActivity($memberDAO,
1224 'Change Membership Status',
1227 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$status['id']]}",
1228 'source_contact_id' => $logParams['modified_id'],
1229 'priority_id' => 'Normal',
1233 CRM_Member_BAO_MembershipLog
::add($logParams, CRM_Core_DAO
::$_nullArray);
1238 * Get the contribution page id from the membership record.
1240 * @param int $membershipID
1243 * contribution page id
1245 public static function getContributionPageId($membershipID) {
1247 SELECT c.contribution_page_id as pageID
1248 FROM civicrm_membership_payment mp, civicrm_contribution c
1249 WHERE mp.contribution_id = c.id
1250 AND c.contribution_page_id IS NOT NULL
1251 AND mp.membership_id = " . CRM_Utils_Type
::escape($membershipID, 'Integer')
1252 . " ORDER BY mp.id DESC";
1254 return CRM_Core_DAO
::singleValueQuery($query,
1255 CRM_Core_DAO
::$_nullArray
1260 * Updated related memberships.
1262 * @param int $ownerMembershipId
1263 * Owner Membership Id.
1264 * @param array $params
1265 * Formatted array of key => value.
1267 public static function updateRelatedMemberships($ownerMembershipId, $params) {
1268 $membership = new CRM_Member_DAO_Membership();
1269 $membership->owner_membership_id
= $ownerMembershipId;
1270 $membership->find();
1272 while ($membership->fetch()) {
1273 $relatedMembership = new CRM_Member_DAO_Membership();
1274 $relatedMembership->id
= $membership->id
;
1275 $relatedMembership->copyValues($params);
1276 $relatedMembership->save();
1277 $relatedMembership->free();
1280 $membership->free();
1284 * Get list of membership fields for profile.
1286 * For now we only allow custom membership fields to be in
1290 * FIXME: This param is ignored
1293 * the list of membership fields
1295 public static function getMembershipFields($mode = NULL) {
1296 $fields = CRM_Member_DAO_Membership
::export();
1298 unset($fields['membership_contact_id']);
1299 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1301 $membershipType = CRM_Member_DAO_MembershipType
::export();
1303 $membershipStatus = CRM_Member_DAO_MembershipStatus
::export();
1305 $fields = array_merge($fields, $membershipType, $membershipStatus);
1311 * Get the sort name of a contact for a particular membership.
1314 * Id of the membership.
1316 * @return null|string
1317 * sort name of the contact if found
1319 public static function sortName($id) {
1320 $id = CRM_Utils_Type
::escape($id, 'Integer');
1323 SELECT civicrm_contact.sort_name
1324 FROM civicrm_membership, civicrm_contact
1325 WHERE civicrm_membership.contact_id = civicrm_contact.id
1326 AND civicrm_membership.id = {$id}
1328 return CRM_Core_DAO
::singleValueQuery($query);
1332 * Create memberships for related contacts, taking into account the maximum related memberships.
1334 * @param array $params
1335 * Array of key - value pairs.
1336 * @param CRM_Core_DAO $dao
1337 * Membership object.
1339 * @param bool $reset
1341 * @return array|null
1342 * Membership details, if created.
1344 * @throws \CRM_Core_Exception
1346 public static function createRelatedMemberships(&$params, &$dao, $reset = FALSE) {
1347 static $relatedContactIds = array();
1349 // not sure why a static var is in use here - we need a way to reset it from the test suite
1350 $relatedContactIds = array();
1354 $membership = new CRM_Member_DAO_Membership();
1355 $membership->id
= $dao->id
;
1357 // required since create method doesn't return all the
1358 // parameters in the returned membership object
1359 if (!$membership->find(TRUE)) {
1362 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1363 // FIXME : While updating/ renewing the
1364 // membership, if the relationship is PAST then
1365 // the membership of the related contact must be
1367 // For that, getting Membership Status for which
1368 // is_current_member is 0. It works for the
1369 // generated data as there is only one membership
1370 // status having is_current_member = 0.
1371 // But this wont work exactly if there will be
1372 // more than one status having is_current_member = 0.
1373 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
1374 $membershipStatus->is_current_member
= 0;
1375 if ($membershipStatus->find(TRUE)) {
1376 $expiredStatusId = $membershipStatus->id
;
1379 $expiredStatusId = array_search('Expired', CRM_Member_PseudoConstant
::membershipStatus());
1382 $allRelatedContacts = array();
1383 $relatedContacts = array();
1384 if (!is_a($membership, 'CRM_Core_Error')) {
1385 $allRelatedContacts = CRM_Member_BAO_Membership
::checkMembershipRelationship($membership->id
,
1386 $membership->contact_id
,
1387 CRM_Utils_Array
::value('action', $params)
1391 // check for loops. CRM-4213
1392 // remove repeated related contacts, which already inherited membership.
1393 $relatedContactIds[$membership->contact_id
] = TRUE;
1394 foreach ($allRelatedContacts as $cid => $status) {
1395 if (empty($relatedContactIds[$cid])) {
1396 $relatedContactIds[$cid] = TRUE;
1398 //don't create membership again for owner contact.
1399 $nestedRelationship = FALSE;
1400 if ($membership->owner_membership_id
) {
1401 $nestedRelMembership = new CRM_Member_DAO_Membership();
1402 $nestedRelMembership->id
= $membership->owner_membership_id
;
1403 $nestedRelMembership->contact_id
= $cid;
1404 $nestedRelationship = $nestedRelMembership->find(TRUE);
1405 $nestedRelMembership->free();
1407 if (!$nestedRelationship) {
1408 $relatedContacts[$cid] = $status;
1413 //lets cleanup related membership if any.
1414 if (empty($relatedContacts)) {
1415 self
::deleteRelatedMemberships($membership->id
);
1418 // Edit the params array
1419 unset($params['id']);
1420 // Reminder should be sent only to the direct membership
1421 unset($params['reminder_date']);
1422 // unset the custom value ids
1423 if (is_array(CRM_Utils_Array
::value('custom', $params))) {
1424 foreach ($params['custom'] as $k => $v) {
1425 unset($params['custom'][$k]['id']);
1428 if (!isset($params['membership_type_id'])) {
1429 $params['membership_type_id'] = $membership->membership_type_id
;
1432 // max_related should be set in the parent membership
1433 unset($params['max_related']);
1434 // Number of inherited memberships available - NULL is interpreted as unlimited, '0' as none
1435 $available = ($membership->max_related
== NULL ? PHP_INT_MAX
: $membership->max_related
);
1436 // will be used to queue potential memberships to be created.
1439 foreach ($relatedContacts as $contactId => $relationshipStatus) {
1440 //use existing membership record.
1441 $relMembership = new CRM_Member_DAO_Membership();
1442 $relMembership->contact_id
= $contactId;
1443 $relMembership->owner_membership_id
= $membership->id
;
1444 $relMemIds = array();
1445 if ($relMembership->find(TRUE)) {
1446 $params['id'] = $relMemIds['membership'] = $relMembership->id
;
1448 $params['contact_id'] = $contactId;
1449 $params['owner_membership_id'] = $membership->id
;
1451 // set status_id as it might have been changed for
1452 // past relationship
1453 $params['status_id'] = $membership->status_id
;
1455 if ($deceasedStatusId &&
1456 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'is_deceased')
1458 $params['status_id'] = $deceasedStatusId;
1460 elseif ((CRM_Utils_Array
::value('action', $params) & CRM_Core_Action
::UPDATE
) &&
1461 ($relationshipStatus == CRM_Contact_BAO_Relationship
::PAST
)
1463 $params['status_id'] = $expiredStatusId;
1466 //don't calculate status again in create( );
1467 $params['skipStatusCal'] = TRUE;
1469 //do create activity if we changed status.
1470 if ($params['status_id'] != $relMembership->status_id
) {
1471 $params['createActivity'] = TRUE;
1474 // we should not created contribution record for related contacts, CRM-3371
1475 unset($params['contribution_status_id']);
1477 //CRM-16857: Do not create multiple line-items for inherited membership through priceset.
1478 unset($params['lineItems']);
1479 unset($params['line_item']);
1481 if (($params['status_id'] == $deceasedStatusId) ||
($params['status_id'] == $expiredStatusId)) {
1482 // related membership is not active so does not count towards maximum
1483 CRM_Member_BAO_Membership
::create($params, $relMemIds);
1486 // related membership already exists, so this is just an update
1487 if (isset($params['id'])) {
1488 if ($available > 0) {
1489 CRM_Member_BAO_Membership
::create($params, $relMemIds);
1493 // we have run out of inherited memberships, so delete extras
1494 self
::deleteMembership($params['id']);
1496 // we need to first check if there will remain inherited memberships, so queue it up
1503 // now go over the queue and create any available related memberships
1505 while (($available > 0) && ($params = each($queue))) {
1506 CRM_Member_BAO_Membership
::create($params['value'], $relMemIds);
1513 * Delete the record that are associated with this Membership Payment.
1515 * @param int $membershipId
1518 * $membershipPayment deleted membership payment object
1520 public static function deleteMembershipPayment($membershipId, $preserveContrib = FALSE) {
1522 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
1523 $membershipPayment->membership_id
= $membershipId;
1524 $membershipPayment->find();
1526 while ($membershipPayment->fetch()) {
1527 if (!$preserveContrib) {
1528 CRM_Contribute_BAO_Contribution
::deleteContribution($membershipPayment->contribution_id
);
1530 CRM_Utils_Hook
::pre('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1531 $membershipPayment->delete();
1532 CRM_Utils_Hook
::post('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1534 return $membershipPayment;
1538 * Build an array of available membership types.
1540 * @param CRM_Core_Form $form
1541 * @param array $membershipTypeID
1542 * @param bool $activeOnly
1543 * Do we only want active ones?
1544 * (probably this should default to TRUE but as a newly added parameter we are leaving default b
1545 * behaviour unchanged).
1549 public static function buildMembershipTypeValues(&$form, $membershipTypeID = array(), $activeOnly = FALSE) {
1550 $whereClause = " WHERE domain_id = " . CRM_Core_Config
::domainID();
1551 $membershipTypeIDS = (array) $membershipTypeID;
1554 $whereClause .= " AND is_active = 1 ";
1556 if (!empty($membershipTypeIDS)) {
1557 $allIDs = implode(',', $membershipTypeIDS);
1558 $whereClause .= " AND id IN ( $allIDs )";
1560 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes, CRM_Core_Action
::ADD
);
1562 if ($financialTypes) {
1563 $whereClause .= " AND financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1566 $whereClause .= " AND financial_type_id IN (0)";
1571 FROM civicrm_membership_type
1574 $dao = CRM_Core_DAO
::executeQuery($query);
1576 $membershipTypeValues = array();
1577 $membershipTypeFields = array(
1583 'financial_type_id',
1585 'member_of_contact_id',
1586 'relationship_type_id',
1587 'relationship_direction',
1590 'duration_interval',
1593 while ($dao->fetch()) {
1594 $membershipTypeValues[$dao->id
] = array();
1595 foreach ($membershipTypeFields as $mtField) {
1596 $membershipTypeValues[$dao->id
][$mtField] = $dao->$mtField;
1601 CRM_Utils_Hook
::membershipTypeValues($form, $membershipTypeValues);
1603 if (is_numeric($membershipTypeID) &&
1604 $membershipTypeID > 0
1606 return $membershipTypeValues[$membershipTypeID];
1609 return $membershipTypeValues;
1614 * Get membership record count for a Contact.
1616 * @param int $contactID
1617 * @param bool $activeOnly
1619 * @return null|string
1621 public static function getContactMembershipCount($contactID, $activeOnly = FALSE) {
1622 CRM_Financial_BAO_FinancialType
::getAvailableMembershipTypes($membershipTypes);
1623 $addWhere = " AND membership_type_id IN (0)";
1624 if (!empty($membershipTypes)) {
1625 $addWhere = " AND membership_type_id IN (" . implode(',', array_keys($membershipTypes)) . ")";
1627 $select = "SELECT count(*) FROM civicrm_membership ";
1628 $where = "WHERE civicrm_membership.contact_id = {$contactID} AND civicrm_membership.is_test = 0 ";
1630 // CRM-6627, all status below 3 (active, pending, grace) are considered active
1632 $select .= " INNER JOIN civicrm_membership_status ON civicrm_membership.status_id = civicrm_membership_status.id ";
1633 $where .= " and civicrm_membership_status.is_current_member = 1";
1636 $query = $select . $where . $addWhere;
1637 return CRM_Core_DAO
::singleValueQuery($query);
1641 * Check whether payment processor supports cancellation of membership subscription.
1646 * @param bool $isNotCancelled
1650 public static function isCancelSubscriptionSupported($mid, $isNotCancelled = TRUE) {
1651 $cacheKeyString = "$mid";
1652 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
1654 static $supportsCancel = array();
1656 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
1657 $supportsCancel[$cacheKeyString] = FALSE;
1658 $isCancelled = FALSE;
1660 if ($isNotCancelled) {
1661 $isCancelled = self
::isSubscriptionCancelled($mid);
1664 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($mid, 'membership', 'obj');
1665 if (!empty($paymentObject)) {
1666 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
1669 return $supportsCancel[$cacheKeyString];
1673 * Check whether subscription is already cancelled.
1679 * contribution status
1681 public static function isSubscriptionCancelled($mid) {
1683 SELECT cr.contribution_status_id
1684 FROM civicrm_contribution_recur cr
1685 LEFT JOIN civicrm_membership mem ON ( cr.id = mem.contribution_recur_id )
1686 WHERE mem.id = %1 LIMIT 1";
1687 $params = array(1 => array($mid, 'Integer'));
1688 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
1689 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
1690 if ($status == 'Cancelled') {
1697 * Get membership joins for a specified membership type.
1699 * Specifically, retrieves a count of still current memberships whose
1700 * join_date and start_date are within a specified date range. Dates match
1701 * the pattern "yyyy-mm-dd".
1703 * @param int $membershipTypeId
1704 * Membership type id.
1705 * @param int $startDate
1706 * Date on which to start counting.
1707 * @param int $endDate
1708 * Date on which to end counting.
1709 * @param bool|int $isTest if true, membership is for a test site
1712 * the number of members of type $membershipTypeId
1713 * whose join_date is between $startDate and $endDate and
1714 * whose start_date is between $startDate and $endDate
1716 public static function getMembershipJoins($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1717 $testClause = 'membership.is_test = 1';
1719 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1721 if (!self
::$_signupActType) {
1722 self
::_getActTypes();
1725 if (!self
::$_signupActType) {
1730 SELECT COUNT(DISTINCT membership.id) as member_count
1731 FROM civicrm_membership membership
1732 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1733 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1734 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1735 WHERE membership.membership_type_id = %2
1736 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1740 1 => array(self
::$_signupActType, 'Integer'),
1741 2 => array($membershipTypeId, 'Integer'),
1744 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1746 return (int) $memberCount;
1750 * Get membership renewals for a specified membership type.
1752 * Specifically, retrieves a count of still current memberships
1753 * whose join_date is before and start_date is within a specified date
1754 * range. Dates match the pattern "yyyy-mm-dd".
1756 * @param int $membershipTypeId
1757 * Membership type id.
1758 * @param int $startDate
1759 * Date on which to start counting.
1760 * @param int $endDate
1761 * Date on which to end counting.
1762 * @param bool|int $isTest if true, membership is for a test site
1765 * returns the number of members of type $membershipTypeId
1766 * whose join_date is before $startDate and
1767 * whose start_date is between $startDate and $endDate
1769 public static function getMembershipRenewals($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1770 $testClause = 'membership.is_test = 1';
1772 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1774 if (!self
::$_renewalActType) {
1775 self
::_getActTypes();
1778 if (!self
::$_renewalActType) {
1783 SELECT COUNT(DISTINCT membership.id) as member_count
1784 FROM civicrm_membership membership
1785 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1786 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1787 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1788 WHERE membership.membership_type_id = %2
1789 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1793 1 => array(self
::$_renewalActType, 'Integer'),
1794 2 => array($membershipTypeId, 'Integer'),
1796 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1798 return (int) $memberCount;
1802 * Create linkages between membership & contribution - note this is the wrong place for this code but this is a
1803 * refactoring step. This should be BAO functionality
1804 * @param $membership
1805 * @param $membershipContribution
1807 public static function linkMembershipPayment($membership, $membershipContribution) {
1808 CRM_Member_BAO_MembershipPayment
::create(array(
1809 'membership_id' => $membership->id
,
1810 'membership_type_id' => $membership->membership_type_id
,
1811 'contribution_id' => $membershipContribution->id
,
1816 * @param int $contactID
1817 * @param int $membershipTypeID
1818 * @param bool $is_test
1819 * @param $changeToday
1820 * @param int $modifiedID
1821 * @param $customFieldsFormatted
1822 * @param $numRenewTerms
1823 * @param int $membershipID
1825 * @param int $contributionRecurID
1826 * @param $membershipSource
1827 * @param $isPayLater
1828 * @param int $campaignId
1829 * @param array $formDates
1830 * @param null|CRM_Contribute_BAO_Contribution $contribution
1831 * @param array $lineItems
1834 * @throws \CRM_Core_Exception
1836 public static function processMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $contributionRecurID, $membershipSource, $isPayLater, $campaignId, $formDates = array(), $contribution = NULL, $lineItems = array()) {
1837 $renewalMode = $updateStatusId = FALSE;
1838 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1840 $statusFormat = '%Y-%m-%d';
1841 $membershipTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipTypeID);
1844 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
1845 // is the same as the parent org of an existing membership of the contact
1846 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($contactID, $membershipTypeID,
1847 $is_test, $membershipID, TRUE
1849 if ($currentMembership) {
1850 $renewalMode = TRUE;
1852 // Do NOT do anything.
1853 //1. membership with status : PENDING/CANCELLED (CRM-2395)
1854 //2. Paylater/IPN renew. CRM-4556.
1855 if ($pending ||
in_array($currentMembership['status_id'], array(
1856 array_search('Pending', $allStatus),
1858 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1862 'id' => $currentMembership['id'],
1863 'contribution' => $contribution,
1864 'status_id' => $currentMembership['status_id'],
1865 'start_date' => $currentMembership['start_date'],
1866 'end_date' => $currentMembership['end_date'],
1867 'line_item' => $lineItems,
1868 'join_date' => $currentMembership['join_date'],
1869 'membership_type_id' => $membershipTypeID,
1870 'max_related' => !empty($membershipTypeDetails['max_related']) ?
$membershipTypeDetails['max_related'] : NULL,
1871 'membership_activity_status' => ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed',
1873 if ($contributionRecurID) {
1874 $memParams['contribution_recur_id'] = $contributionRecurID;
1877 $membership = self
::create($memParams, $ids, FALSE);
1878 return array($membership, $renewalMode, $dates);
1881 // Check and fix the membership if it is STALE
1882 self
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
1884 // Now Renew the membership
1885 if (!$currentMembership['is_current_member']) {
1886 // membership is not CURRENT
1888 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1889 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($currentMembership['id'],
1895 $currentMembership['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1896 foreach (array('start_date', 'end_date') as $dateType) {
1897 $currentMembership[$dateType] = CRM_Utils_Array
::value($dateType, $formDates);
1898 if (empty($currentMembership[$dateType])) {
1899 $currentMembership[$dateType] = CRM_Utils_Array
::value($dateType, $dates);
1902 $currentMembership['is_test'] = $is_test;
1904 if (!empty($membershipSource)) {
1905 $currentMembership['source'] = $membershipSource;
1908 $currentMembership['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
1909 $currentMembership['id'],
1914 if (!empty($currentMembership['id'])) {
1915 $ids['membership'] = $currentMembership['id'];
1917 $memParams = $currentMembership;
1918 $memParams['membership_type_id'] = $membershipTypeID;
1920 //set the log start date.
1921 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1925 // CURRENT Membership
1926 $membership = new CRM_Member_DAO_Membership();
1927 $membership->id
= $currentMembership['id'];
1928 $membership->find(TRUE);
1929 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1930 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
1936 // Insert renewed dates for CURRENT membership
1937 $memParams = array();
1938 $memParams['join_date'] = CRM_Utils_Date
::isoToMysql($membership->join_date
);
1939 $memParams['start_date'] = CRM_Utils_Array
::value('start_date', $formDates, CRM_Utils_Date
::isoToMysql($membership->start_date
));
1940 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $formDates);
1941 if (empty($memParams['end_date'])) {
1942 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $dates);
1944 $memParams['membership_type_id'] = $membershipTypeID;
1946 //set the log start date.
1947 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1950 if (!empty($membershipSource)) {
1951 $memParams['source'] = $membershipSource;
1953 elseif (empty($membership->source
)) {
1954 $memParams['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
1955 $currentMembership['id'],
1960 if (!empty($currentMembership['id'])) {
1961 $ids['membership'] = $currentMembership['id'];
1963 $memParams['membership_activity_status'] = ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed';
1967 $updateStatusId = array_search('Pending', $allStatus);
1973 'contact_id' => $contactID,
1974 'membership_type_id' => $membershipTypeID,
1978 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
1980 foreach (array('join_date', 'start_date', 'end_date') as $dateType) {
1981 $memParams[$dateType] = CRM_Utils_Array
::value($dateType, $formDates);
1982 if (empty($memParams[$dateType])) {
1983 $memParams[$dateType] = CRM_Utils_Array
::value($dateType, $dates);
1987 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(CRM_Utils_Date
::customFormat($dates['start_date'],
1990 CRM_Utils_Date
::customFormat($dates['end_date'],
1993 CRM_Utils_Date
::customFormat($dates['join_date'],
2001 $updateStatusId = CRM_Utils_Array
::value('id', $status);
2004 // if IPN/Pay-Later set status to: PENDING
2005 $updateStatusId = array_search('Pending', $allStatus);
2008 if (!empty($membershipSource)) {
2009 $memParams['source'] = $membershipSource;
2011 $memParams['is_test'] = $is_test;
2012 $memParams['is_pay_later'] = $isPayLater;
2014 // Putting this in an IF is precautionary as it seems likely that it would be ignored if empty, but
2015 // perhaps shouldn't be?
2016 if ($contributionRecurID) {
2017 $memParams['contribution_recur_id'] = $contributionRecurID;
2020 //if we decided status here and want to skip status
2021 //calculation in create( ); then need to pass 'skipStatusCal'.
2022 if ($updateStatusId) {
2023 $memParams['status_id'] = $updateStatusId;
2024 $memParams['skipStatusCal'] = TRUE;
2027 //since we are renewing,
2028 //make status override false.
2029 $memParams['is_override'] = FALSE;
2031 //CRM-4027, create log w/ individual contact.
2033 $ids['userId'] = $modifiedID;
2034 $memParams['is_for_organization'] = TRUE;
2037 $ids['userId'] = $contactID;
2040 //inherit campaign from contrib page.
2041 if (isset($campaignId)) {
2042 $memParams['campaign_id'] = $campaignId;
2045 $memParams['contribution'] = $contribution;
2046 $memParams['custom'] = $customFieldsFormatted;
2047 // Load all line items & process all in membership. Don't do in contribution.
2048 // Relevant tests in api_v3_ContributionPageTest.
2049 $memParams['line_item'] = $lineItems;
2050 $membership = self
::create($memParams, $ids, FALSE);
2052 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
2053 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
2054 $membership->find(TRUE);
2056 return array($membership, $renewalMode, $dates);
2060 * Get line items representing the default price set.
2062 * @param int $membershipOrg
2063 * @param int $membershipTypeID
2064 * @param float $total_amount
2065 * @param int $priceSetId
2069 public static function setQuickConfigMembershipParameters($membershipOrg, $membershipTypeID, $total_amount, $priceSetId) {
2070 $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
2072 // The name of the price field corresponds to the membership_type organization contact.
2074 'price_set_id' => $priceSetId,
2075 'name' => $membershipOrg,
2078 CRM_Price_BAO_PriceField
::retrieve($params, $results);
2080 if (!empty($results)) {
2081 $fields[$results['id']] = $priceSets['fields'][$results['id']];
2082 $fid = $results['id'];
2083 $editedFieldParams = array(
2084 'price_field_id' => $results['id'],
2085 'membership_type_id' => $membershipTypeID,
2088 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $results);
2089 $fields[$fid]['options'][$results['id']] = $priceSets['fields'][$fid]['options'][$results['id']];
2090 if (!empty($total_amount)) {
2091 $fields[$fid]['options'][$results['id']]['amount'] = $total_amount;
2095 $fieldID = key($fields);
2096 $returnParams = array(
2097 'price_set_id' => $priceSetId,
2098 'price_sets' => $priceSets,
2099 'fields' => $fields,
2100 'price_fields' => array(
2101 'price_' . $fieldID => CRM_Utils_Array
::value('id', $results),
2104 return $returnParams;
2108 * Process price set and line items.
2110 * @param int $membershipId
2111 * @param array $lineItem
2113 public function processPriceSet($membershipId, $lineItem) {
2114 //FIXME : need to move this too
2115 if (!$membershipId ||
!is_array($lineItem)
2116 || CRM_Utils_System
::isNull($lineItem)
2121 foreach ($lineItem as $priceSetId => $values) {
2125 foreach ($values as $line) {
2126 $line['entity_table'] = 'civicrm_membership';
2127 $line['entity_id'] = $membershipId;
2128 CRM_Price_BAO_LineItem
::create($line);
2134 * Retrieve the contribution id for the associated Membership id.
2135 * @todo we should get this off the line item
2137 * @param int $membershipId
2140 * if more than one payment associated with membership id need to be returned.
2145 public static function getMembershipContributionId($membershipId, $all = FALSE) {
2147 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
2148 $membershipPayment->membership_id
= $membershipId;
2149 if ($all && $membershipPayment->find()) {
2150 $contributionIds = array();
2151 while ($membershipPayment->fetch()) {
2152 $contributionIds[] = $membershipPayment->contribution_id
;
2154 return $contributionIds;
2157 if ($membershipPayment->find(TRUE)) {
2158 return $membershipPayment->contribution_id
;
2164 * The function checks and updates the status of all membership records for a given domain using the
2165 * calc_membership_status and update_contact_membership APIs.
2168 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
2172 public static function updateAllMembershipStatus() {
2174 //get all active statuses of membership, CRM-3984
2175 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2176 $statusLabels = CRM_Member_PseudoConstant
::membershipStatus(NULL, NULL, 'label');
2177 $allTypes = CRM_Member_PseudoConstant
::membershipType();
2179 // get only memberships with active membership types
2181 SELECT civicrm_membership.id as membership_id,
2182 civicrm_membership.is_override as is_override,
2183 civicrm_membership.membership_type_id as membership_type_id,
2184 civicrm_membership.status_id as status_id,
2185 civicrm_membership.join_date as join_date,
2186 civicrm_membership.start_date as start_date,
2187 civicrm_membership.end_date as end_date,
2188 civicrm_membership.source as source,
2189 civicrm_contact.id as contact_id,
2190 civicrm_contact.is_deceased as is_deceased,
2191 civicrm_membership.owner_membership_id as owner_membership_id,
2192 civicrm_membership.contribution_recur_id as recur_id
2193 FROM civicrm_membership
2194 INNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )
2195 INNER JOIN civicrm_membership_type ON
2196 (civicrm_membership.membership_type_id = civicrm_membership_type.id AND civicrm_membership_type.is_active = 1)
2197 WHERE civicrm_membership.is_test = 0";
2200 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2205 $smarty = CRM_Core_Smarty
::singleton();
2207 while ($dao->fetch()) {
2211 // Put common parameters into array for easy access
2212 $memberParams = array(
2213 'id' => $dao->membership_id
,
2214 'status_id' => $dao->status_id
,
2215 'contact_id' => $dao->contact_id
,
2216 'membership_type_id' => $dao->membership_type_id
,
2217 'membership_type' => $allTypes[$dao->membership_type_id
],
2218 'join_date' => $dao->join_date
,
2219 'start_date' => $dao->start_date
,
2220 'end_date' => $dao->end_date
,
2221 'source' => $dao->source
,
2222 'skipStatusCal' => TRUE,
2223 'skipRecentView' => TRUE,
2226 $smarty->assign_by_ref('memberParams', $memberParams);
2228 //update membership record to Deceased if contact is deceased
2229 if ($dao->is_deceased
) {
2230 // check for 'Deceased' membership status, CRM-5636
2231 $deceaseStatusId = array_search('Deceased', $allStatus);
2232 if (!$deceaseStatusId) {
2233 CRM_Core_Error
::fatal(ts("Deceased Membership status is missing or not active. <a href='%1'>Click here to check</a>.", array(1 => CRM_Utils_System
::url('civicrm/admin/member/membershipStatus', 'reset=1'))));
2236 //process only when status change.
2237 if ($dao->status_id
!= $deceaseStatusId) {
2238 //take all params that need to save.
2239 $deceasedMembership = $memberParams;
2240 $deceasedMembership['status_id'] = $deceaseStatusId;
2241 $deceasedMembership['createActivity'] = TRUE;
2242 $deceasedMembership['version'] = 3;
2244 //since there is change in status.
2245 $statusChange = array('status_id' => $deceaseStatusId);
2246 $smarty->append_by_ref('memberParams', $statusChange, TRUE);
2248 $deceasedMembership['contact_id'],
2249 $deceasedMembership['membership_type_id'],
2250 $deceasedMembership['membership_type'],
2251 $deceasedMembership['join_date'],
2252 $deceasedMembership['start_date'],
2253 $deceasedMembership['end_date'],
2254 $deceasedMembership['source']
2257 //process membership record.
2258 civicrm_api('membership', 'create', $deceasedMembership);
2263 //we fetch related, since we need to check for deceased
2264 //now further processing is handle w/ main membership record.
2265 if ($dao->owner_membership_id
) {
2269 //update membership records where status is NOT - Pending OR Cancelled.
2270 //as well as membership is not override.
2271 //skipping Expired membership records -> reduced extra processing( kiran )
2272 if (!$dao->is_override
&&
2273 !in_array($dao->status_id
, array(
2274 array_search('Pending', $allStatus),
2278 CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)
2280 array_search('Expired', $allStatus),
2284 // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses
2285 //get the membership status as per id.
2286 $newStatus = civicrm_api('membership_status', 'calc',
2288 'membership_id' => $dao->membership_id
,
2290 'ignore_admin_only' => TRUE,
2293 $statusId = CRM_Utils_Array
::value('id', $newStatus);
2295 //process only when status change.
2297 $statusId != $dao->status_id
2299 //take all params that need to save.
2300 $memParams = $memberParams;
2301 $memParams['status_id'] = $statusId;
2302 $memParams['createActivity'] = TRUE;
2303 $memParams['version'] = 3;
2305 // Unset columns which should remain unchanged from their current saved
2306 // values. This avoids race condition in which these values may have
2307 // been changed by other processes.
2309 $memParams['contact_id'],
2310 $memParams['membership_type_id'],
2311 $memParams['membership_type'],
2312 $memParams['join_date'],
2313 $memParams['start_date'],
2314 $memParams['end_date'],
2315 $memParams['source']
2317 //since there is change in status.
2318 $statusChange = array('status_id' => $statusId);
2319 $smarty->append_by_ref('memberParams', $statusChange, TRUE);
2321 //process member record.
2322 civicrm_api('membership', 'create', $memParams);
2327 $result['is_error'] = 0;
2328 $result['messages'] = ts('Processed %1 membership records. Updated %2 records.', array(
2336 * Returns the membership types for a particular contact
2337 * who has lifetime membership without end date.
2339 * @param int $contactID
2340 * @param bool $isTest
2341 * @param bool $onlyLifeTime
2345 public static function getAllContactMembership($contactID, $isTest = FALSE, $onlyLifeTime = FALSE) {
2346 $contactMembershipType = array();
2348 return $contactMembershipType;
2351 $dao = new CRM_Member_DAO_Membership();
2352 $dao->contact_id
= $contactID;
2353 $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
2354 $dao->whereAdd("status_id != $pendingStatusId");
2357 $dao->is_test
= $isTest;
2360 $dao->whereAdd('is_test IS NULL OR is_test = 0');
2363 if ($onlyLifeTime) {
2364 $dao->whereAdd('end_date IS NULL');
2368 while ($dao->fetch()) {
2369 $membership = array();
2370 CRM_Core_DAO
::storeValues($dao, $membership);
2371 $contactMembershipType[$dao->membership_type_id
] = $membership;
2373 return $contactMembershipType;
2377 * Record contribution record associated with membership.
2379 * @param array $params
2380 * Array of submitted params.
2382 * (param in process of being removed - try to use params) array of ids.
2384 * @return CRM_Contribute_BAO_Contribution
2386 public static function recordMembershipContribution(&$params, $ids = array()) {
2387 $membershipId = $params['membership_id'];
2388 $contributionParams = array();
2389 $config = CRM_Core_Config
::singleton();
2390 $contributionParams['currency'] = $config->defaultCurrency
;
2391 $contributionParams['receipt_date'] = (CRM_Utils_Array
::value('receipt_date', $params)) ?
$params['receipt_date'] : 'null';
2392 $contributionParams['source'] = CRM_Utils_Array
::value('contribution_source', $params);
2393 $contributionParams['non_deductible_amount'] = 'null';
2394 $contributionParams['payment_processor'] = CRM_Utils_Array
::value('payment_processor_id', $params);
2395 $contributionSoftParams = CRM_Utils_Array
::value('soft_credit', $params);
2396 $recordContribution = array(
2401 'financial_type_id',
2402 'payment_instrument_id',
2406 'contribution_status_id',
2413 'contribution_recur_id',
2417 foreach ($recordContribution as $f) {
2418 $contributionParams[$f] = CRM_Utils_Array
::value($f, $params);
2421 // make entry in batch entity batch table
2422 if (!empty($params['batch_id'])) {
2423 $contributionParams['batch_id'] = $params['batch_id'];
2426 if (!empty($params['contribution_contact_id'])) {
2427 // deal with possibility of a different person paying for contribution
2428 $contributionParams['contact_id'] = $params['contribution_contact_id'];
2431 if (!empty($params['processPriceSet']) &&
2432 !empty($params['lineItems'])
2434 $contributionParams['line_item'] = CRM_Utils_Array
::value('lineItems', $params, NULL);
2437 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
2439 //CRM-13981, create new soft-credit record as to record payment from different person for this membership
2440 if (!empty($contributionSoftParams)) {
2441 if (!empty($params['batch_id'])) {
2442 foreach ($contributionSoftParams as $contributionSoft) {
2443 $contributionSoft['contribution_id'] = $contribution->id
;
2444 $contributionSoft['currency'] = $contribution->currency
;
2445 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoft);
2449 $contributionSoftParams['contribution_id'] = $contribution->id
;
2450 $contributionSoftParams['currency'] = $contribution->currency
;
2451 $contributionSoftParams['amount'] = $contribution->total_amount
;
2452 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoftParams);
2456 // store contribution id
2457 $params['contribution_id'] = $contribution->id
;
2459 //insert payment record for this membership
2460 if (empty($ids['contribution']) ||
!empty($params['is_recur'])) {
2461 CRM_Member_BAO_MembershipPayment
::create(array(
2462 'membership_id' => $membershipId,
2463 'contribution_id' => $contribution->id
,
2466 return $contribution;
2470 * @todo document me - I seem a bit out of date....
2472 public static function _getActTypes() {
2473 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2474 self
::$_renewalActType = CRM_Utils_Array
::key('Membership Renewal', $activityTypes);
2475 self
::$_signupActType = CRM_Utils_Array
::key('Membership Signup', $activityTypes);
2479 * Get all Cancelled Membership(s) for a contact
2481 * @param int $contactID
2483 * @param bool $isTest
2487 * Array of membership type
2489 public static function getContactsCancelledMembership($contactID, $isTest = FALSE) {
2493 $query = 'SELECT membership_type_id FROM civicrm_membership WHERE contact_id = %1 AND status_id = %2 AND is_test = %3';
2494 $queryParams = array(
2495 1 => array($contactID, 'Integer'),
2500 CRM_Member_PseudoConstant
::membershipStatus(
2502 " name = 'Cancelled' ",
2510 3 => array($isTest, 'Boolean'),
2513 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
2514 $cancelledMembershipIds = array();
2515 while ($dao->fetch()) {
2516 $cancelledMembershipIds[] = $dao->membership_type_id
;
2518 return $cancelledMembershipIds;