3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
35 class CRM_Member_BAO_Membership
extends CRM_Member_DAO_Membership
{
38 * Static field for all the membership information that we can potentially import
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 dont 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.
198 * @return CRM_Member_BAO_Membership|null the found object or null
200 public static function &getValues(&$params, &$values, $active = 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;
227 * Takes an associative array and creates a membership object
229 * @param array $params
230 * (reference ) an assoc array of name/value pairs.
232 * The array that holds all the db ids.
233 * @param bool $skipRedirect
234 * @param string $activityType
236 * @throws CRM_Core_Exception
238 * @return CRM_Member_BAO_Membership|CRM_Core_Error
240 public static function create(&$params, &$ids, $skipRedirect = FALSE, $activityType = 'Membership Signup') {
241 // always calculate status if is_override/skipStatusCal is not true.
242 // giving respect to is_override during import. CRM-4012
244 // To skip status calculation we should use 'skipStatusCal'.
245 // eg pay later membership, membership update cron CRM-3984
247 if (empty($params['is_override']) && empty($params['skipStatusCal'])) {
248 $dates = array('start_date', 'end_date', 'join_date');
249 $start_date = $end_date = $join_date = NULL; // declare these out of courtesy as IDEs don't pick up the setting of them below
250 foreach ($dates as $date) {
251 $
$date = $params[$date] = CRM_Utils_Date
::processDate(CRM_Utils_Array
::value($date, $params), NULL, TRUE, 'Ymd');
254 //fix for CRM-3570, during import exclude the statuses those having is_admin = 1
255 $excludeIsAdmin = CRM_Utils_Array
::value('exclude_is_admin', $params, FALSE);
257 //CRM-3724 always skip is_admin if is_override != true.
258 if (!$excludeIsAdmin && empty($params['is_override'])) {
259 $excludeIsAdmin = TRUE;
262 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($start_date, $end_date, $join_date,
263 'today', $excludeIsAdmin, CRM_Utils_Array
::value('membership_type_id', $params), $params
265 if (empty($calcStatus)) {
266 // Redirect the form in case of error
267 // @todo this redirect in the BAO layer is really bad & should be moved to the form layer
268 // however since we have no idea how (if) this is triggered we can't safely move / remove it
269 // NB I tried really hard to trigger this error from backoffice membership form in order to test it
270 // and am convinced form validation is complete on that form WRT this error.
271 $errorParams = array(
272 'message_title' => ts('No valid membership status for given dates.'),
273 'legacy_redirect_path' => 'civicrm/contact/view',
274 'legacy_redirect_query' => "reset=1&force=1&cid={$params['contact_id']}&selectedChild=member",
276 throw new CRM_Core_Exception(ts('The membership cannot be saved because the status cannot be calculated.'), 0, $errorParams);
278 $params['status_id'] = $calcStatus['id'];
281 // data cleanup only: all verifications on number of related memberships are done upstream in:
282 // CRM_Member_BAO_Membership::createRelatedMemberships()
283 // CRM_Contact_BAO_Relationship::relatedMemberships()
284 if (isset($params['owner_membership_id'])) {
285 unset($params['max_related']);
288 // if membership allows related, default max_related to value in membership_type
289 if (!array_key_exists('max_related', $params) && !empty($params['membership_type_id'])) {
290 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($params['membership_type_id']);
291 if (isset($membershipType['relationship_type_id'])) {
292 $params['max_related'] = CRM_Utils_Array
::value('max_related', $membershipType);
297 $transaction = new CRM_Core_Transaction();
299 $membership = self
::add($params, $ids);
301 if (is_a($membership, 'CRM_Core_Error')) {
302 $transaction->rollback();
306 // add custom field values
307 if (!empty($params['custom']) && is_array($params['custom'])
309 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_membership', $membership->id
);
312 $params['membership_id'] = $membership->id
;
313 if (isset($ids['membership'])) {
314 $ids['contribution'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment',
321 $params['skipLineItem'] = TRUE;
323 //record contribution for this membership
324 if (!empty($params['contribution_status_id']) && empty($params['relate_contribution_id'])) {
325 $memInfo = array_merge($params, array('membership_id' => $membership->id
));
326 $params['contribution'] = self
::recordMembershipContribution($memInfo, $ids);
329 if (!empty($params['lineItems'])) {
330 $params['line_item'] = $params['lineItems'];
333 //do cleanup line items if membership edit the Membership type.
334 if (empty($ids['contribution']) && !empty($ids['membership'])) {
335 CRM_Price_BAO_LineItem
::deleteLineItems($ids['membership'], 'civicrm_membership');
338 if (!empty($params['line_item']) && empty($ids['contribution'])) {
339 CRM_Price_BAO_LineItem
::processPriceSet($membership->id
, $params['line_item'], CRM_Utils_Array
::value('contribution', $params));
342 //insert payment record for this membership
343 if (!empty($params['relate_contribution_id'])) {
344 CRM_Member_BAO_MembershipPayment
::create(array(
345 'membership_id' => $membership->id
,
346 'contribution_id' => $params['relate_contribution_id'],
350 // add activity record only during create mode and renew mode
351 // also add activity if status changed CRM-3984 and CRM-2521
352 if (empty($ids['membership']) ||
353 $activityType == 'Membership Renewal' ||
!empty($params['createActivity'])
355 if (!empty($ids['membership'])) {
357 CRM_Core_DAO
::commonRetrieveAll('CRM_Member_DAO_Membership',
361 array('contact_id', 'membership_type_id', 'source')
364 $membership->contact_id
= $data[$membership->id
]['contact_id'];
365 $membership->membership_type_id
= $data[$membership->id
]['membership_type_id'];
366 $membership->source
= CRM_Utils_Array
::value('source', $data[$membership->id
]);
369 // since we are going to create activity record w/
370 // individual contact as a target in case of on behalf signup,
371 // so get the copy of organization id, CRM-5551
372 $realMembershipContactId = $membership->contact_id
;
374 // create activity source = individual, target = org CRM-4027
375 $targetContactID = NULL;
376 if (!empty($params['is_for_organization'])) {
377 $targetContactID = $membership->contact_id
;
378 $membership->contact_id
= CRM_Utils_Array
::value('userId', $ids);
381 if (empty($membership->contact_id
) && (!empty($membership->owner_membership_id
))) {
382 $membership->contact_id
= $realMembershipContactId;
385 if (!empty($ids['membership']) && $activityType != 'Membership Signup') {
386 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $targetContactID);
388 elseif (empty($ids['membership'])) {
389 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $targetContactID);
392 // we might created activity record w/ individual
393 // contact as target so update membership object w/
394 // original organization id, CRM-5551
395 $membership->contact_id
= $realMembershipContactId;
398 $transaction->commit();
400 self
::createRelatedMemberships($params, $membership);
402 // do not add to recent items for import, CRM-4399
403 if (empty($params['skipRecentView'])) {
404 $url = CRM_Utils_System
::url('civicrm/contact/view/membership',
405 "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
407 if (empty($membership->membership_type_id
)) {// ie in an update situation
408 $membership->find(TRUE);
410 $membershipTypes = CRM_Member_PseudoConstant
::membershipType();
411 $title = CRM_Contact_BAO_Contact
::displayName($membership->contact_id
) . ' - ' . ts('Membership Type:') . ' ' . $membershipTypes[$membership->membership_type_id
];
413 $recentOther = array();
414 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::UPDATE
)) {
415 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
416 "action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
419 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::DELETE
)) {
420 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
421 "action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
425 // add the recently created Membership
426 CRM_Utils_Recent
::add($title,
430 $membership->contact_id
,
440 * Check the membership extended through relationship
442 * @param int $membershipId
444 * @param int $contactId
450 * array of contact_id of all related contacts.
452 public static function checkMembershipRelationship($membershipId, $contactId, $action = CRM_Core_Action
::ADD
) {
454 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $membershipId, 'membership_type_id');
456 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipTypeID);
457 $relationships = array();
458 if (isset($membershipType['relationship_type_id'])) {
459 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
460 CRM_Contact_BAO_Relationship
::CURRENT
462 if ($action & CRM_Core_Action
::UPDATE
) {
463 $pastRelationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
464 CRM_Contact_BAO_Relationship
::PAST
466 $relationships = array_merge($relationships, $pastRelationships);
470 if (!empty($relationships)) {
471 // check for each contact relationships
472 foreach ($relationships as $values) {
473 //get details of the relationship type
474 $relType = array('id' => $values['civicrm_relationship_type_id']);
475 $relValues = array();
476 CRM_Contact_BAO_RelationshipType
::retrieve($relType, $relValues);
477 // Check if contact's relationship type exists in membership type
478 $relTypeDirs = array();
479 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_type_id']);
480 $relDirections = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_direction']);
481 $bidirectional = FALSE;
482 foreach ($relTypeIds as $key => $value) {
483 $relTypeDirs[] = $value . '_' . $relDirections[$key];
484 if (in_array($value, $relType) &&
485 $relValues['name_a_b'] == $relValues['name_b_a']
487 $bidirectional = TRUE;
491 $relTypeDir = $values['civicrm_relationship_type_id'] . '_' . $values['rtype'];
492 if ($bidirectional ||
in_array($relTypeDir, $relTypeDirs)) {
493 // $values['status'] is going to have value for
494 // current or past relationships.
495 $contacts[$values['cid']] = $values['status'];
500 // Sort by contact_id ascending
506 * Takes a bunch of params that are needed to match certain criteria and
507 * retrieves the relevant objects. We'll tweak this function to be more
508 * full featured over a period of time. This is the inverse function of
509 * create. It also stores all the retrieved values in the default array
511 * @param array $params
512 * (reference ) an assoc array of name/value pairs.
513 * @param array $defaults
514 * (reference ) an assoc array to hold the name / value pairs.
515 * in a hierarchical manner
517 * @return CRM_Member_BAO_Membership
519 public static function retrieve(&$params, &$defaults) {
520 $membership = new CRM_Member_DAO_Membership();
522 $membership->copyValues($params);
524 if ($membership->find(TRUE)) {
525 CRM_Core_DAO
::storeValues($membership, $defaults);
527 //get the membership status and type values.
528 $statusANDType = self
::getStatusANDTypeValues($membership->id
);
533 $defaults[$fld] = CRM_Utils_Array
::value($fld, $statusANDType[$membership->id
]);
535 if (!empty($statusANDType[$membership->id
]['is_current_member'])) {
536 $defaults['active'] = TRUE;
549 * get membership status and membership type values
551 * @param int $membershipId
552 * Membership id of values to return.
555 * Array of key value pairs
557 public static function getStatusANDTypeValues($membershipId) {
559 if (!$membershipId) {
563 SELECT membership.id as id,
564 status.id as status_id,
565 status.label as status,
566 status.is_current_member as is_current_member,
567 type.id as membership_type_id,
568 type.name as membership_type,
569 type.relationship_type_id as relationship_type_id
570 FROM civicrm_membership membership
571 INNER JOIN civicrm_membership_status status ON ( status.id = membership.status_id )
572 INNER JOIN civicrm_membership_type type ON ( type.id = membership.membership_type_id )
573 WHERE membership.id = %1';
574 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($membershipId, 'Positive')));
579 'membership_type_id',
581 'relationship_type_id',
583 while ($dao->fetch()) {
584 foreach ($properties as $property) {
585 $values[$dao->id
][$property] = $dao->$property;
594 * Wrapper for most delete calls. Use this unless you JUST want to delete related memberships w/o deleting the parent.
596 * @param int $membershipId
597 * Membership id that needs to be deleted.
600 * @return $results no of deleted Membership on success, false otherwise
602 public static function del($membershipId) {
603 //delete related first and then delete parent.
604 self
::deleteRelatedMemberships($membershipId);
605 return self
::deleteMembership($membershipId);
611 * @param int $membershipId
612 * Membership id that needs to be deleted.
615 * @return $results no of deleted Membership on success, false otherwise
617 public static function deleteMembership($membershipId) {
618 // CRM-12147, retrieve membership data before we delete it for hooks
619 $params = array('id' => $membershipId);
620 $memValues = array();
621 $memberships = self
::getValues($params, $memValues);
623 $membership = $memberships[$membershipId];
625 CRM_Utils_Hook
::pre('delete', 'Membership', $membershipId, $memValues);
627 $transaction = new CRM_Core_Transaction();
630 //delete activity record
631 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
634 $deleteActivity = FALSE;
635 $membershipActivities = array(
637 'Membership Renewal',
638 'Change Membership Status',
639 'Change Membership Type',
640 'Membership Renewal Reminder',
642 foreach ($membershipActivities as $membershipActivity) {
643 $activityId = array_search($membershipActivity, $activityTypes);
645 $params['activity_type_id'][] = $activityId;
646 $deleteActivity = TRUE;
649 if ($deleteActivity) {
650 $params['source_record_id'] = $membershipId;
651 CRM_Activity_BAO_Activity
::deleteActivity($params);
653 self
::deleteMembershipPayment($membershipId);
655 $results = $membership->delete();
656 $transaction->commit();
658 CRM_Utils_Hook
::post('delete', 'Membership', $membership->id
, $membership);
660 // delete the recently created Membership
661 $membershipRecent = array(
662 'id' => $membershipId,
663 'type' => 'Membership',
665 CRM_Utils_Recent
::del($membershipRecent);
671 * Delete related memberships
673 * @param int $ownerMembershipId
674 * @param int $contactId
678 public static function deleteRelatedMemberships($ownerMembershipId, $contactId = NULL) {
679 if (!$ownerMembershipId && !$contactId) {
683 $membership = new CRM_Member_DAO_Membership();
684 $membership->owner_membership_id
= $ownerMembershipId;
687 $membership->contact_id
= $contactId;
691 while ($membership->fetch()) {
692 //delete related first and then delete parent.
693 self
::deleteRelatedMemberships($membership->id
);
694 self
::deleteMembership($membership->id
);
700 * Obtain active/inactive memberships from the list of memberships passed to it.
702 * @param array $memberships
703 * Membership records.
704 * @param string $status
705 * Active or inactive.
708 * array of memberships based on status
710 public static function activeMembers($memberships, $status = 'active') {
712 if ($status == 'active') {
713 foreach ($memberships as $f => $v) {
714 if (!empty($v['active'])) {
720 elseif ($status == 'inactive') {
721 foreach ($memberships as $f => $v) {
722 if (empty($v['active'])) {
732 * Build Membership Block in Contribution Pages
734 * @param CRM_Core_Form $form
739 * Contact checked for having a current membership for a particular membership.
740 * @param bool $formItems
741 * @param int $selectedMembershipTypeID
742 * Selected membership id.
743 * @param bool $thankPage
745 * @param null $isTest
748 * Is this a separate membership payment
751 static function buildMembershipBlock(
756 $selectedMembershipTypeID = NULL,
761 $separateMembershipPayment = FALSE;
762 if ($form->_membershipBlock
) {
763 $form->_currentMemberships
= array();
765 $membershipBlock = $form->_membershipBlock
;
766 $membershipTypeIds = $membershipTypes = $radio = array();
767 $membershipPriceset = (!empty($form->_priceSetId
) && $form->_useForMember
) ?
TRUE : FALSE;
769 $allowAutoRenewMembership = $autoRenewOption = FALSE;
770 $autoRenewMembershipTypeOptions = array();
772 $paymentProcessor = CRM_Core_PseudoConstant
::paymentProcessor(FALSE, FALSE, 'is_recur = 1');
774 $separateMembershipPayment = CRM_Utils_Array
::value('is_separate_payment', $membershipBlock);
776 if ($membershipPriceset) {
777 foreach ($form->_priceSet
['fields'] as $pField) {
778 if (empty($pField['options'])) {
781 foreach ($pField['options'] as $opId => $opValues) {
782 if (empty($opValues['membership_type_id'])) {
785 $membershipTypeIds[$opValues['membership_type_id']] = $opValues['membership_type_id'];
789 elseif (!empty($membershipBlock['membership_types'])) {
790 $membershipTypeIds = explode(',', $membershipBlock['membership_types']);
793 if (!empty($membershipTypeIds)) {
794 //set status message if wrong membershipType is included in membershipBlock
795 if (isset($form->_mid
) && !$membershipPriceset) {
796 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
800 if (!in_array($membershipTypeID, $membershipTypeIds)) {
801 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');
805 $membershipTypeValues = self
::buildMembershipTypeValues($form, $membershipTypeIds);
806 $form->_membershipTypeValues
= $membershipTypeValues;
808 foreach ($membershipTypeIds as $value) {
809 $memType = $membershipTypeValues[$value];
810 if ($selectedMembershipTypeID != NULL) {
811 if ($memType['id'] == $selectedMembershipTypeID) {
812 $form->assign('minimum_fee',
813 CRM_Utils_Array
::value('minimum_fee', $memType)
815 $form->assign('membership_name', $memType['name']);
816 if (!$thankPage && $cid) {
817 $membership = new CRM_Member_DAO_Membership();
818 $membership->contact_id
= $cid;
819 $membership->membership_type_id
= $memType['id'];
820 if ($membership->find(TRUE)) {
821 $form->assign('renewal_mode', TRUE);
822 $memType['current_membership'] = $membership->end_date
;
823 $form->_currentMemberships
[$membership->membership_type_id
] = $membership->membership_type_id
;
826 $membershipTypes[] = $memType;
829 elseif ($memType['is_active']) {
830 $javascriptMethod = NULL;
831 $allowAutoRenewOpt = 1;
832 if (is_array($form->_paymentProcessors
)) {
833 foreach ($form->_paymentProcessors
as $id => $val) {
834 if (!$val['is_recur']) {
835 $allowAutoRenewOpt = 0;
841 $javascriptMethod = array('onclick' => "return showHideAutoRenew( this.value );");
842 $autoRenewMembershipTypeOptions["autoRenewMembershipType_{$value}"] = (int) $allowAutoRenewOpt * CRM_Utils_Array
::value($value, CRM_Utils_Array
::value('auto_renew', $form->_membershipBlock
));;
844 if ($allowAutoRenewOpt) {
845 $allowAutoRenewMembership = TRUE;
848 //add membership type.
849 $radio[$memType['id']] = $form->createElement('radio', NULL, NULL, NULL,
850 $memType['id'], $javascriptMethod
853 $membership = new CRM_Member_DAO_Membership();
854 $membership->contact_id
= $cid;
855 $membership->membership_type_id
= $memType['id'];
857 //show current membership, skip pending and cancelled membership records,
858 //because we take first membership record id for renewal
859 $membership->whereAdd('status_id != 5 AND status_id !=6');
861 if (!is_null($isTest)) {
862 $membership->is_test
= $isTest;
866 $membership->orderBy('end_date DESC');
868 if ($membership->find(TRUE)) {
869 if (!$membership->end_date
) {
870 unset($radio[$memType['id']]);
871 $form->assign('islifetime', TRUE);
874 $form->assign('renewal_mode', TRUE);
875 $form->_currentMemberships
[$membership->membership_type_id
] = $membership->membership_type_id
;
876 $memType['current_membership'] = $membership->end_date
;
878 $endDate = $memType['current_membership'];
879 $form->_defaultMemTypeId
= $memType['id'];
881 if ($memType['current_membership'] < $endDate) {
882 $endDate = $memType['current_membership'];
883 $form->_defaultMemTypeId
= $memType['id'];
887 $membershipTypes[] = $memType;
892 $form->assign('showRadio', $formItems);
894 if (!$membershipPriceset) {
895 if (!$membershipBlock['is_required']) {
896 $form->assign('showRadioNoThanks', TRUE);
897 $radio[''] = $form->createElement('radio', NULL, NULL, NULL, 'no_thanks', NULL);
898 $form->addGroup($radio, 'selectMembership', NULL);
900 elseif ($membershipBlock['is_required'] && count($radio) == 1) {
901 $temp = array_keys($radio);
902 $form->add('hidden', 'selectMembership', $temp[0], array('id' => 'selectMembership'));
903 $form->assign('singleMembership', TRUE);
904 $form->assign('showRadio', FALSE);
907 $form->addGroup($radio, 'selectMembership', NULL);
910 $form->addRule('selectMembership', ts('Please select one of the memberships.'), 'required');
913 $autoRenewOption = CRM_Price_BAO_PriceSet
::checkAutoRenewForPriceSet($form->_priceSetId
);
914 $form->assign('autoRenewOption', $autoRenewOption);
917 if (!$form->_values
['is_pay_later'] && is_array($form->_paymentProcessors
) && ($allowAutoRenewMembership ||
$autoRenewOption)) {
918 $form->addElement('checkbox', 'auto_renew', ts('Please renew my membership automatically.'));
923 $form->assign('membershipBlock', $membershipBlock);
924 $form->assign('membershipTypes', $membershipTypes);
925 $form->assign('allowAutoRenewMembership', $allowAutoRenewMembership);
926 $form->assign('autoRenewMembershipTypeOptions', json_encode($autoRenewMembershipTypeOptions));
928 //give preference to user submitted auto_renew value.
929 $takeUserSubmittedAutoRenew = (!empty($_POST) ||
$form->isSubmitted()) ?
TRUE : FALSE;
930 $form->assign('takeUserSubmittedAutoRenew', $takeUserSubmittedAutoRenew);
933 return $separateMembershipPayment;
937 * Return Membership Block info in Contribution Pages
940 * Contribution page id.
945 public static function getMembershipBlock($pageID) {
946 $membershipBlock = array();
947 $dao = new CRM_Member_DAO_MembershipBlock();
948 $dao->entity_table
= 'civicrm_contribution_page';
950 $dao->entity_id
= $pageID;
952 if ($dao->find(TRUE)) {
953 CRM_Core_DAO
::storeValues($dao, $membershipBlock);
954 if (!empty($membershipBlock['membership_types'])) {
955 $membershipTypes = unserialize($membershipBlock['membership_types']);
956 if (!is_array($membershipTypes)) {
957 return $membershipBlock;
960 foreach ($membershipTypes as $key => $value) {
961 $membershipBlock['auto_renew'][$key] = $value;
962 $memTypes[$key] = $key;
964 $membershipBlock['membership_types'] = implode(',', $memTypes);
971 return $membershipBlock;
975 * Return a current membership of given contact
976 * NB: if more than one membership meets criteria, a randomly selected one is returned.
978 * @param int $contactID
980 * @param int $memType
981 * Membership type, null to retrieve all types.
983 * @param int $membershipId
984 * If provided, then determine if it is current.
985 * @param bool $onlySameParentOrg
986 * True if only Memberships with same parent org as the $memType wanted, false otherwise.
990 public static function getContactMembership($contactID, $memType, $isTest, $membershipId = NULL, $onlySameParentOrg = FALSE) {
991 $dao = new CRM_Member_DAO_Membership();
993 $dao->id
= $membershipId;
995 $dao->contact_id
= $contactID;
996 $dao->membership_type_id
= $memType;
998 //fetch proper membership record.
1000 $dao->is_test
= $isTest;
1003 $dao->whereAdd('is_test IS NULL OR is_test = 0');
1006 //avoid pending membership as current membership: CRM-3027
1007 $statusIds[] = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
1008 if (!$membershipId) {
1010 $statusIds[] = array_search(
1012 CRM_Member_PseudoConstant
::membershipStatus(
1014 " name = 'Cancelled' ",
1021 $dao->whereAdd('status_id NOT IN ( ' . implode(',', $statusIds) . ')');
1023 // order by start date to find most recent membership first, CRM-4545
1024 $dao->orderBy('start_date DESC');
1027 if ($onlySameParentOrg && $memType) {
1028 // require the same parent org as the $memType
1029 $params = array('id' => $memType);
1030 $membershipType = array();
1031 if (CRM_Member_BAO_MembershipType
::retrieve($params, $membershipType)) {
1032 $memberTypesSameParentOrg = CRM_Member_BAO_MembershipType
::getMembershipTypesByOrg($membershipType['member_of_contact_id']);
1033 $memberTypesSameParentOrgList = implode(',', array_keys($memberTypesSameParentOrg));
1034 $dao->whereAdd('membership_type_id IN (' . $memberTypesSameParentOrgList . ')');
1038 if ($dao->find(TRUE)) {
1039 $membership = array();
1040 CRM_Core_DAO
::storeValues($dao, $membership);
1041 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
1042 $membership['status_id'],
1043 'is_current_member', 'id'
1049 if ($onlySameParentOrg && $memType) {
1050 // see if there is a membership that has same parent as $memType but different parent than $membershipID
1051 if ($dao->id
&& CRM_Core_Permission
::check('edit memberships')) {
1052 // CRM-10016, This is probably a backend renewal, and make sure we return the same membership thats being renewed.
1059 unset($dao->membership_type_id
);
1060 if ($dao->find(TRUE)) {
1061 $membership = array();
1062 CRM_Core_DAO
::storeValues($dao, $membership);
1063 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
1064 $membership['status_id'],
1065 'is_current_member', 'id'
1074 * Combine all the importable fields from the lower levels object
1076 * @param string $contactType
1078 * @param bool $status
1081 * array of importable Fields
1083 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
1084 if (!self
::$_importableFields) {
1085 if (!self
::$_importableFields) {
1086 self
::$_importableFields = array();
1090 $fields = array('' => array('title' => '- ' . ts('do not import') . ' -'));
1093 $fields = array('' => array('title' => '- ' . ts('Membership Fields') . ' -'));
1096 $tmpFields = CRM_Member_DAO_Membership
::import();
1097 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
1099 // Using new Dedupe rule.
1100 $ruleParams = array(
1101 'contact_type' => $contactType,
1102 'used' => 'Unsupervised',
1104 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
1106 $tmpContactField = array();
1107 if (is_array($fieldsArray)) {
1108 foreach ($fieldsArray as $value) {
1109 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
1114 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
1115 $tmpContactField[trim($value)] = CRM_Utils_Array
::value(trim($value), $contactFields);
1117 $title = $tmpContactField[trim($value)]['title'] . " " . ts('(match to contact)');
1120 $title = $tmpContactField[trim($value)]['title'];
1122 $tmpContactField[trim($value)]['title'] = $title;
1125 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
1126 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " " . ts('(match to contact)');
1128 $tmpFields['membership_contact_id']['title'] = $tmpFields['membership_contact_id']['title'] . " " . ts('(match to contact)');;
1130 $fields = array_merge($fields, $tmpContactField);
1131 $fields = array_merge($fields, $tmpFields);
1132 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1133 self
::$_importableFields = $fields;
1135 return self
::$_importableFields;
1139 * Get all exportable fields
1141 * @retun array return array of all exportable fields
1143 public static function &exportableFields() {
1144 $expFieldMembership = CRM_Member_DAO_Membership
::export();
1146 $expFieldsMemType = CRM_Member_DAO_MembershipType
::export();
1147 $fields = array_merge($expFieldMembership, $expFieldsMemType);
1148 $fields = array_merge($fields, $expFieldMembership);
1149 $membershipStatus = array(
1150 'membership_status' => array(
1151 'title' => 'Membership Status',
1152 'name' => 'membership_status',
1153 'type' => CRM_Utils_Type
::T_STRING
,
1154 'where' => 'civicrm_membership_status.name',
1157 //CRM-6161 fix for customdata export
1158 $fields = array_merge($fields, $membershipStatus, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1163 * Get membership joins/renewals for a specified membership
1164 * type. Specifically, retrieves a count of memberships whose "Membership
1165 * Signup" or "Membership Renewal" activity falls in the given date range.
1166 * Dates match the pattern "yyyy-mm-dd".
1168 * @param int $membershipTypeId
1169 * Membership type id.
1170 * @param int $startDate
1171 * Date on which to start counting.
1172 * @param int $endDate
1173 * Date on which to end counting.
1174 * @param bool|int $isTest if true, membership is for a test site
1175 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1178 * the number of members of type $membershipTypeId whose
1179 * start_date is between $startDate and $endDate
1181 public static function getMembershipStarts($membershipTypeId, $startDate, $endDate, $isTest = 0, $isOwner = 0) {
1183 $testClause = 'membership.is_test = 1';
1185 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1188 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1189 self
::_getActTypes();
1192 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1197 SELECT COUNT(DISTINCT membership.id) as member_count
1198 FROM civicrm_membership membership
1199 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id in (%1, %2))
1200 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1201 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1202 WHERE membership.membership_type_id = %3
1203 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1206 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1209 1 => array(self
::$_signupActType, 'Integer'),
1210 2 => array(self
::$_renewalActType, 'Integer'),
1211 3 => array($membershipTypeId, 'Integer'),
1214 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1215 return (int) $memberCount;
1219 * Get a count of membership for a specified membership type,
1220 * optionally for a specified date. The date must have the form yyyy-mm-dd.
1222 * If $date is omitted, this function counts as a member anyone whose
1223 * membership status_id indicates they're a current member.
1224 * If $date is given, this function counts as a member anyone who:
1225 * -- Has a start_date before $date and end_date after $date, or
1226 * -- Has a start_date before $date and is currently a member, as indicated
1227 * by the the membership's status_id.
1228 * The second condition takes care of records that have no end_date. These
1229 * are assumed to be lifetime memberships.
1231 * @param int $membershipTypeId
1232 * Membership type id.
1233 * @param string $date
1234 * The date for which to retrieve the count.
1235 * @param bool|int $isTest if true, membership is for a test site
1236 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1239 * the number of members of type $membershipTypeId as of $date.
1241 public static function getMembershipCount($membershipTypeId, $date = NULL, $isTest = 0, $isOwner = 0) {
1242 if (!CRM_Utils_Rule
::date($date)) {
1243 CRM_Core_Error
::fatal(ts('Invalid date "%1" (must have form yyyy-mm-dd).', array(1 => $date)));
1247 1 => array($membershipTypeId, 'Integer'),
1248 2 => array($isTest, 'Boolean'),
1250 $query = "SELECT count(civicrm_membership.id ) as member_count
1251 FROM civicrm_membership left join civicrm_membership_status on ( civicrm_membership.status_id = civicrm_membership_status.id )
1252 WHERE civicrm_membership.membership_type_id = %1
1253 AND civicrm_membership.contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)
1254 AND civicrm_membership.is_test = %2";
1256 $query .= " AND civicrm_membership_status.is_current_member = 1";
1259 $query .= " AND civicrm_membership.start_date <= '$date' AND civicrm_membership_status.is_current_member = 1";
1262 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1263 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1264 return (int) $memberCount;
1268 * Function check the status of the membership before adding membership for a contact
1270 * @param int $contactId
1275 public static function statusAvailabilty($contactId) {
1276 $membership = new CRM_Member_DAO_MembershipStatus();
1277 $membership->whereAdd('is_active=1');
1278 return $membership->count();
1282 * Process the Memberships
1284 * @param array $membershipParams
1285 * Array of membership fields.
1286 * @param int $contactID
1288 * @param CRM_Contribute_Form_Contribution_Confirm $form
1289 * Confirmation form object.
1291 * @param array $premiumParams
1292 * @param null $customFieldsFormatted
1293 * @param null $includeFieldTypes
1295 * @param array $membershipDetails
1297 * @param array $membershipTypeIDs
1299 * @param bool $isPaidMembership
1300 * @param array $membershipID
1302 * @param $isProcessSeparateMembershipTransaction
1304 * @param int $defaultContributionTypeID
1305 * @param array $membershipLineItems
1306 * Line items specific to membership payment that is separate to contribution.
1307 * @throws CRM_Core_Exception
1311 public static function postProcessMembership(
1312 $membershipParams, $contactID, &$form, $premiumParams,
1313 $customFieldsFormatted = NULL, $includeFieldTypes = NULL, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID,
1314 $isProcessSeparateMembershipTransaction, $defaultContributionTypeID, $membershipLineItems, $isPayLater) {
1315 $result = $membershipContribution = NULL;
1316 $isTest = CRM_Utils_Array
::value('is_test', $membershipParams, FALSE);
1317 $errors = $createdMemberships = array();
1319 //@todo move this into the calling function & pass in the correct financialTypeID
1320 if (isset($paymentParams['financial_type'])) {
1321 $financialTypeID = $paymentParams['financial_type'];
1324 $financialTypeID = $defaultContributionTypeID;
1327 if (CRM_Utils_Array
::value('membership_source', $form->_params
)) {
1328 $membershipParams['contribution_source'] = $form->_params
['membership_source'];
1331 if ($isPaidMembership) {
1332 $result = CRM_Contribute_BAO_Contribution_Utils
::processConfirm($form, $membershipParams,
1333 $premiumParams, $contactID,
1340 if (is_a($result[1], 'CRM_Core_Error')) {
1341 $errors[1] = CRM_Core_Error
::getMessages($result[1]);
1343 elseif (!empty($result[1])) {
1344 // Save the contribution ID so that I can be used in email receipts
1345 // For example, if you need to generate a tax receipt for the donation only.
1346 $form->_values
['contribution_other_id'] = $result[1]->id
;
1347 //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
1348 $membershipContribution = $result[1];
1352 if ($isProcessSeparateMembershipTransaction) {
1354 $lineItems = $form->_lineItem
= $membershipLineItems;
1355 $membershipContribution = self
::processSecondaryFinancialTransaction($contactID, $form, $membershipParams, $isTest, $membershipLineItems, CRM_Utils_Array
::value('minimum_fee', $membershipDetails, 0), CRM_Utils_Array
::value('financial_type_id', $membershipDetails));
1357 catch (CRM_Core_Exception
$e) {
1358 $errors[2] = $e->getMessage();
1359 $membershipContribution = NULL;
1364 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1365 $membershipContributionID = $membershipContribution->id
;
1368 //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
1369 if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
1370 $form->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
1372 //@todo it should no longer be possible for it to get to this point & membership to not be an array
1373 if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
1374 $typesTerms = CRM_Utils_Array
::value('types_terms', $membershipParams, array());
1375 foreach ($membershipTypeIDs as $memType) {
1376 $numTerms = CRM_Utils_Array
::value($memType, $typesTerms, 1);
1377 $createdMemberships[$memType] = self
::createOrRenewMembership($membershipParams, $contactID, $customFieldsFormatted, $membershipID, $memType, $isTest, $numTerms, $membershipContribution, $form);
1379 if ($form->_priceSetId
&& !empty($form->_useForMember
) && !empty($form->_lineItem
)) {
1380 foreach ($form->_lineItem
[$form->_priceSetId
] as & $priceFieldOp) {
1381 if (!empty($priceFieldOp['membership_type_id']) &&
1382 isset($createdMemberships[$priceFieldOp['membership_type_id']])
1384 $membershipOb = $createdMemberships[$priceFieldOp['membership_type_id']];
1385 $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date
::customFormat($membershipOb->start_date
, '%B %E%f, %Y') : '-';
1386 $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date
::customFormat($membershipOb->end_date
, '%B %E%f, %Y') : '-';
1389 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1392 $form->_values
['lineItem'] = $form->_lineItem
;
1393 $form->assign('lineItem', $form->_lineItem
);
1397 if (!empty($errors)) {
1398 $message = self
::compileErrorMessage($errors);
1399 throw new CRM_Core_Exception($message);
1401 $form->_params
['createdMembershipIDs'] = array();
1403 // CRM-7851 - Moved after processing Payment Errors
1404 //@todo - the reasoning for this being here seems a little outdated
1405 foreach ($createdMemberships as $createdMembership) {
1406 CRM_Core_BAO_CustomValueTable
::postProcess(
1408 CRM_Core_DAO
::$_nullArray,
1409 'civicrm_membership',
1410 $createdMembership->id
,
1413 $form->_params
['createdMembershipIDs'][] = $createdMembership->id
;
1415 if (count($createdMemberships) == 1) {
1416 //presumably this is only relevant for exactly 1 membership
1417 $form->_params
['membershipID'] = $createdMembership->id
;
1420 //CRM-15232: Check if membership is created and on the basis of it use
1421 //membership reciept template to send payment reciept
1422 if (count($createdMemberships)) {
1423 $form->_values
['isMembership'] = TRUE;
1425 if ($form->_contributeMode
== 'notify') {
1426 if ($form->_values
['is_monetary'] && $form->_amount
> 0.0 && !$form->_params
['is_pay_later']) {
1427 // call postProcess hook before leaving
1428 $form->postProcessHook();
1429 // this does not return
1430 $payment = CRM_Core_Payment
::singleton($form->_mode
, $form->_paymentProcessor
, $form);
1431 $payment->doTransferCheckout($form->_params
, 'contribute');
1435 if (isset($membershipContributionID)) {
1436 $form->_values
['contribution_id'] = $membershipContributionID;
1439 // Do not send an email if Recurring transaction is done via Direct Mode
1440 // Email will we sent when the IPN is received.
1441 if (!empty($form->_params
['is_recur']) && $form->_contributeMode
== 'direct') {
1442 if (!empty($membershipContribution->trxn_id
)) {
1444 civicrm_api3('contribution', 'completetransaction', array(
1445 'id' => $membershipContribution->id
,
1446 'trxn_id' => $membershipContribution->trxn_id
,
1449 catch (CiviCRM_API3_Exception
$e) {
1450 // if for any reason it is already completed this will fail - e.g extensions hacking around core not completing transactions prior to CRM-15296
1451 // so let's be gentle here
1452 CRM_Core_Error
::debug_log_message('contribution ' . $membershipContribution->id
. ' not completed with trxn_id ' . $membershipContribution->trxn_id
. ' and message ' . $e->getMessage());
1458 //finally send an email receipt
1459 CRM_Contribute_BAO_ContributionPage
::sendMail($contactID,
1467 * Function for updating a membership record's contribution_recur_id
1469 * @param CRM_Member_DAO_Membership $membership
1470 * @param \CRM_Contribute_BAO_Contribution|\CRM_Contribute_DAO_Contribution $contribution
1474 static public function updateRecurMembership(CRM_Member_DAO_Membership
$membership, CRM_Contribute_BAO_Contribution
$contribution) {
1476 if (empty($contribution->contribution_recur_id
)) {
1481 1 => array($contribution->contribution_recur_id
, 'Integer'),
1482 2 => array($membership->id
, 'Integer'),
1485 $sql = "UPDATE civicrm_membership SET contribution_recur_id = %1 WHERE id = %2";
1486 CRM_Core_DAO
::executeQuery($sql, $params);
1491 * A wrapper for renewing memberships from a form - including the form in the membership processing adds complexity
1492 * as the forms are being forced to pretend similarity
1493 * Try to call the renewMembership directly
1494 * @todo - this form method needs to have the interaction with the form layer removed from it
1495 * as a BAO function. Note that the api now supports membership renewals & it is not clear this function does anything
1496 * not done by the membership.create api (with a lot less unit tests)
1498 * This method will renew / create the membership depending on
1499 * whether the given contact has a membership or not. And will add
1500 * the modified dates for membership and in the log table.
1502 * @param int $contactID
1503 * Id of the contact.
1504 * @param int $membershipTypeID
1505 * Id of the new membership type.
1506 * @param bool $is_test
1507 * If this is test contribution or live contribution.
1508 * @param CRM_Core_Form $form
1510 * @param null $changeToday
1511 * @param int $modifiedID
1512 * Individual contact id in case of On Behalf signup (CRM-4027 ).
1513 * @param null $customFieldsFormatted
1514 * @param int $numRenewTerms
1515 * How many membership terms are being added to end date (default is 1).
1516 * @param int $membershipID
1517 * Membership ID, this should always be passed in & optionality should be removed.
1519 * @throws CRM_Core_Exception
1522 static function renewMembershipFormWrapper(
1527 $changeToday = NULL,
1529 $customFieldsFormatted = NULL,
1531 $membershipID = NULL
1533 $statusFormat = '%Y-%m-%d';
1536 //@todo would be better to make $membershipID a compulsory function param & make form layer responsible for extracting it
1537 if (!$membershipID && isset($form->_membershipId
)) {
1538 $membershipID = $form->_membershipId
;
1541 //get all active statuses of membership.
1542 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1544 $membershipTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipTypeID);
1546 // check is it pending. - CRM-4555
1547 list($pending, $contributionRecurID, $changeToday, $membershipSource, $isPayLater, $campaignId) = self
::extractFormValues($form, $changeToday, $membershipTypeDetails);
1548 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);
1549 $form->set('renewal_mode', $renewalMode);
1550 if (!empty($dates)) {
1551 $form->assign('mem_start_date',
1552 CRM_Utils_Date
::customFormat($dates['start_date'], $format)
1554 $form->assign('mem_end_date',
1555 CRM_Utils_Date
::customFormat($dates['end_date'], $format)
1563 * Method to fix membership status of stale membership
1565 * This method first checks if the membership is stale. If it is,
1566 * then status will be updated based on existing start and end
1567 * dates and log will be added for the status change.
1569 * @param array $currentMembership
1570 * Reference to the array.
1571 * containing all values of
1572 * the current membership
1573 * @param array $changeToday
1574 * Array of month, day, year.
1575 * values in case today needs
1576 * to be customised, null otherwise
1580 public static function fixMembershipStatusBeforeRenew(&$currentMembership, $changeToday) {
1583 $today = CRM_Utils_Date
::processDate($changeToday, NULL, FALSE, 'Y-m-d');
1586 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
1587 CRM_Utils_Array
::value('start_date', $currentMembership),
1588 CRM_Utils_Array
::value('end_date', $currentMembership),
1589 CRM_Utils_Array
::value('join_date', $currentMembership),
1592 $currentMembership['membership_type_id'],
1596 if (empty($status) ||
1597 empty($status['id'])
1599 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.'));
1602 $currentMembership['today_date'] = $today;
1604 if ($status['id'] !== $currentMembership['status_id']) {
1605 $memberDAO = new CRM_Member_DAO_Membership();
1606 $memberDAO->id
= $currentMembership['id'];
1607 $memberDAO->find(TRUE);
1609 $memberDAO->status_id
= $status['id'];
1610 $memberDAO->join_date
= CRM_Utils_Date
::isoToMysql($memberDAO->join_date
);
1611 $memberDAO->start_date
= CRM_Utils_Date
::isoToMysql($memberDAO->start_date
);
1612 $memberDAO->end_date
= CRM_Utils_Date
::isoToMysql($memberDAO->end_date
);
1614 CRM_Core_DAO
::storeValues($memberDAO, $currentMembership);
1617 $currentMembership['is_current_member'] = CRM_Core_DAO
::getFieldValue(
1618 'CRM_Member_DAO_MembershipStatus',
1619 $currentMembership['status_id'],
1625 'membership_id' => $currentMembership['id'],
1626 'status_id' => $status['id'],
1627 'start_date' => CRM_Utils_Date
::customFormat(
1628 $currentMembership['start_date'],
1631 'end_date' => CRM_Utils_Date
::customFormat(
1632 $currentMembership['end_date'],
1635 'modified_date' => CRM_Utils_Date
::customFormat(
1636 $currentMembership['today_date'],
1639 'membership_type_id' => $currentMembership['membership_type_id'],
1640 'max_related' => $currentMembership['max_related'],
1643 $session = CRM_Core_Session
::singleton();
1644 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
1645 if ($session->get('userID')) {
1646 $logParams['modified_id'] = $session->get('userID');
1649 $logParams['modified_id'] = $currentMembership['contact_id'];
1651 CRM_Member_BAO_MembershipLog
::add($logParams, CRM_Core_DAO
::$_nullArray);
1656 * Get the contribution page id from the membership record
1658 * @param int $membershipID
1661 * contribution page id
1663 public static function getContributionPageId($membershipID) {
1665 SELECT c.contribution_page_id as pageID
1666 FROM civicrm_membership_payment mp, civicrm_contribution c
1667 WHERE mp.contribution_id = c.id
1668 AND c.contribution_page_id IS NOT NULL
1669 AND mp.membership_id = " . CRM_Utils_Type
::escape($membershipID, 'Integer')
1670 . " ORDER BY mp.id DESC";
1672 return CRM_Core_DAO
::singleValueQuery($query,
1673 CRM_Core_DAO
::$_nullArray
1678 * Updated related memberships
1680 * @param int $ownerMembershipId
1681 * Owner Membership Id.
1682 * @param array $params
1683 * Formatted array of key => value.
1685 public static function updateRelatedMemberships($ownerMembershipId, $params) {
1686 $membership = new CRM_Member_DAO_Membership();
1687 $membership->owner_membership_id
= $ownerMembershipId;
1688 $membership->find();
1690 while ($membership->fetch()) {
1691 $relatedMembership = new CRM_Member_DAO_Membership();
1692 $relatedMembership->id
= $membership->id
;
1693 $relatedMembership->copyValues($params);
1694 $relatedMembership->save();
1695 $relatedMembership->free();
1698 $membership->free();
1702 * Get list of membership fields for profile
1703 * For now we only allow custom membership fields to be in
1707 * FIXME: This param is ignored
1710 * the list of membership fields
1712 public static function getMembershipFields($mode = NULL) {
1713 $fields = CRM_Member_DAO_Membership
::export();
1715 unset($fields['membership_contact_id']);
1716 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1718 $membershipType = CRM_Member_DAO_MembershipType
::export();
1720 $membershipStatus = CRM_Member_DAO_MembershipStatus
::export();
1722 $fields = array_merge($fields, $membershipType, $membershipStatus);
1728 * Get the sort name of a contact for a particular membership
1731 * Id of the membership.
1733 * @return null|string
1734 * sort name of the contact if found
1736 public static function sortName($id) {
1737 $id = CRM_Utils_Type
::escape($id, 'Integer');
1740 SELECT civicrm_contact.sort_name
1741 FROM civicrm_membership, civicrm_contact
1742 WHERE civicrm_membership.contact_id = civicrm_contact.id
1743 AND civicrm_membership.id = {$id}
1745 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1749 * Create memberships for related contacts
1750 * takes into account the maximum related memberships
1752 * @param array $params
1753 * Array of key - value pairs.
1754 * @param CRM_Core_DAO $dao
1755 * Membership object.
1757 * @return null|array
1758 * array of memberships if created
1760 public static function createRelatedMemberships(&$params, &$dao, $reset = FALSE) {
1761 static $relatedContactIds = array();
1763 // not sure why a static var is in use here - we need a way to reset it from the test suite
1764 $relatedContactIds = array();
1768 $membership = new CRM_Member_DAO_Membership();
1769 $membership->id
= $dao->id
;
1771 // required since create method doesn't return all the
1772 // parameters in the returned membership object
1773 if (!$membership->find(TRUE)) {
1776 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1777 // FIXME : While updating/ renewing the
1778 // membership, if the relationship is PAST then
1779 // the membership of the related contact must be
1781 // For that, getting Membership Status for which
1782 // is_current_member is 0. It works for the
1783 // generated data as there is only one membership
1784 // status having is_current_member = 0.
1785 // But this wont work exactly if there will be
1786 // more than one status having is_current_member = 0.
1787 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
1788 $membershipStatus->is_current_member
= 0;
1789 if ($membershipStatus->find(TRUE)) {
1790 $expiredStatusId = $membershipStatus->id
;
1793 $expiredStatusId = array_search('Expired', CRM_Member_PseudoConstant
::membershipStatus());
1796 $allRelatedContacts = array();
1797 $relatedContacts = array();
1798 if (!is_a($membership, 'CRM_Core_Error')) {
1799 $allRelatedContacts = CRM_Member_BAO_Membership
::checkMembershipRelationship($membership->id
,
1800 $membership->contact_id
,
1801 CRM_Utils_Array
::value('action', $params)
1805 // check for loops. CRM-4213
1806 // remove repeated related contacts, which already inherited membership.
1807 $relatedContactIds[$membership->contact_id
] = TRUE;
1808 foreach ($allRelatedContacts as $cid => $status) {
1809 if (empty($relatedContactIds[$cid])) {
1810 $relatedContactIds[$cid] = TRUE;
1812 //don't create membership again for owner contact.
1813 $nestedRelationship = FALSE;
1814 if ($membership->owner_membership_id
) {
1815 $nestedRelMembership = new CRM_Member_DAO_Membership();
1816 $nestedRelMembership->id
= $membership->owner_membership_id
;
1817 $nestedRelMembership->contact_id
= $cid;
1818 $nestedRelationship = $nestedRelMembership->find(TRUE);
1819 $nestedRelMembership->free();
1821 if (!$nestedRelationship) {
1822 $relatedContacts[$cid] = $status;
1827 //lets cleanup related membership if any.
1828 if (empty($relatedContacts)) {
1829 self
::deleteRelatedMemberships($membership->id
);
1832 // Edit the params array
1833 unset($params['id']);
1834 // Reminder should be sent only to the direct membership
1835 unset($params['reminder_date']);
1836 // unset the custom value ids
1837 if (is_array(CRM_Utils_Array
::value('custom', $params))) {
1838 foreach ($params['custom'] as $k => $v) {
1839 unset($params['custom'][$k]['id']);
1842 if (!isset($params['membership_type_id'])) {
1843 $params['membership_type_id'] = $membership->membership_type_id
;
1846 // max_related should be set in the parent membership
1847 unset($params['max_related']);
1848 // Number of inherited memberships available - NULL is interpreted as unlimited, '0' as none
1849 $available = ($membership->max_related
== NULL ? PHP_INT_MAX
: $membership->max_related
);
1850 $queue = array(); // will be used to queue potential memberships to be created
1852 foreach ($relatedContacts as $contactId => $relationshipStatus) {
1853 //use existing membership record.
1854 $relMembership = new CRM_Member_DAO_Membership();
1855 $relMembership->contact_id
= $contactId;
1856 $relMembership->owner_membership_id
= $membership->id
;
1857 $relMemIds = array();
1858 if ($relMembership->find(TRUE)) {
1859 $params['id'] = $relMemIds['membership'] = $relMembership->id
;
1861 $params['contact_id'] = $contactId;
1862 $params['owner_membership_id'] = $membership->id
;
1864 // set status_id as it might have been changed for
1865 // past relationship
1866 $params['status_id'] = $membership->status_id
;
1868 if ($deceasedStatusId &&
1869 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'is_deceased')
1871 $params['status_id'] = $deceasedStatusId;
1873 elseif ((CRM_Utils_Array
::value('action', $params) & CRM_Core_Action
::UPDATE
) &&
1874 ($relationshipStatus == CRM_Contact_BAO_Relationship
::PAST
)
1876 $params['status_id'] = $expiredStatusId;
1879 //don't calculate status again in create( );
1880 $params['skipStatusCal'] = TRUE;
1882 //do create activity if we changed status.
1883 if ($params['status_id'] != $relMembership->status_id
) {
1884 $params['createActivity'] = TRUE;
1887 // we should not created contribution record for related contacts, CRM-3371
1888 unset($params['contribution_status_id']);
1890 if (($params['status_id'] == $deceasedStatusId) ||
($params['status_id'] == $expiredStatusId)) {
1891 // related membership is not active so does not count towards maximum
1892 CRM_Member_BAO_Membership
::create($params, $relMemIds);
1895 // related membership already exists, so this is just an update
1896 if (isset($params['id'])) {
1897 if ($available > 0) {
1898 CRM_Member_BAO_Membership
::create($params, $relMemIds);
1901 else { // we have run out of inherited memberships, so delete extras
1902 self
::deleteMembership($params['id']);
1904 // we need to first check if there will remain inherited memberships, so queue it up
1911 // now go over the queue and create any available related memberships
1913 while (($available > 0) && ($params = each($queue))) {
1914 CRM_Member_BAO_Membership
::create($params['value'], $relMemIds);
1921 * Delete the record that are associated with this Membership Payment
1923 * @param int $membershipId
1926 * true if deleted false otherwise
1928 public static function deleteMembershipPayment($membershipId) {
1930 $membesrshipPayment = new CRM_Member_DAO_MembershipPayment();
1931 $membesrshipPayment->membership_id
= $membershipId;
1932 $membesrshipPayment->find();
1934 while ($membesrshipPayment->fetch()) {
1935 CRM_Contribute_BAO_Contribution
::deleteContribution($membesrshipPayment->contribution_id
);
1936 CRM_Utils_Hook
::pre('delete', 'MembershipPayment', $membesrshipPayment->id
, $membesrshipPayment);
1937 $membesrshipPayment->delete();
1938 CRM_Utils_Hook
::post('delete', 'MembershipPayment', $membesrshipPayment->id
, $membesrshipPayment);
1940 return $membesrshipPayment;
1944 * @param CRM_Core_Form $form
1945 * @param int $membershipTypeID
1949 public static function &buildMembershipTypeValues(&$form, $membershipTypeID = NULL) {
1950 $whereClause = " WHERE domain_id = " . CRM_Core_Config
::domainID();
1952 if (is_array($membershipTypeID)) {
1953 $allIDs = implode(',', $membershipTypeID);
1954 $whereClause .= " AND id IN ( $allIDs )";
1956 elseif (is_numeric($membershipTypeID) &&
1957 $membershipTypeID > 0
1959 $whereClause .= " AND id = $membershipTypeID";
1964 FROM civicrm_membership_type
1967 $dao = CRM_Core_DAO
::executeQuery($query);
1969 $membershipTypeValues = array();
1970 $membershipTypeFields = array(
1976 'financial_type_id',
1978 'member_of_contact_id',
1979 'relationship_type_id',
1980 'relationship_direction',
1984 while ($dao->fetch()) {
1985 $membershipTypeValues[$dao->id
] = array();
1986 foreach ($membershipTypeFields as $mtField) {
1987 $membershipTypeValues[$dao->id
][$mtField] = $dao->$mtField;
1992 CRM_Utils_Hook
::membershipTypeValues($form, $membershipTypeValues);
1994 if (is_numeric($membershipTypeID) &&
1995 $membershipTypeID > 0
1997 return $membershipTypeValues[$membershipTypeID];
2000 return $membershipTypeValues;
2005 * Get membership record count for a Contact
2007 * @param int $contactID
2008 * @param bool $activeOnly
2010 * @return null|string
2012 public static function getContactMembershipCount($contactID, $activeOnly = FALSE) {
2013 $select = "SELECT count(*) FROM civicrm_membership ";
2014 $where = "WHERE civicrm_membership.contact_id = {$contactID} AND civicrm_membership.is_test = 0 ";
2016 // CRM-6627, all status below 3 (active, pending, grace) are considered active
2018 $select .= " INNER JOIN civicrm_membership_status ON civicrm_membership.status_id = civicrm_membership_status.id ";
2019 $where .= " and civicrm_membership_status.is_current_member = 1";
2022 $query = $select . $where;
2023 return CRM_Core_DAO
::singleValueQuery($query);
2027 * Check whether payment processor supports
2028 * cancellation of membership subscription
2033 * @param bool $isNotCancelled
2037 public static function isCancelSubscriptionSupported($mid, $isNotCancelled = TRUE) {
2038 $cacheKeyString = "$mid";
2039 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2041 static $supportsCancel = array();
2043 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2044 $supportsCancel[$cacheKeyString] = FALSE;
2045 $isCancelled = FALSE;
2047 if ($isNotCancelled) {
2048 $isCancelled = self
::isSubscriptionCancelled($mid);
2051 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($mid, 'membership', 'obj');
2052 if (!empty($paymentObject)) {
2053 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2056 return $supportsCancel[$cacheKeyString];
2060 * Check whether subscription is already cancelled
2066 * contribution status
2068 public static function isSubscriptionCancelled($mid) {
2070 SELECT cr.contribution_status_id
2071 FROM civicrm_contribution_recur cr
2072 LEFT JOIN civicrm_membership mem ON ( cr.id = mem.contribution_recur_id )
2073 WHERE mem.id = %1 LIMIT 1";
2074 $params = array(1 => array($mid, 'Integer'));
2075 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2076 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
2077 if ($status == 'Cancelled') {
2084 * Get membership joins for a specified membership
2085 * type. Specifically, retrieves a count of still current memberships whose
2086 * join_date and start_date are within a specified date range. Dates match
2087 * the pattern "yyyy-mm-dd".
2089 * @param int $membershipTypeId
2090 * Membership type id.
2091 * @param int $startDate
2092 * Date on which to start counting.
2093 * @param int $endDate
2094 * Date on which to end counting.
2095 * @param bool|int $isTest if true, membership is for a test site
2098 * the number of members of type $membershipTypeId
2099 * whose join_date is between $startDate and $endDate and
2100 * whose start_date is between $startDate and $endDate
2102 public static function getMembershipJoins($membershipTypeId, $startDate, $endDate, $isTest = 0) {
2103 $testClause = 'membership.is_test = 1';
2105 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
2107 if (!self
::$_signupActType) {
2108 self
::_getActTypes();
2111 if (!self
::$_signupActType) {
2116 SELECT COUNT(DISTINCT membership.id) as member_count
2117 FROM civicrm_membership membership
2118 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
2119 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
2120 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
2121 WHERE membership.membership_type_id = %2
2122 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
2126 1 => array(self
::$_signupActType, 'Integer'),
2127 2 => array($membershipTypeId, 'Integer'),
2130 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
2132 return (int) $memberCount;
2136 * Get membership renewals for a specified membership
2137 * type. Specifically, retrieves a count of still current memberships
2138 * whose join_date is before and start_date is within a specified date
2139 * range. Dates match the pattern "yyyy-mm-dd".
2141 * @param int $membershipTypeId
2142 * Membership type id.
2143 * @param int $startDate
2144 * Date on which to start counting.
2145 * @param int $endDate
2146 * Date on which to end counting.
2147 * @param bool|int $isTest if true, membership is for a test site
2150 * returns the number of members of type $membershipTypeId
2151 * whose join_date is before $startDate and
2152 * whose start_date is between $startDate and $endDate
2154 public static function getMembershipRenewals($membershipTypeId, $startDate, $endDate, $isTest = 0) {
2155 $testClause = 'membership.is_test = 1';
2157 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
2159 if (!self
::$_renewalActType) {
2160 self
::_getActTypes();
2163 if (!self
::$_renewalActType) {
2168 SELECT COUNT(DISTINCT membership.id) as member_count
2169 FROM civicrm_membership membership
2170 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
2171 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
2172 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
2173 WHERE membership.membership_type_id = %2
2174 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
2178 1 => array(self
::$_renewalActType, 'Integer'),
2179 2 => array($membershipTypeId, 'Integer'),
2181 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
2183 return (int) $memberCount;
2187 * Where a second separate financial transaction is supported we will process it here
2189 * @param int $contactID
2190 * @param CRM_Contribute_Form_Contribution_Confirm $form
2191 * @param array $tempParams
2193 * @param array $lineItems
2194 * @param $minimumFee
2195 * @param int $financialTypeID
2197 * @throws CRM_Core_Exception
2199 * @return CRM_Contribute_BAO_Contribution
2201 public static function processSecondaryFinancialTransaction($contactID, &$form, $tempParams, $isTest, $lineItems, $minimumFee, $financialTypeID) {
2202 $contributionType = new CRM_Financial_DAO_FinancialType();
2203 $contributionType->id
= $financialTypeID;
2204 if (!$contributionType->find(TRUE)) {
2205 CRM_Core_Error
::fatal(ts("Could not find a system table"));
2207 $tempParams['amount'] = $minimumFee;
2208 $tempParams['invoiceID'] = md5(uniqid(rand(), TRUE));
2211 if ($form->_values
['is_monetary'] && !$form->_params
['is_pay_later'] && $minimumFee > 0.0) {
2212 $payment = CRM_Core_Payment
::singleton($form->_mode
, $form->_paymentProcessor
, $form);
2214 if ($form->_contributeMode
== 'express') {
2215 $result = $payment->doExpressCheckout($tempParams);
2218 $result = $payment->doDirectPayment($tempParams);
2222 if (is_a($result, 'CRM_Core_Error')) {
2223 throw new CRM_Core_Exception(CRM_Core_Error
::getMessages($result));
2226 //assign receive date when separate membership payment
2227 //and contribution amount not selected.
2228 if ($form->_amount
== 0) {
2229 $now = date('YmdHis');
2230 $form->_params
['receive_date'] = $now;
2231 $receiveDate = CRM_Utils_Date
::mysqlToIso($now);
2232 $form->set('params', $form->_params
);
2233 $form->assign('receive_date', $receiveDate);
2236 $form->set('membership_trx_id', $result['trxn_id']);
2237 $form->set('membership_amount', $minimumFee);
2239 $form->assign('membership_trx_id', $result['trxn_id']);
2240 $form->assign('membership_amount', $minimumFee);
2242 // we don't need to create the user twice, so lets disable cms_create_account
2243 // irrespective of the value, CRM-2888
2244 $tempParams['cms_create_account'] = 0;
2246 $pending = $form->_params
['is_pay_later'] ?
(($minimumFee > 0.0) ?
TRUE : FALSE) : FALSE;
2248 //set this variable as we are not creating pledge for
2249 //separate membership payment contribution.
2250 //so for differentiating membership contribution from
2251 //main contribution.
2252 $form->_params
['separate_membership_payment'] = 1;
2253 $membershipContribution = CRM_Contribute_Form_Contribution_Confirm
::processContribution($form,
2263 return $membershipContribution;
2268 * Create linkages between membership & contribution - note this is the wrong place for this code but this is a
2269 * refactoring step. This should be BAO functionality
2270 * @param $membership
2271 * @param $membershipContribution
2273 public static function linkMembershipPayment($membership, $membershipContribution) {
2274 CRM_Member_BAO_MembershipPayment
::create(array(
2275 'membership_id' => $membership->id
,
2276 'contribution_id' => $membershipContribution->id
,
2281 * @param array $membershipParams
2282 * @param int $contactID
2283 * @param $customFieldsFormatted
2284 * @param int $membershipID
2288 * @param $membershipContribution
2289 * @param CRM_Core_Form $form
2293 public static function createOrRenewMembership($membershipParams, $contactID, $customFieldsFormatted, $membershipID, $memType, $isTest, $numTerms, $membershipContribution, &$form) {
2294 $membership = self
::renewMembershipFormWrapper($contactID, $memType,
2295 $isTest, $form, NULL,
2296 CRM_Utils_Array
::value('cms_contactID', $membershipParams),
2297 $customFieldsFormatted, $numTerms,
2301 if (!empty($membershipContribution)) {
2302 // update recurring id for membership record
2303 self
::updateRecurMembership($membership, $membershipContribution);
2305 self
::linkMembershipPayment($membership, $membershipContribution);
2311 * Turn array of errors into message string
2313 * @param array $errors
2317 public static function compileErrorMessage($errors) {
2318 foreach ($errors as $error) {
2319 if (is_string($error)) {
2320 $message[] = $error;
2323 return ts('Payment Processor Error message') . ': ' . implode('<br/>', $message);
2327 * Extract relevant values from the form so we can separate form logic from BAO logcis
2329 * @param CRM_Core_Form $form
2330 * @param $changeToday
2331 * @param $membershipTypeDetails
2335 public static function extractFormValues($form, $changeToday, $membershipTypeDetails) {
2337 //@todo this is a BAO function & should not inspect the form - the form should do this
2338 // & pass required params to the BAO
2339 if (CRM_Utils_Array
::value('minimum_fee', $membershipTypeDetails) > 0.0) {
2340 if (((isset($form->_contributeMode
) && $form->_contributeMode
== 'notify') ||
!empty($form->_params
['is_pay_later']) ||
2341 (!empty($form->_params
['is_recur']) && $form->_contributeMode
== 'direct'
2344 (($form->_values
['is_monetary'] && $form->_amount
> 0.0) ||
!empty($form->_params
['separate_membership_payment']) ||
2345 CRM_Utils_Array
::value('record_contribution', $form->_params
)
2351 $contributionRecurID = isset($form->_params
['contributionRecurID']) ?
$form->_params
['contributionRecurID'] : NULL;
2353 //we renew expired membership, CRM-6277
2354 if (!$changeToday) {
2355 if ($form->get('renewalDate')) {
2356 $changeToday = $form->get('renewalDate');
2358 elseif (get_class($form) == 'CRM_Contribute_Form_Contribution_Confirm') {
2359 $changeToday = date('YmdHis');
2363 $membershipSource = NULL;
2364 if (!empty($form->_params
['membership_source'])) {
2365 $membershipSource = $form->_params
['membership_source'];
2367 elseif (isset($form->_values
['title']) && !empty($form->_values
['title'])) {
2368 $membershipSource = ts('Online Contribution:') . ' ' . $form->_values
['title'];
2371 if (isset($form->_params
)) {
2372 $isPayLater = CRM_Utils_Array
::value('is_pay_later', $form->_params
);
2375 if (isset($form->_values
) && is_array($form->_values
) && !empty($form->_values
)) {
2376 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_params
);
2377 if (!array_key_exists('campaign_id', $form->_params
)) {
2378 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_values
);
2381 return array($pending, $contributionRecurID, $changeToday, $membershipSource, $isPayLater, $campaignId);
2385 * @param int $contactID
2386 * @param int $membershipTypeID
2387 * @param bool $is_test
2388 * @param $changeToday
2389 * @param int $modifiedID
2390 * @param $customFieldsFormatted
2391 * @param $numRenewTerms
2392 * @param int $membershipID
2395 * @param array $membershipTypeDetails
2396 * @param int $contributionRecurID
2398 * @param $membershipSource
2400 * @param $statusFormat
2401 * @param $isPayLater
2402 * @param int $campaignId
2404 * @throws CRM_Core_Exception
2407 public static function renewMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $allStatus, $membershipTypeDetails, $contributionRecurID, $format, $membershipSource, $ids, $statusFormat, $isPayLater, $campaignId) {
2408 $renewalMode = $updateStatusId = FALSE;
2410 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
2411 // is the same as the parent org of an existing membership of the contact
2412 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($contactID, $membershipTypeID,
2413 $is_test, $membershipID, TRUE
2415 if ($currentMembership) {
2416 $activityType = 'Membership Renewal';
2417 $renewalMode = TRUE;
2419 // Do NOT do anything.
2420 //1. membership with status : PENDING/CANCELLED (CRM-2395)
2421 //2. Paylater/IPN renew. CRM-4556.
2422 if ($pending ||
in_array($currentMembership['status_id'], array(
2423 array_search('Pending', $allStatus),
2425 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
2428 $membership = new CRM_Member_DAO_Membership();
2429 $membership->id
= $currentMembership['id'];
2430 $membership->find(TRUE);
2432 // CRM-8141 create a membership_log entry so that we will know the membership_type_id to change to when payment completed
2434 // note that we are logging the requested new membership_type_id that may be different than current membership_type_id
2435 // it will be used when payment is received to update the membership_type_id to what was paid for
2437 'membership_id' => $membership->id
,
2438 'status_id' => $membership->status_id
,
2439 'start_date' => CRM_Utils_Date
::customFormat(
2440 $membership->start_date
,
2443 'end_date' => CRM_Utils_Date
::customFormat(
2444 $membership->end_date
,
2447 'modified_date' => CRM_Utils_Date
::customFormat(
2451 'membership_type_id' => $membershipTypeID,
2452 'max_related' => !empty($membershipTypeDetails['max_related']) ?
$membershipTypeDetails['max_related'] : NULL,
2454 $session = CRM_Core_Session
::singleton();
2455 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
2456 if ($session->get('userID')) {
2457 $logParams['modified_id'] = $session->get('userID');
2460 $logParams['modified_id'] = $membership->contact_id
;
2462 CRM_Member_BAO_MembershipLog
::add($logParams, CRM_Core_DAO
::$_nullArray);
2464 if (!empty($contributionRecurID)) {
2465 CRM_Core_DAO
::setFieldValue('CRM_Member_DAO_Membership', $membership->id
,
2466 'contribution_recur_id', $contributionRecurID
2470 return array($membership, $renewalMode, $dates);
2473 // Check and fix the membership if it is STALE
2474 self
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
2476 // Now Renew the membership
2477 if (!$currentMembership['is_current_member']) {
2478 // membership is not CURRENT
2480 // CRM-7297 Membership Upsell - calculate dates based on new membership type
2481 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($currentMembership['id'],
2487 $currentMembership['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
2488 $currentMembership['start_date'] = CRM_Utils_Array
::value('start_date', $dates);
2489 $currentMembership['end_date'] = CRM_Utils_Array
::value('end_date', $dates);
2490 $currentMembership['is_test'] = $is_test;
2492 if (!empty($membershipSource)) {
2493 $currentMembership['source'] = $membershipSource;
2496 $currentMembership['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
2497 $currentMembership['id'],
2502 if (!empty($currentMembership['id'])) {
2503 $ids['membership'] = $currentMembership['id'];
2505 $memParams = $currentMembership;
2506 $memParams['membership_type_id'] = $membershipTypeID;
2508 //set the log start date.
2509 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
2513 // CURRENT Membership
2514 $membership = new CRM_Member_DAO_Membership();
2515 $membership->id
= $currentMembership['id'];
2516 $membership->find(TRUE);
2517 // CRM-7297 Membership Upsell - calculate dates based on new membership type
2518 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
2524 // Insert renewed dates for CURRENT membership
2525 $memParams = array();
2526 $memParams['join_date'] = CRM_Utils_Date
::isoToMysql($membership->join_date
);
2527 $memParams['start_date'] = CRM_Utils_Date
::isoToMysql($membership->start_date
);
2528 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $dates);
2529 $memParams['membership_type_id'] = $membershipTypeID;
2531 //set the log start date.
2532 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
2533 if (empty($membership->source
)) {
2534 if (!empty($membershipSource)) {
2535 $memParams['source'] = $membershipSource;
2538 $memParams['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
2539 $currentMembership['id'],
2545 if (!empty($currentMembership['id'])) {
2546 $ids['membership'] = $currentMembership['id'];
2551 $updateStatusId = array_search('Pending', $allStatus);
2557 $activityType = 'Membership Signup';
2559 'contact_id' => $contactID,
2560 'membership_type_id' => $membershipTypeID,
2564 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
2566 $memParams['join_date'] = CRM_Utils_Array
::value('join_date', $dates);
2567 $memParams['start_date'] = CRM_Utils_Array
::value('start_date', $dates);
2568 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $dates);
2570 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(CRM_Utils_Date
::customFormat($dates['start_date'],
2573 CRM_Utils_Date
::customFormat($dates['end_date'],
2576 CRM_Utils_Date
::customFormat($dates['join_date'],
2584 $updateStatusId = CRM_Utils_Array
::value('id', $status);
2587 // if IPN/Pay-Later set status to: PENDING
2588 $updateStatusId = array_search('Pending', $allStatus);
2591 if (!empty($membershipSource)) {
2592 $memParams['source'] = $membershipSource;
2594 $memParams['contribution_recur_id'] = $contributionRecurID;
2596 $memParams['is_test'] = $is_test;
2597 $memParams['is_pay_later'] = $isPayLater;
2601 //if we decided status here and want to skip status
2602 //calculation in create( ); then need to pass 'skipStatusCal'.
2603 if ($updateStatusId) {
2604 $memParams['status_id'] = $updateStatusId;
2605 $memParams['skipStatusCal'] = TRUE;
2608 //since we are renewing,
2609 //make status override false.
2610 $memParams['is_override'] = FALSE;
2612 //CRM-4027, create log w/ individual contact.
2614 $ids['userId'] = $modifiedID;
2615 $memParams['is_for_organization'] = TRUE;
2618 $ids['userId'] = $contactID;
2621 //inherit campaign from contrib page.
2622 if (isset($campaignId)) {
2623 $memParams['campaign_id'] = $campaignId;
2626 $memParams['custom'] = $customFieldsFormatted;
2627 $membership = self
::create($memParams, $ids, FALSE, $activityType);
2629 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
2630 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
2631 $membership->find(TRUE);
2633 return array($membership, $renewalMode, $dates);
2637 * Process price set and line items.
2639 * @param int $membershipId
2644 public function processPriceSet($membershipId, $lineItem) {
2645 //FIXME : need to move this too
2646 if (!$membershipId ||
!is_array($lineItem)
2647 || CRM_Utils_System
::isNull($lineItem)
2652 foreach ($lineItem as $priceSetId => $values) {
2656 foreach ($values as $line) {
2657 $line['entity_table'] = 'civicrm_membership';
2658 $line['entity_id'] = $membershipId;
2659 CRM_Price_BAO_LineItem
::create($line);
2665 * Retrieve the contribution id for the associated Membership id
2666 * @todo we should get this off the line item
2668 * @param int $membershipId
2674 public static function getMembershipContributionId($membershipId) {
2676 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
2677 $membershipPayment->membership_id
= $membershipId;
2678 if ($membershipPayment->find(TRUE)) {
2679 return $membershipPayment->contribution_id
;
2685 * The function checks and updates the status of all membership records for a given domain using the
2686 * calc_membership_status and update_contact_membership APIs.
2689 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
2693 public static function updateAllMembershipStatus() {
2695 //get all active statuses of membership, CRM-3984
2696 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2697 $statusLabels = CRM_Member_PseudoConstant
::membershipStatus(NULL, NULL, 'label');
2698 $allTypes = CRM_Member_PseudoConstant
::membershipType();
2700 // get only memberships with active membership types
2702 SELECT civicrm_membership.id as membership_id,
2703 civicrm_membership.is_override as is_override,
2704 civicrm_membership.membership_type_id as membership_type_id,
2705 civicrm_membership.status_id as status_id,
2706 civicrm_membership.join_date as join_date,
2707 civicrm_membership.start_date as start_date,
2708 civicrm_membership.end_date as end_date,
2709 civicrm_membership.source as source,
2710 civicrm_contact.id as contact_id,
2711 civicrm_contact.is_deceased as is_deceased,
2712 civicrm_membership.owner_membership_id as owner_membership_id,
2713 civicrm_membership.contribution_recur_id as recur_id
2714 FROM civicrm_membership
2715 INNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )
2716 INNER JOIN civicrm_membership_type ON
2717 (civicrm_membership.membership_type_id = civicrm_membership_type.id AND civicrm_membership_type.is_active = 1)
2718 WHERE civicrm_membership.is_test = 0";
2721 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2726 $smarty = CRM_Core_Smarty
::singleton();
2728 while ($dao->fetch()) {
2732 // Put common parameters into array for easy access
2733 $memberParams = array(
2734 'id' => $dao->membership_id
,
2735 'status_id' => $dao->status_id
,
2736 'contact_id' => $dao->contact_id
,
2737 'membership_type_id' => $dao->membership_type_id
,
2738 'membership_type' => $allTypes[$dao->membership_type_id
],
2739 'join_date' => $dao->join_date
,
2740 'start_date' => $dao->start_date
,
2741 'end_date' => $dao->end_date
,
2742 'source' => $dao->source
,
2743 'skipStatusCal' => TRUE,
2744 'skipRecentView' => TRUE,
2747 $smarty->assign_by_ref('memberParams', $memberParams);
2749 //update membership record to Deceased if contact is deceased
2750 if ($dao->is_deceased
) {
2751 // check for 'Deceased' membership status, CRM-5636
2752 $deceaseStatusId = array_search('Deceased', $allStatus);
2753 if (!$deceaseStatusId) {
2754 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'))));
2757 //process only when status change.
2758 if ($dao->status_id
!= $deceaseStatusId) {
2759 //take all params that need to save.
2760 $deceasedMembership = $memberParams;
2761 $deceasedMembership['status_id'] = $deceaseStatusId;
2762 $deceasedMembership['createActivity'] = TRUE;
2763 $deceasedMembership['version'] = 3;
2765 //since there is change in status.
2766 $statusChange = array('status_id' => $deceaseStatusId);
2767 $smarty->append_by_ref('memberParams', $statusChange, TRUE);
2769 $deceasedMembership['contact_id'],
2770 $deceasedMembership['membership_type_id'],
2771 $deceasedMembership['membership_type'],
2772 $deceasedMembership['join_date'],
2773 $deceasedMembership['start_date'],
2774 $deceasedMembership['end_date'],
2775 $deceasedMembership['source']
2778 //process membership record.
2779 civicrm_api('membership', 'create', $deceasedMembership);
2784 //we fetch related, since we need to check for deceased
2785 //now further processing is handle w/ main membership record.
2786 if ($dao->owner_membership_id
) {
2790 //update membership records where status is NOT - Pending OR Cancelled.
2791 //as well as membership is not override.
2792 //skipping Expired membership records -> reduced extra processing( kiran )
2793 if (!$dao->is_override
&&
2794 !in_array($dao->status_id
, array(
2795 array_search('Pending', $allStatus),
2799 CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)
2801 array_search('Expired', $allStatus),
2805 // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses
2806 //get the membership status as per id.
2807 $newStatus = civicrm_api('membership_status', 'calc',
2809 'membership_id' => $dao->membership_id
,
2811 'ignore_admin_only' => FALSE,
2814 $statusId = CRM_Utils_Array
::value('id', $newStatus);
2816 //process only when status change.
2818 $statusId != $dao->status_id
2820 //take all params that need to save.
2821 $memParams = $memberParams;
2822 $memParams['status_id'] = $statusId;
2823 $memParams['createActivity'] = TRUE;
2824 $memParams['version'] = 3;
2826 // Unset columns which should remain unchanged from their current saved
2827 // values. This avoids race condition in which these values may have
2828 // been changed by other processes.
2830 $memParams['contact_id'],
2831 $memParams['membership_type_id'],
2832 $memParams['membership_type'],
2833 $memParams['join_date'],
2834 $memParams['start_date'],
2835 $memParams['end_date'],
2836 $memParams['source']
2838 //since there is change in status.
2839 $statusChange = array('status_id' => $statusId);
2840 $smarty->append_by_ref('memberParams', $statusChange, TRUE);
2842 //process member record.
2843 civicrm_api('membership', 'create', $memParams);
2848 $result['is_error'] = 0;
2849 $result['messages'] = ts('Processed %1 membership records. Updated %2 records.', array(
2857 * Returns the membership types for a particular contact
2858 * who has lifetime membership without end date.
2860 * @param int $contactID
2861 * @param bool $isTest
2862 * @param bool $onlyLifeTime
2866 public static function getAllContactMembership($contactID, $isTest = FALSE, $onlyLifeTime = FALSE) {
2867 $contactMembershipType = array();
2869 return $contactMembershipType;
2872 $dao = new CRM_Member_DAO_Membership();
2873 $dao->contact_id
= $contactID;
2874 $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
2875 $dao->whereAdd("status_id != $pendingStatusId");
2878 $dao->is_test
= $isTest;
2881 $dao->whereAdd('is_test IS NULL OR is_test = 0');
2884 if ($onlyLifeTime) {
2885 $dao->whereAdd('end_date IS NULL');
2889 while ($dao->fetch()) {
2890 $membership = array();
2891 CRM_Core_DAO
::storeValues($dao, $membership);
2892 $contactMembershipType[$dao->membership_type_id
] = $membership;
2894 return $contactMembershipType;
2898 * Record contribution record associated with membership
2900 * @param array $params
2901 * Array of submitted params.
2903 * (param in process of being removed - try to use params) array of ids.
2905 * @return CRM_Contribute_BAO_Contribution
2907 public static function recordMembershipContribution(&$params, $ids = array()) {
2908 $membershipId = $params['membership_id'];
2909 $contributionParams = array();
2910 $config = CRM_Core_Config
::singleton();
2911 $contributionParams['currency'] = $config->defaultCurrency
;
2912 $contributionParams['receipt_date'] = (CRM_Utils_Array
::value('receipt_date', $params)) ?
$params['receipt_date'] : 'null';
2913 $contributionParams['source'] = CRM_Utils_Array
::value('contribution_source', $params);
2914 $contributionParams['non_deductible_amount'] = 'null';
2915 $contributionParams['payment_processor'] = CRM_Utils_Array
::value('payment_processor_id', $params);
2916 $contributionSoftParams = CRM_Utils_Array
::value('soft_credit', $params);
2917 $recordContribution = array(
2921 'financial_type_id',
2922 'payment_instrument_id',
2926 'contribution_status_id',
2934 foreach ($recordContribution as $f) {
2935 $contributionParams[$f] = CRM_Utils_Array
::value($f, $params);
2938 // make entry in batch entity batch table
2939 if (!empty($params['batch_id'])) {
2940 $contributionParams['batch_id'] = $params['batch_id'];
2943 if (!empty($params['contribution_contact_id'])) {
2944 // deal with possibility of a different person paying for contribution
2945 $contributionParams['contact_id'] = $params['contribution_contact_id'];
2948 if (!empty($params['processPriceSet']) &&
2949 !empty($params['lineItems'])
2951 $contributionParams['line_item'] = CRM_Utils_Array
::value('lineItems', $params, NULL);
2954 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
2956 //CRM-13981, create new soft-credit record as to record payment from different person for this membership
2957 if (!empty($contributionSoftParams)) {
2958 if (!empty($params['batch_id'])) {
2959 foreach ($contributionSoftParams as $contributionSoft) {
2960 $contributionSoft['contribution_id'] = $contribution->id
;
2961 $contributionSoft['currency'] = $contribution->currency
;
2962 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoft);
2966 $contributionSoftParams['contribution_id'] = $contribution->id
;
2967 $contributionSoftParams['currency'] = $contribution->currency
;
2968 $contributionSoftParams['amount'] = $contribution->total_amount
;
2969 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoftParams);
2973 // store contribution id
2974 $params['contribution_id'] = $contribution->id
;
2976 //insert payment record for this membership
2977 if (empty($ids['contribution']) ||
!empty($params['is_recur'])) {
2978 CRM_Member_BAO_MembershipPayment
::create(array(
2979 'membership_id' => $membershipId,
2980 'contribution_id' => $contribution->id
,
2983 return $contribution;
2987 * Record line items for default membership
2989 * @param CRM_Core_Form $qf
2990 * @param array $membershipType
2991 * Array with membership type and organization.
2992 * @param int $priceSetId
2995 public static function createLineItems(&$qf, $membershipType, &$priceSetId) {
2996 $qf->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
2998 $qf->_priceSet
= $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
3000 $editedFieldParams = array(
3001 'price_set_id' => $priceSetId,
3002 'name' => $membershipType[0],
3004 $editedResults = array();
3005 CRM_Price_BAO_PriceField
::retrieve($editedFieldParams, $editedResults);
3007 if (!empty($editedResults)) {
3008 unset($qf->_priceSet
['fields']);
3009 $qf->_priceSet
['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
3010 unset($qf->_priceSet
['fields'][$editedResults['id']]['options']);
3011 $fid = $editedResults['id'];
3012 $editedFieldParams = array(
3013 'price_field_id' => $editedResults['id'],
3014 'membership_type_id' => $membershipType[1],
3016 $editedResults = array();
3017 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $editedResults);
3018 $qf->_priceSet
['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
3019 if (!empty($qf->_params
['total_amount'])) {
3020 $qf->_priceSet
['fields'][$fid]['options'][$editedResults['id']]['amount'] = $qf->_params
['total_amount'];
3024 $fieldID = key($qf->_priceSet
['fields']);
3025 $qf->_params
['price_' . $fieldID] = CRM_Utils_Array
::value('id', $editedResults);
3029 * @todo document me - I seem a bit out of date....
3031 public static function _getActTypes() {
3032 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
3033 self
::$_renewalActType = CRM_Utils_Array
::key('Membership Renewal', $activityTypes);
3034 self
::$_signupActType = CRM_Utils_Array
::key('Membership Signup', $activityTypes);
3038 * Get all Cancelled Membership(s) for a contact
3040 * @param int $contactID
3042 * @param bool $isTest
3046 * Array of membership type
3048 public static function getContactsCancelledMembership($contactID, $isTest = FALSE) {
3052 $query = 'SELECT membership_type_id FROM civicrm_membership WHERE contact_id = %1 AND status_id = %2 AND is_test = %3';
3053 $queryParams = array(
3054 1 => array($contactID, 'Integer'),
3059 CRM_Member_PseudoConstant
::membershipStatus(
3061 " name = 'Cancelled' ",
3069 3 => array($isTest, 'Boolean'),
3072 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
3073 $cancelledMembershipIds = array();
3074 while ($dao->fetch()) {
3075 $cancelledMembershipIds[] = $dao->membership_type_id
;
3077 return $cancelledMembershipIds;