3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
35 class CRM_Member_BAO_Membership
extends CRM_Member_DAO_Membership
{
38 * Static field for all the membership information that we can potentially import
43 static $_importableFields = NULL;
45 static $_renewalActType = NULL;
47 static $_signupActType = NULL;
52 * @return \CRM_Member_DAO_Membership
57 public function __construct() {
58 parent
::__construct();
62 * Takes an associative array and creates a membership object
64 * the function extracts all the params it needs to initialize the created
65 * membership object. The params array could contain additional unused name/value
68 * @param array $params (reference ) an assoc array of name/value pairs
69 * @param array $ids the array that holds all the db ids
71 * @return CRM_Member_BAO_Membership object
74 public static function add(&$params, $ids = array()) {
75 $oldStatus = $oldType = NULL;
76 $params['id'] = CRM_Utils_Array
::value('id', $params, CRM_Utils_Array
::value('membership', $ids));
78 CRM_Utils_Hook
::pre('edit', 'Membership', $params['id'], $params);
81 CRM_Utils_Hook
::pre('create', 'Membership', $params['id'], $params);
84 // we do this after the hooks are called in case it has been altered
86 $membershipObj = new CRM_Member_DAO_Membership();
87 $membershipObj->id
= $id;
88 $membershipObj->find();
89 while ($membershipObj->fetch()) {
90 $oldStatus = $membershipObj->status_id
;
91 $oldType = $membershipObj->membership_type_id
;
95 if (array_key_exists('is_override', $params) && !$params['is_override']) {
96 $params['is_override'] = 'null';
99 $membership = new CRM_Member_BAO_Membership();
100 $membership->copyValues($params);
101 $membership->id
= $id;
106 if (empty($membership->contact_id
) ||
empty($membership->status_id
)) {
107 // this means we are in renewal mode and are just updating the membership
108 // record or this is an API update call and all fields are not present in the update record
109 // however the hooks dont care and want all data CRM-7784
110 $tempMembership = new CRM_Member_DAO_Membership();
111 $tempMembership->id
= $membership->id
;
112 $tempMembership->find(TRUE);
113 $membership = $tempMembership;
116 //get the log start date.
117 //it is set during renewal of membership.
118 $logStartDate = CRM_Utils_Array
::value('log_start_date', $params);
119 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : CRM_Utils_Date
::isoToMysql($membership->start_date
);
120 $values = self
::getStatusANDTypeValues($membership->id
);
122 $membershipLog = array(
123 'membership_id' => $membership->id
,
124 'status_id' => $membership->status_id
,
125 'start_date' => $logStartDate,
126 'end_date' => CRM_Utils_Date
::isoToMysql($membership->end_date
),
127 'modified_date' => date('Ymd'),
128 'membership_type_id' => $values[$membership->id
]['membership_type_id'],
129 'max_related' => $membership->max_related
,
132 $session = CRM_Core_Session
::singleton();
133 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
134 if ($session->get('userID')) {
135 $membershipLog['modified_id'] = $session->get('userID');
137 elseif (!empty($ids['userId'])) {
138 $membershipLog['modified_id'] = $ids['userId'];
141 $membershipLog['modified_id'] = $membership->contact_id
;
144 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
146 // reset the group contact cache since smart groups might be affected due to this
147 CRM_Contact_BAO_GroupContactCache
::remove();
150 if ($membership->status_id
!= $oldStatus) {
151 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
152 $activityParam = array(
153 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
154 'source_contact_id' => $membershipLog['modified_id'],
155 'target_contact_id' => $membership->contact_id
,
156 'source_record_id' => $membership->id
,
157 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Change Membership Status'),
160 'activity_date_time' => date('Y-m-d H:i:s'),
162 civicrm_api3('activity', 'create', $activityParam);
164 if (isset($membership->membership_type_id
) && $membership->membership_type_id
!= $oldType) {
165 $membershipTypes = CRM_Member_BAO_Membership
::buildOptions('membership_type_id', 'get');
166 $activityParam = array(
167 'subject' => "Type changed from {$membershipTypes[$oldType]} to {$membershipTypes[$membership->membership_type_id]}",
168 'source_contact_id' => $membershipLog['modified_id'],
169 'target_contact_id' => $membership->contact_id
,
170 'source_record_id' => $membership->id
,
171 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Change Membership Type'),
174 'activity_date_time' => date('Y-m-d H:i:s'),
176 civicrm_api3('activity', 'create', $activityParam);
178 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
181 CRM_Utils_Hook
::post('create', 'Membership', $membership->id
, $membership);
188 * Given the list of params in the params array, fetch the object
189 * and store the values in the values array
191 * @param array $params input parameters to find object
192 * @param array $values output values of the object
193 * @param boolean $active do you want only active memberships to
196 * @return CRM_Member_BAO_Membership|null the found object or null
199 public static function &getValues(&$params, &$values, $active = FALSE) {
200 if (empty($params)) {
203 $membership = new CRM_Member_BAO_Membership();
205 $membership->copyValues($params);
207 $memberships = array();
208 while ($membership->fetch()) {
210 (!CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
211 $membership->status_id
,
218 CRM_Core_DAO
::storeValues($membership, $values[$membership->id
]);
219 $memberships[$membership->id
] = $membership;
226 * Takes an associative array and creates a membership object
228 * @param array $params (reference ) an assoc array of name/value pairs
229 * @param array $ids the array that holds all the db ids
230 * @param bool $skipRedirect
231 * @param string $activityType
233 * @throws CRM_Core_Exception
235 * @return CRM_Member_BAO_Membership object
238 public static function create(&$params, &$ids, $skipRedirect = FALSE, $activityType = 'Membership Signup') {
239 // always calculate status if is_override/skipStatusCal is not true.
240 // giving respect to is_override during import. CRM-4012
242 // To skip status calculation we should use 'skipStatusCal'.
243 // eg pay later membership, membership update cron CRM-3984
245 if (empty($params['is_override']) && empty($params['skipStatusCal'])) {
246 $dates = array('start_date', 'end_date', 'join_date');
247 $start_date = $end_date = $join_date = NULL; // declare these out of courtesy as IDEs don't pick up the setting of them below
248 foreach ($dates as $date) {
249 $
$date = $params[$date] = CRM_Utils_Date
::processDate(CRM_Utils_Array
::value($date, $params), NULL, TRUE, 'Ymd');
252 //fix for CRM-3570, during import exclude the statuses those having is_admin = 1
253 $excludeIsAdmin = CRM_Utils_Array
::value('exclude_is_admin', $params, FALSE);
255 //CRM-3724 always skip is_admin if is_override != true.
256 if (!$excludeIsAdmin && empty($params['is_override'])) {
257 $excludeIsAdmin = TRUE;
260 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($start_date, $end_date, $join_date,
261 'today', $excludeIsAdmin, CRM_Utils_Array
::value('membership_type_id', $params), $params
263 if (empty($calcStatus)) {
264 // Redirect the form in case of error
265 // @todo this redirect in the BAO layer is really bad & should be moved to the form layer
266 // however since we have no idea how (if) this is triggered we can't safely move / remove it
267 // NB I tried really hard to trigger this error from backoffice membership form in order to test it
268 // and am convinced form validation is complete on that form WRT this error.
269 $errorParams = array(
270 'message_title' => ts('No valid membership status for given dates.'),
271 'legacy_redirect_path' => 'civicrm/contact/view',
272 'legacy_redirect_query' => "reset=1&force=1&cid={$params['contact_id']}&selectedChild=member",
274 throw new CRM_Core_Exception(ts('The membership cannot be saved because the status cannot be calculated.'), 0, $errorParams);
276 $params['status_id'] = $calcStatus['id'];
279 // data cleanup only: all verifications on number of related memberships are done upstream in:
280 // CRM_Member_BAO_Membership::createRelatedMemberships()
281 // CRM_Contact_BAO_Relationship::relatedMemberships()
282 if (isset($params['owner_membership_id'])) {
283 unset($params['max_related']);
286 // if membership allows related, default max_related to value in membership_type
287 if (!array_key_exists('max_related', $params) && !empty($params['membership_type_id'])) {
288 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($params['membership_type_id']);
289 if (isset($membershipType['relationship_type_id'])) {
290 $params['max_related'] = CRM_Utils_Array
::value('max_related', $membershipType);
295 $transaction = new CRM_Core_Transaction();
297 $membership = self
::add($params, $ids);
299 if (is_a($membership, 'CRM_Core_Error')) {
300 $transaction->rollback();
304 // add custom field values
305 if (!empty($params['custom']) && is_array($params['custom'])
307 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_membership', $membership->id
);
310 $params['membership_id'] = $membership->id
;
311 if (isset($ids['membership'])) {
312 $ids['contribution'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment',
319 $params['skipLineItem'] = TRUE;
321 //record contribution for this membership
322 if (!empty($params['contribution_status_id']) && empty($params['relate_contribution_id'])) {
323 $memInfo = array_merge($params, array('membership_id' => $membership->id
));
324 $params['contribution'] = self
::recordMembershipContribution($memInfo, $ids);
327 if (!empty($params['lineItems'])) {
328 $params['line_item'] = $params['lineItems'];
331 //do cleanup line items if membership edit the Membership type.
332 if (empty($ids['contribution']) && !empty($ids['membership'])) {
333 CRM_Price_BAO_LineItem
::deleteLineItems($ids['membership'], 'civicrm_membership');
336 if (!empty($params['line_item']) && empty($ids['contribution'])) {
337 CRM_Price_BAO_LineItem
::processPriceSet($membership->id
, $params['line_item'], CRM_Utils_Array
::value('contribution', $params));
340 //insert payment record for this membership
341 if (!empty($params['relate_contribution_id'])) {
342 CRM_Member_BAO_MembershipPayment
::create(array('membership_id' => $membership->id
, 'contribution_id' => $params['relate_contribution_id']));
345 // add activity record only during create mode and renew mode
346 // also add activity if status changed CRM-3984 and CRM-2521
347 if (empty($ids['membership']) ||
348 $activityType == 'Membership Renewal' ||
!empty($params['createActivity'])) {
349 if (!empty($ids['membership'])) {
351 CRM_Core_DAO
::commonRetrieveAll('CRM_Member_DAO_Membership',
355 array('contact_id', 'membership_type_id', 'source')
358 $membership->contact_id
= $data[$membership->id
]['contact_id'];
359 $membership->membership_type_id
= $data[$membership->id
]['membership_type_id'];
360 $membership->source
= CRM_Utils_Array
::value('source', $data[$membership->id
]);
363 // since we are going to create activity record w/
364 // individual contact as a target in case of on behalf signup,
365 // so get the copy of organization id, CRM-5551
366 $realMembershipContactId = $membership->contact_id
;
368 // create activity source = individual, target = org CRM-4027
369 $targetContactID = NULL;
370 if (!empty($params['is_for_organization'])) {
371 $targetContactID = $membership->contact_id
;
372 $membership->contact_id
= CRM_Utils_Array
::value('userId', $ids);
375 if (empty($membership->contact_id
) && (!empty($membership->owner_membership_id
))) {
376 $membership->contact_id
= $realMembershipContactId;
379 if (!empty($ids['membership']) && $activityType != 'Membership Signup') {
380 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $targetContactID);
381 } elseif (empty($ids['membership'])) {
382 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $targetContactID);
385 // we might created activity record w/ individual
386 // contact as target so update membership object w/
387 // original organization id, CRM-5551
388 $membership->contact_id
= $realMembershipContactId;
391 $transaction->commit();
393 self
::createRelatedMemberships($params, $membership);
395 // do not add to recent items for import, CRM-4399
396 if (empty($params['skipRecentView'])) {
397 $url = CRM_Utils_System
::url('civicrm/contact/view/membership',
398 "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
400 if(empty($membership->membership_type_id
)){// ie in an update situation
401 $membership->find(TRUE);
403 $membershipTypes = CRM_Member_PseudoConstant
::membershipType();
404 $title = CRM_Contact_BAO_Contact
::displayName($membership->contact_id
) . ' - ' . ts('Membership Type:') . ' ' . $membershipTypes[$membership->membership_type_id
];
406 $recentOther = array();
407 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::UPDATE
)) {
408 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
409 "action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
412 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::DELETE
)) {
413 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
414 "action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
418 // add the recently created Membership
419 CRM_Utils_Recent
::add($title,
423 $membership->contact_id
,
433 * Check the membership extended through relationship
435 * @param int $membershipId membership id
436 * @param int $contactId contact id
438 * @param integer $action
440 * @return Array array of contact_id of all related contacts.
443 public static function checkMembershipRelationship($membershipId, $contactId, $action = CRM_Core_Action
::ADD
) {
445 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $membershipId, 'membership_type_id');
447 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipTypeID);
448 $relationships = array();
449 if (isset($membershipType['relationship_type_id'])) {
450 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
451 CRM_Contact_BAO_Relationship
::CURRENT
453 if ($action & CRM_Core_Action
::UPDATE
) {
454 $pastRelationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
455 CRM_Contact_BAO_Relationship
::PAST
457 $relationships = array_merge($relationships, $pastRelationships);
461 if (!empty($relationships)) {
462 // check for each contact relationships
463 foreach ($relationships as $values) {
464 //get details of the relationship type
465 $relType = array('id' => $values['civicrm_relationship_type_id']);
466 $relValues = array();
467 CRM_Contact_BAO_RelationshipType
::retrieve($relType, $relValues);
468 // Check if contact's relationship type exists in membership type
469 $relTypeDirs = array();
470 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_type_id']);
471 $relDirections = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_direction']);
472 $bidirectional = FALSE;
473 foreach ($relTypeIds as $key => $value) {
474 $relTypeDirs[] = $value . '_' . $relDirections[$key];
475 if (in_array($value, $relType) &&
476 $relValues['name_a_b'] == $relValues['name_b_a']
478 $bidirectional = TRUE;
482 $relTypeDir = $values['civicrm_relationship_type_id'] . '_' . $values['rtype'];
483 if ($bidirectional ||
in_array($relTypeDir, $relTypeDirs)) {
484 // $values['status'] is going to have value for
485 // current or past relationships.
486 $contacts[$values['cid']] = $values['status'];
491 // Sort by contact_id ascending
497 * Takes a bunch of params that are needed to match certain criteria and
498 * retrieves the relevant objects. We'll tweak this function to be more
499 * full featured over a period of time. This is the inverse function of
500 * create. It also stores all the retrieved values in the default array
502 * @param array $params (reference ) an assoc array of name/value pairs
503 * @param array $defaults (reference ) an assoc array to hold the name / value pairs
504 * in a hierarchical manner
506 * @return CRM_Member_BAO_Membership object
509 public static function retrieve(&$params, &$defaults) {
510 $membership = new CRM_Member_DAO_Membership();
512 $membership->copyValues($params);
514 if ($membership->find(TRUE)) {
515 CRM_Core_DAO
::storeValues($membership, $defaults);
517 //get the membership status and type values.
518 $statusANDType = self
::getStatusANDTypeValues($membership->id
);
520 'status', 'membership_type') as $fld) {
521 $defaults[$fld] = CRM_Utils_Array
::value($fld, $statusANDType[$membership->id
]);
523 if (!empty($statusANDType[$membership->id
]['is_current_member'])) {
524 $defaults['active'] = TRUE;
537 * get membership status and membership type values
539 * @param int $membershipId membership id of values to return
541 * @return array of key value pairs
543 public static function getStatusANDTypeValues($membershipId) {
545 if (!$membershipId) {
549 SELECT membership.id as id,
550 status.id as status_id,
551 status.label as status,
552 status.is_current_member as is_current_member,
553 type.id as membership_type_id,
554 type.name as membership_type,
555 type.relationship_type_id as relationship_type_id
556 FROM civicrm_membership membership
557 INNER JOIN civicrm_membership_status status ON ( status.id = membership.status_id )
558 INNER JOIN civicrm_membership_type type ON ( type.id = membership.membership_type_id )
559 WHERE membership.id = %1';
560 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($membershipId, 'Positive')));
561 $properties = array('status', 'status_id', 'membership_type', 'membership_type_id', 'is_current_member', 'relationship_type_id');
562 while ($dao->fetch()) {
563 foreach ($properties as $property) {
564 $values[$dao->id
][$property] = $dao->$property;
573 * Wrapper for most delete calls. Use this unless you JUST want to delete related memberships w/o deleting the parent.
575 * @param int $membershipId membership id that needs to be deleted
579 * @return $results no of deleted Membership on success, false otherwise
581 public static function del($membershipId) {
582 //delete related first and then delete parent.
583 self
::deleteRelatedMemberships($membershipId);
584 return self
::deleteMembership($membershipId);
590 * @param int $membershipId membership id that needs to be deleted
594 * @return $results no of deleted Membership on success, false otherwise
596 public static function deleteMembership($membershipId) {
597 // CRM-12147, retrieve membership data before we delete it for hooks
598 $params = array('id' => $membershipId);
599 $memValues = array();
600 $memberships = self
::getValues($params, $memValues);
602 $membership = $memberships[$membershipId];
604 CRM_Utils_Hook
::pre('delete', 'Membership', $membershipId, $memValues);
606 $transaction = new CRM_Core_Transaction();
609 //delete activity record
610 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
613 $deleteActivity = false;
614 $membershipActivities = array(
616 'Membership Renewal',
617 'Change Membership Status',
618 'Change Membership Type',
619 'Membership Renewal Reminder'
621 foreach($membershipActivities as $membershipActivity) {
622 $activityId = array_search($membershipActivity, $activityTypes);
624 $params['activity_type_id'][] = $activityId;
625 $deleteActivity = true;
628 if ($deleteActivity) {
629 $params['source_record_id'] = $membershipId;
630 CRM_Activity_BAO_Activity
::deleteActivity($params);
632 self
::deleteMembershipPayment($membershipId);
634 $results = $membership->delete();
635 $transaction->commit();
637 CRM_Utils_Hook
::post('delete', 'Membership', $membership->id
, $membership);
639 // delete the recently created Membership
640 $membershipRecent = array(
641 'id' => $membershipId,
642 'type' => 'Membership',
644 CRM_Utils_Recent
::del($membershipRecent);
650 * Delete related memberships
652 * @param int $ownerMembershipId
653 * @param int $contactId
658 public static function deleteRelatedMemberships($ownerMembershipId, $contactId = NULL) {
659 if (!$ownerMembershipId && !$contactId) {
663 $membership = new CRM_Member_DAO_Membership();
664 $membership->owner_membership_id
= $ownerMembershipId;
667 $membership->contact_id
= $contactId;
671 while ($membership->fetch()) {
672 //delete related first and then delete parent.
673 self
::deleteRelatedMemberships($membership->id
);
674 self
::deleteMembership($membership->id
);
680 * Obtain active/inactive memberships from the list of memberships passed to it.
682 * @param array $memberships membership records
683 * @param string $status active or inactive
685 * @return array $actives array of memberships based on status
688 public static function activeMembers($memberships, $status = 'active') {
690 if ($status == 'active') {
691 foreach ($memberships as $f => $v) {
692 if (!empty($v['active'])) {
698 elseif ($status == 'inactive') {
699 foreach ($memberships as $f => $v) {
700 if (empty($v['active'])) {
710 * Build Membership Block in Contribution Pages
712 * @param CRM_Core_Form $form form object
713 * @param int $pageID - unused?
714 * @param int $cid - contact checked for having a current membership for a particular membership
715 * @param boolean $formItems
716 * @param int $selectedMembershipTypeID selected membership id
717 * @param boolean $thankPage thank you page
718 * @param null $isTest
720 * @return bool Is this a separate membership payment
724 static function buildMembershipBlock(&$form,
728 $selectedMembershipTypeID = NULL,
733 $separateMembershipPayment = FALSE;
734 if ($form->_membershipBlock
) {
735 $form->_currentMemberships
= array();
737 $membershipBlock = $form->_membershipBlock
;
738 $membershipTypeIds = $membershipTypes = $radio = array();
739 $membershipPriceset = (!empty($form->_priceSetId
) && $form->_useForMember
) ?
TRUE : FALSE;
741 $allowAutoRenewMembership = $autoRenewOption = FALSE;
742 $autoRenewMembershipTypeOptions = array();
744 $paymentProcessor = CRM_Core_PseudoConstant
::paymentProcessor(FALSE, FALSE, 'is_recur = 1');
746 $separateMembershipPayment = CRM_Utils_Array
::value('is_separate_payment', $membershipBlock);
748 if ($membershipPriceset) {
749 foreach ($form->_priceSet
['fields'] as $pField) {
750 if (empty($pField['options'])) {
753 foreach ($pField['options'] as $opId => $opValues) {
754 if (empty($opValues['membership_type_id'])) {
757 $membershipTypeIds[$opValues['membership_type_id']] = $opValues['membership_type_id'];
761 elseif (!empty($membershipBlock['membership_types'])) {
762 $membershipTypeIds = explode(',', $membershipBlock['membership_types']);
765 if (!empty($membershipTypeIds)) {
766 //set status message if wrong membershipType is included in membershipBlock
767 if (isset($form->_mid
) && !$membershipPriceset) {
768 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
772 if (!in_array($membershipTypeID, $membershipTypeIds)) {
773 CRM_Core_Session
::setStatus(ts("Oops. The membership you're trying to renew appears to be invalid. Contact your site administrator if you need assistance. If you continue, you will be issued a new membership."), ts('Invalid Membership'), 'error');
777 $membershipTypeValues = self
::buildMembershipTypeValues($form, $membershipTypeIds);
778 $form->_membershipTypeValues
= $membershipTypeValues;
780 foreach ($membershipTypeIds as $value) {
781 $memType = $membershipTypeValues[$value];
782 if ($selectedMembershipTypeID != NULL) {
783 if ($memType['id'] == $selectedMembershipTypeID) {
784 $form->assign('minimum_fee',
785 CRM_Utils_Array
::value('minimum_fee', $memType)
787 $form->assign('membership_name', $memType['name']);
788 if (!$thankPage && $cid) {
789 $membership = new CRM_Member_DAO_Membership();
790 $membership->contact_id
= $cid;
791 $membership->membership_type_id
= $memType['id'];
792 if ($membership->find(TRUE)) {
793 $form->assign('renewal_mode', TRUE);
794 $memType['current_membership'] = $membership->end_date
;
795 $form->_currentMemberships
[$membership->membership_type_id
] = $membership->membership_type_id
;
798 $membershipTypes[] = $memType;
801 elseif ($memType['is_active']) {
802 $javascriptMethod = NULL;
803 $allowAutoRenewOpt = 1;
804 if (is_array($form->_paymentProcessors
)){
805 foreach ($form->_paymentProcessors
as $id => $val) {
806 if (!$val['is_recur']) {
807 $allowAutoRenewOpt = 0;
813 $javascriptMethod = array('onclick' => "return showHideAutoRenew( this.value );");
814 $autoRenewMembershipTypeOptions["autoRenewMembershipType_{$value}"] = (int)$allowAutoRenewOpt * CRM_Utils_Array
::value($value, CRM_Utils_Array
::value('auto_renew', $form->_membershipBlock
));;
816 if ($allowAutoRenewOpt) {
817 $allowAutoRenewMembership = TRUE;
820 //add membership type.
821 $radio[$memType['id']] = $form->createElement('radio', NULL, NULL, NULL,
822 $memType['id'], $javascriptMethod
825 $membership = new CRM_Member_DAO_Membership();
826 $membership->contact_id
= $cid;
827 $membership->membership_type_id
= $memType['id'];
829 //show current membership, skip pending and cancelled membership records,
830 //because we take first membership record id for renewal
831 $membership->whereAdd('status_id != 5 AND status_id !=6');
833 if (!is_null($isTest)) {
834 $membership->is_test
= $isTest;
838 $membership->orderBy('end_date DESC');
840 if ($membership->find(TRUE)) {
841 if (!$membership->end_date
) {
842 unset($radio[$memType['id']]);
843 $form->assign('islifetime', TRUE);
846 $form->assign('renewal_mode', TRUE);
847 $form->_currentMemberships
[$membership->membership_type_id
] = $membership->membership_type_id
;
848 $memType['current_membership'] = $membership->end_date
;
850 $endDate = $memType['current_membership'];
851 $form->_defaultMemTypeId
= $memType['id'];
853 if ($memType['current_membership'] < $endDate) {
854 $endDate = $memType['current_membership'];
855 $form->_defaultMemTypeId
= $memType['id'];
859 $membershipTypes[] = $memType;
864 $form->assign('showRadio', $formItems);
866 if (!$membershipPriceset) {
867 if (!$membershipBlock['is_required']) {
868 $form->assign('showRadioNoThanks', TRUE);
869 $radio[''] = $form->createElement('radio', NULL, NULL, NULL, 'no_thanks', NULL);
870 $form->addGroup($radio, 'selectMembership', NULL);
872 elseif ($membershipBlock['is_required'] && count($radio) == 1) {
873 $temp = array_keys($radio);
874 $form->add('hidden', 'selectMembership', $temp[0], array('id' => 'selectMembership'));
875 $form->assign('singleMembership', TRUE);
876 $form->assign('showRadio', FALSE);
879 $form->addGroup($radio, 'selectMembership', NULL);
882 $form->addRule('selectMembership', ts('Please select one of the memberships.'), 'required');
885 $autoRenewOption = CRM_Price_BAO_PriceSet
::checkAutoRenewForPriceSet($form->_priceSetId
);
886 $form->assign('autoRenewOption', $autoRenewOption);
889 if (!$form->_values
['is_pay_later'] && is_array($form->_paymentProcessors
) && ($allowAutoRenewMembership ||
$autoRenewOption)) {
890 $form->addElement('checkbox', 'auto_renew', ts('Please renew my membership automatically.'));
895 $form->assign('membershipBlock', $membershipBlock);
896 $form->assign('membershipTypes', $membershipTypes);
897 $form->assign('allowAutoRenewMembership', $allowAutoRenewMembership);
898 $form->assign('autoRenewMembershipTypeOptions', json_encode($autoRenewMembershipTypeOptions));
900 //give preference to user submitted auto_renew value.
901 $takeUserSubmittedAutoRenew = (!empty($_POST) ||
$form->isSubmitted()) ?
TRUE : FALSE;
902 $form->assign('takeUserSubmittedAutoRenew', $takeUserSubmittedAutoRenew);
905 return $separateMembershipPayment;
909 * Return Membership Block info in Contribution Pages
911 * @param int $pageID contribution page id
917 public static function getMembershipBlock($pageID) {
918 $membershipBlock = array();
919 $dao = new CRM_Member_DAO_MembershipBlock();
920 $dao->entity_table
= 'civicrm_contribution_page';
922 $dao->entity_id
= $pageID;
924 if ($dao->find(TRUE)) {
925 CRM_Core_DAO
::storeValues($dao, $membershipBlock);
926 if (!empty($membershipBlock['membership_types'])) {
927 $membershipTypes = unserialize($membershipBlock['membership_types']);
928 if (!is_array($membershipTypes)) {
929 return $membershipBlock;
932 foreach ($membershipTypes as $key => $value) {
933 $membershipBlock['auto_renew'][$key] = $value;
934 $memTypes[$key] = $key;
936 $membershipBlock['membership_types'] = implode(',', $memTypes);
943 return $membershipBlock;
947 * Return a current membership of given contact
948 * NB: if more than one membership meets criteria, a randomly selected one is returned.
950 * @param int $contactID contact id
951 * @param int $memType membership type, null to retrieve all types
953 * @param int $membershipId if provided, then determine if it is current
954 * @param boolean $onlySameParentOrg true if only Memberships with same parent org as the $memType wanted, false otherwise
959 public static function getContactMembership($contactID, $memType, $isTest, $membershipId = NULL, $onlySameParentOrg = FALSE) {
960 $dao = new CRM_Member_DAO_Membership();
962 $dao->id
= $membershipId;
964 $dao->contact_id
= $contactID;
965 $dao->membership_type_id
= $memType;
967 //fetch proper membership record.
969 $dao->is_test
= $isTest;
972 $dao->whereAdd('is_test IS NULL OR is_test = 0');
975 //avoid pending membership as current membership: CRM-3027
976 $statusIds[] = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
977 if (!$membershipId) {
979 $statusIds[] = array_search(
981 CRM_Member_PseudoConstant
::membershipStatus(
983 " name = 'Cancelled' ",
990 $dao->whereAdd('status_id NOT IN ( ' . implode(',', $statusIds) . ')');
992 // order by start date to find most recent membership first, CRM-4545
993 $dao->orderBy('start_date DESC');
996 if ($onlySameParentOrg && $memType) {
997 // require the same parent org as the $memType
998 $params = array('id' => $memType);
999 $membershipType = array();
1000 if (CRM_Member_BAO_MembershipType
::retrieve($params, $membershipType)) {
1001 $memberTypesSameParentOrg = CRM_Member_BAO_MembershipType
::getMembershipTypesByOrg($membershipType['member_of_contact_id']);
1002 $memberTypesSameParentOrgList = implode(',', array_keys($memberTypesSameParentOrg));
1003 $dao->whereAdd('membership_type_id IN (' . $memberTypesSameParentOrgList . ')');
1007 if ($dao->find(TRUE)) {
1008 $membership = array();
1009 CRM_Core_DAO
::storeValues($dao, $membership);
1010 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
1011 $membership['status_id'],
1012 'is_current_member', 'id'
1018 if ($onlySameParentOrg && $memType) {
1019 // see if there is a membership that has same parent as $memType but different parent than $membershipID
1020 if ($dao->id
&& CRM_Core_Permission
::check('edit memberships')) {
1021 // CRM-10016, This is probably a backend renewal, and make sure we return the same membership thats being renewed.
1028 unset($dao->membership_type_id
);
1029 if ($dao->find(TRUE)) {
1030 $membership = array();
1031 CRM_Core_DAO
::storeValues($dao, $membership);
1032 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
1033 $membership['status_id'],
1034 'is_current_member', 'id'
1043 * Combine all the importable fields from the lower levels object
1045 * @param string $contactType contact type
1046 * @param boolean $status
1048 * @return array array of importable Fields
1051 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
1052 if (!self
::$_importableFields) {
1053 if (!self
::$_importableFields) {
1054 self
::$_importableFields = array();
1058 $fields = array('' => array('title' => '- ' . ts('do not import') . ' -'));
1061 $fields = array('' => array('title' => '- ' . ts('Membership Fields') . ' -'));
1064 $tmpFields = CRM_Member_DAO_Membership
::import();
1065 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
1067 // Using new Dedupe rule.
1068 $ruleParams = array(
1069 'contact_type' => $contactType,
1070 'used' => 'Unsupervised',
1072 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
1074 $tmpContactField = array();
1075 if (is_array($fieldsArray)) {
1076 foreach ($fieldsArray as $value) {
1077 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
1082 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
1083 $tmpContactField[trim($value)] = CRM_Utils_Array
::value(trim($value), $contactFields);
1085 $title = $tmpContactField[trim($value)]['title'] . " " . ts('(match to contact)');
1088 $title = $tmpContactField[trim($value)]['title'];
1090 $tmpContactField[trim($value)]['title'] = $title;
1093 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
1094 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " " . ts('(match to contact)');
1096 $tmpFields['membership_contact_id']['title'] = $tmpFields['membership_contact_id']['title'] . " " . ts('(match to contact)');;
1098 $fields = array_merge($fields, $tmpContactField);
1099 $fields = array_merge($fields, $tmpFields);
1100 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1101 self
::$_importableFields = $fields;
1103 return self
::$_importableFields;
1107 * Get all exportable fields
1109 * @retun array return array of all exportable fields
1112 public static function &exportableFields() {
1113 $expFieldMembership = CRM_Member_DAO_Membership
::export();
1115 $expFieldsMemType = CRM_Member_DAO_MembershipType
::export();
1116 $fields = array_merge($expFieldMembership, $expFieldsMemType);
1117 $fields = array_merge($fields, $expFieldMembership);
1118 $membershipStatus = array(
1119 'membership_status' => array('title' => 'Membership Status',
1120 'name' => 'membership_status',
1121 'type' => CRM_Utils_Type
::T_STRING
,
1122 'where' => 'civicrm_membership_status.name',
1124 //CRM-6161 fix for customdata export
1125 $fields = array_merge($fields, $membershipStatus, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1130 * Get membership joins/renewals for a specified membership
1131 * type. Specifically, retrieves a count of memberships whose "Membership
1132 * Signup" or "Membership Renewal" activity falls in the given date range.
1133 * Dates match the pattern "yyyy-mm-dd".
1135 * @param int $membershipTypeId membership type id
1136 * @param int $startDate date on which to start counting
1137 * @param int $endDate date on which to end counting
1138 * @param bool|int $isTest if true, membership is for a test site
1139 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1141 * @return integer the number of members of type $membershipTypeId whose
1142 * start_date is between $startDate and $endDate
1145 public static function getMembershipStarts($membershipTypeId, $startDate, $endDate, $isTest = 0, $isOwner = 0) {
1147 $testClause = 'membership.is_test = 1';
1149 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1152 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1153 self
::_getActTypes();
1156 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1161 SELECT COUNT(DISTINCT membership.id) as member_count
1162 FROM civicrm_membership membership
1163 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id in (%1, %2))
1164 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1165 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1166 WHERE membership.membership_type_id = %3
1167 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1170 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1173 1 => array(self
::$_signupActType, 'Integer'),
1174 2 => array(self
::$_renewalActType, 'Integer'),
1175 3 => array($membershipTypeId, 'Integer'),
1178 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1179 return (int)$memberCount;
1183 * Get a count of membership for a specified membership type,
1184 * optionally for a specified date. The date must have the form yyyy-mm-dd.
1186 * If $date is omitted, this function counts as a member anyone whose
1187 * membership status_id indicates they're a current member.
1188 * If $date is given, this function counts as a member anyone who:
1189 * -- Has a start_date before $date and end_date after $date, or
1190 * -- Has a start_date before $date and is currently a member, as indicated
1191 * by the the membership's status_id.
1192 * The second condition takes care of records that have no end_date. These
1193 * are assumed to be lifetime memberships.
1195 * @param int $membershipTypeId membership type id
1196 * @param string $date the date for which to retrieve the count
1197 * @param bool|int $isTest if true, membership is for a test site
1198 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1200 * @return returns the number of members of type $membershipTypeId as of
1203 public static function getMembershipCount($membershipTypeId, $date = NULL, $isTest = 0, $isOwner = 0) {
1204 if (!CRM_Utils_Rule
::date($date)) {
1205 CRM_Core_Error
::fatal(ts('Invalid date "%1" (must have form yyyy-mm-dd).', array(1 => $date)));
1208 $params = array(1 => array($membershipTypeId, 'Integer'),
1209 2 => array($isTest, 'Boolean'),
1211 $query = "SELECT count(civicrm_membership.id ) as member_count
1212 FROM civicrm_membership left join civicrm_membership_status on ( civicrm_membership.status_id = civicrm_membership_status.id )
1213 WHERE civicrm_membership.membership_type_id = %1
1214 AND civicrm_membership.contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)
1215 AND civicrm_membership.is_test = %2";
1217 $query .= " AND civicrm_membership_status.is_current_member = 1";
1220 $query .= " AND civicrm_membership.start_date <= '$date' AND civicrm_membership_status.is_current_member = 1";
1223 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1224 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1225 return (int)$memberCount;
1229 * Function check the status of the membership before adding membership for a contact
1231 * @param int $contactId contact id
1235 public static function statusAvailabilty($contactId) {
1236 $membership = new CRM_Member_DAO_MembershipStatus();
1237 $membership->whereAdd('is_active=1');
1238 return $membership->count();
1242 * Process the Memberships
1244 * @param array $membershipParams array of membership fields
1245 * @param int $contactID contact id
1246 * @param CRM_Contribute_Form_Contribution_Confirm $form Confirmation form object
1248 * @param array $premiumParams
1249 * @param null $customFieldsFormatted
1250 * @param null $includeFieldTypes
1252 * @param array $membershipDetails
1254 * @param array $membershipTypeIDs
1256 * @param bool $isPaidMembership
1257 * @param array $membershipID
1259 * @param $isProcessSeparateMembershipTransaction
1261 * @param int $defaultContributionTypeID
1262 * @param array $membershipLineItems Line items specific to membership payment that is separate to contribution
1263 * @throws CRM_Core_Exception
1267 public static function postProcessMembership($membershipParams, $contactID, &$form, $premiumParams,
1268 $customFieldsFormatted = NULL, $includeFieldTypes = NULL, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID,
1269 $isProcessSeparateMembershipTransaction, $defaultContributionTypeID, $membershipLineItems, $isPayLater) {
1270 $result = $membershipContribution = NULL;
1271 $isTest = CRM_Utils_Array
::value('is_test', $membershipParams, FALSE);
1272 $errors = $createdMemberships = array();
1274 //@todo move this into the calling function & pass in the correct financialTypeID
1275 if (isset($paymentParams['financial_type'])) {
1276 $financialTypeID = $paymentParams['financial_type'];
1279 $financialTypeID = $defaultContributionTypeID;
1283 if (CRM_Utils_Array
::value('membership_source', $form->_params
)) {
1284 $membershipParams['contribution_source'] = $form->_params
['membership_source'];
1287 if ($isPaidMembership) {
1288 $result = CRM_Contribute_BAO_Contribution_Utils
::processConfirm($form, $membershipParams,
1289 $premiumParams, $contactID,
1296 if (is_a($result[1], 'CRM_Core_Error')) {
1297 $errors[1] = CRM_Core_Error
::getMessages($result[1]);
1299 elseif (!empty($result[1])) {
1300 // Save the contribution ID so that I can be used in email receipts
1301 // For example, if you need to generate a tax receipt for the donation only.
1302 $form->_values
['contribution_other_id'] = $result[1]->id
;
1303 //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
1304 $membershipContribution = $result[1];
1308 if ($isProcessSeparateMembershipTransaction) {
1310 $lineItems = $form->_lineItem
= $membershipLineItems;
1311 $membershipContribution = self
::processSecondaryFinancialTransaction($contactID, $form, $membershipParams, $isTest, $membershipLineItems, CRM_Utils_Array
::value('minimum_fee', $membershipDetails, 0), CRM_Utils_Array
::value('financial_type_id', $membershipDetails));
1313 catch (CRM_Core_Exception
$e) {
1314 $errors[2] = $e->getMessage();
1315 $membershipContribution = NULL;
1320 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1321 $membershipContributionID = $membershipContribution->id
;
1324 //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
1325 if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
1326 $form->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
1328 //@todo it should no longer be possible for it to get to this point & membership to not be an array
1329 if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
1330 $typesTerms = CRM_Utils_Array
::value('types_terms', $membershipParams, array());
1331 foreach ($membershipTypeIDs as $memType) {
1332 $numTerms = CRM_Utils_Array
::value($memType, $typesTerms, 1);
1333 $createdMemberships[$memType] = self
::createOrRenewMembership($membershipParams, $contactID, $customFieldsFormatted, $membershipID, $memType, $isTest, $numTerms, $membershipContribution, $form);
1335 if ($form->_priceSetId
&& !empty($form->_useForMember
) && !empty($form->_lineItem
)) {
1336 foreach ($form->_lineItem
[$form->_priceSetId
] as & $priceFieldOp) {
1337 if (!empty($priceFieldOp['membership_type_id']) &&
1338 isset($createdMemberships[$priceFieldOp['membership_type_id']])
1340 $membershipOb = $createdMemberships[$priceFieldOp['membership_type_id']];
1341 $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date
::customFormat($membershipOb->start_date
, '%B %E%f, %Y') : '-';
1342 $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date
::customFormat($membershipOb->end_date
, '%B %E%f, %Y') : '-';
1345 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1348 $form->_values
['lineItem'] = $form->_lineItem
;
1349 $form->assign('lineItem', $form->_lineItem
);
1353 if (!empty($errors)) {
1354 $message = self
::compileErrorMessage($errors);
1355 throw new CRM_Core_Exception($message);
1357 $form->_params
['createdMembershipIDs'] = array();
1359 // CRM-7851 - Moved after processing Payment Errors
1360 //@todo - the reasoning for this being here seems a little outdated
1361 foreach ($createdMemberships as $createdMembership) {
1362 CRM_Core_BAO_CustomValueTable
::postProcess(
1364 CRM_Core_DAO
::$_nullArray,
1365 'civicrm_membership',
1366 $createdMembership->id
,
1369 $form->_params
['createdMembershipIDs'][] = $createdMembership->id
;
1371 if(count($createdMemberships) == 1) {
1372 //presumably this is only relevant for exactly 1 membership
1373 $form->_params
['membershipID'] = $createdMembership->id
;
1376 //CRM-15232: Check if membership is created and on the basis of it use
1377 //membership reciept template to send payment reciept
1378 if (count($createdMemberships)) {
1379 $form->_values
['isMembership'] = TRUE;
1381 if ($form->_contributeMode
== 'notify') {
1382 if ($form->_values
['is_monetary'] && $form->_amount
> 0.0 && !$form->_params
['is_pay_later']) {
1383 // call postProcess hook before leaving
1384 $form->postProcessHook();
1385 // this does not return
1386 $payment = CRM_Core_Payment
::singleton($form->_mode
, $form->_paymentProcessor
, $form);
1387 $payment->doTransferCheckout($form->_params
, 'contribute');
1391 if (isset($membershipContributionID)) {
1392 $form->_values
['contribution_id'] = $membershipContributionID;
1395 // Do not send an email if Recurring transaction is done via Direct Mode
1396 // Email will we sent when the IPN is received.
1397 if (!empty($form->_params
['is_recur']) && $form->_contributeMode
== 'direct') {
1398 if (!empty($membershipContribution->trxn_id
)) {
1400 civicrm_api3('contribution', 'completetransaction', array('id' => $membershipContribution->id
, 'trxn_id' => $membershipContribution->trxn_id
));
1402 catch (CiviCRM_API3_Exception
$e) {
1403 // if for any reason it is already completed this will fail - e.g extensions hacking around core not completing transactions prior to CRM-15296
1404 // so let's be gentle here
1405 CRM_Core_Error
::debug_log_message('contribution ' . $membershipContribution->id
. ' not completed with trxn_id ' . $membershipContribution->trxn_id
. ' and message ' . $e->getMessage());
1411 //finally send an email receipt
1412 CRM_Contribute_BAO_ContributionPage
::sendMail($contactID,
1420 * Function for updating a membership record's contribution_recur_id
1422 * @param object CRM_Member_DAO_Membership $membership
1423 * @param \CRM_Contribute_BAO_Contribution|\CRM_Contribute_DAO_Contribution $contribution
1428 static public function updateRecurMembership(CRM_Member_DAO_Membership
$membership,
1429 CRM_Contribute_BAO_Contribution
$contribution) {
1431 if (empty($contribution->contribution_recur_id
)) {
1436 1 => array($contribution->contribution_recur_id
, 'Integer'),
1437 2 => array($membership->id
, 'Integer'),
1440 $sql = "UPDATE civicrm_membership SET contribution_recur_id = %1 WHERE id = %2";
1441 CRM_Core_DAO
::executeQuery($sql, $params);
1446 * A wrapper for renewing memberships from a form - including the form in the membership processing adds complexity
1447 * as the forms are being forced to pretend similarity
1448 * Try to call the renewMembership directly
1449 * @todo - this form method needs to have the interaction with the form layer removed from it
1450 * as a BAO function. Note that the api now supports membership renewals & it is not clear this function does anything
1451 * not done by the membership.create api (with a lot less unit tests)
1453 * This method will renew / create the membership depending on
1454 * whether the given contact has a membership or not. And will add
1455 * the modified dates for membership and in the log table.
1457 * @param int $contactID id of the contact
1458 * @param int $membershipTypeID id of the new membership type
1459 * @param boolean $is_test if this is test contribution or live contribution
1460 * @param CRM_Core_Form $form form object
1461 * @param null $changeToday
1462 * @param int $modifiedID individual contact id in case of On Behalf signup (CRM-4027 )
1463 * @param null $customFieldsFormatted
1464 * @param int $numRenewTerms how many membership terms are being added to end date (default is 1)
1465 * @param integer $membershipID Membership ID, this should always be passed in & optionality should be removed
1467 * @throws CRM_Core_Exception
1471 static function renewMembershipFormWrapper(
1476 $changeToday = NULL,
1478 $customFieldsFormatted = NULL,
1480 $membershipID = NULL
1482 $statusFormat = '%Y-%m-%d';
1485 //@todo would be better to make $membershipID a compulsory function param & make form layer responsible for extracting it
1486 if(!$membershipID && isset($form->_membershipId
)) {
1487 $membershipID = $form->_membershipId
;
1490 //get all active statuses of membership.
1491 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1493 $membershipTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipTypeID);
1495 // check is it pending. - CRM-4555
1496 list($pending, $contributionRecurID, $changeToday, $membershipSource, $isPayLater, $campaignId) = self
::extractFormValues($form, $changeToday, $membershipTypeDetails);
1497 list($membership, $renewalMode, $dates) = self
::renewMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $allStatus, $membershipTypeDetails, $contributionRecurID, $format, $membershipSource, $ids, $statusFormat, $isPayLater, $campaignId);
1498 $form->set('renewal_mode', $renewalMode);
1499 if (!empty($dates)) {
1500 $form->assign('mem_start_date',
1501 CRM_Utils_Date
::customFormat($dates['start_date'], $format)
1503 $form->assign('mem_end_date',
1504 CRM_Utils_Date
::customFormat($dates['end_date'], $format)
1512 * Method to fix membership status of stale membership
1514 * This method first checks if the membership is stale. If it is,
1515 * then status will be updated based on existing start and end
1516 * dates and log will be added for the status change.
1518 * @param array $currentMembership reference to the array
1519 * containing all values of
1520 * the current membership
1521 * @param array $changeToday array of month, day, year
1522 * values in case today needs
1523 * to be customised, null otherwise
1528 public static function fixMembershipStatusBeforeRenew(&$currentMembership, $changeToday) {
1531 $today = CRM_Utils_Date
::processDate($changeToday, NULL, FALSE, 'Y-m-d');
1534 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
1535 CRM_Utils_Array
::value('start_date', $currentMembership),
1536 CRM_Utils_Array
::value('end_date', $currentMembership),
1537 CRM_Utils_Array
::value('join_date', $currentMembership),
1540 $currentMembership['membership_type_id'],
1544 if (empty($status) ||
1545 empty($status['id'])
1547 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.'));
1550 $currentMembership['today_date'] = $today;
1552 if ($status['id'] !== $currentMembership['status_id']) {
1553 $memberDAO = new CRM_Member_DAO_Membership();
1554 $memberDAO->id
= $currentMembership['id'];
1555 $memberDAO->find(TRUE);
1557 $memberDAO->status_id
= $status['id'];
1558 $memberDAO->join_date
= CRM_Utils_Date
::isoToMysql($memberDAO->join_date
);
1559 $memberDAO->start_date
= CRM_Utils_Date
::isoToMysql($memberDAO->start_date
);
1560 $memberDAO->end_date
= CRM_Utils_Date
::isoToMysql($memberDAO->end_date
);
1562 CRM_Core_DAO
::storeValues($memberDAO, $currentMembership);
1565 $currentMembership['is_current_member'] = CRM_Core_DAO
::getFieldValue(
1566 'CRM_Member_DAO_MembershipStatus',
1567 $currentMembership['status_id'],
1573 'membership_id' => $currentMembership['id'],
1574 'status_id' => $status['id'],
1575 'start_date' => CRM_Utils_Date
::customFormat(
1576 $currentMembership['start_date'],
1579 'end_date' => CRM_Utils_Date
::customFormat(
1580 $currentMembership['end_date'],
1583 'modified_date' => CRM_Utils_Date
::customFormat(
1584 $currentMembership['today_date'],
1587 'membership_type_id' => $currentMembership['membership_type_id'],
1588 'max_related' => $currentMembership['max_related'],
1591 $session = CRM_Core_Session
::singleton();
1592 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
1593 if ($session->get('userID')) {
1594 $logParams['modified_id'] = $session->get('userID');
1597 $logParams['modified_id'] = $currentMembership['contact_id'];
1599 CRM_Member_BAO_MembershipLog
::add($logParams, CRM_Core_DAO
::$_nullArray);
1604 * Get the contribution page id from the membership record
1606 * @param int membershipId membership id
1608 * @return int $contributionPageId contribution page id
1611 public static function getContributionPageId($membershipID) {
1613 SELECT c.contribution_page_id as pageID
1614 FROM civicrm_membership_payment mp, civicrm_contribution c
1615 WHERE mp.contribution_id = c.id
1616 AND c.contribution_page_id IS NOT NULL
1617 AND mp.membership_id = " . CRM_Utils_Type
::escape($membershipID, 'Integer')
1618 . " ORDER BY mp.id DESC";
1620 return CRM_Core_DAO
::singleValueQuery($query,
1621 CRM_Core_DAO
::$_nullArray
1626 * Updated related memberships
1628 * @param int $ownerMembershipId owner Membership Id
1629 * @param array $params formatted array of key => value..
1632 public static function updateRelatedMemberships($ownerMembershipId, $params) {
1633 $membership = new CRM_Member_DAO_Membership();
1634 $membership->owner_membership_id
= $ownerMembershipId;
1635 $membership->find();
1637 while ($membership->fetch()) {
1638 $relatedMembership = new CRM_Member_DAO_Membership();
1639 $relatedMembership->id
= $membership->id
;
1640 $relatedMembership->copyValues($params);
1641 $relatedMembership->save();
1642 $relatedMembership->free();
1645 $membership->free();
1649 * Get list of membership fields for profile
1650 * For now we only allow custom membership fields to be in
1655 * @return array the list of membership fields
1658 public static function getMembershipFields($mode = NULL) {
1659 $fields = CRM_Member_DAO_Membership
::export();
1661 unset($fields['membership_contact_id']);
1662 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1664 $membershipType = CRM_Member_DAO_MembershipType
::export();
1666 $membershipStatus = CRM_Member_DAO_MembershipStatus
::export();
1668 $fields = array_merge($fields, $membershipType, $membershipStatus);
1674 * Get the sort name of a contact for a particular membership
1676 * @param int $id id of the membership
1678 * @return null|string sort name of the contact if found
1681 public static function sortName($id) {
1682 $id = CRM_Utils_Type
::escape($id, 'Integer');
1685 SELECT civicrm_contact.sort_name
1686 FROM civicrm_membership, civicrm_contact
1687 WHERE civicrm_membership.contact_id = civicrm_contact.id
1688 AND civicrm_membership.id = {$id}
1690 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1694 * Create memberships for related contacts
1695 * takes into account the maximum related memberships
1697 * @param array $params array of key - value pairs
1698 * @param CRM_Core_DAO $dao membership object
1700 * @return null|array array of memberships if created
1703 public static function createRelatedMemberships(&$params, &$dao, $reset = FALSE) {
1704 static $relatedContactIds = array();
1706 // not sure why a static var is in use here - we need a way to reset it from the test suite
1707 $relatedContactIds = array();
1711 $membership = new CRM_Member_DAO_Membership();
1712 $membership->id
= $dao->id
;
1714 // required since create method doesn't return all the
1715 // parameters in the returned membership object
1716 if (!$membership->find(TRUE)) {
1719 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1720 // FIXME : While updating/ renewing the
1721 // membership, if the relationship is PAST then
1722 // the membership of the related contact must be
1724 // For that, getting Membership Status for which
1725 // is_current_member is 0. It works for the
1726 // generated data as there is only one membership
1727 // status having is_current_member = 0.
1728 // But this wont work exactly if there will be
1729 // more than one status having is_current_member = 0.
1730 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
1731 $membershipStatus->is_current_member
= 0;
1732 if ($membershipStatus->find(TRUE)) {
1733 $expiredStatusId = $membershipStatus->id
;
1735 $expiredStatusId = array_search('Expired', CRM_Member_PseudoConstant
::membershipStatus());
1738 $allRelatedContacts = array();
1739 $relatedContacts = array();
1740 if (!is_a($membership, 'CRM_Core_Error')) {
1741 $allRelatedContacts = CRM_Member_BAO_Membership
::checkMembershipRelationship($membership->id
,
1742 $membership->contact_id
,
1743 CRM_Utils_Array
::value('action', $params)
1747 // check for loops. CRM-4213
1748 // remove repeated related contacts, which already inherited membership.
1749 $relatedContactIds[$membership->contact_id
] = TRUE;
1750 foreach ($allRelatedContacts as $cid => $status) {
1751 if (empty($relatedContactIds[$cid])) {
1752 $relatedContactIds[$cid] = TRUE;
1754 //don't create membership again for owner contact.
1755 $nestedRelationship = FALSE;
1756 if ($membership->owner_membership_id
) {
1757 $nestedRelMembership = new CRM_Member_DAO_Membership();
1758 $nestedRelMembership->id
= $membership->owner_membership_id
;
1759 $nestedRelMembership->contact_id
= $cid;
1760 $nestedRelationship = $nestedRelMembership->find(TRUE);
1761 $nestedRelMembership->free();
1763 if (!$nestedRelationship) {
1764 $relatedContacts[$cid] = $status;
1769 //lets cleanup related membership if any.
1770 if (empty($relatedContacts)) {
1771 self
::deleteRelatedMemberships($membership->id
);
1774 // Edit the params array
1775 unset($params['id']);
1776 // Reminder should be sent only to the direct membership
1777 unset($params['reminder_date']);
1778 // unset the custom value ids
1779 if (is_array(CRM_Utils_Array
::value('custom', $params))) {
1780 foreach ($params['custom'] as $k => $v) {
1781 unset($params['custom'][$k]['id']);
1784 if (!isset($params['membership_type_id'])) {
1785 $params['membership_type_id'] = $membership->membership_type_id
;
1788 // max_related should be set in the parent membership
1789 unset($params['max_related']);
1790 // Number of inherited memberships available - NULL is interpreted as unlimited, '0' as none
1791 $available = ($membership->max_related
== NULL ? PHP_INT_MAX
: $membership->max_related
);
1792 $queue = array(); // will be used to queue potential memberships to be created
1794 foreach ($relatedContacts as $contactId => $relationshipStatus) {
1795 //use existing membership record.
1796 $relMembership = new CRM_Member_DAO_Membership();
1797 $relMembership->contact_id
= $contactId;
1798 $relMembership->owner_membership_id
= $membership->id
;
1799 $relMemIds = array();
1800 if ($relMembership->find(TRUE)) {
1801 $params['id'] = $relMemIds['membership'] = $relMembership->id
;
1803 $params['contact_id'] = $contactId;
1804 $params['owner_membership_id'] = $membership->id
;
1806 // set status_id as it might have been changed for
1807 // past relationship
1808 $params['status_id'] = $membership->status_id
;
1810 if ($deceasedStatusId &&
1811 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'is_deceased')
1813 $params['status_id'] = $deceasedStatusId;
1815 elseif ((CRM_Utils_Array
::value('action', $params) & CRM_Core_Action
::UPDATE
) &&
1816 ($relationshipStatus == CRM_Contact_BAO_Relationship
::PAST
)
1818 $params['status_id'] = $expiredStatusId;
1821 //don't calculate status again in create( );
1822 $params['skipStatusCal'] = TRUE;
1824 //do create activity if we changed status.
1825 if ($params['status_id'] != $relMembership->status_id
) {
1826 $params['createActivity'] = TRUE;
1829 // we should not created contribution record for related contacts, CRM-3371
1830 unset($params['contribution_status_id']);
1832 if (($params['status_id'] == $deceasedStatusId) ||
($params['status_id'] == $expiredStatusId)) {
1833 // related membership is not active so does not count towards maximum
1834 CRM_Member_BAO_Membership
::create($params, $relMemIds);
1837 // related membership already exists, so this is just an update
1838 if (isset($params['id'])) {
1839 if ($available > 0) {
1840 CRM_Member_BAO_Membership
::create($params, $relMemIds);
1842 } else { // we have run out of inherited memberships, so delete extras
1843 self
::deleteMembership($params['id']);
1845 // we need to first check if there will remain inherited memberships, so queue it up
1851 // now go over the queue and create any available related memberships
1853 while (($available > 0) && ($params = each($queue))) {
1854 CRM_Member_BAO_Membership
::create($params['value'], $relMemIds);
1861 * Delete the record that are associated with this Membership Payment
1863 * @param int $membershipId membsership id.
1865 * @return boolean true if deleted false otherwise
1867 public static function deleteMembershipPayment($membershipId) {
1869 $membesrshipPayment = new CRM_Member_DAO_MembershipPayment();
1870 $membesrshipPayment->membership_id
= $membershipId;
1871 $membesrshipPayment->find();
1873 while ($membesrshipPayment->fetch()) {
1874 CRM_Contribute_BAO_Contribution
::deleteContribution($membesrshipPayment->contribution_id
);
1875 CRM_Utils_Hook
::pre('delete', 'MembershipPayment', $membesrshipPayment->id
, $membesrshipPayment);
1876 $membesrshipPayment->delete();
1877 CRM_Utils_Hook
::post('delete', 'MembershipPayment', $membesrshipPayment->id
, $membesrshipPayment);
1879 return $membesrshipPayment;
1883 * @param CRM_Core_Form $form
1884 * @param int $membershipTypeID
1888 public static function &buildMembershipTypeValues(&$form, $membershipTypeID = NULL) {
1889 $whereClause = " WHERE domain_id = ". CRM_Core_Config
::domainID();
1891 if (is_array($membershipTypeID)) {
1892 $allIDs = implode(',', $membershipTypeID);
1893 $whereClause .= " AND id IN ( $allIDs )";
1895 elseif (is_numeric($membershipTypeID) &&
1896 $membershipTypeID > 0
1898 $whereClause .= " AND id = $membershipTypeID";
1903 FROM civicrm_membership_type
1906 $dao = CRM_Core_DAO
::executeQuery($query);
1908 $membershipTypeValues = array();
1909 $membershipTypeFields = array(
1910 'id', 'minimum_fee', 'name', 'is_active',
1911 'description', 'financial_type_id', 'auto_renew','member_of_contact_id',
1912 'relationship_type_id', 'relationship_direction', 'max_related',
1915 while ($dao->fetch()) {
1916 $membershipTypeValues[$dao->id
] = array();
1917 foreach ($membershipTypeFields as $mtField) {
1918 $membershipTypeValues[$dao->id
][$mtField] = $dao->$mtField;
1923 CRM_Utils_Hook
::membershipTypeValues($form, $membershipTypeValues);
1925 if (is_numeric($membershipTypeID) &&
1926 $membershipTypeID > 0
1928 return $membershipTypeValues[$membershipTypeID];
1931 return $membershipTypeValues;
1936 * Get membership record count for a Contact
1938 * @param int $contactID
1939 * @param boolean $activeOnly
1941 * @return null|string
1944 public static function getContactMembershipCount($contactID, $activeOnly = FALSE) {
1945 $select = "SELECT count(*) FROM civicrm_membership ";
1946 $where = "WHERE civicrm_membership.contact_id = {$contactID} AND civicrm_membership.is_test = 0 ";
1948 // CRM-6627, all status below 3 (active, pending, grace) are considered active
1950 $select .= " INNER JOIN civicrm_membership_status ON civicrm_membership.status_id = civicrm_membership_status.id ";
1951 $where .= " and civicrm_membership_status.is_current_member = 1";
1954 $query = $select . $where;
1955 return CRM_Core_DAO
::singleValueQuery($query);
1959 * Check whether payment processor supports
1960 * cancellation of membership subscription
1962 * @param int $mid membership id
1964 * @param bool $isNotCancelled
1969 public static function isCancelSubscriptionSupported($mid, $isNotCancelled = TRUE) {
1970 $cacheKeyString = "$mid";
1971 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
1973 static $supportsCancel = array();
1975 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
1976 $supportsCancel[$cacheKeyString] = FALSE;
1977 $isCancelled = FALSE;
1979 if ($isNotCancelled) {
1980 $isCancelled = self
::isSubscriptionCancelled($mid);
1983 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($mid, 'membership', 'obj');
1984 if (!empty($paymentObject)) {
1985 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
1988 return $supportsCancel[$cacheKeyString];
1992 * Check whether subscription is already cancelled
1994 * @param int $mid membership id
1996 * @return string $status contribution status
1999 public static function isSubscriptionCancelled($mid) {
2001 SELECT cr.contribution_status_id
2002 FROM civicrm_contribution_recur cr
2003 LEFT JOIN civicrm_membership mem ON ( cr.id = mem.contribution_recur_id )
2004 WHERE mem.id = %1 LIMIT 1";
2005 $params = array(1 => array($mid, 'Integer'));
2006 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2007 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
2008 if ($status == 'Cancelled') {
2015 * Get membership joins for a specified membership
2016 * type. Specifically, retrieves a count of still current memberships whose
2017 * join_date and start_date are within a specified date range. Dates match
2018 * the pattern "yyyy-mm-dd".
2020 * @param int $membershipTypeId membership type id
2021 * @param int $startDate date on which to start counting
2022 * @param int $endDate date on which to end counting
2023 * @param bool|int $isTest if true, membership is for a test site
2025 * @return returns the number of members of type $membershipTypeId
2026 * whose join_date is between $startDate and $endDate and
2027 * whose start_date is between $startDate and $endDate
2029 public static function getMembershipJoins($membershipTypeId, $startDate, $endDate, $isTest = 0) {
2030 $testClause = 'membership.is_test = 1';
2032 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
2034 if (!self
::$_signupActType) {
2035 self
::_getActTypes();
2038 if (!self
::$_signupActType) {
2043 SELECT COUNT(DISTINCT membership.id) as member_count
2044 FROM civicrm_membership membership
2045 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
2046 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
2047 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
2048 WHERE membership.membership_type_id = %2
2049 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
2053 1 => array(self
::$_signupActType, 'Integer'),
2054 2 => array($membershipTypeId, 'Integer'),
2057 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
2059 return (int)$memberCount;
2063 * Get membership renewals for a specified membership
2064 * type. Specifically, retrieves a count of still current memberships
2065 * whose join_date is before and start_date is within a specified date
2066 * range. Dates match the pattern "yyyy-mm-dd".
2068 * @param int $membershipTypeId membership type id
2069 * @param int $startDate date on which to start counting
2070 * @param int $endDate date on which to end counting
2071 * @param bool|int $isTest if true, membership is for a test site
2073 * @return integer returns the number of members of type $membershipTypeId
2074 * whose join_date is before $startDate and
2075 * whose start_date is between $startDate and $endDate
2077 public static function getMembershipRenewals($membershipTypeId, $startDate, $endDate, $isTest = 0) {
2078 $testClause = 'membership.is_test = 1';
2080 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
2082 if (!self
::$_renewalActType) {
2083 self
::_getActTypes();
2086 if (!self
::$_renewalActType) {
2091 SELECT COUNT(DISTINCT membership.id) as member_count
2092 FROM civicrm_membership membership
2093 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
2094 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
2095 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
2096 WHERE membership.membership_type_id = %2
2097 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
2101 1 => array(self
::$_renewalActType, 'Integer'),
2102 2 => array($membershipTypeId, 'Integer'),
2104 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
2106 return (int)$memberCount;
2110 * Where a second separate financial transaction is supported we will process it here
2112 * @param int $contactID
2113 * @param CRM_Contribute_Form_Contribution_Confirm $form
2114 * @param array $tempParams
2116 * @param array $lineItems
2117 * @param $minimumFee
2118 * @param int $financialTypeID
2120 * @throws CRM_Core_Exception
2122 * @return CRM_Contribute_BAO_Contribution
2124 public static function processSecondaryFinancialTransaction($contactID, &$form, $tempParams, $isTest, $lineItems, $minimumFee, $financialTypeID) {
2125 $contributionType = new CRM_Financial_DAO_FinancialType();
2126 $contributionType->id
= $financialTypeID;
2127 if (!$contributionType->find(TRUE)) {
2128 CRM_Core_Error
::fatal(ts("Could not find a system table"));
2130 $tempParams['amount'] = $minimumFee;
2131 $tempParams['invoiceID'] = md5(uniqid(rand(), TRUE));
2134 if ($form->_values
['is_monetary'] && !$form->_params
['is_pay_later'] && $minimumFee > 0.0) {
2135 $payment = CRM_Core_Payment
::singleton($form->_mode
, $form->_paymentProcessor
, $form);
2137 if ($form->_contributeMode
== 'express') {
2138 $result = $payment->doExpressCheckout($tempParams);
2141 $result = $payment->doDirectPayment($tempParams);
2145 if (is_a($result, 'CRM_Core_Error')) {
2146 throw new CRM_Core_Exception(CRM_Core_Error
::getMessages($result));
2149 //assign receive date when separate membership payment
2150 //and contribution amount not selected.
2151 if ($form->_amount
== 0) {
2152 $now = date('YmdHis');
2153 $form->_params
['receive_date'] = $now;
2154 $receiveDate = CRM_Utils_Date
::mysqlToIso($now);
2155 $form->set('params', $form->_params
);
2156 $form->assign('receive_date', $receiveDate);
2159 $form->set('membership_trx_id', $result['trxn_id']);
2160 $form->set('membership_amount', $minimumFee);
2162 $form->assign('membership_trx_id', $result['trxn_id']);
2163 $form->assign('membership_amount', $minimumFee);
2165 // we don't need to create the user twice, so lets disable cms_create_account
2166 // irrespective of the value, CRM-2888
2167 $tempParams['cms_create_account'] = 0;
2169 $pending = $form->_params
['is_pay_later'] ?
(($minimumFee > 0.0) ?
TRUE : FALSE) : FALSE;
2171 //set this variable as we are not creating pledge for
2172 //separate membership payment contribution.
2173 //so for differentiating membership contribution from
2174 //main contribution.
2175 $form->_params
['separate_membership_payment'] = 1;
2176 $membershipContribution = CRM_Contribute_Form_Contribution_Confirm
::processContribution($form,
2186 return $membershipContribution;
2191 * Create linkages between membership & contribution - note this is the wrong place for this code but this is a
2192 * refactoring step. This should be BAO functionality
2193 * @param $membership
2194 * @param $membershipContribution
2196 public static function linkMembershipPayment($membership, $membershipContribution) {
2197 CRM_Member_BAO_MembershipPayment
::create(array('membership_id' => $membership->id
, 'contribution_id' => $membershipContribution->id
));
2201 * @param array $membershipParams
2202 * @param int $contactID
2203 * @param $customFieldsFormatted
2204 * @param int $membershipID
2208 * @param $membershipContribution
2209 * @param CRM_Core_Form $form
2213 public static function createOrRenewMembership($membershipParams, $contactID, $customFieldsFormatted, $membershipID, $memType, $isTest, $numTerms, $membershipContribution, &$form) {
2214 $membership = self
::renewMembershipFormWrapper($contactID, $memType,
2215 $isTest, $form, NULL,
2216 CRM_Utils_Array
::value('cms_contactID', $membershipParams),
2217 $customFieldsFormatted, $numTerms,
2221 if (!empty($membershipContribution)) {
2222 // update recurring id for membership record
2223 self
::updateRecurMembership($membership, $membershipContribution);
2225 self
::linkMembershipPayment($membership, $membershipContribution);
2231 * Turn array of errors into message string
2233 * @param array $errors
2238 public static function compileErrorMessage($errors)
2240 foreach($errors as $error) {
2241 if (is_string($error)) {
2242 $message[] = $error;
2245 return ts('Payment Processor Error message') . ': ' . implode('<br/>', $message);
2249 * Extract relevant values from the form so we can separate form logic from BAO logcis
2250 * @param CRM_Core_Form $form
2251 * @param $changeToday
2252 * @param $membershipTypeDetails
2256 public static function extractFormValues($form, $changeToday, $membershipTypeDetails)
2259 //@todo this is a BAO function & should not inspect the form - the form should do this
2260 // & pass required params to the BAO
2261 if (CRM_Utils_Array
::value('minimum_fee', $membershipTypeDetails) > 0.0) {
2262 if (((isset($form->_contributeMode
) && $form->_contributeMode
== 'notify') ||
!empty($form->_params
['is_pay_later']) ||
2263 (!empty($form->_params
['is_recur']) && $form->_contributeMode
== 'direct'
2266 (($form->_values
['is_monetary'] && $form->_amount
> 0.0) ||
!empty($form->_params
['separate_membership_payment']) ||
2267 CRM_Utils_Array
::value('record_contribution', $form->_params
)
2273 $contributionRecurID = isset($form->_params
['contributionRecurID']) ?
$form->_params
['contributionRecurID'] : NULL;
2275 //we renew expired membership, CRM-6277
2276 if (!$changeToday) {
2277 if ($form->get('renewalDate')) {
2278 $changeToday = $form->get('renewalDate');
2280 elseif (get_class($form) == 'CRM_Contribute_Form_Contribution_Confirm') {
2281 $changeToday = date('YmdHis');
2285 $membershipSource = NULL;
2286 if (!empty($form->_params
['membership_source'])) {
2287 $membershipSource = $form->_params
['membership_source'];
2289 elseif (isset($form->_values
['title']) && !empty($form->_values
['title'])) {
2290 $membershipSource = ts('Online Contribution:') . ' ' . $form->_values
['title'];
2293 if(isset($form->_params
)) {
2294 $isPayLater = CRM_Utils_Array
::value('is_pay_later', $form->_params
);
2297 if (isset($form->_values
) && is_array($form->_values
) && !empty($form->_values
)) {
2298 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_params
);
2299 if (!array_key_exists('campaign_id', $form->_params
)) {
2300 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_values
);
2303 return array($pending, $contributionRecurID, $changeToday, $membershipSource, $isPayLater, $campaignId);
2307 * @param integer $contactID
2308 * @param int $membershipTypeID
2309 * @param bool $is_test
2310 * @param $changeToday
2311 * @param integer $modifiedID
2312 * @param $customFieldsFormatted
2313 * @param $numRenewTerms
2314 * @param int $membershipID
2317 * @param array $membershipTypeDetails
2318 * @param integer $contributionRecurID
2320 * @param $membershipSource
2322 * @param $statusFormat
2323 * @param $isPayLater
2324 * @param integer $campaignId
2326 * @throws CRM_Core_Exception
2329 public static function renewMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $allStatus, $membershipTypeDetails, $contributionRecurID, $format, $membershipSource, $ids, $statusFormat, $isPayLater, $campaignId) {
2330 $renewalMode = $updateStatusId = FALSE;
2332 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
2333 // is the same as the parent org of an existing membership of the contact
2334 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($contactID, $membershipTypeID,
2335 $is_test, $membershipID, TRUE
2337 if ($currentMembership) {
2338 $activityType = 'Membership Renewal';
2339 $renewalMode = TRUE;
2341 // Do NOT do anything.
2342 //1. membership with status : PENDING/CANCELLED (CRM-2395)
2343 //2. Paylater/IPN renew. CRM-4556.
2344 if ($pending ||
in_array($currentMembership['status_id'], array(array_search('Pending', $allStatus),
2346 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
2349 $membership = new CRM_Member_DAO_Membership();
2350 $membership->id
= $currentMembership['id'];
2351 $membership->find(TRUE);
2353 // CRM-8141 create a membership_log entry so that we will know the membership_type_id to change to when payment completed
2355 // note that we are logging the requested new membership_type_id that may be different than current membership_type_id
2356 // it will be used when payment is received to update the membership_type_id to what was paid for
2358 'membership_id' => $membership->id
,
2359 'status_id' => $membership->status_id
,
2360 'start_date' => CRM_Utils_Date
::customFormat(
2361 $membership->start_date
,
2364 'end_date' => CRM_Utils_Date
::customFormat(
2365 $membership->end_date
,
2368 'modified_date' => CRM_Utils_Date
::customFormat(
2372 'membership_type_id' => $membershipTypeID,
2373 'max_related' => !empty($membershipTypeDetails['max_related']) ?
$membershipTypeDetails['max_related'] : NULL,
2375 $session = CRM_Core_Session
::singleton();
2376 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
2377 if ($session->get('userID')) {
2378 $logParams['modified_id'] = $session->get('userID');
2381 $logParams['modified_id'] = $membership->contact_id
;
2383 CRM_Member_BAO_MembershipLog
::add($logParams, CRM_Core_DAO
::$_nullArray);
2385 if (!empty($contributionRecurID)) {
2386 CRM_Core_DAO
::setFieldValue('CRM_Member_DAO_Membership', $membership->id
,
2387 'contribution_recur_id', $contributionRecurID
2391 return array($membership, $renewalMode, $dates);
2394 // Check and fix the membership if it is STALE
2395 self
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
2397 // Now Renew the membership
2398 if (!$currentMembership['is_current_member']) {
2399 // membership is not CURRENT
2401 // CRM-7297 Membership Upsell - calculate dates based on new membership type
2402 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($currentMembership['id'],
2408 $currentMembership['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
2409 $currentMembership['start_date'] = CRM_Utils_Array
::value('start_date', $dates);
2410 $currentMembership['end_date'] = CRM_Utils_Array
::value('end_date', $dates);
2411 $currentMembership['is_test'] = $is_test;
2413 if (!empty($membershipSource)) {
2414 $currentMembership['source'] = $membershipSource;
2417 $currentMembership['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
2418 $currentMembership['id'],
2423 if (!empty($currentMembership['id'])) {
2424 $ids['membership'] = $currentMembership['id'];
2426 $memParams = $currentMembership;
2427 $memParams['membership_type_id'] = $membershipTypeID;
2429 //set the log start date.
2430 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
2434 // CURRENT Membership
2435 $membership = new CRM_Member_DAO_Membership();
2436 $membership->id
= $currentMembership['id'];
2437 $membership->find(TRUE);
2438 // CRM-7297 Membership Upsell - calculate dates based on new membership type
2439 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
2445 // Insert renewed dates for CURRENT membership
2446 $memParams = array();
2447 $memParams['join_date'] = CRM_Utils_Date
::isoToMysql($membership->join_date
);
2448 $memParams['start_date'] = CRM_Utils_Date
::isoToMysql($membership->start_date
);
2449 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $dates);
2450 $memParams['membership_type_id'] = $membershipTypeID;
2452 //set the log start date.
2453 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
2454 if (empty($membership->source
)) {
2455 if (!empty($membershipSource)) {
2456 $memParams['source'] = $membershipSource;
2459 $memParams['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
2460 $currentMembership['id'],
2466 if (!empty($currentMembership['id'])) {
2467 $ids['membership'] = $currentMembership['id'];
2472 $updateStatusId = array_search('Pending', $allStatus);
2478 $activityType = 'Membership Signup';
2480 'contact_id' => $contactID,
2481 'membership_type_id' => $membershipTypeID,
2485 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
2487 $memParams['join_date'] = CRM_Utils_Array
::value('join_date', $dates);
2488 $memParams['start_date'] = CRM_Utils_Array
::value('start_date', $dates);
2489 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $dates);
2491 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(CRM_Utils_Date
::customFormat($dates['start_date'],
2494 CRM_Utils_Date
::customFormat($dates['end_date'],
2497 CRM_Utils_Date
::customFormat($dates['join_date'],
2505 $updateStatusId = CRM_Utils_Array
::value('id', $status);
2508 // if IPN/Pay-Later set status to: PENDING
2509 $updateStatusId = array_search('Pending', $allStatus);
2512 if (!empty($membershipSource)) {
2513 $memParams['source'] = $membershipSource;
2515 $memParams['contribution_recur_id'] = $contributionRecurID;
2517 $memParams['is_test'] = $is_test;
2518 $memParams['is_pay_later'] = $isPayLater;
2522 //if we decided status here and want to skip status
2523 //calculation in create( ); then need to pass 'skipStatusCal'.
2524 if ($updateStatusId) {
2525 $memParams['status_id'] = $updateStatusId;
2526 $memParams['skipStatusCal'] = TRUE;
2529 //since we are renewing,
2530 //make status override false.
2531 $memParams['is_override'] = FALSE;
2533 //CRM-4027, create log w/ individual contact.
2535 $ids['userId'] = $modifiedID;
2536 $memParams['is_for_organization'] = TRUE;
2539 $ids['userId'] = $contactID;
2542 //inherit campaign from contrib page.
2543 if (isset($campaignId)) {
2544 $memParams['campaign_id'] = $campaignId;
2547 $memParams['custom'] = $customFieldsFormatted;
2548 $membership = self
::create($memParams, $ids, FALSE, $activityType);
2550 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
2551 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
2552 $membership->find(TRUE);
2554 return array($membership, $renewalMode, $dates);
2558 * Process price set and line items.
2561 * @param int $membershipId
2566 public function processPriceSet($membershipId, $lineItem) {
2567 //FIXME : need to move this too
2568 if (!$membershipId ||
!is_array($lineItem)
2569 || CRM_Utils_System
::isNull($lineItem)
2574 foreach ($lineItem as $priceSetId => $values) {
2578 foreach ($values as $line) {
2579 $line['entity_table'] = 'civicrm_membership';
2580 $line['entity_id'] = $membershipId;
2581 CRM_Price_BAO_LineItem
::create($line);
2587 * Retrieve the contribution id for the associated Membership id
2588 * @todo we should get this off the line item
2590 * @param int $membershipId membership id.
2592 * @return integer contribution id
2594 public static function getMembershipContributionId($membershipId) {
2596 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
2597 $membershipPayment->membership_id
= $membershipId;
2598 if ($membershipPayment->find(TRUE)) {
2599 return $membershipPayment->contribution_id
;
2605 * The function checks and updates the status of all membership records for a given domain using the
2606 * calc_membership_status and update_contact_membership APIs.
2609 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
2611 * @return array $result
2613 public static function updateAllMembershipStatus() {
2615 //get all active statuses of membership, CRM-3984
2616 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2617 $statusLabels = CRM_Member_PseudoConstant
::membershipStatus(NULL, NULL, 'label');
2618 $allTypes = CRM_Member_PseudoConstant
::membershipType();
2620 // get only memberships with active membership types
2622 SELECT civicrm_membership.id as membership_id,
2623 civicrm_membership.is_override as is_override,
2624 civicrm_membership.membership_type_id as membership_type_id,
2625 civicrm_membership.status_id as status_id,
2626 civicrm_membership.join_date as join_date,
2627 civicrm_membership.start_date as start_date,
2628 civicrm_membership.end_date as end_date,
2629 civicrm_membership.source as source,
2630 civicrm_contact.id as contact_id,
2631 civicrm_contact.is_deceased as is_deceased,
2632 civicrm_membership.owner_membership_id as owner_membership_id,
2633 civicrm_membership.contribution_recur_id as recur_id
2634 FROM civicrm_membership
2635 INNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )
2636 INNER JOIN civicrm_membership_type ON
2637 (civicrm_membership.membership_type_id = civicrm_membership_type.id AND civicrm_membership_type.is_active = 1)
2638 WHERE civicrm_membership.is_test = 0";
2641 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2646 $smarty = CRM_Core_Smarty
::singleton();
2648 while ($dao->fetch()) {
2652 // Put common parameters into array for easy access
2653 $memberParams = array(
2654 'id' => $dao->membership_id
,
2655 'status_id' => $dao->status_id
,
2656 'contact_id' => $dao->contact_id
,
2657 'membership_type_id' => $dao->membership_type_id
,
2658 'membership_type' => $allTypes[$dao->membership_type_id
],
2659 'join_date' => $dao->join_date
,
2660 'start_date' => $dao->start_date
,
2661 'end_date' => $dao->end_date
,
2662 'source' => $dao->source
,
2663 'skipStatusCal' => TRUE,
2664 'skipRecentView' => TRUE,
2667 $smarty->assign_by_ref('memberParams', $memberParams);
2669 //update membership record to Deceased if contact is deceased
2670 if ($dao->is_deceased
) {
2671 // check for 'Deceased' membership status, CRM-5636
2672 $deceaseStatusId = array_search('Deceased', $allStatus);
2673 if (!$deceaseStatusId) {
2674 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'))));
2677 //process only when status change.
2678 if ($dao->status_id
!= $deceaseStatusId) {
2679 //take all params that need to save.
2680 $deceasedMembership = $memberParams;
2681 $deceasedMembership['status_id'] = $deceaseStatusId;
2682 $deceasedMembership['createActivity'] = TRUE;
2683 $deceasedMembership['version'] = 3;
2685 //since there is change in status.
2686 $statusChange = array('status_id' => $deceaseStatusId);
2687 $smarty->append_by_ref('memberParams', $statusChange, TRUE);
2689 $deceasedMembership['contact_id'],
2690 $deceasedMembership['membership_type_id'],
2691 $deceasedMembership['membership_type'],
2692 $deceasedMembership['join_date'],
2693 $deceasedMembership['start_date'],
2694 $deceasedMembership['end_date'],
2695 $deceasedMembership['source']
2698 //process membership record.
2699 civicrm_api('membership', 'create', $deceasedMembership);
2704 //we fetch related, since we need to check for deceased
2705 //now further processing is handle w/ main membership record.
2706 if ($dao->owner_membership_id
) {
2710 //update membership records where status is NOT - Pending OR Cancelled.
2711 //as well as membership is not override.
2712 //skipping Expired membership records -> reduced extra processing( kiran )
2713 if (!$dao->is_override
&&
2714 !in_array($dao->status_id
, array(array_search('Pending', $allStatus),
2718 CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)
2720 array_search('Expired', $allStatus),
2724 // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses
2725 //get the membership status as per id.
2726 $newStatus = civicrm_api('membership_status', 'calc',
2728 'membership_id' => $dao->membership_id
, 'version' => 3, 'ignore_admin_only'=> FALSE), TRUE
2730 $statusId = CRM_Utils_Array
::value('id', $newStatus);
2732 //process only when status change.
2734 $statusId != $dao->status_id
2736 //take all params that need to save.
2737 $memParams = $memberParams;
2738 $memParams['status_id'] = $statusId;
2739 $memParams['createActivity'] = TRUE;
2740 $memParams['version'] = 3;
2742 // Unset columns which should remain unchanged from their current saved
2743 // values. This avoids race condition in which these values may have
2744 // been changed by other processes.
2746 $memParams['contact_id'],
2747 $memParams['membership_type_id'],
2748 $memParams['membership_type'],
2749 $memParams['join_date'],
2750 $memParams['start_date'],
2751 $memParams['end_date'],
2752 $memParams['source']
2754 //since there is change in status.
2755 $statusChange = array('status_id' => $statusId);
2756 $smarty->append_by_ref('memberParams', $statusChange, TRUE);
2758 //process member record.
2759 civicrm_api('membership', 'create', $memParams);
2764 $result['is_error'] = 0;
2765 $result['messages'] = ts('Processed %1 membership records. Updated %2 records.', array(1 => $processCount, 2 => $updateCount));
2770 * The function returns the membershiptypes for a particular contact
2771 * who has lifetime membership without end date.
2773 * @param int $contactID
2774 * @param bool $isTest
2775 * @param bool $onlyLifeTime
2779 public static function getAllContactMembership($contactID, $isTest = FALSE, $onlyLifeTime = FALSE) {
2780 $contactMembershipType = array();
2782 return $contactMembershipType;
2785 $dao = new CRM_Member_DAO_Membership();
2786 $dao->contact_id
= $contactID;
2787 $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
2788 $dao->whereAdd("status_id != $pendingStatusId");
2791 $dao->is_test
= $isTest;
2794 $dao->whereAdd('is_test IS NULL OR is_test = 0');
2797 if ($onlyLifeTime) {
2798 $dao->whereAdd('end_date IS NULL');
2802 while ($dao->fetch()) {
2803 $membership = array();
2804 CRM_Core_DAO
::storeValues($dao, $membership);
2805 $contactMembershipType[$dao->membership_type_id
] = $membership;
2807 return $contactMembershipType;
2811 * Record contribution record associated with membership
2813 * @param array $params array of submitted params
2814 * @param array $ids (param in process of being removed - try to use params) array of ids
2816 * @return CRM_Contribute_BAO_Contribution
2819 public static function recordMembershipContribution( &$params, $ids = array()) {
2820 $membershipId = $params['membership_id'];
2821 $contributionParams = array();
2822 $config = CRM_Core_Config
::singleton();
2823 $contributionParams['currency'] = $config->defaultCurrency
;
2824 $contributionParams['receipt_date'] = (CRM_Utils_Array
::value('receipt_date', $params)) ?
$params['receipt_date'] : 'null';
2825 $contributionParams['source'] = CRM_Utils_Array
::value('contribution_source', $params);
2826 $contributionParams['non_deductible_amount'] = 'null';
2827 $contributionParams['payment_processor'] = CRM_Utils_Array
::value('payment_processor_id', $params);
2828 $contributionSoftParams = CRM_Utils_Array
::value('soft_credit', $params);
2829 $recordContribution = array(
2830 'contact_id', 'total_amount', 'receive_date', 'financial_type_id',
2831 'payment_instrument_id', 'trxn_id', 'invoice_id', 'is_test',
2832 'contribution_status_id', 'check_number', 'campaign_id', 'is_pay_later',
2833 'membership_id', 'tax_amount', 'skipLineItem'
2835 foreach ($recordContribution as $f) {
2836 $contributionParams[$f] = CRM_Utils_Array
::value($f, $params);
2839 // make entry in batch entity batch table
2840 if (!empty($params['batch_id'])) {
2841 $contributionParams['batch_id'] = $params['batch_id'];
2844 if (!empty($params['contribution_contact_id'])) {
2845 // deal with possibility of a different person paying for contribution
2846 $contributionParams['contact_id'] = $params['contribution_contact_id'];
2849 if (!empty($params['processPriceSet']) &&
2850 !empty($params['lineItems'])
2852 $contributionParams['line_item'] = CRM_Utils_Array
::value('lineItems', $params, NULL);
2855 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
2857 //CRM-13981, create new soft-credit record as to record payment from different person for this membership
2858 if (!empty($contributionSoftParams)) {
2859 if (!empty($params['batch_id'])) {
2860 foreach ($contributionSoftParams as $contributionSoft) {
2861 $contributionSoft['contribution_id'] = $contribution->id
;
2862 $contributionSoft['currency'] = $contribution->currency
;
2863 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoft);
2867 $contributionSoftParams['contribution_id'] = $contribution->id
;
2868 $contributionSoftParams['currency'] = $contribution->currency
;
2869 $contributionSoftParams['amount'] = $contribution->total_amount
;
2870 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoftParams);
2874 // store contribution id
2875 $params['contribution_id'] = $contribution->id
;
2878 //insert payment record for this membership
2879 if (empty($ids['contribution']) ||
!empty($params['is_recur'])) {
2880 CRM_Member_BAO_MembershipPayment
::create(array('membership_id' => $membershipId, 'contribution_id' => $contribution->id
));
2882 return $contribution;
2886 * Record line items for default membership
2888 * @param CRM_Core_Form $qf
2889 * @param array $membershipType array with membership type and organization
2890 * @param int $priceSetId
2894 public static function createLineItems(&$qf, $membershipType, &$priceSetId) {
2895 $qf->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
2897 $qf->_priceSet
= $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
2899 $editedFieldParams = array(
2900 'price_set_id' => $priceSetId,
2901 'name' => $membershipType[0],
2903 $editedResults = array();
2904 CRM_Price_BAO_PriceField
::retrieve($editedFieldParams, $editedResults);
2906 if (!empty($editedResults)) {
2907 unset($qf->_priceSet
['fields']);
2908 $qf->_priceSet
['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
2909 unset($qf->_priceSet
['fields'][$editedResults['id']]['options']);
2910 $fid = $editedResults['id'];
2911 $editedFieldParams = array(
2912 'price_field_id' => $editedResults['id'],
2913 'membership_type_id' => $membershipType[1],
2915 $editedResults = array();
2916 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $editedResults);
2917 $qf->_priceSet
['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
2918 if (!empty($qf->_params
['total_amount'])) {
2919 $qf->_priceSet
['fields'][$fid]['options'][$editedResults['id']]['amount'] = $qf->_params
['total_amount'];
2923 $fieldID = key($qf->_priceSet
['fields']);
2924 $qf->_params
['price_' . $fieldID] = CRM_Utils_Array
::value('id', $editedResults);
2928 * @todo document me - I seem a bit out of date....
2930 public static function _getActTypes() {
2931 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2932 self
::$_renewalActType = CRM_Utils_Array
::key('Membership Renewal', $activityTypes);
2933 self
::$_signupActType = CRM_Utils_Array
::key('Membership Signup', $activityTypes);
2937 * Get all Cancelled Membership(s) for a contact
2939 * @param int $contactID contact id
2940 * @param boolean $isTest mode of payment
2942 * @return array of membership type
2945 public static function getContactsCancelledMembership($contactID, $isTest = FALSE) {
2949 $query = 'SELECT membership_type_id FROM civicrm_membership WHERE contact_id = %1 AND status_id = %2 AND is_test = %3';
2950 $queryParams = array(
2951 1 => array($contactID, 'Integer'),
2956 CRM_Member_PseudoConstant
::membershipStatus(
2958 " name = 'Cancelled' ",
2966 3 => array($isTest, 'Boolean'),
2969 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
2970 $cancelledMembershipIds = array();
2971 while ($dao->fetch()) {
2972 $cancelledMembershipIds[] = $dao->membership_type_id
;
2974 return $cancelledMembershipIds;