3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
35 class CRM_Member_BAO_Membership
extends CRM_Member_DAO_Membership
{
38 * Static field for all the membership information that we can potentially import.
42 static $_importableFields = NULL;
44 static $_renewalActType = NULL;
46 static $_signupActType = NULL;
51 * @return \CRM_Member_DAO_Membership
55 public function __construct() {
56 parent
::__construct();
60 * Takes an associative array and creates a membership object.
62 * the function extracts all the params it needs to initialize the created
63 * membership object. The params array could contain additional unused name/value
66 * @param array $params
67 * (reference ) an assoc array of name/value pairs.
69 * The array that holds all the db ids.
71 * @return CRM_Member_BAO_Membership
73 public static function add(&$params, $ids = array()) {
74 $oldStatus = $oldType = NULL;
75 $params['id'] = CRM_Utils_Array
::value('id', $params, CRM_Utils_Array
::value('membership', $ids));
77 CRM_Utils_Hook
::pre('edit', 'Membership', $params['id'], $params);
80 CRM_Utils_Hook
::pre('create', 'Membership', NULL, $params);
83 // we do this after the hooks are called in case it has been altered
85 $membershipObj = new CRM_Member_DAO_Membership();
86 $membershipObj->id
= $id;
87 $membershipObj->find();
88 while ($membershipObj->fetch()) {
89 $oldStatus = $membershipObj->status_id
;
90 $oldType = $membershipObj->membership_type_id
;
94 if (array_key_exists('is_override', $params) && !$params['is_override']) {
95 $params['is_override'] = 'null';
98 $membership = new CRM_Member_BAO_Membership();
99 $membership->copyValues($params);
100 $membership->id
= $id;
105 if (empty($membership->contact_id
) ||
empty($membership->status_id
)) {
106 // this means we are in renewal mode and are just updating the membership
107 // record or this is an API update call and all fields are not present in the update record
108 // however the hooks don't care and want all data CRM-7784
109 $tempMembership = new CRM_Member_DAO_Membership();
110 $tempMembership->id
= $membership->id
;
111 $tempMembership->find(TRUE);
112 $membership = $tempMembership;
115 //get the log start date.
116 //it is set during renewal of membership.
117 $logStartDate = CRM_Utils_Array
::value('log_start_date', $params);
118 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : CRM_Utils_Date
::isoToMysql($membership->start_date
);
119 $values = self
::getStatusANDTypeValues($membership->id
);
121 $membershipLog = array(
122 'membership_id' => $membership->id
,
123 'status_id' => $membership->status_id
,
124 'start_date' => $logStartDate,
125 'end_date' => CRM_Utils_Date
::isoToMysql($membership->end_date
),
126 'modified_date' => date('Ymd'),
127 'membership_type_id' => $values[$membership->id
]['membership_type_id'],
128 'max_related' => $membership->max_related
,
131 $session = CRM_Core_Session
::singleton();
132 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
133 if ($session->get('userID')) {
134 $membershipLog['modified_id'] = $session->get('userID');
136 elseif (!empty($ids['userId'])) {
137 $membershipLog['modified_id'] = $ids['userId'];
140 $membershipLog['modified_id'] = $membership->contact_id
;
143 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
145 // reset the group contact cache since smart groups might be affected due to this
146 CRM_Contact_BAO_GroupContactCache
::remove();
149 if ($membership->status_id
!= $oldStatus) {
150 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
151 $activityParam = array(
152 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
153 'source_contact_id' => $membershipLog['modified_id'],
154 'target_contact_id' => $membership->contact_id
,
155 'source_record_id' => $membership->id
,
156 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Change Membership Status'),
159 'activity_date_time' => date('Y-m-d H:i:s'),
161 civicrm_api3('activity', 'create', $activityParam);
163 if (isset($membership->membership_type_id
) && $membership->membership_type_id
!= $oldType) {
164 $membershipTypes = CRM_Member_BAO_Membership
::buildOptions('membership_type_id', 'get');
165 $activityParam = array(
166 'subject' => "Type changed from {$membershipTypes[$oldType]} to {$membershipTypes[$membership->membership_type_id]}",
167 'source_contact_id' => $membershipLog['modified_id'],
168 'target_contact_id' => $membership->contact_id
,
169 'source_record_id' => $membership->id
,
170 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Change Membership Type'),
173 'activity_date_time' => date('Y-m-d H:i:s'),
175 civicrm_api3('activity', 'create', $activityParam);
177 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
180 CRM_Utils_Hook
::post('create', 'Membership', $membership->id
, $membership);
187 * Given the list of params in the params array, fetch the object
188 * and store the values in the values array
190 * @param array $params
191 * Input parameters to find object.
192 * @param array $values
193 * Output values of the object.
194 * @param bool $active
195 * Do you want only active memberships to.
197 * @param bool $relatedMemberships
198 * @return CRM_Member_BAO_Membership|null the found object or null
200 public static function &getValues(&$params, &$values, $active = FALSE, $relatedMemberships = FALSE) {
201 if (empty($params)) {
204 $membership = new CRM_Member_BAO_Membership();
206 $membership->copyValues($params);
208 $memberships = array();
209 while ($membership->fetch()) {
211 (!CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
212 $membership->status_id
,
219 CRM_Core_DAO
::storeValues($membership, $values[$membership->id
]);
220 $memberships[$membership->id
] = $membership;
221 if ($relatedMemberships && !empty($membership->owner_membership_id
)) {
222 $values['owner_membership_ids'][] = $membership->owner_membership_id
;
230 * Takes an associative array and creates a membership object.
232 * @param array $params
233 * (reference ) an assoc array of name/value pairs.
235 * The array that holds all the db ids.
236 * @param bool $skipRedirect
237 * @param string $activityType
239 * @throws CRM_Core_Exception
241 * @return CRM_Member_BAO_Membership|CRM_Core_Error
243 public static function create(&$params, &$ids, $skipRedirect = FALSE, $activityType = 'Membership Signup') {
244 // always calculate status if is_override/skipStatusCal is not true.
245 // giving respect to is_override during import. CRM-4012
247 // To skip status calculation we should use 'skipStatusCal'.
248 // eg pay later membership, membership update cron CRM-3984
250 if (empty($params['is_override']) && empty($params['skipStatusCal'])) {
251 $dates = array('start_date', 'end_date', 'join_date');
252 $start_date = $end_date = $join_date = NULL; // declare these out of courtesy as IDEs don't pick up the setting of them below
253 foreach ($dates as $date) {
254 $
$date = $params[$date] = CRM_Utils_Date
::processDate(CRM_Utils_Array
::value($date, $params), NULL, TRUE, 'Ymd');
257 //fix for CRM-3570, during import exclude the statuses those having is_admin = 1
258 $excludeIsAdmin = CRM_Utils_Array
::value('exclude_is_admin', $params, FALSE);
260 //CRM-3724 always skip is_admin if is_override != true.
261 if (!$excludeIsAdmin && empty($params['is_override'])) {
262 $excludeIsAdmin = TRUE;
265 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($start_date, $end_date, $join_date,
266 'today', $excludeIsAdmin, CRM_Utils_Array
::value('membership_type_id', $params), $params
268 if (empty($calcStatus)) {
269 // Redirect the form in case of error
270 // @todo this redirect in the BAO layer is really bad & should be moved to the form layer
271 // however since we have no idea how (if) this is triggered we can't safely move / remove it
272 // NB I tried really hard to trigger this error from backoffice membership form in order to test it
273 // and am convinced form validation is complete on that form WRT this error.
274 $errorParams = array(
275 'message_title' => ts('No valid membership status for given dates.'),
276 'legacy_redirect_path' => 'civicrm/contact/view',
277 'legacy_redirect_query' => "reset=1&force=1&cid={$params['contact_id']}&selectedChild=member",
279 throw new CRM_Core_Exception(ts('The membership cannot be saved because the status cannot be calculated.'), 0, $errorParams);
281 $params['status_id'] = $calcStatus['id'];
284 // data cleanup only: all verifications on number of related memberships are done upstream in:
285 // CRM_Member_BAO_Membership::createRelatedMemberships()
286 // CRM_Contact_BAO_Relationship::relatedMemberships()
287 if (isset($params['owner_membership_id'])) {
288 unset($params['max_related']);
291 // if membership allows related, default max_related to value in membership_type
292 if (!array_key_exists('max_related', $params) && !empty($params['membership_type_id'])) {
293 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($params['membership_type_id']);
294 if (isset($membershipType['relationship_type_id'])) {
295 $params['max_related'] = CRM_Utils_Array
::value('max_related', $membershipType);
300 $transaction = new CRM_Core_Transaction();
302 $membership = self
::add($params, $ids);
304 if (is_a($membership, 'CRM_Core_Error')) {
305 $transaction->rollback();
309 // add custom field values
310 if (!empty($params['custom']) && is_array($params['custom'])
312 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_membership', $membership->id
);
315 $params['membership_id'] = $membership->id
;
316 if (isset($ids['membership'])) {
317 $ids['contribution'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment',
324 $params['skipLineItem'] = TRUE;
326 //record contribution for this membership
327 if (!empty($params['contribution_status_id']) && empty($params['relate_contribution_id'])) {
328 $memInfo = array_merge($params, array('membership_id' => $membership->id
));
329 $params['contribution'] = self
::recordMembershipContribution($memInfo, $ids);
332 if (!empty($params['lineItems'])) {
333 $params['line_item'] = $params['lineItems'];
336 //do cleanup line items if membership edit the Membership type.
337 if (empty($ids['contribution']) && !empty($ids['membership'])) {
338 CRM_Price_BAO_LineItem
::deleteLineItems($ids['membership'], 'civicrm_membership');
341 if (!empty($params['line_item']) && empty($ids['contribution'])) {
342 CRM_Price_BAO_LineItem
::processPriceSet($membership->id
, $params['line_item'], CRM_Utils_Array
::value('contribution', $params));
345 //insert payment record for this membership
346 if (!empty($params['relate_contribution_id'])) {
347 CRM_Member_BAO_MembershipPayment
::create(array(
348 'membership_id' => $membership->id
,
349 'contribution_id' => $params['relate_contribution_id'],
353 // add activity record only during create mode and renew mode
354 // also add activity if status changed CRM-3984 and CRM-2521
355 if (empty($ids['membership']) ||
356 $activityType == 'Membership Renewal' ||
!empty($params['createActivity'])
358 if (!empty($ids['membership'])) {
360 CRM_Core_DAO
::commonRetrieveAll('CRM_Member_DAO_Membership',
364 array('contact_id', 'membership_type_id', 'source')
367 $membership->contact_id
= $data[$membership->id
]['contact_id'];
368 $membership->membership_type_id
= $data[$membership->id
]['membership_type_id'];
369 $membership->source
= CRM_Utils_Array
::value('source', $data[$membership->id
]);
372 // since we are going to create activity record w/
373 // individual contact as a target in case of on behalf signup,
374 // so get the copy of organization id, CRM-5551
375 $realMembershipContactId = $membership->contact_id
;
377 // create activity source = individual, target = org CRM-4027
378 $targetContactID = NULL;
379 if (!empty($params['is_for_organization'])) {
380 $targetContactID = $membership->contact_id
;
381 $membership->contact_id
= CRM_Utils_Array
::value('userId', $ids);
384 if (empty($membership->contact_id
) && (!empty($membership->owner_membership_id
))) {
385 $membership->contact_id
= $realMembershipContactId;
388 if (!empty($ids['membership']) && $activityType != 'Membership Signup') {
389 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $targetContactID);
391 elseif (empty($ids['membership'])) {
392 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $targetContactID);
395 // we might created activity record w/ individual
396 // contact as target so update membership object w/
397 // original organization id, CRM-5551
398 $membership->contact_id
= $realMembershipContactId;
401 $transaction->commit();
403 self
::createRelatedMemberships($params, $membership);
405 // do not add to recent items for import, CRM-4399
406 if (empty($params['skipRecentView'])) {
407 $url = CRM_Utils_System
::url('civicrm/contact/view/membership',
408 "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
410 if (empty($membership->membership_type_id
)) {// ie in an update situation
411 $membership->find(TRUE);
413 $membershipTypes = CRM_Member_PseudoConstant
::membershipType();
414 $title = CRM_Contact_BAO_Contact
::displayName($membership->contact_id
) . ' - ' . ts('Membership Type:') . ' ' . $membershipTypes[$membership->membership_type_id
];
416 $recentOther = array();
417 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::UPDATE
)) {
418 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
419 "action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
422 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::DELETE
)) {
423 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
424 "action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
428 // add the recently created Membership
429 CRM_Utils_Recent
::add($title,
433 $membership->contact_id
,
443 * Check the membership extended through relationship.
445 * @param int $membershipId
447 * @param int $contactId
453 * array of contact_id of all related contacts.
455 public static function checkMembershipRelationship($membershipId, $contactId, $action = CRM_Core_Action
::ADD
) {
457 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $membershipId, 'membership_type_id');
459 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipTypeID);
460 $relationships = array();
461 if (isset($membershipType['relationship_type_id'])) {
462 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
463 CRM_Contact_BAO_Relationship
::CURRENT
465 if ($action & CRM_Core_Action
::UPDATE
) {
466 $pastRelationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
467 CRM_Contact_BAO_Relationship
::PAST
469 $relationships = array_merge($relationships, $pastRelationships);
473 if (!empty($relationships)) {
474 // check for each contact relationships
475 foreach ($relationships as $values) {
476 //get details of the relationship type
477 $relType = array('id' => $values['civicrm_relationship_type_id']);
478 $relValues = array();
479 CRM_Contact_BAO_RelationshipType
::retrieve($relType, $relValues);
480 // Check if contact's relationship type exists in membership type
481 $relTypeDirs = array();
482 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_type_id']);
483 $relDirections = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_direction']);
484 $bidirectional = FALSE;
485 foreach ($relTypeIds as $key => $value) {
486 $relTypeDirs[] = $value . '_' . $relDirections[$key];
487 if (in_array($value, $relType) &&
488 $relValues['name_a_b'] == $relValues['name_b_a']
490 $bidirectional = TRUE;
494 $relTypeDir = $values['civicrm_relationship_type_id'] . '_' . $values['rtype'];
495 if ($bidirectional ||
in_array($relTypeDir, $relTypeDirs)) {
496 // $values['status'] is going to have value for
497 // current or past relationships.
498 $contacts[$values['cid']] = $values['status'];
503 // Sort by contact_id ascending
509 * Retrieve DB object based on input parameters.
511 * It also stores all the retrieved values in the default array.
513 * @param array $params
514 * (reference ) an assoc array of name/value pairs.
515 * @param array $defaults
516 * (reference ) an assoc array to hold the name / value pairs.
517 * in a hierarchical manner
519 * @return CRM_Member_BAO_Membership
521 public static function retrieve(&$params, &$defaults) {
522 $membership = new CRM_Member_DAO_Membership();
524 $membership->copyValues($params);
526 if ($membership->find(TRUE)) {
527 CRM_Core_DAO
::storeValues($membership, $defaults);
529 //get the membership status and type values.
530 $statusANDType = self
::getStatusANDTypeValues($membership->id
);
535 $defaults[$fld] = CRM_Utils_Array
::value($fld, $statusANDType[$membership->id
]);
537 if (!empty($statusANDType[$membership->id
]['is_current_member'])) {
538 $defaults['active'] = TRUE;
551 * get membership status and membership type values
553 * @param int $membershipId
554 * Membership id of values to return.
557 * Array of key value pairs
559 public static function getStatusANDTypeValues($membershipId) {
561 if (!$membershipId) {
565 SELECT membership.id as id,
566 status.id as status_id,
567 status.label as status,
568 status.is_current_member as is_current_member,
569 type.id as membership_type_id,
570 type.name as membership_type,
571 type.relationship_type_id as relationship_type_id
572 FROM civicrm_membership membership
573 INNER JOIN civicrm_membership_status status ON ( status.id = membership.status_id )
574 INNER JOIN civicrm_membership_type type ON ( type.id = membership.membership_type_id )
575 WHERE membership.id = %1';
576 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($membershipId, 'Positive')));
581 'membership_type_id',
583 'relationship_type_id',
585 while ($dao->fetch()) {
586 foreach ($properties as $property) {
587 $values[$dao->id
][$property] = $dao->$property;
596 * Wrapper for most delete calls. Use this unless you JUST want to delete related memberships w/o deleting the parent.
598 * @param int $membershipId
599 * Membership id that needs to be deleted.
602 * @return int $results id of deleted Membership on success, false otherwise
604 public static function del($membershipId) {
605 //delete related first and then delete parent.
606 self
::deleteRelatedMemberships($membershipId);
607 return self
::deleteMembership($membershipId);
613 * @param int $membershipId
614 * Membership id that needs to be deleted.
617 * @return int $results id of deleted Membership on success, false otherwise
619 public static function deleteMembership($membershipId) {
620 // CRM-12147, retrieve membership data before we delete it for hooks
621 $params = array('id' => $membershipId);
622 $memValues = array();
623 $memberships = self
::getValues($params, $memValues);
625 $membership = $memberships[$membershipId];
627 CRM_Utils_Hook
::pre('delete', 'Membership', $membershipId, $memValues);
629 $transaction = new CRM_Core_Transaction();
632 //delete activity record
633 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
636 $deleteActivity = FALSE;
637 $membershipActivities = array(
639 'Membership Renewal',
640 'Change Membership Status',
641 'Change Membership Type',
642 'Membership Renewal Reminder',
644 foreach ($membershipActivities as $membershipActivity) {
645 $activityId = array_search($membershipActivity, $activityTypes);
647 $params['activity_type_id'][] = $activityId;
648 $deleteActivity = TRUE;
651 if ($deleteActivity) {
652 $params['source_record_id'] = $membershipId;
653 CRM_Activity_BAO_Activity
::deleteActivity($params);
655 self
::deleteMembershipPayment($membershipId);
657 $results = $membership->delete();
658 $transaction->commit();
660 CRM_Utils_Hook
::post('delete', 'Membership', $membership->id
, $membership);
662 // delete the recently created Membership
663 $membershipRecent = array(
664 'id' => $membershipId,
665 'type' => 'Membership',
667 CRM_Utils_Recent
::del($membershipRecent);
673 * Delete related memberships.
675 * @param int $ownerMembershipId
676 * @param int $contactId
680 public static function deleteRelatedMemberships($ownerMembershipId, $contactId = NULL) {
681 if (!$ownerMembershipId && !$contactId) {
685 $membership = new CRM_Member_DAO_Membership();
686 $membership->owner_membership_id
= $ownerMembershipId;
689 $membership->contact_id
= $contactId;
693 while ($membership->fetch()) {
694 //delete related first and then delete parent.
695 self
::deleteRelatedMemberships($membership->id
);
696 self
::deleteMembership($membership->id
);
702 * Obtain active/inactive memberships from the list of memberships passed to it.
704 * @param array $memberships
705 * Membership records.
706 * @param string $status
707 * Active or inactive.
710 * array of memberships based on status
712 public static function activeMembers($memberships, $status = 'active') {
714 if ($status == 'active') {
715 foreach ($memberships as $f => $v) {
716 if (!empty($v['active'])) {
722 elseif ($status == 'inactive') {
723 foreach ($memberships as $f => $v) {
724 if (empty($v['active'])) {
734 * Build Membership Block in Contribution Pages.
736 * @param CRM_Core_Form $form
741 * Contact checked for having a current membership for a particular membership.
742 * @param bool $formItems
743 * @param int $selectedMembershipTypeID
744 * Selected membership id.
745 * @param bool $thankPage
747 * @param null $isTest
750 * Is this a separate membership payment
753 public static function buildMembershipBlock(
758 $selectedMembershipTypeID = NULL,
763 $separateMembershipPayment = FALSE;
764 if ($form->_membershipBlock
) {
765 $form->_currentMemberships
= array();
767 $membershipBlock = $form->_membershipBlock
;
768 $membershipTypeIds = $membershipTypes = $radio = array();
769 $membershipPriceset = (!empty($form->_priceSetId
) && $form->_useForMember
) ?
TRUE : FALSE;
771 $allowAutoRenewMembership = $autoRenewOption = FALSE;
772 $autoRenewMembershipTypeOptions = array();
774 $paymentProcessor = CRM_Core_PseudoConstant
::paymentProcessor(FALSE, FALSE, 'is_recur = 1');
776 $separateMembershipPayment = CRM_Utils_Array
::value('is_separate_payment', $membershipBlock);
778 if ($membershipPriceset) {
779 foreach ($form->_priceSet
['fields'] as $pField) {
780 if (empty($pField['options'])) {
783 foreach ($pField['options'] as $opId => $opValues) {
784 if (empty($opValues['membership_type_id'])) {
787 $membershipTypeIds[$opValues['membership_type_id']] = $opValues['membership_type_id'];
791 elseif (!empty($membershipBlock['membership_types'])) {
792 $membershipTypeIds = explode(',', $membershipBlock['membership_types']);
795 if (!empty($membershipTypeIds)) {
796 //set status message if wrong membershipType is included in membershipBlock
797 if (isset($form->_mid
) && !$membershipPriceset) {
798 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
802 if (!in_array($membershipTypeID, $membershipTypeIds)) {
803 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');
807 $membershipTypeValues = self
::buildMembershipTypeValues($form, $membershipTypeIds);
808 $form->_membershipTypeValues
= $membershipTypeValues;
810 foreach ($membershipTypeIds as $value) {
811 $memType = $membershipTypeValues[$value];
812 if ($selectedMembershipTypeID != NULL) {
813 if ($memType['id'] == $selectedMembershipTypeID) {
814 $form->assign('minimum_fee',
815 CRM_Utils_Array
::value('minimum_fee', $memType)
817 $form->assign('membership_name', $memType['name']);
818 if (!$thankPage && $cid) {
819 $membership = new CRM_Member_DAO_Membership();
820 $membership->contact_id
= $cid;
821 $membership->membership_type_id
= $memType['id'];
822 if ($membership->find(TRUE)) {
823 $form->assign('renewal_mode', TRUE);
824 $memType['current_membership'] = $membership->end_date
;
825 $form->_currentMemberships
[$membership->membership_type_id
] = $membership->membership_type_id
;
828 $membershipTypes[] = $memType;
831 elseif ($memType['is_active']) {
832 $javascriptMethod = NULL;
833 $allowAutoRenewOpt = 1;
834 if (is_array($form->_paymentProcessors
)) {
835 foreach ($form->_paymentProcessors
as $id => $val) {
836 if (!$val['is_recur']) {
837 $allowAutoRenewOpt = 0;
843 $javascriptMethod = array('onclick' => "return showHideAutoRenew( this.value );");
844 $autoRenewMembershipTypeOptions["autoRenewMembershipType_{$value}"] = (int) $allowAutoRenewOpt * CRM_Utils_Array
::value($value, CRM_Utils_Array
::value('auto_renew', $form->_membershipBlock
));;
846 if ($allowAutoRenewOpt) {
847 $allowAutoRenewMembership = TRUE;
850 //add membership type.
851 $radio[$memType['id']] = $form->createElement('radio', NULL, NULL, NULL,
852 $memType['id'], $javascriptMethod
855 $membership = new CRM_Member_DAO_Membership();
856 $membership->contact_id
= $cid;
857 $membership->membership_type_id
= $memType['id'];
859 //show current membership, skip pending and cancelled membership records,
860 //because we take first membership record id for renewal
861 $membership->whereAdd('status_id != 5 AND status_id !=6');
863 if (!is_null($isTest)) {
864 $membership->is_test
= $isTest;
868 $membership->orderBy('end_date DESC');
870 if ($membership->find(TRUE)) {
871 if (!$membership->end_date
) {
872 unset($radio[$memType['id']]);
873 $form->assign('islifetime', TRUE);
876 $form->assign('renewal_mode', TRUE);
877 $form->_currentMemberships
[$membership->membership_type_id
] = $membership->membership_type_id
;
878 $memType['current_membership'] = $membership->end_date
;
880 $endDate = $memType['current_membership'];
881 $form->_defaultMemTypeId
= $memType['id'];
883 if ($memType['current_membership'] < $endDate) {
884 $endDate = $memType['current_membership'];
885 $form->_defaultMemTypeId
= $memType['id'];
889 $membershipTypes[] = $memType;
894 $form->assign('showRadio', $formItems);
896 if (!$membershipPriceset) {
897 if (!$membershipBlock['is_required']) {
898 $form->assign('showRadioNoThanks', TRUE);
899 $radio[''] = $form->createElement('radio', NULL, NULL, NULL, 'no_thanks', NULL);
900 $form->addGroup($radio, 'selectMembership', NULL);
902 elseif ($membershipBlock['is_required'] && count($radio) == 1) {
903 $temp = array_keys($radio);
904 $form->add('hidden', 'selectMembership', $temp[0], array('id' => 'selectMembership'));
905 $form->assign('singleMembership', TRUE);
906 $form->assign('showRadio', FALSE);
909 $form->addGroup($radio, 'selectMembership', NULL);
912 $form->addRule('selectMembership', ts('Please select one of the memberships.'), 'required');
915 $autoRenewOption = CRM_Price_BAO_PriceSet
::checkAutoRenewForPriceSet($form->_priceSetId
);
916 $form->assign('autoRenewOption', $autoRenewOption);
919 if (!$form->_values
['is_pay_later'] && is_array($form->_paymentProcessors
) && ($allowAutoRenewMembership ||
$autoRenewOption)) {
920 $form->addElement('checkbox', 'auto_renew', ts('Please renew my membership automatically.'));
925 $form->assign('membershipBlock', $membershipBlock);
926 $form->assign('membershipTypes', $membershipTypes);
927 $form->assign('allowAutoRenewMembership', $allowAutoRenewMembership);
928 $form->assign('autoRenewMembershipTypeOptions', json_encode($autoRenewMembershipTypeOptions));
930 //give preference to user submitted auto_renew value.
931 $takeUserSubmittedAutoRenew = (!empty($_POST) ||
$form->isSubmitted()) ?
TRUE : FALSE;
932 $form->assign('takeUserSubmittedAutoRenew', $takeUserSubmittedAutoRenew);
935 return $separateMembershipPayment;
939 * Return Membership Block info in Contribution Pages.
942 * Contribution page id.
947 public static function getMembershipBlock($pageID) {
948 $membershipBlock = array();
949 $dao = new CRM_Member_DAO_MembershipBlock();
950 $dao->entity_table
= 'civicrm_contribution_page';
952 $dao->entity_id
= $pageID;
954 if ($dao->find(TRUE)) {
955 CRM_Core_DAO
::storeValues($dao, $membershipBlock);
956 if (!empty($membershipBlock['membership_types'])) {
957 $membershipTypes = unserialize($membershipBlock['membership_types']);
958 if (!is_array($membershipTypes)) {
959 return $membershipBlock;
962 foreach ($membershipTypes as $key => $value) {
963 $membershipBlock['auto_renew'][$key] = $value;
964 $memTypes[$key] = $key;
966 $membershipBlock['membership_types'] = implode(',', $memTypes);
973 return $membershipBlock;
977 * Return a current membership of given contact.
978 * NB: if more than one membership meets criteria, a randomly selected one is returned.
980 * @param int $contactID
982 * @param int $memType
983 * Membership type, null to retrieve all types.
985 * @param int $membershipId
986 * If provided, then determine if it is current.
987 * @param bool $onlySameParentOrg
988 * True if only Memberships with same parent org as the $memType wanted, false otherwise.
992 public static function getContactMembership($contactID, $memType, $isTest, $membershipId = NULL, $onlySameParentOrg = FALSE) {
993 $dao = new CRM_Member_DAO_Membership();
995 $dao->id
= $membershipId;
997 $dao->contact_id
= $contactID;
998 $dao->membership_type_id
= $memType;
1000 //fetch proper membership record.
1002 $dao->is_test
= $isTest;
1005 $dao->whereAdd('is_test IS NULL OR is_test = 0');
1008 //avoid pending membership as current membership: CRM-3027
1009 $statusIds[] = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
1010 if (!$membershipId) {
1012 $statusIds[] = array_search(
1014 CRM_Member_PseudoConstant
::membershipStatus(
1016 " name = 'Cancelled' ",
1023 $dao->whereAdd('status_id NOT IN ( ' . implode(',', $statusIds) . ')');
1025 // order by start date to find most recent membership first, CRM-4545
1026 $dao->orderBy('start_date DESC');
1029 if ($onlySameParentOrg && $memType) {
1030 // require the same parent org as the $memType
1031 $params = array('id' => $memType);
1032 $membershipType = array();
1033 if (CRM_Member_BAO_MembershipType
::retrieve($params, $membershipType)) {
1034 $memberTypesSameParentOrg = CRM_Member_BAO_MembershipType
::getMembershipTypesByOrg($membershipType['member_of_contact_id']);
1035 $memberTypesSameParentOrgList = implode(',', array_keys($memberTypesSameParentOrg));
1036 $dao->whereAdd('membership_type_id IN (' . $memberTypesSameParentOrgList . ')');
1040 if ($dao->find(TRUE)) {
1041 $membership = array();
1042 CRM_Core_DAO
::storeValues($dao, $membership);
1043 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
1044 $membership['status_id'],
1045 'is_current_member', 'id'
1051 if ($onlySameParentOrg && $memType) {
1052 // see if there is a membership that has same parent as $memType but different parent than $membershipID
1053 if ($dao->id
&& CRM_Core_Permission
::check('edit memberships')) {
1054 // CRM-10016, This is probably a backend renewal, and make sure we return the same membership thats being renewed.
1061 unset($dao->membership_type_id
);
1062 if ($dao->find(TRUE)) {
1063 $membership = array();
1064 CRM_Core_DAO
::storeValues($dao, $membership);
1065 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
1066 $membership['status_id'],
1067 'is_current_member', 'id'
1076 * Combine all the importable fields from the lower levels object.
1078 * @param string $contactType
1080 * @param bool $status
1083 * array of importable Fields
1085 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
1086 if (!self
::$_importableFields) {
1087 if (!self
::$_importableFields) {
1088 self
::$_importableFields = array();
1092 $fields = array('' => array('title' => '- ' . ts('do not import') . ' -'));
1095 $fields = array('' => array('title' => '- ' . ts('Membership Fields') . ' -'));
1098 $tmpFields = CRM_Member_DAO_Membership
::import();
1099 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
1101 // Using new Dedupe rule.
1102 $ruleParams = array(
1103 'contact_type' => $contactType,
1104 'used' => 'Unsupervised',
1106 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
1108 $tmpContactField = array();
1109 if (is_array($fieldsArray)) {
1110 foreach ($fieldsArray as $value) {
1111 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
1116 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
1117 $tmpContactField[trim($value)] = CRM_Utils_Array
::value(trim($value), $contactFields);
1119 $title = $tmpContactField[trim($value)]['title'] . " " . ts('(match to contact)');
1122 $title = $tmpContactField[trim($value)]['title'];
1124 $tmpContactField[trim($value)]['title'] = $title;
1127 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
1128 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " " . ts('(match to contact)');
1130 $tmpFields['membership_contact_id']['title'] = $tmpFields['membership_contact_id']['title'] . " " . ts('(match to contact)');;
1132 $fields = array_merge($fields, $tmpContactField);
1133 $fields = array_merge($fields, $tmpFields);
1134 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1135 self
::$_importableFields = $fields;
1137 return self
::$_importableFields;
1141 * Get all exportable fields.
1143 * @retun array return array of all exportable fields
1145 public static function &exportableFields() {
1146 $expFieldMembership = CRM_Member_DAO_Membership
::export();
1148 $expFieldsMemType = CRM_Member_DAO_MembershipType
::export();
1149 $fields = array_merge($expFieldMembership, $expFieldsMemType);
1150 $fields = array_merge($fields, $expFieldMembership);
1151 $membershipStatus = array(
1152 'membership_status' => array(
1153 'title' => 'Membership Status',
1154 'name' => 'membership_status',
1155 'type' => CRM_Utils_Type
::T_STRING
,
1156 'where' => 'civicrm_membership_status.name',
1159 //CRM-6161 fix for customdata export
1160 $fields = array_merge($fields, $membershipStatus, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1165 * Get membership joins/renewals for a specified membership
1166 * type. Specifically, retrieves a count of memberships whose "Membership
1167 * Signup" or "Membership Renewal" activity falls in the given date range.
1168 * Dates match the pattern "yyyy-mm-dd".
1170 * @param int $membershipTypeId
1171 * Membership type id.
1172 * @param int $startDate
1173 * Date on which to start counting.
1174 * @param int $endDate
1175 * Date on which to end counting.
1176 * @param bool|int $isTest if true, membership is for a test site
1177 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1180 * the number of members of type $membershipTypeId whose
1181 * start_date is between $startDate and $endDate
1183 public static function getMembershipStarts($membershipTypeId, $startDate, $endDate, $isTest = 0, $isOwner = 0) {
1185 $testClause = 'membership.is_test = 1';
1187 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1190 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1191 self
::_getActTypes();
1194 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1199 SELECT COUNT(DISTINCT membership.id) as member_count
1200 FROM civicrm_membership membership
1201 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id in (%1, %2))
1202 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1203 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1204 WHERE membership.membership_type_id = %3
1205 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1208 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1211 1 => array(self
::$_signupActType, 'Integer'),
1212 2 => array(self
::$_renewalActType, 'Integer'),
1213 3 => array($membershipTypeId, 'Integer'),
1216 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1217 return (int) $memberCount;
1221 * Get a count of membership for a specified membership type,
1222 * optionally for a specified date. The date must have the form yyyy-mm-dd.
1224 * If $date is omitted, this function counts as a member anyone whose
1225 * membership status_id indicates they're a current member.
1226 * If $date is given, this function counts as a member anyone who:
1227 * -- Has a start_date before $date and end_date after $date, or
1228 * -- Has a start_date before $date and is currently a member, as indicated
1229 * by the the membership's status_id.
1230 * The second condition takes care of records that have no end_date. These
1231 * are assumed to be lifetime memberships.
1233 * @param int $membershipTypeId
1234 * Membership type id.
1235 * @param string $date
1236 * The date for which to retrieve the count.
1237 * @param bool|int $isTest if true, membership is for a test site
1238 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1241 * the number of members of type $membershipTypeId as of $date.
1243 public static function getMembershipCount($membershipTypeId, $date = NULL, $isTest = 0, $isOwner = 0) {
1244 if (!CRM_Utils_Rule
::date($date)) {
1245 CRM_Core_Error
::fatal(ts('Invalid date "%1" (must have form yyyy-mm-dd).', array(1 => $date)));
1249 1 => array($membershipTypeId, 'Integer'),
1250 2 => array($isTest, 'Boolean'),
1252 $query = "SELECT count(civicrm_membership.id ) as member_count
1253 FROM civicrm_membership left join civicrm_membership_status on ( civicrm_membership.status_id = civicrm_membership_status.id )
1254 WHERE civicrm_membership.membership_type_id = %1
1255 AND civicrm_membership.contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)
1256 AND civicrm_membership.is_test = %2";
1258 $query .= " AND civicrm_membership_status.is_current_member = 1";
1261 $query .= " AND civicrm_membership.start_date <= '$date' AND civicrm_membership_status.is_current_member = 1";
1264 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1265 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1266 return (int) $memberCount;
1270 * Function check the status of the membership before adding membership for a contact.
1272 * @param int $contactId
1277 public static function statusAvailabilty($contactId) {
1278 $membership = new CRM_Member_DAO_MembershipStatus();
1279 $membership->whereAdd('is_active=1');
1280 return $membership->count();
1284 * Process the Memberships.
1286 * @param array $membershipParams
1287 * Array of membership fields.
1288 * @param int $contactID
1290 * @param CRM_Contribute_Form_Contribution_Confirm $form
1291 * Confirmation form object.
1293 * @param array $premiumParams
1294 * @param null $customFieldsFormatted
1295 * @param null $includeFieldTypes
1297 * @param array $membershipDetails
1299 * @param array $membershipTypeIDs
1301 * @param bool $isPaidMembership
1302 * @param array $membershipID
1304 * @param $isProcessSeparateMembershipTransaction
1306 * @param int $defaultContributionTypeID
1307 * @param array $membershipLineItems
1308 * Line items specific to membership payment that is separate to contribution.
1309 * @param $isPayLater
1311 * @throws \CRM_Core_Exception
1313 public static function postProcessMembership(
1314 $membershipParams, $contactID, &$form, $premiumParams,
1315 $customFieldsFormatted = NULL, $includeFieldTypes = NULL, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID,
1316 $isProcessSeparateMembershipTransaction, $defaultContributionTypeID, $membershipLineItems, $isPayLater) {
1317 $result = $membershipContribution = NULL;
1318 $isTest = CRM_Utils_Array
::value('is_test', $membershipParams, FALSE);
1319 $errors = $createdMemberships = array();
1321 //@todo move this into the calling function & pass in the correct financialTypeID
1322 if (isset($paymentParams['financial_type'])) {
1323 $financialTypeID = $paymentParams['financial_type'];
1326 $financialTypeID = $defaultContributionTypeID;
1329 if (CRM_Utils_Array
::value('membership_source', $form->_params
)) {
1330 $membershipParams['contribution_source'] = $form->_params
['membership_source'];
1333 if ($isPaidMembership) {
1334 $result = CRM_Contribute_BAO_Contribution_Utils
::processConfirm($form, $membershipParams,
1335 $premiumParams, $contactID,
1342 if (is_a($result[1], 'CRM_Core_Error')) {
1343 $errors[1] = CRM_Core_Error
::getMessages($result[1]);
1345 elseif (!empty($result[1])) {
1346 // Save the contribution ID so that I can be used in email receipts
1347 // For example, if you need to generate a tax receipt for the donation only.
1348 $form->_values
['contribution_other_id'] = $result[1]->id
;
1349 //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
1350 $membershipContribution = $result[1];
1354 if ($isProcessSeparateMembershipTransaction) {
1356 $lineItems = $form->_lineItem
= $membershipLineItems;
1357 $membershipContribution = self
::processSecondaryFinancialTransaction($contactID, $form, $membershipParams, $isTest, $membershipLineItems, CRM_Utils_Array
::value('minimum_fee', $membershipDetails, 0), CRM_Utils_Array
::value('financial_type_id', $membershipDetails));
1359 catch (CRM_Core_Exception
$e) {
1360 $errors[2] = $e->getMessage();
1361 $membershipContribution = NULL;
1366 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1367 $membershipContributionID = $membershipContribution->id
;
1370 //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
1371 if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
1372 $form->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
1374 //@todo it should no longer be possible for it to get to this point & membership to not be an array
1375 if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
1376 $typesTerms = CRM_Utils_Array
::value('types_terms', $membershipParams, array());
1377 foreach ($membershipTypeIDs as $memType) {
1378 $numTerms = CRM_Utils_Array
::value($memType, $typesTerms, 1);
1379 $createdMemberships[$memType] = self
::createOrRenewMembership($membershipParams, $contactID, $customFieldsFormatted, $membershipID, $memType, $isTest, $numTerms, $membershipContribution, $form);
1381 if ($form->_priceSetId
&& !empty($form->_useForMember
) && !empty($form->_lineItem
)) {
1382 foreach ($form->_lineItem
[$form->_priceSetId
] as & $priceFieldOp) {
1383 if (!empty($priceFieldOp['membership_type_id']) &&
1384 isset($createdMemberships[$priceFieldOp['membership_type_id']])
1386 $membershipOb = $createdMemberships[$priceFieldOp['membership_type_id']];
1387 $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date
::customFormat($membershipOb->start_date
, '%B %E%f, %Y') : '-';
1388 $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date
::customFormat($membershipOb->end_date
, '%B %E%f, %Y') : '-';
1391 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1394 $form->_values
['lineItem'] = $form->_lineItem
;
1395 $form->assign('lineItem', $form->_lineItem
);
1399 if (!empty($errors)) {
1400 $message = self
::compileErrorMessage($errors);
1401 throw new CRM_Core_Exception($message);
1403 $form->_params
['createdMembershipIDs'] = array();
1405 // CRM-7851 - Moved after processing Payment Errors
1406 //@todo - the reasoning for this being here seems a little outdated
1407 foreach ($createdMemberships as $createdMembership) {
1408 CRM_Core_BAO_CustomValueTable
::postProcess(
1410 CRM_Core_DAO
::$_nullArray,
1411 'civicrm_membership',
1412 $createdMembership->id
,
1415 $form->_params
['createdMembershipIDs'][] = $createdMembership->id
;
1417 if (count($createdMemberships) == 1) {
1418 //presumably this is only relevant for exactly 1 membership
1419 $form->_params
['membershipID'] = $createdMembership->id
;
1422 //CRM-15232: Check if membership is created and on the basis of it use
1423 //membership reciept template to send payment reciept
1424 if (count($createdMemberships)) {
1425 $form->_values
['isMembership'] = TRUE;
1427 if ($form->_contributeMode
== 'notify') {
1428 if ($form->_values
['is_monetary'] && $form->_amount
> 0.0 && !$form->_params
['is_pay_later']) {
1429 // call postProcess hook before leaving
1430 $form->postProcessHook();
1431 // this does not return
1432 $payment = CRM_Core_Payment
::singleton($form->_mode
, $form->_paymentProcessor
, $form);
1433 $payment->doTransferCheckout($form->_params
, 'contribute');
1437 if (isset($membershipContributionID)) {
1438 $form->_values
['contribution_id'] = $membershipContributionID;
1441 // Do not send an email if Recurring transaction is done via Direct Mode
1442 // Email will we sent when the IPN is received.
1443 if (!empty($form->_params
['is_recur']) && $form->_contributeMode
== 'direct') {
1444 if (!empty($membershipContribution->trxn_id
)) {
1446 civicrm_api3('contribution', 'completetransaction', array(
1447 'id' => $membershipContribution->id
,
1448 'trxn_id' => $membershipContribution->trxn_id
,
1451 catch (CiviCRM_API3_Exception
$e) {
1452 // if for any reason it is already completed this will fail - e.g extensions hacking around core not completing transactions prior to CRM-15296
1453 // so let's be gentle here
1454 CRM_Core_Error
::debug_log_message('contribution ' . $membershipContribution->id
. ' not completed with trxn_id ' . $membershipContribution->trxn_id
. ' and message ' . $e->getMessage());
1460 //finally send an email receipt
1461 CRM_Contribute_BAO_ContributionPage
::sendMail($contactID,
1469 * Function for updating a membership record's contribution_recur_id
1471 * @param CRM_Member_DAO_Membership $membership
1472 * @param \CRM_Contribute_BAO_Contribution|\CRM_Contribute_DAO_Contribution $contribution
1476 static public function updateRecurMembership(CRM_Member_DAO_Membership
$membership, CRM_Contribute_BAO_Contribution
$contribution) {
1478 if (empty($contribution->contribution_recur_id
)) {
1483 1 => array($contribution->contribution_recur_id
, 'Integer'),
1484 2 => array($membership->id
, 'Integer'),
1487 $sql = "UPDATE civicrm_membership SET contribution_recur_id = %1 WHERE id = %2";
1488 CRM_Core_DAO
::executeQuery($sql, $params);
1493 * A wrapper for renewing memberships from a form - including the form in the membership processing adds complexity
1494 * as the forms are being forced to pretend similarity
1495 * Try to call the renewMembership directly
1496 * @todo - this form method needs to have the interaction with the form layer removed from it
1497 * as a BAO function. Note that the api now supports membership renewals & it is not clear this function does anything
1498 * not done by the membership.create api (with a lot less unit tests)
1500 * This method will renew / create the membership depending on
1501 * whether the given contact has a membership or not. And will add
1502 * the modified dates for membership and in the log table.
1504 * @param int $contactID
1505 * Id of the contact.
1506 * @param int $membershipTypeID
1507 * Id of the new membership type.
1508 * @param bool $is_test
1509 * If this is test contribution or live contribution.
1510 * @param CRM_Core_Form $form
1512 * @param null $changeToday
1513 * @param int $modifiedID
1514 * Individual contact id in case of On Behalf signup (CRM-4027 ).
1515 * @param null $customFieldsFormatted
1516 * @param int $numRenewTerms
1517 * How many membership terms are being added to end date (default is 1).
1518 * @param int $membershipID
1519 * Membership ID, this should always be passed in & optionality should be removed.
1521 * @throws CRM_Core_Exception
1524 public static function renewMembershipFormWrapper(
1529 $changeToday = NULL,
1531 $customFieldsFormatted = NULL,
1533 $membershipID = NULL
1535 $statusFormat = '%Y-%m-%d';
1538 //@todo would be better to make $membershipID a compulsory function param & make form layer responsible for extracting it
1539 if (!$membershipID && isset($form->_membershipId
)) {
1540 $membershipID = $form->_membershipId
;
1543 //get all active statuses of membership.
1544 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1546 $membershipTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipTypeID);
1548 // check is it pending. - CRM-4555
1549 list($pending, $contributionRecurID, $changeToday, $membershipSource, $isPayLater, $campaignId) = self
::extractFormValues($form, $changeToday, $membershipTypeDetails);
1550 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);
1551 $form->set('renewal_mode', $renewalMode);
1552 if (!empty($dates)) {
1553 $form->assign('mem_start_date',
1554 CRM_Utils_Date
::customFormat($dates['start_date'], $format)
1556 $form->assign('mem_end_date',
1557 CRM_Utils_Date
::customFormat($dates['end_date'], $format)
1565 * Method to fix membership status of stale membership.
1567 * This method first checks if the membership is stale. If it is,
1568 * then status will be updated based on existing start and end
1569 * dates and log will be added for the status change.
1571 * @param array $currentMembership
1572 * Reference to the array.
1573 * containing all values of
1574 * the current membership
1575 * @param array $changeToday
1576 * Array of month, day, year.
1577 * values in case today needs
1578 * to be customised, null otherwise
1582 public static function fixMembershipStatusBeforeRenew(&$currentMembership, $changeToday) {
1585 $today = CRM_Utils_Date
::processDate($changeToday, NULL, FALSE, 'Y-m-d');
1588 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
1589 CRM_Utils_Array
::value('start_date', $currentMembership),
1590 CRM_Utils_Array
::value('end_date', $currentMembership),
1591 CRM_Utils_Array
::value('join_date', $currentMembership),
1594 $currentMembership['membership_type_id'],
1598 if (empty($status) ||
1599 empty($status['id'])
1601 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.'));
1604 $currentMembership['today_date'] = $today;
1606 if ($status['id'] !== $currentMembership['status_id']) {
1607 $memberDAO = new CRM_Member_DAO_Membership();
1608 $memberDAO->id
= $currentMembership['id'];
1609 $memberDAO->find(TRUE);
1611 $memberDAO->status_id
= $status['id'];
1612 $memberDAO->join_date
= CRM_Utils_Date
::isoToMysql($memberDAO->join_date
);
1613 $memberDAO->start_date
= CRM_Utils_Date
::isoToMysql($memberDAO->start_date
);
1614 $memberDAO->end_date
= CRM_Utils_Date
::isoToMysql($memberDAO->end_date
);
1616 CRM_Core_DAO
::storeValues($memberDAO, $currentMembership);
1619 $currentMembership['is_current_member'] = CRM_Core_DAO
::getFieldValue(
1620 'CRM_Member_DAO_MembershipStatus',
1621 $currentMembership['status_id'],
1627 'membership_id' => $currentMembership['id'],
1628 'status_id' => $status['id'],
1629 'start_date' => CRM_Utils_Date
::customFormat(
1630 $currentMembership['start_date'],
1633 'end_date' => CRM_Utils_Date
::customFormat(
1634 $currentMembership['end_date'],
1637 'modified_date' => CRM_Utils_Date
::customFormat(
1638 $currentMembership['today_date'],
1641 'membership_type_id' => $currentMembership['membership_type_id'],
1642 'max_related' => $currentMembership['max_related'],
1645 $session = CRM_Core_Session
::singleton();
1646 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
1647 if ($session->get('userID')) {
1648 $logParams['modified_id'] = $session->get('userID');
1651 $logParams['modified_id'] = $currentMembership['contact_id'];
1653 CRM_Member_BAO_MembershipLog
::add($logParams, CRM_Core_DAO
::$_nullArray);
1658 * Get the contribution page id from the membership record.
1660 * @param int $membershipID
1663 * contribution page id
1665 public static function getContributionPageId($membershipID) {
1667 SELECT c.contribution_page_id as pageID
1668 FROM civicrm_membership_payment mp, civicrm_contribution c
1669 WHERE mp.contribution_id = c.id
1670 AND c.contribution_page_id IS NOT NULL
1671 AND mp.membership_id = " . CRM_Utils_Type
::escape($membershipID, 'Integer')
1672 . " ORDER BY mp.id DESC";
1674 return CRM_Core_DAO
::singleValueQuery($query,
1675 CRM_Core_DAO
::$_nullArray
1680 * Updated related memberships.
1682 * @param int $ownerMembershipId
1683 * Owner Membership Id.
1684 * @param array $params
1685 * Formatted array of key => value.
1687 public static function updateRelatedMemberships($ownerMembershipId, $params) {
1688 $membership = new CRM_Member_DAO_Membership();
1689 $membership->owner_membership_id
= $ownerMembershipId;
1690 $membership->find();
1692 while ($membership->fetch()) {
1693 $relatedMembership = new CRM_Member_DAO_Membership();
1694 $relatedMembership->id
= $membership->id
;
1695 $relatedMembership->copyValues($params);
1696 $relatedMembership->save();
1697 $relatedMembership->free();
1700 $membership->free();
1704 * Get list of membership fields for profile.
1705 * For now we only allow custom membership fields to be in
1709 * FIXME: This param is ignored
1712 * the list of membership fields
1714 public static function getMembershipFields($mode = NULL) {
1715 $fields = CRM_Member_DAO_Membership
::export();
1717 unset($fields['membership_contact_id']);
1718 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1720 $membershipType = CRM_Member_DAO_MembershipType
::export();
1722 $membershipStatus = CRM_Member_DAO_MembershipStatus
::export();
1724 $fields = array_merge($fields, $membershipType, $membershipStatus);
1730 * Get the sort name of a contact for a particular membership.
1733 * Id of the membership.
1735 * @return null|string
1736 * sort name of the contact if found
1738 public static function sortName($id) {
1739 $id = CRM_Utils_Type
::escape($id, 'Integer');
1742 SELECT civicrm_contact.sort_name
1743 FROM civicrm_membership, civicrm_contact
1744 WHERE civicrm_membership.contact_id = civicrm_contact.id
1745 AND civicrm_membership.id = {$id}
1747 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1751 * Create memberships for related contacts.
1752 * takes into account the maximum related memberships
1754 * @param array $params
1755 * Array of key - value pairs.
1756 * @param CRM_Core_DAO $dao
1757 * Membership object.
1759 * @return null|array
1760 * array of memberships if created
1762 public static function createRelatedMemberships(&$params, &$dao, $reset = FALSE) {
1763 static $relatedContactIds = array();
1765 // not sure why a static var is in use here - we need a way to reset it from the test suite
1766 $relatedContactIds = array();
1770 $membership = new CRM_Member_DAO_Membership();
1771 $membership->id
= $dao->id
;
1773 // required since create method doesn't return all the
1774 // parameters in the returned membership object
1775 if (!$membership->find(TRUE)) {
1778 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1779 // FIXME : While updating/ renewing the
1780 // membership, if the relationship is PAST then
1781 // the membership of the related contact must be
1783 // For that, getting Membership Status for which
1784 // is_current_member is 0. It works for the
1785 // generated data as there is only one membership
1786 // status having is_current_member = 0.
1787 // But this wont work exactly if there will be
1788 // more than one status having is_current_member = 0.
1789 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
1790 $membershipStatus->is_current_member
= 0;
1791 if ($membershipStatus->find(TRUE)) {
1792 $expiredStatusId = $membershipStatus->id
;
1795 $expiredStatusId = array_search('Expired', CRM_Member_PseudoConstant
::membershipStatus());
1798 $allRelatedContacts = array();
1799 $relatedContacts = array();
1800 if (!is_a($membership, 'CRM_Core_Error')) {
1801 $allRelatedContacts = CRM_Member_BAO_Membership
::checkMembershipRelationship($membership->id
,
1802 $membership->contact_id
,
1803 CRM_Utils_Array
::value('action', $params)
1807 // check for loops. CRM-4213
1808 // remove repeated related contacts, which already inherited membership.
1809 $relatedContactIds[$membership->contact_id
] = TRUE;
1810 foreach ($allRelatedContacts as $cid => $status) {
1811 if (empty($relatedContactIds[$cid])) {
1812 $relatedContactIds[$cid] = TRUE;
1814 //don't create membership again for owner contact.
1815 $nestedRelationship = FALSE;
1816 if ($membership->owner_membership_id
) {
1817 $nestedRelMembership = new CRM_Member_DAO_Membership();
1818 $nestedRelMembership->id
= $membership->owner_membership_id
;
1819 $nestedRelMembership->contact_id
= $cid;
1820 $nestedRelationship = $nestedRelMembership->find(TRUE);
1821 $nestedRelMembership->free();
1823 if (!$nestedRelationship) {
1824 $relatedContacts[$cid] = $status;
1829 //lets cleanup related membership if any.
1830 if (empty($relatedContacts)) {
1831 self
::deleteRelatedMemberships($membership->id
);
1834 // Edit the params array
1835 unset($params['id']);
1836 // Reminder should be sent only to the direct membership
1837 unset($params['reminder_date']);
1838 // unset the custom value ids
1839 if (is_array(CRM_Utils_Array
::value('custom', $params))) {
1840 foreach ($params['custom'] as $k => $v) {
1841 unset($params['custom'][$k]['id']);
1844 if (!isset($params['membership_type_id'])) {
1845 $params['membership_type_id'] = $membership->membership_type_id
;
1848 // max_related should be set in the parent membership
1849 unset($params['max_related']);
1850 // Number of inherited memberships available - NULL is interpreted as unlimited, '0' as none
1851 $available = ($membership->max_related
== NULL ? PHP_INT_MAX
: $membership->max_related
);
1852 $queue = array(); // will be used to queue potential memberships to be created
1854 foreach ($relatedContacts as $contactId => $relationshipStatus) {
1855 //use existing membership record.
1856 $relMembership = new CRM_Member_DAO_Membership();
1857 $relMembership->contact_id
= $contactId;
1858 $relMembership->owner_membership_id
= $membership->id
;
1859 $relMemIds = array();
1860 if ($relMembership->find(TRUE)) {
1861 $params['id'] = $relMemIds['membership'] = $relMembership->id
;
1863 $params['contact_id'] = $contactId;
1864 $params['owner_membership_id'] = $membership->id
;
1866 // set status_id as it might have been changed for
1867 // past relationship
1868 $params['status_id'] = $membership->status_id
;
1870 if ($deceasedStatusId &&
1871 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'is_deceased')
1873 $params['status_id'] = $deceasedStatusId;
1875 elseif ((CRM_Utils_Array
::value('action', $params) & CRM_Core_Action
::UPDATE
) &&
1876 ($relationshipStatus == CRM_Contact_BAO_Relationship
::PAST
)
1878 $params['status_id'] = $expiredStatusId;
1881 //don't calculate status again in create( );
1882 $params['skipStatusCal'] = TRUE;
1884 //do create activity if we changed status.
1885 if ($params['status_id'] != $relMembership->status_id
) {
1886 $params['createActivity'] = TRUE;
1889 // we should not created contribution record for related contacts, CRM-3371
1890 unset($params['contribution_status_id']);
1892 if (($params['status_id'] == $deceasedStatusId) ||
($params['status_id'] == $expiredStatusId)) {
1893 // related membership is not active so does not count towards maximum
1894 CRM_Member_BAO_Membership
::create($params, $relMemIds);
1897 // related membership already exists, so this is just an update
1898 if (isset($params['id'])) {
1899 if ($available > 0) {
1900 CRM_Member_BAO_Membership
::create($params, $relMemIds);
1904 // we have run out of inherited memberships, so delete extras
1905 self
::deleteMembership($params['id']);
1907 // we need to first check if there will remain inherited memberships, so queue it up
1914 // now go over the queue and create any available related memberships
1916 while (($available > 0) && ($params = each($queue))) {
1917 CRM_Member_BAO_Membership
::create($params['value'], $relMemIds);
1924 * Delete the record that are associated with this Membership Payment.
1926 * @param int $membershipId
1929 * $membershipPayment deleted membership payment object
1931 public static function deleteMembershipPayment($membershipId) {
1933 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
1934 $membershipPayment->membership_id
= $membershipId;
1935 $membershipPayment->find();
1937 while ($membershipPayment->fetch()) {
1938 CRM_Contribute_BAO_Contribution
::deleteContribution($membershipPayment->contribution_id
);
1939 CRM_Utils_Hook
::pre('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1940 $membershipPayment->delete();
1941 CRM_Utils_Hook
::post('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1943 return $membershipPayment;
1947 * @param CRM_Core_Form $form
1948 * @param int $membershipTypeID
1952 public static function &buildMembershipTypeValues(&$form, $membershipTypeID = NULL) {
1953 $whereClause = " WHERE domain_id = " . CRM_Core_Config
::domainID();
1955 if (is_array($membershipTypeID)) {
1956 $allIDs = implode(',', $membershipTypeID);
1957 $whereClause .= " AND id IN ( $allIDs )";
1959 elseif (is_numeric($membershipTypeID) &&
1960 $membershipTypeID > 0
1962 $whereClause .= " AND id = $membershipTypeID";
1967 FROM civicrm_membership_type
1970 $dao = CRM_Core_DAO
::executeQuery($query);
1972 $membershipTypeValues = array();
1973 $membershipTypeFields = array(
1979 'financial_type_id',
1981 'member_of_contact_id',
1982 'relationship_type_id',
1983 'relationship_direction',
1987 while ($dao->fetch()) {
1988 $membershipTypeValues[$dao->id
] = array();
1989 foreach ($membershipTypeFields as $mtField) {
1990 $membershipTypeValues[$dao->id
][$mtField] = $dao->$mtField;
1995 CRM_Utils_Hook
::membershipTypeValues($form, $membershipTypeValues);
1997 if (is_numeric($membershipTypeID) &&
1998 $membershipTypeID > 0
2000 return $membershipTypeValues[$membershipTypeID];
2003 return $membershipTypeValues;
2008 * Get membership record count for a Contact.
2010 * @param int $contactID
2011 * @param bool $activeOnly
2013 * @return null|string
2015 public static function getContactMembershipCount($contactID, $activeOnly = FALSE) {
2016 $select = "SELECT count(*) FROM civicrm_membership ";
2017 $where = "WHERE civicrm_membership.contact_id = {$contactID} AND civicrm_membership.is_test = 0 ";
2019 // CRM-6627, all status below 3 (active, pending, grace) are considered active
2021 $select .= " INNER JOIN civicrm_membership_status ON civicrm_membership.status_id = civicrm_membership_status.id ";
2022 $where .= " and civicrm_membership_status.is_current_member = 1";
2025 $query = $select . $where;
2026 return CRM_Core_DAO
::singleValueQuery($query);
2030 * Check whether payment processor supports
2031 * cancellation of membership subscription
2036 * @param bool $isNotCancelled
2040 public static function isCancelSubscriptionSupported($mid, $isNotCancelled = TRUE) {
2041 $cacheKeyString = "$mid";
2042 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2044 static $supportsCancel = array();
2046 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2047 $supportsCancel[$cacheKeyString] = FALSE;
2048 $isCancelled = FALSE;
2050 if ($isNotCancelled) {
2051 $isCancelled = self
::isSubscriptionCancelled($mid);
2054 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($mid, 'membership', 'obj');
2055 if (!empty($paymentObject)) {
2056 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2059 return $supportsCancel[$cacheKeyString];
2063 * Check whether subscription is already cancelled.
2069 * contribution status
2071 public static function isSubscriptionCancelled($mid) {
2073 SELECT cr.contribution_status_id
2074 FROM civicrm_contribution_recur cr
2075 LEFT JOIN civicrm_membership mem ON ( cr.id = mem.contribution_recur_id )
2076 WHERE mem.id = %1 LIMIT 1";
2077 $params = array(1 => array($mid, 'Integer'));
2078 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2079 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
2080 if ($status == 'Cancelled') {
2087 * Get membership joins for a specified membership
2088 * type. Specifically, retrieves a count of still current memberships whose
2089 * join_date and start_date are within a specified date range. Dates match
2090 * the pattern "yyyy-mm-dd".
2092 * @param int $membershipTypeId
2093 * Membership type id.
2094 * @param int $startDate
2095 * Date on which to start counting.
2096 * @param int $endDate
2097 * Date on which to end counting.
2098 * @param bool|int $isTest if true, membership is for a test site
2101 * the number of members of type $membershipTypeId
2102 * whose join_date is between $startDate and $endDate and
2103 * whose start_date is between $startDate and $endDate
2105 public static function getMembershipJoins($membershipTypeId, $startDate, $endDate, $isTest = 0) {
2106 $testClause = 'membership.is_test = 1';
2108 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
2110 if (!self
::$_signupActType) {
2111 self
::_getActTypes();
2114 if (!self
::$_signupActType) {
2119 SELECT COUNT(DISTINCT membership.id) as member_count
2120 FROM civicrm_membership membership
2121 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
2122 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
2123 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
2124 WHERE membership.membership_type_id = %2
2125 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
2129 1 => array(self
::$_signupActType, 'Integer'),
2130 2 => array($membershipTypeId, 'Integer'),
2133 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
2135 return (int) $memberCount;
2139 * Get membership renewals for a specified membership
2140 * type. Specifically, retrieves a count of still current memberships
2141 * whose join_date is before and start_date is within a specified date
2142 * range. Dates match the pattern "yyyy-mm-dd".
2144 * @param int $membershipTypeId
2145 * Membership type id.
2146 * @param int $startDate
2147 * Date on which to start counting.
2148 * @param int $endDate
2149 * Date on which to end counting.
2150 * @param bool|int $isTest if true, membership is for a test site
2153 * returns the number of members of type $membershipTypeId
2154 * whose join_date is before $startDate and
2155 * whose start_date is between $startDate and $endDate
2157 public static function getMembershipRenewals($membershipTypeId, $startDate, $endDate, $isTest = 0) {
2158 $testClause = 'membership.is_test = 1';
2160 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
2162 if (!self
::$_renewalActType) {
2163 self
::_getActTypes();
2166 if (!self
::$_renewalActType) {
2171 SELECT COUNT(DISTINCT membership.id) as member_count
2172 FROM civicrm_membership membership
2173 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
2174 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
2175 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
2176 WHERE membership.membership_type_id = %2
2177 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
2181 1 => array(self
::$_renewalActType, 'Integer'),
2182 2 => array($membershipTypeId, 'Integer'),
2184 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
2186 return (int) $memberCount;
2190 * Where a second separate financial transaction is supported we will process it here.
2192 * @param int $contactID
2193 * @param CRM_Contribute_Form_Contribution_Confirm $form
2194 * @param array $tempParams
2196 * @param array $lineItems
2197 * @param $minimumFee
2198 * @param int $financialTypeID
2200 * @throws CRM_Core_Exception
2202 * @return CRM_Contribute_BAO_Contribution
2204 public static function processSecondaryFinancialTransaction($contactID, &$form, $tempParams, $isTest, $lineItems, $minimumFee, $financialTypeID) {
2205 $financialType = new CRM_Financial_DAO_FinancialType();
2206 $financialType->id
= $financialTypeID;
2207 if (!$financialType->find(TRUE)) {
2208 CRM_Core_Error
::fatal(ts("Could not find a system table"));
2210 $tempParams['amount'] = $minimumFee;
2211 $tempParams['invoiceID'] = md5(uniqid(rand(), TRUE));
2214 if ($form->_values
['is_monetary'] && !$form->_params
['is_pay_later'] && $minimumFee > 0.0) {
2215 $payment = CRM_Core_Payment
::singleton($form->_mode
, $form->_paymentProcessor
, $form);
2217 if ($form->_contributeMode
== 'express') {
2218 $result = $payment->doExpressCheckout($tempParams);
2219 if (is_a($result, 'CRM_Core_Error')) {
2220 throw new CRM_Core_Exception(CRM_Core_Error
::getMessages($result));
2224 $result = $payment->doPayment($tempParams, 'contribute');
2228 //assign receive date when separate membership payment
2229 //and contribution amount not selected.
2230 if ($form->_amount
== 0) {
2231 $now = date('YmdHis');
2232 $form->_params
['receive_date'] = $now;
2233 $receiveDate = CRM_Utils_Date
::mysqlToIso($now);
2234 $form->set('params', $form->_params
);
2235 $form->assign('receive_date', $receiveDate);
2238 $form->set('membership_trx_id', $result['trxn_id']);
2239 $form->set('membership_amount', $minimumFee);
2241 $form->assign('membership_trx_id', $result['trxn_id']);
2242 $form->assign('membership_amount', $minimumFee);
2244 // we don't need to create the user twice, so lets disable cms_create_account
2245 // irrespective of the value, CRM-2888
2246 $tempParams['cms_create_account'] = 0;
2248 $pending = $form->_params
['is_pay_later'] ?
(($minimumFee > 0.0) ?
TRUE : FALSE) : FALSE;
2250 //set this variable as we are not creating pledge for
2251 //separate membership payment contribution.
2252 //so for differentiating membership contribution from
2253 //main contribution.
2254 $form->_params
['separate_membership_payment'] = 1;
2255 $membershipContribution = CRM_Contribute_Form_Contribution_Confirm
::processContribution($form,
2265 return $membershipContribution;
2269 * Create linkages between membership & contribution - note this is the wrong place for this code but this is a
2270 * refactoring step. This should be BAO functionality
2271 * @param $membership
2272 * @param $membershipContribution
2274 public static function linkMembershipPayment($membership, $membershipContribution) {
2275 CRM_Member_BAO_MembershipPayment
::create(array(
2276 'membership_id' => $membership->id
,
2277 'contribution_id' => $membershipContribution->id
,
2282 * @param array $membershipParams
2283 * @param int $contactID
2284 * @param $customFieldsFormatted
2285 * @param int $membershipID
2289 * @param $membershipContribution
2290 * @param CRM_Core_Form $form
2294 public static function createOrRenewMembership($membershipParams, $contactID, $customFieldsFormatted, $membershipID, $memType, $isTest, $numTerms, $membershipContribution, &$form) {
2295 $membership = self
::renewMembershipFormWrapper($contactID, $memType,
2296 $isTest, $form, NULL,
2297 CRM_Utils_Array
::value('cms_contactID', $membershipParams),
2298 $customFieldsFormatted, $numTerms,
2302 if (!empty($membershipContribution)) {
2303 // update recurring id for membership record
2304 self
::updateRecurMembership($membership, $membershipContribution);
2306 self
::linkMembershipPayment($membership, $membershipContribution);
2312 * Turn array of errors into message string.
2314 * @param array $errors
2318 public static function compileErrorMessage($errors) {
2319 foreach ($errors as $error) {
2320 if (is_string($error)) {
2321 $message[] = $error;
2324 return ts('Payment Processor Error message') . ': ' . implode('<br/>', $message);
2328 * Extract relevant values from the form so we can separate form logic from BAO logcis.
2330 * @param CRM_Core_Form $form
2331 * @param $changeToday
2332 * @param $membershipTypeDetails
2336 public static function extractFormValues($form, $changeToday, $membershipTypeDetails) {
2338 //@todo this is a BAO function & should not inspect the form - the form should do this
2339 // & pass required params to the BAO
2340 if (CRM_Utils_Array
::value('minimum_fee', $membershipTypeDetails) > 0.0) {
2341 if (((isset($form->_contributeMode
) && $form->_contributeMode
== 'notify') ||
!empty($form->_params
['is_pay_later']) ||
2342 (!empty($form->_params
['is_recur']) && $form->_contributeMode
== 'direct'
2345 (($form->_values
['is_monetary'] && $form->_amount
> 0.0) ||
!empty($form->_params
['separate_membership_payment']) ||
2346 CRM_Utils_Array
::value('record_contribution', $form->_params
)
2352 $contributionRecurID = isset($form->_params
['contributionRecurID']) ?
$form->_params
['contributionRecurID'] : NULL;
2354 //we renew expired membership, CRM-6277
2355 if (!$changeToday) {
2356 if ($form->get('renewalDate')) {
2357 $changeToday = $form->get('renewalDate');
2359 elseif (get_class($form) == 'CRM_Contribute_Form_Contribution_Confirm') {
2360 $changeToday = date('YmdHis');
2364 $membershipSource = NULL;
2365 if (!empty($form->_params
['membership_source'])) {
2366 $membershipSource = $form->_params
['membership_source'];
2368 elseif (isset($form->_values
['title']) && !empty($form->_values
['title'])) {
2369 $membershipSource = ts('Online Contribution:') . ' ' . $form->_values
['title'];
2372 if (isset($form->_params
)) {
2373 $isPayLater = CRM_Utils_Array
::value('is_pay_later', $form->_params
);
2376 if (isset($form->_values
) && is_array($form->_values
) && !empty($form->_values
)) {
2377 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_params
);
2378 if (!array_key_exists('campaign_id', $form->_params
)) {
2379 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_values
);
2382 return array($pending, $contributionRecurID, $changeToday, $membershipSource, $isPayLater, $campaignId);
2386 * @param int $contactID
2387 * @param int $membershipTypeID
2388 * @param bool $is_test
2389 * @param $changeToday
2390 * @param int $modifiedID
2391 * @param $customFieldsFormatted
2392 * @param $numRenewTerms
2393 * @param int $membershipID
2396 * @param array $membershipTypeDetails
2397 * @param int $contributionRecurID
2399 * @param $membershipSource
2401 * @param $statusFormat
2402 * @param $isPayLater
2403 * @param int $campaignId
2405 * @throws CRM_Core_Exception
2408 public static function renewMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $allStatus, $membershipTypeDetails, $contributionRecurID, $format, $membershipSource, $ids, $statusFormat, $isPayLater, $campaignId) {
2409 $renewalMode = $updateStatusId = FALSE;
2411 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
2412 // is the same as the parent org of an existing membership of the contact
2413 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($contactID, $membershipTypeID,
2414 $is_test, $membershipID, TRUE
2416 if ($currentMembership) {
2417 $activityType = 'Membership Renewal';
2418 $renewalMode = TRUE;
2420 // Do NOT do anything.
2421 //1. membership with status : PENDING/CANCELLED (CRM-2395)
2422 //2. Paylater/IPN renew. CRM-4556.
2423 if ($pending ||
in_array($currentMembership['status_id'], array(
2424 array_search('Pending', $allStatus),
2426 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
2429 $membership = new CRM_Member_DAO_Membership();
2430 $membership->id
= $currentMembership['id'];
2431 $membership->find(TRUE);
2433 // CRM-8141 create a membership_log entry so that we will know the membership_type_id to change to when payment completed
2435 // note that we are logging the requested new membership_type_id that may be different than current membership_type_id
2436 // it will be used when payment is received to update the membership_type_id to what was paid for
2438 'membership_id' => $membership->id
,
2439 'status_id' => $membership->status_id
,
2440 'start_date' => CRM_Utils_Date
::customFormat(
2441 $membership->start_date
,
2444 'end_date' => CRM_Utils_Date
::customFormat(
2445 $membership->end_date
,
2448 'modified_date' => CRM_Utils_Date
::customFormat(
2452 'membership_type_id' => $membershipTypeID,
2453 'max_related' => !empty($membershipTypeDetails['max_related']) ?
$membershipTypeDetails['max_related'] : NULL,
2455 $session = CRM_Core_Session
::singleton();
2456 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
2457 if ($session->get('userID')) {
2458 $logParams['modified_id'] = $session->get('userID');
2461 $logParams['modified_id'] = $membership->contact_id
;
2463 CRM_Member_BAO_MembershipLog
::add($logParams, CRM_Core_DAO
::$_nullArray);
2465 if (!empty($contributionRecurID)) {
2466 CRM_Core_DAO
::setFieldValue('CRM_Member_DAO_Membership', $membership->id
,
2467 'contribution_recur_id', $contributionRecurID
2471 return array($membership, $renewalMode, $dates);
2474 // Check and fix the membership if it is STALE
2475 self
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
2477 // Now Renew the membership
2478 if (!$currentMembership['is_current_member']) {
2479 // membership is not CURRENT
2481 // CRM-7297 Membership Upsell - calculate dates based on new membership type
2482 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($currentMembership['id'],
2488 $currentMembership['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
2489 $currentMembership['start_date'] = CRM_Utils_Array
::value('start_date', $dates);
2490 $currentMembership['end_date'] = CRM_Utils_Array
::value('end_date', $dates);
2491 $currentMembership['is_test'] = $is_test;
2493 if (!empty($membershipSource)) {
2494 $currentMembership['source'] = $membershipSource;
2497 $currentMembership['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
2498 $currentMembership['id'],
2503 if (!empty($currentMembership['id'])) {
2504 $ids['membership'] = $currentMembership['id'];
2506 $memParams = $currentMembership;
2507 $memParams['membership_type_id'] = $membershipTypeID;
2509 //set the log start date.
2510 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
2514 // CURRENT Membership
2515 $membership = new CRM_Member_DAO_Membership();
2516 $membership->id
= $currentMembership['id'];
2517 $membership->find(TRUE);
2518 // CRM-7297 Membership Upsell - calculate dates based on new membership type
2519 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
2525 // Insert renewed dates for CURRENT membership
2526 $memParams = array();
2527 $memParams['join_date'] = CRM_Utils_Date
::isoToMysql($membership->join_date
);
2528 $memParams['start_date'] = CRM_Utils_Date
::isoToMysql($membership->start_date
);
2529 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $dates);
2530 $memParams['membership_type_id'] = $membershipTypeID;
2532 //set the log start date.
2533 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
2534 if (empty($membership->source
)) {
2535 if (!empty($membershipSource)) {
2536 $memParams['source'] = $membershipSource;
2539 $memParams['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
2540 $currentMembership['id'],
2546 if (!empty($currentMembership['id'])) {
2547 $ids['membership'] = $currentMembership['id'];
2552 $updateStatusId = array_search('Pending', $allStatus);
2558 $activityType = 'Membership Signup';
2560 'contact_id' => $contactID,
2561 'membership_type_id' => $membershipTypeID,
2565 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
2567 $memParams['join_date'] = CRM_Utils_Array
::value('join_date', $dates);
2568 $memParams['start_date'] = CRM_Utils_Array
::value('start_date', $dates);
2569 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $dates);
2571 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(CRM_Utils_Date
::customFormat($dates['start_date'],
2574 CRM_Utils_Date
::customFormat($dates['end_date'],
2577 CRM_Utils_Date
::customFormat($dates['join_date'],
2585 $updateStatusId = CRM_Utils_Array
::value('id', $status);
2588 // if IPN/Pay-Later set status to: PENDING
2589 $updateStatusId = array_search('Pending', $allStatus);
2592 if (!empty($membershipSource)) {
2593 $memParams['source'] = $membershipSource;
2595 $memParams['contribution_recur_id'] = $contributionRecurID;
2597 $memParams['is_test'] = $is_test;
2598 $memParams['is_pay_later'] = $isPayLater;
2602 //if we decided status here and want to skip status
2603 //calculation in create( ); then need to pass 'skipStatusCal'.
2604 if ($updateStatusId) {
2605 $memParams['status_id'] = $updateStatusId;
2606 $memParams['skipStatusCal'] = TRUE;
2609 //since we are renewing,
2610 //make status override false.
2611 $memParams['is_override'] = FALSE;
2613 //CRM-4027, create log w/ individual contact.
2615 $ids['userId'] = $modifiedID;
2616 $memParams['is_for_organization'] = TRUE;
2619 $ids['userId'] = $contactID;
2622 //inherit campaign from contrib page.
2623 if (isset($campaignId)) {
2624 $memParams['campaign_id'] = $campaignId;
2627 $memParams['custom'] = $customFieldsFormatted;
2628 $membership = self
::create($memParams, $ids, FALSE, $activityType);
2630 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
2631 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
2632 $membership->find(TRUE);
2634 return array($membership, $renewalMode, $dates);
2638 * Process price set and line items.
2640 * @param int $membershipId
2645 public function processPriceSet($membershipId, $lineItem) {
2646 //FIXME : need to move this too
2647 if (!$membershipId ||
!is_array($lineItem)
2648 || CRM_Utils_System
::isNull($lineItem)
2653 foreach ($lineItem as $priceSetId => $values) {
2657 foreach ($values as $line) {
2658 $line['entity_table'] = 'civicrm_membership';
2659 $line['entity_id'] = $membershipId;
2660 CRM_Price_BAO_LineItem
::create($line);
2666 * Retrieve the contribution id for the associated Membership id.
2667 * @todo we should get this off the line item
2669 * @param int $membershipId
2675 public static function getMembershipContributionId($membershipId) {
2677 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
2678 $membershipPayment->membership_id
= $membershipId;
2679 if ($membershipPayment->find(TRUE)) {
2680 return $membershipPayment->contribution_id
;
2686 * The function checks and updates the status of all membership records for a given domain using the
2687 * calc_membership_status and update_contact_membership APIs.
2690 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
2694 public static function updateAllMembershipStatus() {
2696 //get all active statuses of membership, CRM-3984
2697 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2698 $statusLabels = CRM_Member_PseudoConstant
::membershipStatus(NULL, NULL, 'label');
2699 $allTypes = CRM_Member_PseudoConstant
::membershipType();
2701 // get only memberships with active membership types
2703 SELECT civicrm_membership.id as membership_id,
2704 civicrm_membership.is_override as is_override,
2705 civicrm_membership.membership_type_id as membership_type_id,
2706 civicrm_membership.status_id as status_id,
2707 civicrm_membership.join_date as join_date,
2708 civicrm_membership.start_date as start_date,
2709 civicrm_membership.end_date as end_date,
2710 civicrm_membership.source as source,
2711 civicrm_contact.id as contact_id,
2712 civicrm_contact.is_deceased as is_deceased,
2713 civicrm_membership.owner_membership_id as owner_membership_id,
2714 civicrm_membership.contribution_recur_id as recur_id
2715 FROM civicrm_membership
2716 INNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )
2717 INNER JOIN civicrm_membership_type ON
2718 (civicrm_membership.membership_type_id = civicrm_membership_type.id AND civicrm_membership_type.is_active = 1)
2719 WHERE civicrm_membership.is_test = 0";
2722 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2727 $smarty = CRM_Core_Smarty
::singleton();
2729 while ($dao->fetch()) {
2733 // Put common parameters into array for easy access
2734 $memberParams = array(
2735 'id' => $dao->membership_id
,
2736 'status_id' => $dao->status_id
,
2737 'contact_id' => $dao->contact_id
,
2738 'membership_type_id' => $dao->membership_type_id
,
2739 'membership_type' => $allTypes[$dao->membership_type_id
],
2740 'join_date' => $dao->join_date
,
2741 'start_date' => $dao->start_date
,
2742 'end_date' => $dao->end_date
,
2743 'source' => $dao->source
,
2744 'skipStatusCal' => TRUE,
2745 'skipRecentView' => TRUE,
2748 $smarty->assign_by_ref('memberParams', $memberParams);
2750 //update membership record to Deceased if contact is deceased
2751 if ($dao->is_deceased
) {
2752 // check for 'Deceased' membership status, CRM-5636
2753 $deceaseStatusId = array_search('Deceased', $allStatus);
2754 if (!$deceaseStatusId) {
2755 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'))));
2758 //process only when status change.
2759 if ($dao->status_id
!= $deceaseStatusId) {
2760 //take all params that need to save.
2761 $deceasedMembership = $memberParams;
2762 $deceasedMembership['status_id'] = $deceaseStatusId;
2763 $deceasedMembership['createActivity'] = TRUE;
2764 $deceasedMembership['version'] = 3;
2766 //since there is change in status.
2767 $statusChange = array('status_id' => $deceaseStatusId);
2768 $smarty->append_by_ref('memberParams', $statusChange, TRUE);
2770 $deceasedMembership['contact_id'],
2771 $deceasedMembership['membership_type_id'],
2772 $deceasedMembership['membership_type'],
2773 $deceasedMembership['join_date'],
2774 $deceasedMembership['start_date'],
2775 $deceasedMembership['end_date'],
2776 $deceasedMembership['source']
2779 //process membership record.
2780 civicrm_api('membership', 'create', $deceasedMembership);
2785 //we fetch related, since we need to check for deceased
2786 //now further processing is handle w/ main membership record.
2787 if ($dao->owner_membership_id
) {
2791 //update membership records where status is NOT - Pending OR Cancelled.
2792 //as well as membership is not override.
2793 //skipping Expired membership records -> reduced extra processing( kiran )
2794 if (!$dao->is_override
&&
2795 !in_array($dao->status_id
, array(
2796 array_search('Pending', $allStatus),
2800 CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)
2802 array_search('Expired', $allStatus),
2806 // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses
2807 //get the membership status as per id.
2808 $newStatus = civicrm_api('membership_status', 'calc',
2810 'membership_id' => $dao->membership_id
,
2812 'ignore_admin_only' => FALSE,
2815 $statusId = CRM_Utils_Array
::value('id', $newStatus);
2817 //process only when status change.
2819 $statusId != $dao->status_id
2821 //take all params that need to save.
2822 $memParams = $memberParams;
2823 $memParams['status_id'] = $statusId;
2824 $memParams['createActivity'] = TRUE;
2825 $memParams['version'] = 3;
2827 // Unset columns which should remain unchanged from their current saved
2828 // values. This avoids race condition in which these values may have
2829 // been changed by other processes.
2831 $memParams['contact_id'],
2832 $memParams['membership_type_id'],
2833 $memParams['membership_type'],
2834 $memParams['join_date'],
2835 $memParams['start_date'],
2836 $memParams['end_date'],
2837 $memParams['source']
2839 //since there is change in status.
2840 $statusChange = array('status_id' => $statusId);
2841 $smarty->append_by_ref('memberParams', $statusChange, TRUE);
2843 //process member record.
2844 civicrm_api('membership', 'create', $memParams);
2849 $result['is_error'] = 0;
2850 $result['messages'] = ts('Processed %1 membership records. Updated %2 records.', array(
2858 * Returns the membership types for a particular contact
2859 * who has lifetime membership without end date.
2861 * @param int $contactID
2862 * @param bool $isTest
2863 * @param bool $onlyLifeTime
2867 public static function getAllContactMembership($contactID, $isTest = FALSE, $onlyLifeTime = FALSE) {
2868 $contactMembershipType = array();
2870 return $contactMembershipType;
2873 $dao = new CRM_Member_DAO_Membership();
2874 $dao->contact_id
= $contactID;
2875 $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
2876 $dao->whereAdd("status_id != $pendingStatusId");
2879 $dao->is_test
= $isTest;
2882 $dao->whereAdd('is_test IS NULL OR is_test = 0');
2885 if ($onlyLifeTime) {
2886 $dao->whereAdd('end_date IS NULL');
2890 while ($dao->fetch()) {
2891 $membership = array();
2892 CRM_Core_DAO
::storeValues($dao, $membership);
2893 $contactMembershipType[$dao->membership_type_id
] = $membership;
2895 return $contactMembershipType;
2899 * Record contribution record associated with membership.
2901 * @param array $params
2902 * Array of submitted params.
2904 * (param in process of being removed - try to use params) array of ids.
2906 * @return CRM_Contribute_BAO_Contribution
2908 public static function recordMembershipContribution(&$params, $ids = array()) {
2909 $membershipId = $params['membership_id'];
2910 $contributionParams = array();
2911 $config = CRM_Core_Config
::singleton();
2912 $contributionParams['currency'] = $config->defaultCurrency
;
2913 $contributionParams['receipt_date'] = (CRM_Utils_Array
::value('receipt_date', $params)) ?
$params['receipt_date'] : 'null';
2914 $contributionParams['source'] = CRM_Utils_Array
::value('contribution_source', $params);
2915 $contributionParams['non_deductible_amount'] = 'null';
2916 $contributionParams['payment_processor'] = CRM_Utils_Array
::value('payment_processor_id', $params);
2917 $contributionSoftParams = CRM_Utils_Array
::value('soft_credit', $params);
2918 $recordContribution = array(
2922 'financial_type_id',
2923 'payment_instrument_id',
2927 'contribution_status_id',
2935 foreach ($recordContribution as $f) {
2936 $contributionParams[$f] = CRM_Utils_Array
::value($f, $params);
2939 // make entry in batch entity batch table
2940 if (!empty($params['batch_id'])) {
2941 $contributionParams['batch_id'] = $params['batch_id'];
2944 if (!empty($params['contribution_contact_id'])) {
2945 // deal with possibility of a different person paying for contribution
2946 $contributionParams['contact_id'] = $params['contribution_contact_id'];
2949 if (!empty($params['processPriceSet']) &&
2950 !empty($params['lineItems'])
2952 $contributionParams['line_item'] = CRM_Utils_Array
::value('lineItems', $params, NULL);
2955 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
2957 //CRM-13981, create new soft-credit record as to record payment from different person for this membership
2958 if (!empty($contributionSoftParams)) {
2959 if (!empty($params['batch_id'])) {
2960 foreach ($contributionSoftParams as $contributionSoft) {
2961 $contributionSoft['contribution_id'] = $contribution->id
;
2962 $contributionSoft['currency'] = $contribution->currency
;
2963 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoft);
2967 $contributionSoftParams['contribution_id'] = $contribution->id
;
2968 $contributionSoftParams['currency'] = $contribution->currency
;
2969 $contributionSoftParams['amount'] = $contribution->total_amount
;
2970 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoftParams);
2974 // store contribution id
2975 $params['contribution_id'] = $contribution->id
;
2977 //insert payment record for this membership
2978 if (empty($ids['contribution']) ||
!empty($params['is_recur'])) {
2979 CRM_Member_BAO_MembershipPayment
::create(array(
2980 'membership_id' => $membershipId,
2981 'contribution_id' => $contribution->id
,
2984 return $contribution;
2988 * Record line items for default membership.
2990 * @param CRM_Core_Form $qf
2991 * @param array $membershipType
2992 * Array with membership type and organization.
2993 * @param int $priceSetId
2996 public static function createLineItems(&$qf, $membershipType, &$priceSetId) {
2997 $qf->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
2999 $qf->_priceSet
= $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
3001 $editedFieldParams = array(
3002 'price_set_id' => $priceSetId,
3003 'name' => $membershipType[0],
3005 $editedResults = array();
3006 CRM_Price_BAO_PriceField
::retrieve($editedFieldParams, $editedResults);
3008 if (!empty($editedResults)) {
3009 unset($qf->_priceSet
['fields']);
3010 $qf->_priceSet
['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
3011 unset($qf->_priceSet
['fields'][$editedResults['id']]['options']);
3012 $fid = $editedResults['id'];
3013 $editedFieldParams = array(
3014 'price_field_id' => $editedResults['id'],
3015 'membership_type_id' => $membershipType[1],
3017 $editedResults = array();
3018 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $editedResults);
3019 $qf->_priceSet
['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
3020 if (!empty($qf->_params
['total_amount'])) {
3021 $qf->_priceSet
['fields'][$fid]['options'][$editedResults['id']]['amount'] = $qf->_params
['total_amount'];
3025 $fieldID = key($qf->_priceSet
['fields']);
3026 $qf->_params
['price_' . $fieldID] = CRM_Utils_Array
::value('id', $editedResults);
3030 * @todo document me - I seem a bit out of date....
3032 public static function _getActTypes() {
3033 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
3034 self
::$_renewalActType = CRM_Utils_Array
::key('Membership Renewal', $activityTypes);
3035 self
::$_signupActType = CRM_Utils_Array
::key('Membership Signup', $activityTypes);
3039 * Get all Cancelled Membership(s) for a contact
3041 * @param int $contactID
3043 * @param bool $isTest
3047 * Array of membership type
3049 public static function getContactsCancelledMembership($contactID, $isTest = FALSE) {
3053 $query = 'SELECT membership_type_id FROM civicrm_membership WHERE contact_id = %1 AND status_id = %2 AND is_test = %3';
3054 $queryParams = array(
3055 1 => array($contactID, 'Integer'),
3060 CRM_Member_PseudoConstant
::membershipStatus(
3062 " name = 'Cancelled' ",
3070 3 => array($isTest, 'Boolean'),
3073 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
3074 $cancelledMembershipIds = array();
3075 while ($dao->fetch()) {
3076 $cancelledMembershipIds[] = $dao->membership_type_id
;
3078 return $cancelledMembershipIds;