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($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 $memberDAO = new CRM_Member_DAO_Membership();
1174 $memberDAO->id
= $currentMembership['id'];
1175 $memberDAO->find(TRUE);
1177 $memberDAO->status_id
= $status['id'];
1178 $memberDAO->join_date
= CRM_Utils_Date
::isoToMysql($memberDAO->join_date
);
1179 $memberDAO->start_date
= CRM_Utils_Date
::isoToMysql($memberDAO->start_date
);
1180 $memberDAO->end_date
= CRM_Utils_Date
::isoToMysql($memberDAO->end_date
);
1182 CRM_Core_DAO
::storeValues($memberDAO, $currentMembership);
1185 $currentMembership['is_current_member'] = CRM_Core_DAO
::getFieldValue(
1186 'CRM_Member_DAO_MembershipStatus',
1187 $currentMembership['status_id'],
1193 'membership_id' => $currentMembership['id'],
1194 'status_id' => $status['id'],
1195 'start_date' => CRM_Utils_Date
::customFormat(
1196 $currentMembership['start_date'],
1199 'end_date' => CRM_Utils_Date
::customFormat(
1200 $currentMembership['end_date'],
1203 'modified_date' => CRM_Utils_Date
::customFormat(
1204 $currentMembership['today_date'],
1207 'membership_type_id' => $currentMembership['membership_type_id'],
1208 'max_related' => CRM_Utils_Array
::value('max_related', $currentMembership, 0),
1211 $session = CRM_Core_Session
::singleton();
1212 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
1213 if ($session->get('userID')) {
1214 $logParams['modified_id'] = $session->get('userID');
1217 $logParams['modified_id'] = $currentMembership['contact_id'];
1219 CRM_Member_BAO_MembershipLog
::add($logParams, CRM_Core_DAO
::$_nullArray);
1224 * Get the contribution page id from the membership record.
1226 * @param int $membershipID
1229 * contribution page id
1231 public static function getContributionPageId($membershipID) {
1233 SELECT c.contribution_page_id as pageID
1234 FROM civicrm_membership_payment mp, civicrm_contribution c
1235 WHERE mp.contribution_id = c.id
1236 AND c.contribution_page_id IS NOT NULL
1237 AND mp.membership_id = " . CRM_Utils_Type
::escape($membershipID, 'Integer')
1238 . " ORDER BY mp.id DESC";
1240 return CRM_Core_DAO
::singleValueQuery($query,
1241 CRM_Core_DAO
::$_nullArray
1246 * Updated related memberships.
1248 * @param int $ownerMembershipId
1249 * Owner Membership Id.
1250 * @param array $params
1251 * Formatted array of key => value.
1253 public static function updateRelatedMemberships($ownerMembershipId, $params) {
1254 $membership = new CRM_Member_DAO_Membership();
1255 $membership->owner_membership_id
= $ownerMembershipId;
1256 $membership->find();
1258 while ($membership->fetch()) {
1259 $relatedMembership = new CRM_Member_DAO_Membership();
1260 $relatedMembership->id
= $membership->id
;
1261 $relatedMembership->copyValues($params);
1262 $relatedMembership->save();
1263 $relatedMembership->free();
1266 $membership->free();
1270 * Get list of membership fields for profile.
1272 * For now we only allow custom membership fields to be in
1276 * FIXME: This param is ignored
1279 * the list of membership fields
1281 public static function getMembershipFields($mode = NULL) {
1282 $fields = CRM_Member_DAO_Membership
::export();
1284 unset($fields['membership_contact_id']);
1285 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1287 $membershipType = CRM_Member_DAO_MembershipType
::export();
1289 $membershipStatus = CRM_Member_DAO_MembershipStatus
::export();
1291 $fields = array_merge($fields, $membershipType, $membershipStatus);
1297 * Get the sort name of a contact for a particular membership.
1300 * Id of the membership.
1302 * @return null|string
1303 * sort name of the contact if found
1305 public static function sortName($id) {
1306 $id = CRM_Utils_Type
::escape($id, 'Integer');
1309 SELECT civicrm_contact.sort_name
1310 FROM civicrm_membership, civicrm_contact
1311 WHERE civicrm_membership.contact_id = civicrm_contact.id
1312 AND civicrm_membership.id = {$id}
1314 return CRM_Core_DAO
::singleValueQuery($query);
1318 * Create memberships for related contacts, taking into account the maximum related memberships.
1320 * @param array $params
1321 * Array of key - value pairs.
1322 * @param CRM_Core_DAO $dao
1323 * Membership object.
1325 * @param bool $reset
1327 * @return array|null
1328 * Membership details, if created.
1330 * @throws \CRM_Core_Exception
1332 public static function createRelatedMemberships(&$params, &$dao, $reset = FALSE) {
1333 static $relatedContactIds = array();
1335 // not sure why a static var is in use here - we need a way to reset it from the test suite
1336 $relatedContactIds = array();
1340 $membership = new CRM_Member_DAO_Membership();
1341 $membership->id
= $dao->id
;
1343 // required since create method doesn't return all the
1344 // parameters in the returned membership object
1345 if (!$membership->find(TRUE)) {
1348 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1349 // FIXME : While updating/ renewing the
1350 // membership, if the relationship is PAST then
1351 // the membership of the related contact must be
1353 // For that, getting Membership Status for which
1354 // is_current_member is 0. It works for the
1355 // generated data as there is only one membership
1356 // status having is_current_member = 0.
1357 // But this wont work exactly if there will be
1358 // more than one status having is_current_member = 0.
1359 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
1360 $membershipStatus->is_current_member
= 0;
1361 if ($membershipStatus->find(TRUE)) {
1362 $expiredStatusId = $membershipStatus->id
;
1365 $expiredStatusId = array_search('Expired', CRM_Member_PseudoConstant
::membershipStatus());
1368 $allRelatedContacts = array();
1369 $relatedContacts = array();
1370 if (!is_a($membership, 'CRM_Core_Error')) {
1371 $allRelatedContacts = CRM_Member_BAO_Membership
::checkMembershipRelationship($membership->id
,
1372 $membership->contact_id
,
1373 CRM_Utils_Array
::value('action', $params)
1377 // check for loops. CRM-4213
1378 // remove repeated related contacts, which already inherited membership.
1379 $relatedContactIds[$membership->contact_id
] = TRUE;
1380 foreach ($allRelatedContacts as $cid => $status) {
1381 if (empty($relatedContactIds[$cid])) {
1382 $relatedContactIds[$cid] = TRUE;
1384 //don't create membership again for owner contact.
1385 $nestedRelationship = FALSE;
1386 if ($membership->owner_membership_id
) {
1387 $nestedRelMembership = new CRM_Member_DAO_Membership();
1388 $nestedRelMembership->id
= $membership->owner_membership_id
;
1389 $nestedRelMembership->contact_id
= $cid;
1390 $nestedRelationship = $nestedRelMembership->find(TRUE);
1391 $nestedRelMembership->free();
1393 if (!$nestedRelationship) {
1394 $relatedContacts[$cid] = $status;
1399 //lets cleanup related membership if any.
1400 if (empty($relatedContacts)) {
1401 self
::deleteRelatedMemberships($membership->id
);
1404 // Edit the params array
1405 unset($params['id']);
1406 // Reminder should be sent only to the direct membership
1407 unset($params['reminder_date']);
1408 // unset the custom value ids
1409 if (is_array(CRM_Utils_Array
::value('custom', $params))) {
1410 foreach ($params['custom'] as $k => $v) {
1411 unset($params['custom'][$k]['id']);
1414 if (!isset($params['membership_type_id'])) {
1415 $params['membership_type_id'] = $membership->membership_type_id
;
1418 // max_related should be set in the parent membership
1419 unset($params['max_related']);
1420 // Number of inherited memberships available - NULL is interpreted as unlimited, '0' as none
1421 $available = ($membership->max_related
== NULL ? PHP_INT_MAX
: $membership->max_related
);
1422 // will be used to queue potential memberships to be created.
1425 foreach ($relatedContacts as $contactId => $relationshipStatus) {
1426 //use existing membership record.
1427 $relMembership = new CRM_Member_DAO_Membership();
1428 $relMembership->contact_id
= $contactId;
1429 $relMembership->owner_membership_id
= $membership->id
;
1430 $relMemIds = array();
1431 if ($relMembership->find(TRUE)) {
1432 $params['id'] = $relMemIds['membership'] = $relMembership->id
;
1434 $params['contact_id'] = $contactId;
1435 $params['owner_membership_id'] = $membership->id
;
1437 // set status_id as it might have been changed for
1438 // past relationship
1439 $params['status_id'] = $membership->status_id
;
1441 if ($deceasedStatusId &&
1442 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'is_deceased')
1444 $params['status_id'] = $deceasedStatusId;
1446 elseif ((CRM_Utils_Array
::value('action', $params) & CRM_Core_Action
::UPDATE
) &&
1447 ($relationshipStatus == CRM_Contact_BAO_Relationship
::PAST
)
1449 $params['status_id'] = $expiredStatusId;
1452 //don't calculate status again in create( );
1453 $params['skipStatusCal'] = TRUE;
1455 //do create activity if we changed status.
1456 if ($params['status_id'] != $relMembership->status_id
) {
1457 $params['createActivity'] = TRUE;
1460 // we should not created contribution record for related contacts, CRM-3371
1461 unset($params['contribution_status_id']);
1463 //CRM-16857: Do not create multiple line-items for inherited membership through priceset.
1464 unset($params['lineItems']);
1465 unset($params['line_item']);
1467 if (($params['status_id'] == $deceasedStatusId) ||
($params['status_id'] == $expiredStatusId)) {
1468 // related membership is not active so does not count towards maximum
1469 CRM_Member_BAO_Membership
::create($params, $relMemIds);
1472 // related membership already exists, so this is just an update
1473 if (isset($params['id'])) {
1474 if ($available > 0) {
1475 CRM_Member_BAO_Membership
::create($params, $relMemIds);
1479 // we have run out of inherited memberships, so delete extras
1480 self
::deleteMembership($params['id']);
1482 // we need to first check if there will remain inherited memberships, so queue it up
1489 // now go over the queue and create any available related memberships
1491 while (($available > 0) && ($params = each($queue))) {
1492 CRM_Member_BAO_Membership
::create($params['value'], $relMemIds);
1499 * Delete the record that are associated with this Membership Payment.
1501 * @param int $membershipId
1504 * $membershipPayment deleted membership payment object
1506 public static function deleteMembershipPayment($membershipId, $preserveContrib = FALSE) {
1508 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
1509 $membershipPayment->membership_id
= $membershipId;
1510 $membershipPayment->find();
1512 while ($membershipPayment->fetch()) {
1513 if (!$preserveContrib) {
1514 CRM_Contribute_BAO_Contribution
::deleteContribution($membershipPayment->contribution_id
);
1516 CRM_Utils_Hook
::pre('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1517 $membershipPayment->delete();
1518 CRM_Utils_Hook
::post('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1520 return $membershipPayment;
1524 * Build an array of available membership types.
1526 * @param CRM_Core_Form $form
1527 * @param array $membershipTypeID
1528 * @param bool $activeOnly
1529 * Do we only want active ones?
1530 * (probably this should default to TRUE but as a newly added parameter we are leaving default b
1531 * behaviour unchanged).
1535 public static function buildMembershipTypeValues(&$form, $membershipTypeID = array(), $activeOnly = FALSE) {
1536 $whereClause = " WHERE domain_id = " . CRM_Core_Config
::domainID();
1537 $membershipTypeIDS = (array) $membershipTypeID;
1540 $whereClause .= " AND is_active = 1 ";
1542 if (!empty($membershipTypeIDS)) {
1543 $allIDs = implode(',', $membershipTypeIDS);
1544 $whereClause .= " AND id IN ( $allIDs )";
1546 CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes, CRM_Core_Action
::ADD
);
1548 if ($financialTypes) {
1549 $whereClause .= " AND financial_type_id IN (" . implode(',', array_keys($financialTypes)) . ")";
1552 $whereClause .= " AND financial_type_id IN (0)";
1557 FROM civicrm_membership_type
1560 $dao = CRM_Core_DAO
::executeQuery($query);
1562 $membershipTypeValues = array();
1563 $membershipTypeFields = array(
1569 'financial_type_id',
1571 'member_of_contact_id',
1572 'relationship_type_id',
1573 'relationship_direction',
1576 'duration_interval',
1579 while ($dao->fetch()) {
1580 $membershipTypeValues[$dao->id
] = array();
1581 foreach ($membershipTypeFields as $mtField) {
1582 $membershipTypeValues[$dao->id
][$mtField] = $dao->$mtField;
1587 CRM_Utils_Hook
::membershipTypeValues($form, $membershipTypeValues);
1589 if (is_numeric($membershipTypeID) &&
1590 $membershipTypeID > 0
1592 return $membershipTypeValues[$membershipTypeID];
1595 return $membershipTypeValues;
1600 * Get membership record count for a Contact.
1602 * @param int $contactID
1603 * @param bool $activeOnly
1605 * @return null|string
1607 public static function getContactMembershipCount($contactID, $activeOnly = FALSE) {
1608 CRM_Financial_BAO_FinancialType
::getAvailableMembershipTypes($membershipTypes);
1609 $addWhere = " AND membership_type_id IN (0)";
1610 if (!empty($membershipTypes)) {
1611 $addWhere = " AND membership_type_id IN (" . implode(',', array_keys($membershipTypes)) . ")";
1613 $select = "SELECT count(*) FROM civicrm_membership ";
1614 $where = "WHERE civicrm_membership.contact_id = {$contactID} AND civicrm_membership.is_test = 0 ";
1616 // CRM-6627, all status below 3 (active, pending, grace) are considered active
1618 $select .= " INNER JOIN civicrm_membership_status ON civicrm_membership.status_id = civicrm_membership_status.id ";
1619 $where .= " and civicrm_membership_status.is_current_member = 1";
1622 $query = $select . $where . $addWhere;
1623 return CRM_Core_DAO
::singleValueQuery($query);
1627 * Check whether payment processor supports cancellation of membership subscription.
1632 * @param bool $isNotCancelled
1636 public static function isCancelSubscriptionSupported($mid, $isNotCancelled = TRUE) {
1637 $cacheKeyString = "$mid";
1638 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
1640 static $supportsCancel = array();
1642 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
1643 $supportsCancel[$cacheKeyString] = FALSE;
1644 $isCancelled = FALSE;
1646 if ($isNotCancelled) {
1647 $isCancelled = self
::isSubscriptionCancelled($mid);
1650 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($mid, 'membership', 'obj');
1651 if (!empty($paymentObject)) {
1652 $supportsCancel[$cacheKeyString] = $paymentObject->supports('cancelRecurring') && !$isCancelled;
1655 return $supportsCancel[$cacheKeyString];
1659 * Check whether subscription is already cancelled.
1665 * contribution status
1667 public static function isSubscriptionCancelled($mid) {
1669 SELECT cr.contribution_status_id
1670 FROM civicrm_contribution_recur cr
1671 LEFT JOIN civicrm_membership mem ON ( cr.id = mem.contribution_recur_id )
1672 WHERE mem.id = %1 LIMIT 1";
1673 $params = array(1 => array($mid, 'Integer'));
1674 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
1675 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
1676 if ($status == 'Cancelled') {
1683 * Get membership joins for a specified membership type.
1685 * Specifically, retrieves a count of still current memberships whose
1686 * join_date and start_date are within a specified date range. Dates match
1687 * the pattern "yyyy-mm-dd".
1689 * @param int $membershipTypeId
1690 * Membership type id.
1691 * @param int $startDate
1692 * Date on which to start counting.
1693 * @param int $endDate
1694 * Date on which to end counting.
1695 * @param bool|int $isTest if true, membership is for a test site
1698 * the number of members of type $membershipTypeId
1699 * whose join_date is between $startDate and $endDate and
1700 * whose start_date is between $startDate and $endDate
1702 public static function getMembershipJoins($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1703 $testClause = 'membership.is_test = 1';
1705 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1707 if (!self
::$_signupActType) {
1708 self
::_getActTypes();
1711 if (!self
::$_signupActType) {
1716 SELECT COUNT(DISTINCT membership.id) as member_count
1717 FROM civicrm_membership membership
1718 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1719 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1720 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1721 WHERE membership.membership_type_id = %2
1722 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1726 1 => array(self
::$_signupActType, 'Integer'),
1727 2 => array($membershipTypeId, 'Integer'),
1730 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1732 return (int) $memberCount;
1736 * Get membership renewals for a specified membership type.
1738 * Specifically, retrieves a count of still current memberships
1739 * whose join_date is before and start_date is within a specified date
1740 * range. Dates match the pattern "yyyy-mm-dd".
1742 * @param int $membershipTypeId
1743 * Membership type id.
1744 * @param int $startDate
1745 * Date on which to start counting.
1746 * @param int $endDate
1747 * Date on which to end counting.
1748 * @param bool|int $isTest if true, membership is for a test site
1751 * returns the number of members of type $membershipTypeId
1752 * whose join_date is before $startDate and
1753 * whose start_date is between $startDate and $endDate
1755 public static function getMembershipRenewals($membershipTypeId, $startDate, $endDate, $isTest = 0) {
1756 $testClause = 'membership.is_test = 1';
1758 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1760 if (!self
::$_renewalActType) {
1761 self
::_getActTypes();
1764 if (!self
::$_renewalActType) {
1769 SELECT COUNT(DISTINCT membership.id) as member_count
1770 FROM civicrm_membership membership
1771 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
1772 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1773 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1774 WHERE membership.membership_type_id = %2
1775 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1779 1 => array(self
::$_renewalActType, 'Integer'),
1780 2 => array($membershipTypeId, 'Integer'),
1782 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1784 return (int) $memberCount;
1788 * Create linkages between membership & contribution - note this is the wrong place for this code but this is a
1789 * refactoring step. This should be BAO functionality
1790 * @param $membership
1791 * @param $membershipContribution
1793 public static function linkMembershipPayment($membership, $membershipContribution) {
1794 CRM_Member_BAO_MembershipPayment
::create(array(
1795 'membership_id' => $membership->id
,
1796 'membership_type_id' => $membership->membership_type_id
,
1797 'contribution_id' => $membershipContribution->id
,
1802 * @param int $contactID
1803 * @param int $membershipTypeID
1804 * @param bool $is_test
1805 * @param $changeToday
1806 * @param int $modifiedID
1807 * @param $customFieldsFormatted
1808 * @param $numRenewTerms
1809 * @param int $membershipID
1811 * @param int $contributionRecurID
1812 * @param $membershipSource
1813 * @param $isPayLater
1814 * @param int $campaignId
1815 * @param array $formDates
1816 * @param null|CRM_Contribute_BAO_Contribution $contribution
1817 * @param array $lineItems
1820 * @throws \CRM_Core_Exception
1822 public static function processMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $contributionRecurID, $membershipSource, $isPayLater, $campaignId, $formDates = array(), $contribution = NULL, $lineItems = array()) {
1823 $renewalMode = $updateStatusId = FALSE;
1824 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1826 $statusFormat = '%Y-%m-%d';
1827 $membershipTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipTypeID);
1830 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
1831 // is the same as the parent org of an existing membership of the contact
1832 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($contactID, $membershipTypeID,
1833 $is_test, $membershipID, TRUE
1835 if ($currentMembership) {
1836 $renewalMode = TRUE;
1838 // Do NOT do anything.
1839 //1. membership with status : PENDING/CANCELLED (CRM-2395)
1840 //2. Paylater/IPN renew. CRM-4556.
1841 if ($pending ||
in_array($currentMembership['status_id'], array(
1842 array_search('Pending', $allStatus),
1844 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1848 'id' => $currentMembership['id'],
1849 'contribution' => $contribution,
1850 'status_id' => $currentMembership['status_id'],
1851 'start_date' => $currentMembership['start_date'],
1852 'end_date' => $currentMembership['end_date'],
1853 'line_item' => $lineItems,
1854 'join_date' => $currentMembership['join_date'],
1855 'membership_type_id' => $membershipTypeID,
1856 'max_related' => !empty($membershipTypeDetails['max_related']) ?
$membershipTypeDetails['max_related'] : NULL,
1857 'membership_activity_status' => ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed',
1859 if ($contributionRecurID) {
1860 $memParams['contribution_recur_id'] = $contributionRecurID;
1863 $membership = self
::create($memParams, $ids, FALSE);
1864 return array($membership, $renewalMode, $dates);
1867 // Check and fix the membership if it is STALE
1868 self
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
1870 // Now Renew the membership
1871 if (!$currentMembership['is_current_member']) {
1872 // membership is not CURRENT
1874 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1875 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($currentMembership['id'],
1881 $currentMembership['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
1882 foreach (array('start_date', 'end_date') as $dateType) {
1883 $currentMembership[$dateType] = CRM_Utils_Array
::value($dateType, $formDates);
1884 if (empty($currentMembership[$dateType])) {
1885 $currentMembership[$dateType] = CRM_Utils_Array
::value($dateType, $dates);
1888 $currentMembership['is_test'] = $is_test;
1890 if (!empty($membershipSource)) {
1891 $currentMembership['source'] = $membershipSource;
1894 $currentMembership['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
1895 $currentMembership['id'],
1900 if (!empty($currentMembership['id'])) {
1901 $ids['membership'] = $currentMembership['id'];
1903 $memParams = $currentMembership;
1904 $memParams['membership_type_id'] = $membershipTypeID;
1906 //set the log start date.
1907 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1911 // CURRENT Membership
1912 $membership = new CRM_Member_DAO_Membership();
1913 $membership->id
= $currentMembership['id'];
1914 $membership->find(TRUE);
1915 // CRM-7297 Membership Upsell - calculate dates based on new membership type
1916 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
1922 // Insert renewed dates for CURRENT membership
1923 $memParams = array();
1924 $memParams['join_date'] = CRM_Utils_Date
::isoToMysql($membership->join_date
);
1925 $memParams['start_date'] = CRM_Utils_Array
::value('start_date', $formDates, CRM_Utils_Date
::isoToMysql($membership->start_date
));
1926 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $formDates);
1927 if (empty($memParams['end_date'])) {
1928 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $dates);
1930 $memParams['membership_type_id'] = $membershipTypeID;
1932 //set the log start date.
1933 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
1936 if (!empty($membershipSource)) {
1937 $memParams['source'] = $membershipSource;
1939 elseif (empty($membership->source
)) {
1940 $memParams['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
1941 $currentMembership['id'],
1946 if (!empty($currentMembership['id'])) {
1947 $ids['membership'] = $currentMembership['id'];
1952 $updateStatusId = array_search('Pending', $allStatus);
1958 'contact_id' => $contactID,
1959 'membership_type_id' => $membershipTypeID,
1963 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
1965 foreach (array('join_date', 'start_date', 'end_date') as $dateType) {
1966 $memParams[$dateType] = CRM_Utils_Array
::value($dateType, $formDates);
1967 if (empty($memParams[$dateType])) {
1968 $memParams[$dateType] = CRM_Utils_Array
::value($dateType, $dates);
1972 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(CRM_Utils_Date
::customFormat($dates['start_date'],
1975 CRM_Utils_Date
::customFormat($dates['end_date'],
1978 CRM_Utils_Date
::customFormat($dates['join_date'],
1986 $updateStatusId = CRM_Utils_Array
::value('id', $status);
1989 // if IPN/Pay-Later set status to: PENDING
1990 $updateStatusId = array_search('Pending', $allStatus);
1993 if (!empty($membershipSource)) {
1994 $memParams['source'] = $membershipSource;
1996 $memParams['is_test'] = $is_test;
1997 $memParams['is_pay_later'] = $isPayLater;
1999 // Putting this in an IF is precautionary as it seems likely that it would be ignored if empty, but
2000 // perhaps shouldn't be?
2001 if ($contributionRecurID) {
2002 $memParams['contribution_recur_id'] = $contributionRecurID;
2005 //if we decided status here and want to skip status
2006 //calculation in create( ); then need to pass 'skipStatusCal'.
2007 if ($updateStatusId) {
2008 $memParams['status_id'] = $updateStatusId;
2009 $memParams['skipStatusCal'] = TRUE;
2012 //since we are renewing,
2013 //make status override false.
2014 $memParams['is_override'] = FALSE;
2016 //CRM-4027, create log w/ individual contact.
2018 $ids['userId'] = $modifiedID;
2019 $memParams['is_for_organization'] = TRUE;
2022 $ids['userId'] = $contactID;
2025 //inherit campaign from contrib page.
2026 if (isset($campaignId)) {
2027 $memParams['campaign_id'] = $campaignId;
2030 $memParams['contribution'] = $contribution;
2031 $memParams['custom'] = $customFieldsFormatted;
2032 // Load all line items & process all in membership. Don't do in contribution.
2033 // Relevant tests in api_v3_ContributionPageTest.
2034 $memParams['line_item'] = $lineItems;
2035 $membership = self
::create($memParams, $ids, FALSE);
2037 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
2038 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
2039 $membership->find(TRUE);
2041 return array($membership, $renewalMode, $dates);
2045 * Get line items representing the default price set.
2047 * @param int $membershipOrg
2048 * @param int $membershipTypeID
2049 * @param float $total_amount
2050 * @param int $priceSetId
2054 public static function setQuickConfigMembershipParameters($membershipOrg, $membershipTypeID, $total_amount, $priceSetId) {
2055 $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
2057 // The name of the price field corresponds to the membership_type organization contact.
2059 'price_set_id' => $priceSetId,
2060 'name' => $membershipOrg,
2063 CRM_Price_BAO_PriceField
::retrieve($params, $results);
2065 if (!empty($results)) {
2066 $fields[$results['id']] = $priceSets['fields'][$results['id']];
2067 $fid = $results['id'];
2068 $editedFieldParams = array(
2069 'price_field_id' => $results['id'],
2070 'membership_type_id' => $membershipTypeID,
2073 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $results);
2074 $fields[$fid]['options'][$results['id']] = $priceSets['fields'][$fid]['options'][$results['id']];
2075 if (!empty($total_amount)) {
2076 $fields[$fid]['options'][$results['id']]['amount'] = $total_amount;
2080 $fieldID = key($fields);
2081 $returnParams = array(
2082 'price_set_id' => $priceSetId,
2083 'price_sets' => $priceSets,
2084 'fields' => $fields,
2085 'price_fields' => array(
2086 'price_' . $fieldID => CRM_Utils_Array
::value('id', $results),
2089 return $returnParams;
2093 * Process price set and line items.
2095 * @param int $membershipId
2096 * @param array $lineItem
2098 public function processPriceSet($membershipId, $lineItem) {
2099 //FIXME : need to move this too
2100 if (!$membershipId ||
!is_array($lineItem)
2101 || CRM_Utils_System
::isNull($lineItem)
2106 foreach ($lineItem as $priceSetId => $values) {
2110 foreach ($values as $line) {
2111 $line['entity_table'] = 'civicrm_membership';
2112 $line['entity_id'] = $membershipId;
2113 CRM_Price_BAO_LineItem
::create($line);
2119 * Retrieve the contribution id for the associated Membership id.
2120 * @todo we should get this off the line item
2122 * @param int $membershipId
2128 public static function getMembershipContributionId($membershipId) {
2130 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
2131 $membershipPayment->membership_id
= $membershipId;
2132 if ($membershipPayment->find(TRUE)) {
2133 return $membershipPayment->contribution_id
;
2139 * The function checks and updates the status of all membership records for a given domain using the
2140 * calc_membership_status and update_contact_membership APIs.
2143 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
2147 public static function updateAllMembershipStatus() {
2149 //get all active statuses of membership, CRM-3984
2150 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2151 $statusLabels = CRM_Member_PseudoConstant
::membershipStatus(NULL, NULL, 'label');
2152 $allTypes = CRM_Member_PseudoConstant
::membershipType();
2154 // get only memberships with active membership types
2156 SELECT civicrm_membership.id as membership_id,
2157 civicrm_membership.is_override as is_override,
2158 civicrm_membership.membership_type_id as membership_type_id,
2159 civicrm_membership.status_id as status_id,
2160 civicrm_membership.join_date as join_date,
2161 civicrm_membership.start_date as start_date,
2162 civicrm_membership.end_date as end_date,
2163 civicrm_membership.source as source,
2164 civicrm_contact.id as contact_id,
2165 civicrm_contact.is_deceased as is_deceased,
2166 civicrm_membership.owner_membership_id as owner_membership_id,
2167 civicrm_membership.contribution_recur_id as recur_id
2168 FROM civicrm_membership
2169 INNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )
2170 INNER JOIN civicrm_membership_type ON
2171 (civicrm_membership.membership_type_id = civicrm_membership_type.id AND civicrm_membership_type.is_active = 1)
2172 WHERE civicrm_membership.is_test = 0";
2175 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2180 $smarty = CRM_Core_Smarty
::singleton();
2182 while ($dao->fetch()) {
2186 // Put common parameters into array for easy access
2187 $memberParams = array(
2188 'id' => $dao->membership_id
,
2189 'status_id' => $dao->status_id
,
2190 'contact_id' => $dao->contact_id
,
2191 'membership_type_id' => $dao->membership_type_id
,
2192 'membership_type' => $allTypes[$dao->membership_type_id
],
2193 'join_date' => $dao->join_date
,
2194 'start_date' => $dao->start_date
,
2195 'end_date' => $dao->end_date
,
2196 'source' => $dao->source
,
2197 'skipStatusCal' => TRUE,
2198 'skipRecentView' => TRUE,
2201 $smarty->assign_by_ref('memberParams', $memberParams);
2203 //update membership record to Deceased if contact is deceased
2204 if ($dao->is_deceased
) {
2205 // check for 'Deceased' membership status, CRM-5636
2206 $deceaseStatusId = array_search('Deceased', $allStatus);
2207 if (!$deceaseStatusId) {
2208 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'))));
2211 //process only when status change.
2212 if ($dao->status_id
!= $deceaseStatusId) {
2213 //take all params that need to save.
2214 $deceasedMembership = $memberParams;
2215 $deceasedMembership['status_id'] = $deceaseStatusId;
2216 $deceasedMembership['createActivity'] = TRUE;
2217 $deceasedMembership['version'] = 3;
2219 //since there is change in status.
2220 $statusChange = array('status_id' => $deceaseStatusId);
2221 $smarty->append_by_ref('memberParams', $statusChange, TRUE);
2223 $deceasedMembership['contact_id'],
2224 $deceasedMembership['membership_type_id'],
2225 $deceasedMembership['membership_type'],
2226 $deceasedMembership['join_date'],
2227 $deceasedMembership['start_date'],
2228 $deceasedMembership['end_date'],
2229 $deceasedMembership['source']
2232 //process membership record.
2233 civicrm_api('membership', 'create', $deceasedMembership);
2238 //we fetch related, since we need to check for deceased
2239 //now further processing is handle w/ main membership record.
2240 if ($dao->owner_membership_id
) {
2244 //update membership records where status is NOT - Pending OR Cancelled.
2245 //as well as membership is not override.
2246 //skipping Expired membership records -> reduced extra processing( kiran )
2247 if (!$dao->is_override
&&
2248 !in_array($dao->status_id
, array(
2249 array_search('Pending', $allStatus),
2253 CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)
2255 array_search('Expired', $allStatus),
2259 // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses
2260 //get the membership status as per id.
2261 $newStatus = civicrm_api('membership_status', 'calc',
2263 'membership_id' => $dao->membership_id
,
2265 'ignore_admin_only' => TRUE,
2268 $statusId = CRM_Utils_Array
::value('id', $newStatus);
2270 //process only when status change.
2272 $statusId != $dao->status_id
2274 //take all params that need to save.
2275 $memParams = $memberParams;
2276 $memParams['status_id'] = $statusId;
2277 $memParams['createActivity'] = TRUE;
2278 $memParams['version'] = 3;
2280 // Unset columns which should remain unchanged from their current saved
2281 // values. This avoids race condition in which these values may have
2282 // been changed by other processes.
2284 $memParams['contact_id'],
2285 $memParams['membership_type_id'],
2286 $memParams['membership_type'],
2287 $memParams['join_date'],
2288 $memParams['start_date'],
2289 $memParams['end_date'],
2290 $memParams['source']
2292 //since there is change in status.
2293 $statusChange = array('status_id' => $statusId);
2294 $smarty->append_by_ref('memberParams', $statusChange, TRUE);
2296 //process member record.
2297 civicrm_api('membership', 'create', $memParams);
2302 $result['is_error'] = 0;
2303 $result['messages'] = ts('Processed %1 membership records. Updated %2 records.', array(
2311 * Returns the membership types for a particular contact
2312 * who has lifetime membership without end date.
2314 * @param int $contactID
2315 * @param bool $isTest
2316 * @param bool $onlyLifeTime
2320 public static function getAllContactMembership($contactID, $isTest = FALSE, $onlyLifeTime = FALSE) {
2321 $contactMembershipType = array();
2323 return $contactMembershipType;
2326 $dao = new CRM_Member_DAO_Membership();
2327 $dao->contact_id
= $contactID;
2328 $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
2329 $dao->whereAdd("status_id != $pendingStatusId");
2332 $dao->is_test
= $isTest;
2335 $dao->whereAdd('is_test IS NULL OR is_test = 0');
2338 if ($onlyLifeTime) {
2339 $dao->whereAdd('end_date IS NULL');
2343 while ($dao->fetch()) {
2344 $membership = array();
2345 CRM_Core_DAO
::storeValues($dao, $membership);
2346 $contactMembershipType[$dao->membership_type_id
] = $membership;
2348 return $contactMembershipType;
2352 * Record contribution record associated with membership.
2354 * @param array $params
2355 * Array of submitted params.
2357 * (param in process of being removed - try to use params) array of ids.
2359 * @return CRM_Contribute_BAO_Contribution
2361 public static function recordMembershipContribution(&$params, $ids = array()) {
2362 $membershipId = $params['membership_id'];
2363 $contributionParams = array();
2364 $config = CRM_Core_Config
::singleton();
2365 $contributionParams['currency'] = $config->defaultCurrency
;
2366 $contributionParams['receipt_date'] = (CRM_Utils_Array
::value('receipt_date', $params)) ?
$params['receipt_date'] : 'null';
2367 $contributionParams['source'] = CRM_Utils_Array
::value('contribution_source', $params);
2368 $contributionParams['non_deductible_amount'] = 'null';
2369 $contributionParams['payment_processor'] = CRM_Utils_Array
::value('payment_processor_id', $params);
2370 $contributionSoftParams = CRM_Utils_Array
::value('soft_credit', $params);
2371 $recordContribution = array(
2376 'financial_type_id',
2377 'payment_instrument_id',
2381 'contribution_status_id',
2388 'contribution_recur_id',
2392 foreach ($recordContribution as $f) {
2393 $contributionParams[$f] = CRM_Utils_Array
::value($f, $params);
2396 // make entry in batch entity batch table
2397 if (!empty($params['batch_id'])) {
2398 $contributionParams['batch_id'] = $params['batch_id'];
2401 if (!empty($params['contribution_contact_id'])) {
2402 // deal with possibility of a different person paying for contribution
2403 $contributionParams['contact_id'] = $params['contribution_contact_id'];
2406 if (!empty($params['processPriceSet']) &&
2407 !empty($params['lineItems'])
2409 $contributionParams['line_item'] = CRM_Utils_Array
::value('lineItems', $params, NULL);
2412 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
2414 //CRM-13981, create new soft-credit record as to record payment from different person for this membership
2415 if (!empty($contributionSoftParams)) {
2416 if (!empty($params['batch_id'])) {
2417 foreach ($contributionSoftParams as $contributionSoft) {
2418 $contributionSoft['contribution_id'] = $contribution->id
;
2419 $contributionSoft['currency'] = $contribution->currency
;
2420 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoft);
2424 $contributionSoftParams['contribution_id'] = $contribution->id
;
2425 $contributionSoftParams['currency'] = $contribution->currency
;
2426 $contributionSoftParams['amount'] = $contribution->total_amount
;
2427 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoftParams);
2431 // store contribution id
2432 $params['contribution_id'] = $contribution->id
;
2434 //insert payment record for this membership
2435 if (empty($ids['contribution']) ||
!empty($params['is_recur'])) {
2436 CRM_Member_BAO_MembershipPayment
::create(array(
2437 'membership_id' => $membershipId,
2438 'contribution_id' => $contribution->id
,
2441 return $contribution;
2445 * @todo document me - I seem a bit out of date....
2447 public static function _getActTypes() {
2448 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2449 self
::$_renewalActType = CRM_Utils_Array
::key('Membership Renewal', $activityTypes);
2450 self
::$_signupActType = CRM_Utils_Array
::key('Membership Signup', $activityTypes);
2454 * Get all Cancelled Membership(s) for a contact
2456 * @param int $contactID
2458 * @param bool $isTest
2462 * Array of membership type
2464 public static function getContactsCancelledMembership($contactID, $isTest = FALSE) {
2468 $query = 'SELECT membership_type_id FROM civicrm_membership WHERE contact_id = %1 AND status_id = %2 AND is_test = %3';
2469 $queryParams = array(
2470 1 => array($contactID, 'Integer'),
2475 CRM_Member_PseudoConstant
::membershipStatus(
2477 " name = 'Cancelled' ",
2485 3 => array($isTest, 'Boolean'),
2488 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
2489 $cancelledMembershipIds = array();
2490 while ($dao->fetch()) {
2491 $cancelledMembershipIds[] = $dao->membership_type_id
;
2493 return $cancelledMembershipIds;