3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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;
53 * @return \CRM_Member_DAO_Membership
58 function __construct() {
59 parent
::__construct();
63 * takes an associative array and creates a membership object
65 * the function extracts all the params it needs to initialize the created
66 * membership object. The params array could contain additional unused name/value
69 * @param array $params (reference ) an assoc array of name/value pairs
70 * @param array $ids the array that holds all the db ids
72 * @return object CRM_Member_BAO_Membership object
76 static function add(&$params, $ids = array()) {
77 $oldStatus = $oldType = NULL;
78 if (!empty($ids['membership'])) {
79 CRM_Utils_Hook
::pre('edit', 'Membership', $ids['membership'], $params);
81 $membershipObj = new CRM_Member_DAO_Membership();
82 $membershipObj->id
= $ids['membership'];
83 $membershipObj->find();
84 while ($membershipObj->fetch()) {
85 $oldStatus = $membershipObj->status_id
;
86 $oldType = $membershipObj->membership_type_id
;
90 CRM_Utils_Hook
::pre('create', 'Membership', NULL, $params);
93 if (array_key_exists('is_override', $params) && !$params['is_override']) {
94 $params['is_override'] = 'null';
97 $membership = new CRM_Member_BAO_Membership();
98 $membership->copyValues($params);
99 $membership->id
= CRM_Utils_Array
::value('membership', $ids);
104 if (empty($membership->contact_id
) ||
empty($membership->status_id
)) {
105 // this means we are in renewal mode and are just updating the membership
106 // record or this is an API update call and all fields are not present in the update record
107 // however the hooks dont care and want all data CRM-7784
108 $tempMembership = new CRM_Member_DAO_Membership();
109 $tempMembership->id
= $membership->id
;
110 $tempMembership->find(TRUE);
111 $membership = $tempMembership;
114 //get the log start date.
115 //it is set during renewal of membership.
116 $logStartDate = CRM_Utils_Array
::value('log_start_date', $params);
117 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : CRM_Utils_Date
::isoToMysql($membership->start_date
);
118 $values = self
::getStatusANDTypeValues($membership->id
);
120 $membershipLog = array(
121 'membership_id' => $membership->id
,
122 'status_id' => $membership->status_id
,
123 'start_date' => $logStartDate,
124 'end_date' => CRM_Utils_Date
::isoToMysql($membership->end_date
),
125 'modified_date' => date('Ymd'),
126 'membership_type_id' => $values[$membership->id
]['membership_type_id'],
127 'max_related' => $membership->max_related
,
130 $session = CRM_Core_Session
::singleton();
131 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
132 if ($session->get('userID')) {
133 $membershipLog['modified_id'] = $session->get('userID');
135 elseif (!empty($ids['userId'])) {
136 $membershipLog['modified_id'] = $ids['userId'];
139 $membershipLog['modified_id'] = $membership->contact_id
;
142 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
144 // reset the group contact cache since smart groups might be affected due to this
145 CRM_Contact_BAO_GroupContactCache
::remove();
147 if (!empty($ids['membership'])) {
148 if ($membership->status_id
!= $oldStatus) {
149 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
150 $activityParam = array(
151 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
152 'source_contact_id' => $membershipLog['modified_id'],
153 'target_contact_id' => $membership->contact_id
,
154 'source_record_id' => $membership->id
,
155 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Change Membership Status'),
158 'activity_date_time' => date('Y-m-d H:i:s'),
160 civicrm_api3('activity', 'create', $activityParam);
162 if (isset($membership->membership_type_id
) && $membership->membership_type_id
!= $oldType) {
163 $membershipTypes = CRM_Member_BAO_Membership
::buildOptions('membership_type_id', 'get');
164 $activityParam = array(
165 'subject' => "Type changed from {$membershipTypes[$oldType]} to {$membershipTypes[$membership->membership_type_id]}",
166 'source_contact_id' => $membershipLog['modified_id'],
167 'target_contact_id' => $membership->contact_id
,
168 'source_record_id' => $membership->id
,
169 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Change Membership Type'),
172 'activity_date_time' => date('Y-m-d H:i:s'),
174 civicrm_api3('activity', 'create', $activityParam);
176 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
179 CRM_Utils_Hook
::post('create', 'Membership', $membership->id
, $membership);
186 * Given the list of params in the params array, fetch the object
187 * and store the values in the values array
189 * @param array $params input parameters to find object
190 * @param array $values output values of the object
191 * @param boolean $active do you want only active memberships to
194 * @return CRM_Member_BAO_Membership|null the found object or null
198 static function &getValues(&$params, &$values, $active = FALSE) {
199 if (empty($params)) {
202 $membership = new CRM_Member_BAO_Membership();
204 $membership->copyValues($params);
206 $memberships = array();
207 while ($membership->fetch()) {
209 (!CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
210 $membership->status_id
,
217 CRM_Core_DAO
::storeValues($membership, $values[$membership->id
]);
218 $memberships[$membership->id
] = $membership;
225 * takes an associative array and creates a membership object
227 * @param array $params (reference ) an assoc array of name/value pairs
228 * @param array $ids the array that holds all the db ids
229 * @param bool $skipRedirect
230 * @param string $activityType
232 * @throws CRM_Core_Exception
233 * @internal param bool $callFromAPI Is this function called from API?
235 * @return CRM_Member_BAO_Membership object
239 static function create(&$params, &$ids, $skipRedirect = FALSE, $activityType = 'Membership Signup') {
240 // always calculate status if is_override/skipStatusCal is not true.
241 // giving respect to is_override during import. CRM-4012
243 // To skip status calculation we should use 'skipStatusCal'.
244 // eg pay later membership, membership update cron CRM-3984
246 if (empty($params['is_override']) && empty($params['skipStatusCal'])) {
247 $dates = array('start_date', 'end_date', 'join_date');
248 $start_date = $end_date = $join_date = NULL; // declare these out of courtesy as IDEs don't pick up the setting of them below
249 foreach ($dates as $date) {
250 $
$date = $params[$date] = CRM_Utils_Date
::processDate(CRM_Utils_Array
::value($date, $params), NULL, TRUE, 'Ymd');
253 //fix for CRM-3570, during import exclude the statuses those having is_admin = 1
254 $excludeIsAdmin = CRM_Utils_Array
::value('exclude_is_admin', $params, FALSE);
256 //CRM-3724 always skip is_admin if is_override != true.
257 if (!$excludeIsAdmin && empty($params['is_override'])) {
258 $excludeIsAdmin = TRUE;
261 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($start_date, $end_date, $join_date,
262 'today', $excludeIsAdmin, CRM_Utils_Array
::value('membership_type_id', $params), $params
264 if (empty($calcStatus)) {
265 // Redirect the form in case of error
266 // @todo this redirect in the BAO layer is really bad & should be moved to the form layer
267 // however since we have no idea how (if) this is triggered we can't safely move / remove it
268 // NB I tried really hard to trigger this error from backoffice membership form in order to test it
269 // and am convinced form validation is complete on that form WRT this error.
270 $errorParams = array(
271 'message_title' => ts('No valid membership status for given dates.'),
272 'legacy_redirect_path' => 'civicrm/contact/view',
273 'legacy_redirect_query' => "reset=1&force=1&cid={$params['contact_id']}&selectedChild=member",
275 throw new CRM_Core_Exception(ts('The membership cannot be saved because the status cannot be calculated.'), 0, $errorParams);
277 $params['status_id'] = $calcStatus['id'];
280 // data cleanup only: all verifications on number of related memberships are done upstream in:
281 // CRM_Member_BAO_Membership::createRelatedMemberships()
282 // CRM_Contact_BAO_Relationship::relatedMemberships()
283 if (isset($params['owner_membership_id'])) {
284 unset($params['max_related']);
287 // if membership allows related, default max_related to value in membership_type
288 if (!array_key_exists('max_related', $params) && !empty($params['membership_type_id'])) {
289 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($params['membership_type_id']);
290 if (isset($membershipType['relationship_type_id'])) {
291 $params['max_related'] = CRM_Utils_Array
::value('max_related', $membershipType);
296 $transaction = new CRM_Core_Transaction();
298 $membership = self
::add($params, $ids);
300 if (is_a($membership, 'CRM_Core_Error')) {
301 $transaction->rollback();
305 // add custom field values
306 if (!empty($params['custom']) && is_array($params['custom'])
308 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_membership', $membership->id
);
311 $params['membership_id'] = $membership->id
;
312 if (isset($ids['membership'])) {
313 $ids['contribution'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment',
320 $params['skipLineItem'] = TRUE;
322 //record contribution for this membership
323 if (!empty($params['contribution_status_id']) && empty($params['relate_contribution_id'])) {
324 $memInfo = array_merge($params, array('membership_id' => $membership->id
));
325 $params['contribution'] = self
::recordMembershipContribution($memInfo, $ids);
328 if (CRM_Utils_Array
::value('lineItems', $params) && empty($params['contributionId'])) {
329 CRM_Price_BAO_LineItem
::processPriceSet($membership->id
, $params['lineItems'], CRM_Utils_Array
::value('contribution', $params));
332 //insert payment record for this membership
333 if (!empty($params['relate_contribution_id'])) {
334 $mpDAO = new CRM_Member_DAO_MembershipPayment();
335 $mpDAO->membership_id
= $membership->id
;
336 $mpDAO->contribution_id
= $params['relate_contribution_id'];
337 if (!($mpDAO->find(TRUE))) {
338 CRM_Utils_Hook
::pre('create', 'MembershipPayment', NULL, $mpDAO);
340 CRM_Utils_Hook
::post('create', 'MembershipPayment', $mpDAO->id
, $mpDAO);
344 // add activity record only during create mode and renew mode
345 // also add activity if status changed CRM-3984 and CRM-2521
346 if (empty($ids['membership']) ||
347 $activityType == 'Membership Renewal' ||
!empty($params['createActivity'])) {
348 if (!empty($ids['membership'])) {
350 CRM_Core_DAO
::commonRetrieveAll('CRM_Member_DAO_Membership',
354 array('contact_id', 'membership_type_id', 'source')
357 $membership->contact_id
= $data[$membership->id
]['contact_id'];
358 $membership->membership_type_id
= $data[$membership->id
]['membership_type_id'];
359 $membership->source
= CRM_Utils_Array
::value('source', $data[$membership->id
]);
362 // since we are going to create activity record w/
363 // individual contact as a target in case of on behalf signup,
364 // so get the copy of organization id, CRM-5551
365 $realMembershipContactId = $membership->contact_id
;
367 // create activity source = individual, target = org CRM-4027
368 $targetContactID = NULL;
369 if (!empty($params['is_for_organization'])) {
370 $targetContactID = $membership->contact_id
;
371 $membership->contact_id
= CRM_Utils_Array
::value('userId', $ids);
374 if (empty($membership->contact_id
) && (!empty($membership->owner_membership_id
))) {
375 $membership->contact_id
= $realMembershipContactId;
378 if (!empty($ids['membership']) && $activityType != 'Membership Signup') {
379 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $targetContactID);
380 } elseif (empty($ids['membership'])) {
381 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $targetContactID);
384 // we might created activity record w/ individual
385 // contact as target so update membership object w/
386 // original organization id, CRM-5551
387 $membership->contact_id
= $realMembershipContactId;
390 $transaction->commit();
392 self
::createRelatedMemberships($params, $membership);
394 // do not add to recent items for import, CRM-4399
395 if (empty($params['skipRecentView'])) {
396 $url = CRM_Utils_System
::url('civicrm/contact/view/membership',
397 "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
399 if(empty($membership->membership_type_id
)){// ie in an update situation
400 $membership->find(TRUE);
402 $membershipTypes = CRM_Member_PseudoConstant
::membershipType();
403 $title = CRM_Contact_BAO_Contact
::displayName($membership->contact_id
) . ' - ' . ts('Membership Type:') . ' ' . $membershipTypes[$membership->membership_type_id
];
405 $recentOther = array();
406 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::UPDATE
)) {
407 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
408 "action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
411 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::DELETE
)) {
412 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
413 "action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
417 // add the recently created Membership
418 CRM_Utils_Recent
::add($title,
422 $membership->contact_id
,
432 * Function to check the membership extended through relationship
434 * @param int $membershipId membership id
435 * @param int $contactId contact id
437 * @param const $action
439 * @return Array array of contact_id of all related contacts.
442 static function checkMembershipRelationship($membershipId, $contactId, $action = CRM_Core_Action
::ADD
) {
444 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $membershipId, 'membership_type_id');
446 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipTypeID);
447 $relationships = array();
448 if (isset($membershipType['relationship_type_id'])) {
449 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
450 CRM_Contact_BAO_Relationship
::CURRENT
452 if ($action & CRM_Core_Action
::UPDATE
) {
453 $pastRelationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
454 CRM_Contact_BAO_Relationship
::PAST
456 $relationships = array_merge($relationships, $pastRelationships);
460 if (!empty($relationships)) {
461 // check for each contact relationships
462 foreach ($relationships as $values) {
463 //get details of the relationship type
464 $relType = array('id' => $values['civicrm_relationship_type_id']);
465 $relValues = array();
466 CRM_Contact_BAO_RelationshipType
::retrieve($relType, $relValues);
467 // Check if contact's relationship type exists in membership type
468 $relTypeDirs = array();
469 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_type_id']);
470 $relDirections = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_direction']);
471 $bidirectional = FALSE;
472 foreach ($relTypeIds as $key => $value) {
473 $relTypeDirs[] = $value . '_' . $relDirections[$key];
474 if (in_array($value, $relType) &&
475 $relValues['name_a_b'] == $relValues['name_b_a']
477 $bidirectional = TRUE;
481 $relTypeDir = $values['civicrm_relationship_type_id'] . '_' . $values['rtype'];
482 if ($bidirectional ||
in_array($relTypeDir, $relTypeDirs)) {
483 // $values['status'] is going to have value for
484 // current or past relationships.
485 $contacts[$values['cid']] = $values['status'];
490 // Sort by contact_id ascending
496 * Takes a bunch of params that are needed to match certain criteria and
497 * retrieves the relevant objects. We'll tweak this function to be more
498 * full featured over a period of time. This is the inverse function of
499 * create. It also stores all the retrieved values in the default array
501 * @param array $params (reference ) an assoc array of name/value pairs
502 * @param array $defaults (reference ) an assoc array to hold the name / value pairs
503 * in a hierarchical manner
505 * @internal param array $ids (reference) the array that holds all the db ids
507 * @return object CRM_Member_BAO_Membership object
511 static function retrieve(&$params, &$defaults) {
512 $membership = new CRM_Member_DAO_Membership();
514 $membership->copyValues($params);
516 if ($membership->find(TRUE)) {
517 CRM_Core_DAO
::storeValues($membership, $defaults);
519 //get the membership status and type values.
520 $statusANDType = self
::getStatusANDTypeValues($membership->id
);
522 'status', 'membership_type') as $fld) {
523 $defaults[$fld] = CRM_Utils_Array
::value($fld, $statusANDType[$membership->id
]);
525 if (!empty($statusANDType[$membership->id
]['is_current_member'])) {
526 $defaults['active'] = TRUE;
539 * Function to get membership status and membership type values
541 * @param int $membershipId membership id of values to return
543 * @return array of key value pairs
546 static function getStatusANDTypeValues($membershipId) {
548 if (!$membershipId) {
552 SELECT membership.id as id,
553 status.id as status_id,
554 status.label as status,
555 status.is_current_member as is_current_member,
556 type.id as membership_type_id,
557 type.name as membership_type,
558 type.relationship_type_id as relationship_type_id
559 FROM civicrm_membership membership
560 INNER JOIN civicrm_membership_status status ON ( status.id = membership.status_id )
561 INNER JOIN civicrm_membership_type type ON ( type.id = membership.membership_type_id )
562 WHERE membership.id = %1';
563 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($membershipId, 'Positive')));
564 $properties = array('status', 'status_id', 'membership_type', 'membership_type_id', 'is_current_member', 'relationship_type_id');
565 while ($dao->fetch()) {
566 foreach ($properties as $property) {
567 $values[$dao->id
][$property] = $dao->$property;
575 * Function to delete membership.
576 * Wrapper for most delete calls. Use this unless you JUST want to delete related memberships w/o deleting the parent.
578 * @param int $membershipId membership id that needs to be deleted
582 * @return $results no of deleted Membership on success, false otherwise
585 static function del($membershipId) {
586 //delete related first and then delete parent.
587 self
::deleteRelatedMemberships($membershipId);
588 return self
::deleteMembership($membershipId);
592 * Function to delete membership.
594 * @param int $membershipId membership id that needs to be deleted
598 * @return $results no of deleted Membership on success, false otherwise
601 static function deleteMembership($membershipId) {
602 // CRM-12147, retrieve membership data before we delete it for hooks
603 $params = array('id' => $membershipId);
604 $memValues = array();
605 $memberships = self
::getValues($params, $memValues);
607 $membership = $memberships[$membershipId];
609 CRM_Utils_Hook
::pre('delete', 'Membership', $membershipId, $memValues);
611 $transaction = new CRM_Core_Transaction();
614 //delete activity record
615 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
618 $deleteActivity = false;
619 $membershipActivities = array(
621 'Membership Renewal',
622 'Change Membership Status',
623 'Change Membership Type',
624 'Membership Renewal Reminder'
626 foreach($membershipActivities as $membershipActivity) {
627 $activityId = array_search($membershipActivity, $activityTypes);
629 $params['activity_type_id'][] = $activityId;
630 $deleteActivity = true;
633 if ($deleteActivity) {
634 $params['source_record_id'] = $membershipId;
635 CRM_Activity_BAO_Activity
::deleteActivity($params);
637 self
::deleteMembershipPayment($membershipId);
639 $results = $membership->delete();
640 $transaction->commit();
642 CRM_Utils_Hook
::post('delete', 'Membership', $membership->id
, $membership);
644 // delete the recently created Membership
645 $membershipRecent = array(
646 'id' => $membershipId,
647 'type' => 'Membership',
649 CRM_Utils_Recent
::del($membershipRecent);
655 * Function to delete related memberships
657 * @param int $ownerMembershipId
658 * @param int $contactId
663 static function deleteRelatedMemberships($ownerMembershipId, $contactId = NULL) {
664 if (!$ownerMembershipId && !$contactId) {
668 $membership = new CRM_Member_DAO_Membership();
669 $membership->owner_membership_id
= $ownerMembershipId;
672 $membership->contact_id
= $contactId;
676 while ($membership->fetch()) {
677 //delete related first and then delete parent.
678 self
::deleteRelatedMemberships($membership->id
);
679 self
::deleteMembership($membership->id
);
685 * Function to obtain active/inactive memberships from the list of memberships passed to it.
687 * @param array $memberships membership records
688 * @param string $status active or inactive
690 * @return array $actives array of memberships based on status
694 static function activeMembers($memberships, $status = 'active') {
696 if ($status == 'active') {
697 foreach ($memberships as $f => $v) {
698 if (!empty($v['active'])) {
704 elseif ($status == 'inactive') {
705 foreach ($memberships as $f => $v) {
706 if (empty($v['active'])) {
716 * Function to build Membership Block in Contribution Pages
718 * @param object $form form object
721 * @param boolean $formItems
722 * @param int $selectedMembershipTypeID selected membership id
723 * @param boolean $thankPage thank you page
724 * @param null $isTest
726 * @return bool Is this a separate membership payment
727 * @internal param int $pageId contribution page id
728 * @internal param bool $memContactId contact who is to be
729 * checked for having a current membership for a particular membership
733 static function buildMembershipBlock(&$form,
737 $selectedMembershipTypeID = NULL,
742 $separateMembershipPayment = FALSE;
743 if ($form->_membershipBlock
) {
744 $form->_currentMemberships
= array();
746 $membershipBlock = $form->_membershipBlock
;
747 $membershipTypeIds = $membershipTypes = $radio = array();
748 $membershipPriceset = (!empty($form->_priceSetId
) && $form->_useForMember
) ?
TRUE : FALSE;
750 $allowAutoRenewMembership = $autoRenewOption = FALSE;
751 $autoRenewMembershipTypeOptions = array();
753 $paymentProcessor = CRM_Core_PseudoConstant
::paymentProcessor(FALSE, FALSE, 'is_recur = 1');
755 $separateMembershipPayment = CRM_Utils_Array
::value('is_separate_payment', $membershipBlock);
757 if ($membershipPriceset) {
758 foreach ($form->_priceSet
['fields'] as $pField) {
759 if (empty($pField['options'])) {
762 foreach ($pField['options'] as $opId => $opValues) {
763 if (empty($opValues['membership_type_id'])) {
766 $membershipTypeIds[$opValues['membership_type_id']] = $opValues['membership_type_id'];
770 elseif (!empty($membershipBlock['membership_types'])) {
771 $membershipTypeIds = explode(',', $membershipBlock['membership_types']);
774 if (!empty($membershipTypeIds)) {
775 //set status message if wrong membershipType is included in membershipBlock
776 if (isset($form->_mid
) && !$membershipPriceset) {
777 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
781 if (!in_array($membershipTypeID, $membershipTypeIds)) {
782 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');
786 $membershipTypeValues = self
::buildMembershipTypeValues($form, $membershipTypeIds);
787 $form->_membershipTypeValues
= $membershipTypeValues;
789 foreach ($membershipTypeIds as $value) {
790 $memType = $membershipTypeValues[$value];
791 if ($selectedMembershipTypeID != NULL) {
792 if ($memType['id'] == $selectedMembershipTypeID) {
793 $form->assign('minimum_fee',
794 CRM_Utils_Array
::value('minimum_fee', $memType)
796 $form->assign('membership_name', $memType['name']);
797 if (!$thankPage && $cid) {
798 $membership = new CRM_Member_DAO_Membership();
799 $membership->contact_id
= $cid;
800 $membership->membership_type_id
= $memType['id'];
801 if ($membership->find(TRUE)) {
802 $form->assign('renewal_mode', TRUE);
803 $memType['current_membership'] = $membership->end_date
;
804 $form->_currentMemberships
[$membership->membership_type_id
] = $membership->membership_type_id
;
807 $membershipTypes[] = $memType;
810 elseif ($memType['is_active']) {
811 $javascriptMethod = NULL;
812 $allowAutoRenewOpt = 1;
813 if (is_array($form->_paymentProcessors
)){
814 foreach ($form->_paymentProcessors
as $id => $val) {
815 if (!$val['is_recur']) {
816 $allowAutoRenewOpt = 0;
822 $javascriptMethod = array('onclick' => "return showHideAutoRenew( this.value );");
823 $autoRenewMembershipTypeOptions["autoRenewMembershipType_{$value}"] = (int)$allowAutoRenewOpt * CRM_Utils_Array
::value($value, CRM_Utils_Array
::value('auto_renew', $form->_membershipBlock
));;
825 if ($allowAutoRenewOpt) {
826 $allowAutoRenewMembership = TRUE;
829 //add membership type.
830 $radio[$memType['id']] = $form->createElement('radio', NULL, NULL, NULL,
831 $memType['id'], $javascriptMethod
834 $membership = new CRM_Member_DAO_Membership();
835 $membership->contact_id
= $cid;
836 $membership->membership_type_id
= $memType['id'];
838 //show current membership, skip pending and cancelled membership records,
839 //because we take first membership record id for renewal
840 $membership->whereAdd('status_id != 5 AND status_id !=6');
842 if (!is_null($isTest)) {
843 $membership->is_test
= $isTest;
847 $membership->orderBy('end_date DESC');
849 if ($membership->find(TRUE)) {
850 if (!$membership->end_date
) {
851 unset($radio[$memType['id']]);
852 $form->assign('islifetime', TRUE);
855 $form->assign('renewal_mode', TRUE);
856 $form->_currentMemberships
[$membership->membership_type_id
] = $membership->membership_type_id
;
857 $memType['current_membership'] = $membership->end_date
;
859 $endDate = $memType['current_membership'];
860 $form->_defaultMemTypeId
= $memType['id'];
862 if ($memType['current_membership'] < $endDate) {
863 $endDate = $memType['current_membership'];
864 $form->_defaultMemTypeId
= $memType['id'];
868 $membershipTypes[] = $memType;
873 $form->assign('showRadio', $formItems);
875 if (!$membershipPriceset) {
876 if (!$membershipBlock['is_required']) {
877 $form->assign('showRadioNoThanks', TRUE);
878 $radio[''] = $form->createElement('radio', NULL, NULL, NULL, 'no_thanks', NULL);
879 $form->addGroup($radio, 'selectMembership', NULL);
881 elseif ($membershipBlock['is_required'] && count($radio) == 1) {
882 $temp = array_keys($radio);
883 $form->add('hidden', 'selectMembership', $temp[0], array('id' => 'selectMembership'));
884 $form->assign('singleMembership', TRUE);
885 $form->assign('showRadio', FALSE);
888 $form->addGroup($radio, 'selectMembership', NULL);
891 $form->addRule('selectMembership', ts('Please select one of the memberships.'), 'required');
894 $autoRenewOption = CRM_Price_BAO_PriceSet
::checkAutoRenewForPriceSet($form->_priceSetId
);
895 $form->assign('autoRenewOption', $autoRenewOption);
898 if (!$form->_values
['is_pay_later'] && is_array($form->_paymentProcessors
) && ($allowAutoRenewMembership ||
$autoRenewOption)) {
899 $form->addElement('checkbox', 'auto_renew', ts('Please renew my membership automatically.'));
904 $form->assign('membershipBlock', $membershipBlock);
905 $form->assign('membershipTypes', $membershipTypes);
906 $form->assign('allowAutoRenewMembership', $allowAutoRenewMembership);
907 $form->assign('autoRenewMembershipTypeOptions', json_encode($autoRenewMembershipTypeOptions));
909 //give preference to user submitted auto_renew value.
910 $takeUserSubmittedAutoRenew = (!empty($_POST) ||
$form->isSubmitted()) ?
TRUE : FALSE;
911 $form->assign('takeUserSubmittedAutoRenew', $takeUserSubmittedAutoRenew);
914 return $separateMembershipPayment;
918 * Function to return Membership Block info in Contribution Pages
923 * @internal param int $pageId contribution page id
927 static function getMembershipBlock($pageID) {
928 $membershipBlock = array();
929 $dao = new CRM_Member_DAO_MembershipBlock();
930 $dao->entity_table
= 'civicrm_contribution_page';
932 $dao->entity_id
= $pageID;
934 if ($dao->find(TRUE)) {
935 CRM_Core_DAO
::storeValues($dao, $membershipBlock);
936 if (!empty($membershipBlock['membership_types'])) {
937 $membershipTypes = unserialize($membershipBlock['membership_types']);
938 if (!is_array($membershipTypes)) {
939 return $membershipBlock;
942 foreach ($membershipTypes as $key => $value) {
943 $membershipBlock['auto_renew'][$key] = $value;
944 $memTypes[$key] = $key;
946 $membershipBlock['membership_types'] = implode(',', $memTypes);
953 return $membershipBlock;
957 * Function to return a current membership of given contact
958 * NB: if more than one membership meets criteria, a randomly selected one is returned.
960 * @param int $contactID contact id
961 * @param int $memType membership type, null to retrieve all types
963 * @param null $membershipId
964 * @param boolean $onlySameParentOrg true if only Memberships with same parent org as the $memType wanted, false otherwise
967 * @internal param int $membershipID if provided, then determine if it is current
970 static function getContactMembership($contactID, $memType, $isTest, $membershipId = NULL, $onlySameParentOrg = FALSE) {
971 $dao = new CRM_Member_DAO_Membership();
973 $dao->id
= $membershipId;
975 $dao->contact_id
= $contactID;
976 $dao->membership_type_id
= $memType;
978 //fetch proper membership record.
980 $dao->is_test
= $isTest;
983 $dao->whereAdd('is_test IS NULL OR is_test = 0');
986 //avoid pending membership as current membership: CRM-3027
987 $statusIds[] = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
988 if (!$membershipId) {
989 $statusIds[] = array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus());
991 $dao->whereAdd('status_id NOT IN ( ' . implode(',', $statusIds) . ')');
993 // order by start date to find most recent membership first, CRM-4545
994 $dao->orderBy('start_date DESC');
997 if ($onlySameParentOrg && $memType) {
998 // require the same parent org as the $memType
999 $params = array('id' => $memType);
1000 $membershipType = array();
1001 if (CRM_Member_BAO_MembershipType
::retrieve($params, $membershipType)) {
1002 $memberTypesSameParentOrg = CRM_Member_BAO_MembershipType
::getMembershipTypesByOrg($membershipType['member_of_contact_id']);
1003 $memberTypesSameParentOrgList = implode(',', array_keys($memberTypesSameParentOrg));
1004 $dao->whereAdd('membership_type_id IN (' . $memberTypesSameParentOrgList . ')');
1008 if ($dao->find(TRUE)) {
1009 $membership = array();
1010 CRM_Core_DAO
::storeValues($dao, $membership);
1011 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
1012 $membership['status_id'],
1013 'is_current_member', 'id'
1019 if ($onlySameParentOrg && $memType) {
1020 // see if there is a membership that has same parent as $memType but different parent than $membershipID
1022 if ( $dao->id
&& CRM_Core_Permission
::check( 'edit memberships' ) ) {
1023 // CRM-10016, This is probably a backend renewal, and make sure we return the same membership thats being renewed.
1029 unset($dao->membership_type_id
);
1030 if ($dao->find(TRUE)) {
1031 $membership = array();
1032 CRM_Core_DAO
::storeValues($dao, $membership);
1033 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
1034 $membership['status_id'],
1035 'is_current_member', 'id'
1044 * Combine all the importable fields from the lower levels object
1046 * @param string $contactType contact type
1047 * @param boolean $status
1049 * @return array array of importable Fields
1053 static function &importableFields($contactType = 'Individual', $status = TRUE) {
1054 if (!self
::$_importableFields) {
1055 if (!self
::$_importableFields) {
1056 self
::$_importableFields = array();
1060 $fields = array('' => array('title' => '- ' . ts('do not import') . ' -'));
1063 $fields = array('' => array('title' => '- ' . ts('Membership Fields') . ' -'));
1066 $tmpFields = CRM_Member_DAO_Membership
::import();
1067 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
1069 // Using new Dedupe rule.
1070 $ruleParams = array(
1071 'contact_type' => $contactType,
1072 'used' => 'Unsupervised',
1074 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
1076 $tmpContactField = array();
1077 if (is_array($fieldsArray)) {
1078 foreach ($fieldsArray as $value) {
1079 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
1084 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
1085 $tmpContactField[trim($value)] = CRM_Utils_Array
::value(trim($value), $contactFields);
1087 $title = $tmpContactField[trim($value)]['title'] . " " . ts('(match to contact)');
1090 $title = $tmpContactField[trim($value)]['title'];
1092 $tmpContactField[trim($value)]['title'] = $title;
1095 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
1096 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " " . ts('(match to contact)');
1098 $tmpFields['membership_contact_id']['title'] = $tmpFields['membership_contact_id']['title'] . " " . ts('(match to contact)');;
1100 $fields = array_merge($fields, $tmpContactField);
1101 $fields = array_merge($fields, $tmpFields);
1102 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1103 self
::$_importableFields = $fields;
1105 return self
::$_importableFields;
1109 * function to get all exportable fields
1111 * @retun array return array of all exportable fields
1114 static function &exportableFields() {
1115 $expFieldMembership = CRM_Member_DAO_Membership
::export();
1117 $expFieldsMemType = CRM_Member_DAO_MembershipType
::export();
1118 $fields = array_merge($expFieldMembership, $expFieldsMemType);
1119 $fields = array_merge($fields, $expFieldMembership);
1120 $membershipStatus = array(
1121 'membership_status' => array('title' => 'Membership Status',
1122 'name' => 'membership_status',
1123 'type' => CRM_Utils_Type
::T_STRING
,
1124 'where' => 'civicrm_membership_status.name',
1126 //CRM-6161 fix for customdata export
1127 $fields = array_merge($fields, $membershipStatus, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1132 * Function to get membership joins/renewals for a specified membership
1133 * type. Specifically, retrieves a count of memberships whose "Membership
1134 * Signup" or "Membership Renewal" activity falls in the given date range.
1135 * Dates match the pattern "yyyy-mm-dd".
1137 * @param int $membershipTypeId membership type id
1138 * @param int $startDate date on which to start counting
1139 * @param int $endDate date on which to end counting
1140 * @param bool|int $isTest if true, membership is for a test site
1141 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1143 * @return integer the number of members of type $membershipTypeId whose
1144 * start_date is between $startDate and $endDate
1147 public static function getMembershipStarts($membershipTypeId, $startDate, $endDate, $isTest = 0, $isOwner = 0) {
1149 $testClause = 'membership.is_test = 1';
1151 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1154 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1155 self
::_getActTypes();
1158 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1163 SELECT COUNT(DISTINCT membership.id) as member_count
1164 FROM civicrm_membership membership
1165 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id in (%1, %2))
1166 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1167 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1168 WHERE membership.membership_type_id = %3
1169 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1172 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1175 1 => array(self
::$_signupActType, 'Integer'),
1176 2 => array(self
::$_renewalActType, 'Integer'),
1177 3 => array($membershipTypeId, 'Integer'),
1180 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1181 return (int)$memberCount;
1185 * Function to get a count of membership for a specified membership type,
1186 * optionally for a specified date. The date must have the form yyyy-mm-dd.
1188 * If $date is omitted, this function counts as a member anyone whose
1189 * membership status_id indicates they're a current member.
1190 * If $date is given, this function counts as a member anyone who:
1191 * -- Has a start_date before $date and end_date after $date, or
1192 * -- Has a start_date before $date and is currently a member, as indicated
1193 * by the the membership's status_id.
1194 * The second condition takes care of records that have no end_date. These
1195 * are assumed to be lifetime memberships.
1197 * @param int $membershipTypeId membership type id
1198 * @param string $date the date for which to retrieve the count
1199 * @param bool|int $isTest if true, membership is for a test site
1200 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1202 * @return returns the number of members of type $membershipTypeId as of
1205 public static function getMembershipCount($membershipTypeId, $date = NULL, $isTest = 0, $isOwner = 0) {
1206 if (!CRM_Utils_Rule
::date($date)) {
1207 CRM_Core_Error
::fatal(ts('Invalid date "%1" (must have form yyyy-mm-dd).', array(1 => $date)));
1210 $params = array(1 => array($membershipTypeId, 'Integer'),
1211 2 => array($isTest, 'Boolean'),
1213 $query = "SELECT count(civicrm_membership.id ) as member_count
1214 FROM civicrm_membership left join civicrm_membership_status on ( civicrm_membership.status_id = civicrm_membership_status.id )
1215 WHERE civicrm_membership.membership_type_id = %1
1216 AND civicrm_membership.contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)
1217 AND civicrm_membership.is_test = %2";
1219 $query .= " AND civicrm_membership_status.is_current_member = 1";
1222 $query .= " AND civicrm_membership.start_date <= '$date' AND civicrm_membership_status.is_current_member = 1";
1225 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1226 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1227 return (int)$memberCount;
1231 * Function check the status of the membership before adding membership for a contact
1233 * @param int $contactId contact id
1237 static function statusAvailabilty($contactId) {
1238 $membership = new CRM_Member_DAO_MembershipStatus();
1239 $membership->whereAdd('is_active=1');
1240 return $membership->count();
1244 * Process the Memberships
1246 * @param array $membershipParams array of membership fields
1247 * @param int $contactID contact id
1248 * @param CRM_Contribute_Form_Contribution_Confirm $form Confirmation form object
1250 * @param $premiumParams
1251 * @param null $customFieldsFormatted
1252 * @param null $includeFieldTypes
1254 * @param array $membershipDetails
1256 * @param array $membershipTypeID
1258 * @param bool $isPaidMembership
1259 * @param integer $membershipID
1261 * @param $isProcessSeparateMembershipTransaction
1263 * @param $defaultContributionTypeID
1264 * @param array $membershipLineItems Line items specific to membership payment that is separate to contribution
1265 * @throws CRM_Core_Exception
1270 public static function postProcessMembership($membershipParams, $contactID, &$form, $premiumParams,
1271 $customFieldsFormatted = NULL, $includeFieldTypes = NULL, $membershipDetails, $membershipTypeID, $isPaidMembership, $membershipID,
1272 $isProcessSeparateMembershipTransaction, $defaultContributionTypeID, $membershipLineItems) {
1273 $result = $membershipContribution = NULL;
1274 $isTest = CRM_Utils_Array
::value('is_test', $membershipParams, FALSE);
1275 $errors = $createdMemberships = array();
1277 $membershipLineItem = array();
1278 if (is_array($membershipTypeID)) {
1279 $lineItems = $form->_lineItem
;
1280 if ($isProcessSeparateMembershipTransaction) {
1281 $lineItems[$form->_priceSetId
] = array_merge($lineItems[$form->_priceSetId
], $membershipLineItems[$form->_priceSetId
]);
1283 foreach ($lineItems[$form->_priceSetId
] as $key => $line) {
1284 if (!empty($line['membership_type_id'])) {
1285 $membershipLineItem[$line['membership_type_id']] = $line;
1286 unset($lineItems[$form->_priceSetId
][$key]);
1289 if (empty($lineItems[$form->_priceSetId
])) {
1290 $membershipParams['skipLineItem'] = TRUE;
1292 $form->_lineItem
= $lineItems;
1295 if ($isPaidMembership) {
1296 $result = CRM_Contribute_BAO_Contribution_Utils
::processConfirm($form, $membershipParams,
1297 $premiumParams, $contactID,
1298 $defaultContributionTypeID,
1301 if (is_a($result[1], 'CRM_Core_Error')) {
1302 $errors[1] = CRM_Core_Error
::getMessages($result[1]);
1304 elseif (!empty($result[1])) {
1305 // Save the contribution ID so that I can be used in email receipts
1306 // For example, if you need to generate a tax receipt for the donation only.
1307 $form->_values
['contribution_other_id'] = $result[1]->id
;
1308 //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
1309 $membershipContribution = $result[1];
1313 if ($isProcessSeparateMembershipTransaction) {
1315 $membershipParams['skipLineItem'] = TRUE;
1316 $membershipContribution = self
::processSecondaryFinancialTransaction($contactID, $form, $membershipParams, $isTest, $membershipLineItems, CRM_Utils_Array
::value('minimum_fee', $membershipDetails, 0), CRM_Utils_Array
::value('financial_type_id', $membershipDetails));
1318 catch (CRM_Core_Exception
$e) {
1319 $errors[2] = $e->getMessage();
1320 $membershipContribution = NULL;
1325 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1326 $membershipContributionID = $membershipContribution->id
;
1329 //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
1330 if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
1331 $form->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
1333 //@todo it should no longer be possible for it to get to this point & membership to not be an array
1334 if (is_array($membershipTypeID)) {
1335 $typesTerms = CRM_Utils_Array
::value('types_terms', $membershipParams, array());
1336 foreach ($membershipTypeID as $memType) {
1337 $numTerms = CRM_Utils_Array
::value($memType, $typesTerms, 1);
1338 $createdMemberships[$memType] = self
::createOrRenewMembership($membershipParams, $contactID, $customFieldsFormatted, $membershipID, $memType, $isTest, $numTerms, $membershipContribution, $form);
1339 if (CRM_Utils_Array
::value($memType, $membershipLineItem)) {
1340 CRM_Price_BAO_LineItem
::processPriceSet($createdMemberships[$memType]->id
, array($form->_priceSetId
=> array($membershipLineItem[$memType])), $membershipContribution);
1341 $form->_lineItem
[$form->_priceSetId
][] = $membershipLineItem[$memType];
1344 if ($form->_priceSetId
&& !empty($form->_useForMember
) && !empty($form->_lineItem
)) {
1345 foreach ($form->_lineItem
[$form->_priceSetId
] as & $priceFieldOp) {
1346 if (!empty($priceFieldOp['membership_type_id']) &&
1347 isset($createdMemberships[$priceFieldOp['membership_type_id']])
1349 $membershipOb = $createdMemberships[$priceFieldOp['membership_type_id']];
1350 $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date
::customFormat($membershipOb->start_date
, '%d%f %b, %Y') : '-';
1351 $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date
::customFormat($membershipOb->end_date
, '%d%f %b, %Y') : '-';
1354 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1357 $form->_values
['lineItem'] = $form->_lineItem
;
1358 $form->assign('lineItem', $form->_lineItem
);
1362 if (!empty($errors)) {
1363 $message = self
::compileErrorMessage($errors);
1364 throw new CRM_Core_Exception($message);
1366 $form->_params
['createdMembershipIDs'] = array();
1368 // CRM-7851 - Moved after processing Payment Errors
1369 //@todo - the reasoning for this being here seems a little outdated
1370 foreach ($createdMemberships as $createdMembership) {
1371 CRM_Core_BAO_CustomValueTable
::postProcess(
1373 CRM_Core_DAO
::$_nullArray,
1374 'civicrm_membership',
1375 $createdMembership->id
,
1378 $form->_params
['createdMembershipIDs'][] = $createdMembership->id
;
1380 if(count($createdMemberships) == 1) {
1381 //presumably this is only relevant for exactly 1 membership
1382 $form->_params
['membershipID'] = $form->_values
['membership_id'] = $createdMembership->id
;
1385 if ($form->_contributeMode
== 'notify') {
1386 if ($form->_values
['is_monetary'] && $form->_amount
> 0.0 && !$form->_params
['is_pay_later']) {
1387 // call postProcess hook before leaving
1388 $form->postProcessHook();
1389 // this does not return
1390 $payment = CRM_Core_Payment
::singleton($form->_mode
, $form->_paymentProcessor
, $form);
1391 $payment->doTransferCheckout($form->_params
, 'contribute');
1395 if (isset($membershipContributionID)) {
1396 $form->_values
['contribution_id'] = $membershipContributionID;
1399 // Do not send an email if Recurring transaction is done via Direct Mode
1400 // Email will we sent when the IPN is received.
1401 if (!empty($form->_params
['is_recur']) && $form->_contributeMode
== 'direct') {
1405 //finally send an email receipt
1406 CRM_Contribute_BAO_ContributionPage
::sendMail($contactID,
1414 * Function for updating a membership record's contribution_recur_id
1416 * @param object CRM_Member_DAO_Membership $membership
1417 * @param \CRM_Contribute_BAO_Contribution|\CRM_Contribute_DAO_Contribution $contribution
1423 static public function updateRecurMembership(CRM_Member_DAO_Membership
$membership,
1424 CRM_Contribute_BAO_Contribution
$contribution) {
1426 if (empty($contribution->contribution_recur_id
)) {
1431 1 => array($contribution->contribution_recur_id
, 'Integer'),
1432 2 => array($membership->id
, 'Integer'),
1435 $sql = "UPDATE civicrm_membership SET contribution_recur_id = %1 WHERE id = %2";
1436 CRM_Core_DAO
::executeQuery($sql, $params);
1441 * A wrapper for renewing memberships from a form - including the form in the membership processing adds complexity
1442 * as the forms are being forced to pretend similarity
1443 * Try to call the renewMembership directly
1444 * @todo - this form method needs to have the interaction with the form layer removed from it
1445 * as a BAO function. Note that the api now supports membership renewals & it is not clear this function does anything
1446 * not done by the membership.create api (with a lot less unit tests)
1448 * This method will renew / create the membership depending on
1449 * whether the given contact has a membership or not. And will add
1450 * the modified dates for membership and in the log table.
1452 * @param int $contactID id of the contact
1453 * @param int $membershipTypeID id of the new membership type
1454 * @param boolean $is_test if this is test contribution or live contribution
1455 * @param object $form form object
1456 * @param null $changeToday
1457 * @param int $modifiedID individual contact id in case of On Behalf signup (CRM-4027 )
1458 * @param null $customFieldsFormatted
1459 * @param int $numRenewTerms how many membership terms are being added to end date (default is 1)
1461 * @param integer $membershipID Membership ID, this should always be passed in & optionality should be removed
1463 * @throws CRM_Core_Exception
1464 * @internal param array $ipnParams array of name value pairs, to be used (for e.g source) when $form not present
1465 * @return CRM_Member_DAO_Membership $membership object of membership
1470 static function renewMembershipFormWrapper(
1475 $changeToday = NULL,
1477 $customFieldsFormatted = NULL,
1479 $membershipID = NULL
1481 $statusFormat = '%Y-%m-%d';
1484 //@todo would be better to make $membershipID a compulsory function param & make form layer responsible for extracting it
1485 if(!$membershipID && isset($form->_membershipId
)) {
1486 $membershipID = $form->_membershipId
;
1489 //get all active statuses of membership.
1490 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1492 $membershipTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipTypeID);
1494 // check is it pending. - CRM-4555
1495 list($pending, $contributionRecurID, $changeToday, $membershipSource, $isPayLater, $campaignId) = self
::extractFormValues($form, $changeToday, $membershipTypeDetails);
1496 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);
1497 $form->set('renewal_mode', $renewalMode);
1498 if (!empty($dates)) {
1499 $form->assign('mem_start_date',
1500 CRM_Utils_Date
::customFormat($dates['start_date'], $format)
1502 $form->assign('mem_end_date',
1503 CRM_Utils_Date
::customFormat($dates['end_date'], $format)
1511 * Method to fix membership status of stale membership
1513 * This method first checks if the membership is stale. If it is,
1514 * then status will be updated based on existing start and end
1515 * dates and log will be added for the status change.
1517 * @param array $currentMembership referance to the array
1518 * containing all values of
1519 * the current membership
1520 * @param array $changeToday array of month, day, year
1521 * values in case today needs
1522 * to be customised, null otherwise
1527 static function fixMembershipStatusBeforeRenew(&$currentMembership, $changeToday) {
1530 $today = CRM_Utils_Date
::processDate($changeToday, NULL, FALSE, 'Y-m-d');
1533 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
1534 CRM_Utils_Array
::value('start_date', $currentMembership),
1535 CRM_Utils_Array
::value('end_date', $currentMembership),
1536 CRM_Utils_Array
::value('join_date', $currentMembership),
1539 $currentMembership['membership_type_id'],
1543 if (empty($status) ||
1544 empty($status['id'])
1546 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.'));
1549 $currentMembership['today_date'] = $today;
1551 if ($status['id'] !== $currentMembership['status_id']) {
1552 $memberDAO = new CRM_Member_DAO_Membership();
1553 $memberDAO->id
= $currentMembership['id'];
1554 $memberDAO->find(TRUE);
1556 $memberDAO->status_id
= $status['id'];
1557 $memberDAO->join_date
= CRM_Utils_Date
::isoToMysql($memberDAO->join_date
);
1558 $memberDAO->start_date
= CRM_Utils_Date
::isoToMysql($memberDAO->start_date
);
1559 $memberDAO->end_date
= CRM_Utils_Date
::isoToMysql($memberDAO->end_date
);
1561 CRM_Core_DAO
::storeValues($memberDAO, $currentMembership);
1564 $currentMembership['is_current_member'] = CRM_Core_DAO
::getFieldValue(
1565 'CRM_Member_DAO_MembershipStatus',
1566 $currentMembership['status_id'],
1572 'membership_id' => $currentMembership['id'],
1573 'status_id' => $status['id'],
1574 'start_date' => CRM_Utils_Date
::customFormat(
1575 $currentMembership['start_date'],
1578 'end_date' => CRM_Utils_Date
::customFormat(
1579 $currentMembership['end_date'],
1582 'modified_date' => CRM_Utils_Date
::customFormat(
1583 $currentMembership['today_date'],
1586 'membership_type_id' => $currentMembership['membership_type_id'],
1587 'max_related' => $currentMembership['max_related'],
1590 $session = CRM_Core_Session
::singleton();
1591 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
1592 if ($session->get('userID')) {
1593 $logParams['modified_id'] = $session->get('userID');
1596 $logParams['modified_id'] = $currentMembership['contact_id'];
1598 CRM_Member_BAO_MembershipLog
::add($logParams, CRM_Core_DAO
::$_nullArray);
1603 * Function to get the contribution page id from the membership record
1605 * @param int membershipId membership id
1607 * @return int $contributionPageId contribution page id
1611 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 * Function to updated related memberships
1628 * @param int $ownerMembershipId owner Membership Id
1629 * @param array $params formatted array of key => value..
1632 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 * Function to 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
1659 static function getMembershipFields($mode = NULL) {
1660 $fields = CRM_Member_DAO_Membership
::export();
1662 unset($fields['membership_contact_id']);
1663 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1665 $membershipType = CRM_Member_DAO_MembershipType
::export();
1667 $membershipStatus = CRM_Member_DAO_MembershipStatus
::export();
1669 $fields = array_merge($fields, $membershipType, $membershipStatus);
1675 * function to get the sort name of a contact for a particular membership
1677 * @param int $id id of the membership
1679 * @return null|string sort name of the contact if found
1683 static function sortName($id) {
1684 $id = CRM_Utils_Type
::escape($id, 'Integer');
1687 SELECT civicrm_contact.sort_name
1688 FROM civicrm_membership, civicrm_contact
1689 WHERE civicrm_membership.contact_id = civicrm_contact.id
1690 AND civicrm_membership.id = {$id}
1692 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1696 * function to create memberships for related contacts
1697 * takes into account the maximum related memberships
1699 * @param array $params array of key - value pairs
1702 * @internal param object $membership membership object
1704 * @return null|relatedMembership array of memberships if created
1708 static function createRelatedMemberships(&$params, &$dao) {
1709 static $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
1868 static function deleteMembershipPayment($membershipId) {
1870 $membesrshipPayment = new CRM_Member_DAO_MembershipPayment();
1871 $membesrshipPayment->membership_id
= $membershipId;
1872 $membesrshipPayment->find();
1874 while ($membesrshipPayment->fetch()) {
1875 CRM_Contribute_BAO_Contribution
::deleteContribution($membesrshipPayment->contribution_id
);
1876 CRM_Utils_Hook
::pre('delete', 'MembershipPayment', $membesrshipPayment->id
, $membesrshipPayment);
1877 $membesrshipPayment->delete();
1878 CRM_Utils_Hook
::post('delete', 'MembershipPayment', $membesrshipPayment->id
, $membesrshipPayment);
1880 return $membesrshipPayment;
1885 * @param null $membershipTypeID
1889 static function &buildMembershipTypeValues(&$form, $membershipTypeID = NULL) {
1890 $whereClause = " WHERE domain_id = ". CRM_Core_Config
::domainID();
1892 if (is_array($membershipTypeID)) {
1893 $allIDs = implode(',', $membershipTypeID);
1894 $whereClause .= " AND id IN ( $allIDs )";
1896 elseif (is_numeric($membershipTypeID) &&
1897 $membershipTypeID > 0
1899 $whereClause .= " AND id = $membershipTypeID";
1904 FROM civicrm_membership_type
1907 $dao = CRM_Core_DAO
::executeQuery($query);
1909 $membershipTypeValues = array();
1910 $membershipTypeFields = array(
1911 'id', 'minimum_fee', 'name', 'is_active',
1912 'description', 'financial_type_id', 'auto_renew','member_of_contact_id',
1913 'relationship_type_id', 'relationship_direction', 'max_related',
1916 while ($dao->fetch()) {
1917 $membershipTypeValues[$dao->id
] = array();
1918 foreach ($membershipTypeFields as $mtField) {
1919 $membershipTypeValues[$dao->id
][$mtField] = $dao->$mtField;
1924 CRM_Utils_Hook
::membershipTypeValues($form, $membershipTypeValues);
1926 if (is_numeric($membershipTypeID) &&
1927 $membershipTypeID > 0
1929 return $membershipTypeValues[$membershipTypeID];
1932 return $membershipTypeValues;
1937 * Function to get membership record count for a Contact
1940 * @param boolean $activeOnly
1942 * @internal param int $contactId Contact ID
1943 * @return int count of membership records
1947 static function getContactMembershipCount($contactID, $activeOnly = FALSE) {
1948 $select = "SELECT count(*) FROM civicrm_membership ";
1949 $where = "WHERE civicrm_membership.contact_id = {$contactID} AND civicrm_membership.is_test = 0 ";
1951 // CRM-6627, all status below 3 (active, pending, grace) are considered active
1953 $select .= " INNER JOIN civicrm_membership_status ON civicrm_membership.status_id = civicrm_membership_status.id ";
1954 $where .= " and civicrm_membership_status.is_current_member = 1";
1957 $query = $select . $where;
1958 return CRM_Core_DAO
::singleValueQuery($query);
1962 * Function to check whether payment processor supports
1963 * cancellation of membership subscription
1965 * @param int $mid membership id
1967 * @param bool $isNotCancelled
1973 static function isCancelSubscriptionSupported($mid, $isNotCancelled = TRUE) {
1974 $cacheKeyString = "$mid";
1975 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
1977 static $supportsCancel = array();
1979 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
1980 $supportsCancel[$cacheKeyString] = FALSE;
1981 $isCancelled = FALSE;
1983 if ($isNotCancelled) {
1984 $isCancelled = self
::isSubscriptionCancelled($mid);
1987 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($mid, 'membership', 'obj');
1988 if (!empty($paymentObject)) {
1989 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
1992 return $supportsCancel[$cacheKeyString];
1996 * Function to check whether subscription is already cancelled
1998 * @param int $mid membership id
2000 * @return string $status contribution status
2004 static function isSubscriptionCancelled($mid) {
2006 SELECT cr.contribution_status_id
2007 FROM civicrm_contribution_recur cr
2008 LEFT JOIN civicrm_membership mem ON ( cr.id = mem.contribution_recur_id )
2009 WHERE mem.id = %1 LIMIT 1";
2010 $params = array(1 => array($mid, 'Integer'));
2011 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2012 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId);
2013 if ($status == 'Cancelled') {
2020 * Function to get membership joins for a specified membership
2021 * type. Specifically, retrieves a count of still current memberships whose
2022 * join_date and start_date are within a specified date range. Dates match
2023 * the pattern "yyyy-mm-dd".
2025 * @param int $membershipTypeId membership type id
2026 * @param int $startDate date on which to start counting
2027 * @param int $endDate date on which to end counting
2028 * @param bool|int $isTest if true, membership is for a test site
2030 * @return returns the number of members of type $membershipTypeId
2031 * whose join_date is between $startDate and $endDate and
2032 * whose start_date is between $startDate and $endDate
2034 static function getMembershipJoins($membershipTypeId, $startDate, $endDate, $isTest = 0) {
2035 $testClause = 'membership.is_test = 1';
2037 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
2039 if (!self
::$_signupActType) {
2040 self
::_getActTypes();
2043 if (!self
::$_signupActType) {
2048 SELECT COUNT(DISTINCT membership.id) as member_count
2049 FROM civicrm_membership membership
2050 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
2051 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
2052 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
2053 WHERE membership.membership_type_id = %2
2054 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
2058 1 => array(self
::$_signupActType, 'Integer'),
2059 2 => array($membershipTypeId, 'Integer'),
2062 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
2064 return (int)$memberCount;
2068 * Function to get membership renewals for a specified membership
2069 * type. Specifically, retrieves a count of still current memberships
2070 * whose join_date is before and start_date is within a specified date
2071 * range. Dates match the pattern "yyyy-mm-dd".
2073 * @param int $membershipTypeId membership type id
2074 * @param int $startDate date on which to start counting
2075 * @param int $endDate date on which to end counting
2076 * @param bool|int $isTest if true, membership is for a test site
2078 * @return integer returns the number of members of type $membershipTypeId
2079 * whose join_date is before $startDate and
2080 * whose start_date is between $startDate and $endDate
2082 static function getMembershipRenewals($membershipTypeId, $startDate, $endDate, $isTest = 0) {
2083 $testClause = 'membership.is_test = 1';
2085 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
2087 if (!self
::$_renewalActType) {
2088 self
::_getActTypes();
2091 if (!self
::$_renewalActType) {
2096 SELECT COUNT(DISTINCT membership.id) as member_count
2097 FROM civicrm_membership membership
2098 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
2099 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
2100 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
2101 WHERE membership.membership_type_id = %2
2102 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
2106 1 => array(self
::$_renewalActType, 'Integer'),
2107 2 => array($membershipTypeId, 'Integer'),
2109 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
2111 return (int)$memberCount;
2115 * Where a second separate financial transaction is supported we will process it here
2118 * @param CRM_Contribute_Form_Contribution_Confirm $form
2119 * @param $membershipDetails
2120 * @param $tempParams
2123 * @throws CRM_Core_Exception
2124 * @return CRM_Contribute_BAO_Contribution
2126 public static function processSecondaryFinancialTransaction($contactID, &$form, $tempParams, $isTest, $lineItems, $minimumFee, $financialTypeID) {
2127 $contributionType = new CRM_Financial_DAO_FinancialType();
2128 $contributionType->id
= $financialTypeID;
2129 if (!$contributionType->find(TRUE)) {
2130 CRM_Core_Error
::fatal(ts("Could not find a system table"));
2132 $tempParams['amount'] = $minimumFee;
2133 $tempParams['invoiceID'] = md5(uniqid(rand(), TRUE));
2136 if ($form->_values
['is_monetary'] && !$form->_params
['is_pay_later'] && $minimumFee > 0.0) {
2137 $payment = CRM_Core_Payment
::singleton($form->_mode
, $form->_paymentProcessor
, $form);
2139 if ($form->_contributeMode
== 'express') {
2140 $result = $payment->doExpressCheckout($tempParams);
2143 $result = $payment->doDirectPayment($tempParams);
2147 if (is_a($result, 'CRM_Core_Error')) {
2148 throw new CRM_Core_Exception(CRM_Core_Error
::getMessages($result));
2151 //assign receive date when separate membership payment
2152 //and contribution amount not selected.
2153 if ($form->_amount
== 0) {
2154 $now = date('YmdHis');
2155 $form->_params
['receive_date'] = $now;
2156 $receiveDate = CRM_Utils_Date
::mysqlToIso($now);
2157 $form->set('params', $form->_params
);
2158 $form->assign('receive_date', $receiveDate);
2161 $form->set('membership_trx_id', $result['trxn_id']);
2162 $form->set('membership_amount', $minimumFee);
2164 // we don't need to create the user twice, so lets disable cms_create_account
2165 // irrespective of the value, CRM-2888
2166 $tempParams['cms_create_account'] = 0;
2168 $pending = $form->_params
['is_pay_later'] ?
(($minimumFee > 0.0) ?
TRUE : FALSE) : FALSE;
2170 //set this variable as we are not creating pledge for
2171 //separate membership payment contribution.
2172 //so for differentiating membership contribution from
2173 //main contribution.
2174 $form->_params
['separate_membership_payment'] = 1;
2175 $membershipContribution = CRM_Contribute_Form_Contribution_Confirm
::processContribution($form,
2185 return $membershipContribution;
2190 * Create linkages between membership & contribution - note this is the wrong place for this code but this is a
2191 * refactoring step. This should be BAO functionality
2192 * @param $membership
2193 * @param $membershipContribution
2195 public static function linkMembershipPayment($membership, $membershipContribution) {
2196 CRM_Member_BAO_MembershipPayment
::create(array('membership_id' => $membership->id
, 'contribution_id' => $membershipContribution->id
));
2200 * @param $membershipParams
2202 * @param $customFieldsFormatted
2203 * @param $membershipID
2207 * @param $membershipContribution
2210 * @internal param $createdMemberships
2214 public static function createOrRenewMembership($membershipParams, $contactID, $customFieldsFormatted, $membershipID, $memType, $isTest, $numTerms, $membershipContribution, &$form) {
2215 $membership = self
::renewMembershipFormWrapper($contactID, $memType,
2216 $isTest, $form, NULL,
2217 CRM_Utils_Array
::value('cms_contactID', $membershipParams),
2218 $customFieldsFormatted, $numTerms,
2222 if (!empty($membershipContribution)) {
2223 // update recurring id for membership record
2224 self
::updateRecurMembership($membership, $membershipContribution);
2226 self
::linkMembershipPayment($membership, $membershipContribution);
2232 * Turn array of errors into message string
2234 * @param array $errors
2236 * @internal param $message
2240 public static function compileErrorMessage($errors)
2242 foreach($errors as $error) {
2243 if (is_string($error)) {
2244 $message[] = $error;
2247 return ts('Payment Processor Error message') . ': ' . implode('<br/>', $message);
2251 * Extract relevant values from the form so we can separate form logic from BAO logcis
2253 * @param $changeToday
2254 * @param $membershipTypeDetails
2258 public static function extractFormValues($form, $changeToday, $membershipTypeDetails)
2261 //@todo this is a BAO function & should not inspect the form - the form should do this
2262 // & pass required params to the BAO
2263 if (CRM_Utils_Array
::value('minimum_fee', $membershipTypeDetails) > 0.0) {
2264 if (((isset($form->_contributeMode
) && $form->_contributeMode
== 'notify') ||
!empty($form->_params
['is_pay_later']) ||
2265 (!empty($form->_params
['is_recur']) && $form->_contributeMode
== 'direct'
2268 (($form->_values
['is_monetary'] && $form->_amount
> 0.0) ||
!empty($form->_params
['separate_membership_payment']) ||
2269 CRM_Utils_Array
::value('record_contribution', $form->_params
)
2275 $contributionRecurID = isset($form->_params
['contributionRecurID']) ?
$form->_params
['contributionRecurID'] : NULL;
2277 //we renew expired membership, CRM-6277
2278 if (!$changeToday) {
2279 if ($form->get('renewalDate')) {
2280 $changeToday = $form->get('renewalDate');
2282 elseif (get_class($form) == 'CRM_Contribute_Form_Contribution_Confirm') {
2283 $changeToday = date('YmdHis');
2287 $membershipSource = NULL;
2288 if (!empty($form->_params
['membership_source'])) {
2289 $membershipSource = $form->_params
['membership_source'];
2291 elseif (isset($form->_values
['title']) && !empty($form->_values
['title'])) {
2292 $membershipSource = ts('Online Contribution:') . ' ' . $form->_values
['title'];
2295 if(isset($form->_params
)) {
2296 $isPayLater = CRM_Utils_Array
::value('is_pay_later', $form->_params
);
2299 if (isset($form->_values
) && is_array($form->_values
) && !empty($form->_values
)) {
2300 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_params
);
2301 if (!array_key_exists('campaign_id', $form->_params
)) {
2302 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_values
);
2305 return array($pending, $contributionRecurID, $changeToday, $membershipSource, $isPayLater, $campaignId);
2309 * @param integer $contactID
2310 * @param $membershipTypeID
2311 * @param bool $is_test
2312 * @param $changeToday
2313 * @param integer $modifiedID
2314 * @param $customFieldsFormatted
2315 * @param $numRenewTerms
2316 * @param $membershipID
2319 * @param array $membershipTypeDetails
2320 * @param integer $contributionRecurID
2322 * @param $membershipSource
2324 * @param $statusFormat
2325 * @param $isPayLater
2326 * @param integer $campaignId
2328 * @throws CRM_Core_Exception
2331 public static function renewMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $allStatus, $membershipTypeDetails, $contributionRecurID, $format, $membershipSource, $ids, $statusFormat, $isPayLater, $campaignId) {
2332 $renewalMode = $updateStatusId = FALSE;
2334 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
2335 // is the same as the parent org of an existing membership of the contact
2336 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($contactID, $membershipTypeID,
2337 $is_test, $membershipID, TRUE
2339 if ($currentMembership) {
2340 $activityType = 'Membership Renewal';
2341 $renewalMode = TRUE;
2343 // Do NOT do anything.
2344 //1. membership with status : PENDING/CANCELLED (CRM-2395)
2345 //2. Paylater/IPN renew. CRM-4556.
2346 if ($pending ||
in_array($currentMembership['status_id'], array(array_search('Pending', $allStatus),
2347 array_search('Cancelled', $allStatus),
2350 $membership = new CRM_Member_DAO_Membership();
2351 $membership->id
= $currentMembership['id'];
2352 $membership->find(TRUE);
2354 // CRM-8141 create a membership_log entry so that we will know the membership_type_id to change to when payment completed
2356 // note that we are logging the requested new membership_type_id that may be different than current membership_type_id
2357 // it will be used when payment is received to update the membership_type_id to what was paid for
2359 'membership_id' => $membership->id
,
2360 'status_id' => $membership->status_id
,
2361 'start_date' => CRM_Utils_Date
::customFormat(
2362 $membership->start_date
,
2365 'end_date' => CRM_Utils_Date
::customFormat(
2366 $membership->end_date
,
2369 'modified_date' => CRM_Utils_Date
::customFormat(
2373 'membership_type_id' => $membershipTypeID,
2374 'max_related' => $membershipTypeDetails['max_related'],
2376 $session = CRM_Core_Session
::singleton();
2377 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
2378 if ($session->get('userID')) {
2379 $logParams['modified_id'] = $session->get('userID');
2382 $logParams['modified_id'] = $membership->contact_id
;
2384 CRM_Member_BAO_MembershipLog
::add($logParams, CRM_Core_DAO
::$_nullArray);
2386 if (!empty($contributionRecurID)) {
2387 CRM_Core_DAO
::setFieldValue('CRM_Member_DAO_Membership', $membership->id
,
2388 'contribution_recur_id', $contributionRecurID
2392 return array($membership, $renewalMode, $dates);
2395 // Check and fix the membership if it is STALE
2396 self
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
2398 // Now Renew the membership
2399 if (!$currentMembership['is_current_member']) {
2400 // membership is not CURRENT
2402 // CRM-7297 Membership Upsell - calculate dates based on new membership type
2403 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($currentMembership['id'],
2409 $currentMembership['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
2410 $currentMembership['start_date'] = CRM_Utils_Array
::value('start_date', $dates);
2411 $currentMembership['end_date'] = CRM_Utils_Array
::value('end_date', $dates);
2412 $currentMembership['is_test'] = $is_test;
2414 if (!empty($membershipSource)) {
2415 $currentMembership['source'] = $membershipSource;
2418 $currentMembership['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
2419 $currentMembership['id'],
2424 if (!empty($currentMembership['id'])) {
2425 $ids['membership'] = $currentMembership['id'];
2427 $memParams = $currentMembership;
2428 $memParams['membership_type_id'] = $membershipTypeID;
2430 //set the log start date.
2431 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
2435 // CURRENT Membership
2436 $membership = new CRM_Member_DAO_Membership();
2437 $membership->id
= $currentMembership['id'];
2438 $membership->find(TRUE);
2439 // CRM-7297 Membership Upsell - calculate dates based on new membership type
2440 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
2446 // Insert renewed dates for CURRENT membership
2447 $memParams = array();
2448 $memParams['join_date'] = CRM_Utils_Date
::isoToMysql($membership->join_date
);
2449 $memParams['start_date'] = CRM_Utils_Date
::isoToMysql($membership->start_date
);
2450 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $dates);
2451 $memParams['membership_type_id'] = $membershipTypeID;
2453 //set the log start date.
2454 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
2455 if (empty($membership->source
)) {
2456 if (!empty($membershipSource)) {
2457 $memParams['source'] = $membershipSource;
2460 $memParams['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
2461 $currentMembership['id'],
2467 if (!empty($currentMembership['id'])) {
2468 $ids['membership'] = $currentMembership['id'];
2473 $updateStatusId = array_search('Pending', $allStatus);
2479 $activityType = 'Membership Signup';
2481 'contact_id' => $contactID,
2482 'membership_type_id' => $membershipTypeID,
2486 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
2488 $memParams['join_date'] = CRM_Utils_Array
::value('join_date', $dates);
2489 $memParams['start_date'] = CRM_Utils_Array
::value('start_date', $dates);
2490 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $dates);
2492 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(CRM_Utils_Date
::customFormat($dates['start_date'],
2495 CRM_Utils_Date
::customFormat($dates['end_date'],
2498 CRM_Utils_Date
::customFormat($dates['join_date'],
2506 $updateStatusId = CRM_Utils_Array
::value('id', $status);
2509 // if IPN/Pay-Later set status to: PENDING
2510 $updateStatusId = array_search('Pending', $allStatus);
2513 if (!empty($membershipSource)) {
2514 $memParams['source'] = $membershipSource;
2516 $memParams['contribution_recur_id'] = $contributionRecurID;
2518 $memParams['is_test'] = $is_test;
2519 $memParams['is_pay_later'] = $isPayLater;
2523 //if we decided status here and want to skip status
2524 //calculation in create( ); then need to pass 'skipStatusCal'.
2525 if ($updateStatusId) {
2526 $memParams['status_id'] = $updateStatusId;
2527 $memParams['skipStatusCal'] = TRUE;
2530 //since we are renewing,
2531 //make status override false.
2532 $memParams['is_override'] = FALSE;
2534 //CRM-4027, create log w/ individual contact.
2536 $ids['userId'] = $modifiedID;
2537 $memParams['is_for_organization'] = TRUE;
2540 $ids['userId'] = $contactID;
2543 //inherit campaign from contrib page.
2544 if (isset($campaignId)) {
2545 $memParams['campaign_id'] = $campaignId;
2548 $memParams['custom'] = $customFieldsFormatted;
2549 $membership = self
::create($memParams, $ids, FALSE, $activityType);
2551 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
2552 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
2553 $membership->find(TRUE);
2555 return array($membership, $renewalMode, $dates);
2559 * Function to process price set and line items.
2563 * @param $membershipId
2568 function processPriceSet($membershipId, $lineItem) {
2569 //FIXME : need to move this too
2570 if (!$membershipId ||
!is_array($lineItem)
2571 || CRM_Utils_System
::isNull($lineItem)
2576 foreach ($lineItem as $priceSetId => $values) {
2580 foreach ($values as $line) {
2581 $line['entity_table'] = 'civicrm_membership';
2582 $line['entity_id'] = $membershipId;
2583 CRM_Price_BAO_LineItem
::create($line);
2589 * retrieve the contribution id for the associated Membership id
2590 * @todo we should get this off the line item
2592 * @param int $membershipId membership id.
2594 * @return integer contribution id
2597 static function getMembershipContributionId($membershipId) {
2599 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
2600 $membershipPayment->membership_id
= $membershipId;
2601 if ($membershipPayment->find(TRUE)) {
2602 return $membershipPayment->contribution_id
;
2608 * The function checks and updates the status of all membership records for a given domain using the
2609 * calc_membership_status and update_contact_membership APIs.
2612 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
2614 * @return array $result
2617 static function updateAllMembershipStatus() {
2619 //get all active statuses of membership, CRM-3984
2620 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2621 $statusLabels = CRM_Member_PseudoConstant
::membershipStatus(NULL, NULL, 'label');
2622 $allTypes = CRM_Member_PseudoConstant
::membershipType();
2624 // get only memberships with active membership types
2626 SELECT civicrm_membership.id as membership_id,
2627 civicrm_membership.is_override as is_override,
2628 civicrm_membership.membership_type_id as membership_type_id,
2629 civicrm_membership.status_id as status_id,
2630 civicrm_membership.join_date as join_date,
2631 civicrm_membership.start_date as start_date,
2632 civicrm_membership.end_date as end_date,
2633 civicrm_membership.source as source,
2634 civicrm_contact.id as contact_id,
2635 civicrm_contact.is_deceased as is_deceased,
2636 civicrm_membership.owner_membership_id as owner_membership_id,
2637 civicrm_membership.contribution_recur_id as recur_id
2638 FROM civicrm_membership
2639 INNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )
2640 INNER JOIN civicrm_membership_type ON
2641 (civicrm_membership.membership_type_id = civicrm_membership_type.id AND civicrm_membership_type.is_active = 1)
2642 WHERE civicrm_membership.is_test = 0";
2645 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2650 $smarty = CRM_Core_Smarty
::singleton();
2652 while ($dao->fetch()) {
2656 // Put common parameters into array for easy access
2657 $memberParams = array(
2658 'id' => $dao->membership_id
,
2659 'status_id' => $dao->status_id
,
2660 'contact_id' => $dao->contact_id
,
2661 'membership_type_id' => $dao->membership_type_id
,
2662 'membership_type' => $allTypes[$dao->membership_type_id
],
2663 'join_date' => $dao->join_date
,
2664 'start_date' => $dao->start_date
,
2665 'end_date' => $dao->end_date
,
2666 'source' => $dao->source
,
2667 'skipStatusCal' => TRUE,
2668 'skipRecentView' => TRUE,
2671 $smarty->assign_by_ref('memberParams', $memberParams);
2673 //update membership record to Deceased if contact is deceased
2674 if ($dao->is_deceased
) {
2675 // check for 'Deceased' membership status, CRM-5636
2676 $deceaseStatusId = array_search('Deceased', $allStatus);
2677 if (!$deceaseStatusId) {
2678 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'))));
2681 //process only when status change.
2682 if ($dao->status_id
!= $deceaseStatusId) {
2683 //take all params that need to save.
2684 $deceasedMembership = $memberParams;
2685 $deceasedMembership['status_id'] = $deceaseStatusId;
2686 $deceasedMembership['createActivity'] = TRUE;
2687 $deceasedMembership['version'] = 3;
2689 //since there is change in status.
2690 $statusChange = array('status_id' => $deceaseStatusId);
2691 $smarty->append_by_ref('memberParams', $statusChange, TRUE);
2693 $deceasedMembership['contact_id'],
2694 $deceasedMembership['membership_type_id'],
2695 $deceasedMembership['membership_type'],
2696 $deceasedMembership['join_date'],
2697 $deceasedMembership['start_date'],
2698 $deceasedMembership['end_date'],
2699 $deceasedMembership['source']
2702 //process membership record.
2703 civicrm_api('membership', 'create', $deceasedMembership);
2708 //we fetch related, since we need to check for deceased
2709 //now further processing is handle w/ main membership record.
2710 if ($dao->owner_membership_id
) {
2714 //update membership records where status is NOT - Pending OR Cancelled.
2715 //as well as membership is not override.
2716 //skipping Expired membership records -> reduced extra processing( kiran )
2717 if (!$dao->is_override
&&
2718 !in_array($dao->status_id
, array(array_search('Pending', $allStatus),
2719 array_search('Cancelled', $allStatus),
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);
2763 // CRM_Core_Error::debug( 'fEnd', count( $GLOBALS['_DB_DATAOBJECT']['RESULTS'] ) );
2765 $result['is_error'] = 0;
2766 $result['messages'] = ts('Processed %1 membership records. Updated %2 records.', array(1 => $processCount, 2 => $updateCount));
2771 * The function returns the membershiptypes for a particular contact
2772 * who has lifetime membership without end date.
2775 * @param bool $isTest
2776 * @param bool $onlyLifeTime
2779 * @internal param array $contactMembershipType array of allMembershipTypes Key - value pairs
2782 static function getAllContactMembership($contactID, $isTest = FALSE, $onlyLifeTime = FALSE) {
2783 $contactMembershipType = array();
2785 return $contactMembershipType;
2788 $dao = new CRM_Member_DAO_Membership();
2789 $dao->contact_id
= $contactID;
2790 $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
2791 $dao->whereAdd("status_id != $pendingStatusId");
2794 $dao->is_test
= $isTest;
2797 $dao->whereAdd('is_test IS NULL OR is_test = 0');
2800 if ($onlyLifeTime) {
2801 $dao->whereAdd('end_date IS NULL');
2805 while ($dao->fetch()) {
2806 $membership = array();
2807 CRM_Core_DAO
::storeValues($dao, $membership);
2808 $contactMembershipType[$dao->membership_type_id
] = $membership;
2810 return $contactMembershipType;
2814 * Function to record contribution record associated with membership
2816 * @param array $params array of submitted params
2817 * @param array $ids (param in process of being removed - try to use params) array of ids
2819 * @return CRM_Contribute_BAO_Contribution
2822 static function recordMembershipContribution( &$params, $ids = array()) {
2823 $membershipId = $params['membership_id'];
2824 $contributionParams = array();
2825 $config = CRM_Core_Config
::singleton();
2826 $contributionParams['currency'] = $config->defaultCurrency
;
2827 $contributionParams['receipt_date'] = (CRM_Utils_Array
::value('receipt_date', $params)) ?
$params['receipt_date'] : 'null';
2828 $contributionParams['source'] = CRM_Utils_Array
::value('contribution_source', $params);
2829 $contributionParams['non_deductible_amount'] = 'null';
2830 $contributionSoftParams = CRM_Utils_Array
::value('soft_credit', $params);
2831 $recordContribution = array(
2832 'contact_id', 'total_amount', 'receive_date', 'financial_type_id',
2833 'payment_instrument_id', 'trxn_id', 'invoice_id', 'is_test',
2834 'contribution_status_id', 'check_number', 'campaign_id', 'is_pay_later',
2835 'membership_id', 'skipLineItem'
2837 foreach ($recordContribution as $f) {
2838 $contributionParams[$f] = CRM_Utils_Array
::value($f, $params);
2841 // make entry in batch entity batch table
2842 if (!empty($params['batch_id'])) {
2843 $contributionParams['batch_id'] = $params['batch_id'];
2846 if (!empty($params['contribution_contact_id'])) {
2847 // deal with possibility of a different person paying for contribution
2848 $contributionParams['contact_id'] = $params['contribution_contact_id'];
2851 if (!empty($params['processPriceSet']) &&
2852 !empty($params['lineItems'])
2854 $contributionParams['line_item'] = CRM_Utils_Array
::value('lineItems', $params, NULL);
2857 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
2859 //CRM-13981, create new soft-credit record as to record payment from differnt person for this membership
2860 if (!empty($contributionSoftParams)) {
2861 $contributionSoftParams['contribution_id'] = $contribution->id
;
2862 $contributionSoftParams['currency'] = $contribution->currency
;
2863 $contributionSoftParams['amount'] = $contribution->total_amount
;
2864 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoftParams);
2867 // store contribution id
2868 $params['contribution_id'] = $contribution->id
;
2871 //insert payment record for this membership
2872 if (empty($ids['contribution']) ||
!empty($params['is_recur'])) {
2873 $mpDAO = new CRM_Member_DAO_MembershipPayment();
2874 $mpDAO->membership_id
= $membershipId;
2875 $mpDAO->contribution_id
= $contribution->id
;
2876 if (!empty($params['is_recur'])) {
2880 CRM_Utils_Hook
::pre('create', 'MembershipPayment', NULL, $mpDAO);
2882 CRM_Utils_Hook
::post('create', 'MembershipPayment', $mpDAO->id
, $mpDAO);
2884 return $contribution;
2888 * Function to record line items for default membership
2892 * @param $membershipType array with membership type and organization
2894 * @param $priceSetId
2896 * @internal param $ $ priceSetId priceset id
2900 static function createLineItems(&$qf, $membershipType, &$priceSetId) {
2901 $qf->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
2903 $qf->_priceSet
= $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
2905 $editedFieldParams = array(
2906 'price_set_id' => $priceSetId,
2907 'name' => $membershipType[0],
2909 $editedResults = array();
2910 CRM_Price_BAO_PriceField
::retrieve($editedFieldParams, $editedResults);
2912 if (!empty($editedResults)) {
2913 unset($qf->_priceSet
['fields']);
2914 $qf->_priceSet
['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
2915 unset($qf->_priceSet
['fields'][$editedResults['id']]['options']);
2916 $fid = $editedResults['id'];
2917 $editedFieldParams = array(
2918 'price_field_id' => $editedResults['id'],
2919 'membership_type_id' => $membershipType[1],
2921 $editedResults = array();
2922 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $editedResults);
2923 $qf->_priceSet
['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
2924 if (!empty($qf->_params
['total_amount'])) {
2925 $qf->_priceSet
['fields'][$fid]['options'][$editedResults['id']]['amount'] = $qf->_params
['total_amount'];
2929 $fieldID = key($qf->_priceSet
['fields']);
2930 $qf->_params
['price_' . $fieldID] = CRM_Utils_Array
::value('id', $editedResults);
2934 * @todo document me - I seem a bit out of date....
2936 static function _getActTypes() {
2937 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
2938 self
::$_renewalActType = CRM_Utils_Array
::key('Membership Renewal', $activityTypes);
2939 self
::$_signupActType = CRM_Utils_Array
::key('Membership Signup', $activityTypes);
2943 * Get all Cancelled Membership(s) for a contact
2945 * @param int $contactID contact id
2946 * @param boolean $isTest mode of payment
2948 * @return array of membership type
2952 static function getContactsCancelledMembership($contactID, $isTest = FALSE) {
2956 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2957 $query = 'SELECT membership_type_id FROM civicrm_membership WHERE contact_id = %1 AND status_id = %2 AND is_test = %3';
2958 $queryParams = array(
2959 1 => array($contactID, 'Integer'),
2960 2 => array(array_search('Cancelled', $allStatus), 'Integer'),
2961 3 => array($isTest, 'Boolean'),
2964 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
2965 $cancelledMembershipIds = array();
2966 while ($dao->fetch()) {
2967 $cancelledMembershipIds[] = $dao->membership_type_id
;
2969 return $cancelledMembershipIds;