3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2015
33 class CRM_Member_BAO_Membership
extends CRM_Member_DAO_Membership
{
36 * Static field for all the membership information that we can potentially import.
40 static $_importableFields = NULL;
42 static $_renewalActType = NULL;
44 static $_signupActType = NULL;
49 public function __construct() {
50 parent
::__construct();
54 * Takes an associative array and creates a membership object.
56 * the function extracts all the params it needs to initialize the created
57 * membership object. The params array could contain additional unused name/value
60 * @param array $params
61 * (reference ) an assoc array of name/value pairs.
63 * The array that holds all the db ids.
65 * @return CRM_Member_BAO_Membership
67 public static function add(&$params, $ids = array()) {
68 $oldStatus = $oldType = NULL;
69 $params['id'] = CRM_Utils_Array
::value('id', $params, CRM_Utils_Array
::value('membership', $ids));
71 CRM_Utils_Hook
::pre('edit', 'Membership', $params['id'], $params);
74 CRM_Utils_Hook
::pre('create', 'Membership', NULL, $params);
77 // we do this after the hooks are called in case it has been altered
79 $membershipObj = new CRM_Member_DAO_Membership();
80 $membershipObj->id
= $id;
81 $membershipObj->find();
82 while ($membershipObj->fetch()) {
83 $oldStatus = $membershipObj->status_id
;
84 $oldType = $membershipObj->membership_type_id
;
88 if (array_key_exists('is_override', $params) && !$params['is_override']) {
89 $params['is_override'] = 'null';
92 $membership = new CRM_Member_BAO_Membership();
93 $membership->copyValues($params);
94 $membership->id
= $id;
99 if (empty($membership->contact_id
) ||
empty($membership->status_id
)) {
100 // this means we are in renewal mode and are just updating the membership
101 // record or this is an API update call and all fields are not present in the update record
102 // however the hooks don't care and want all data CRM-7784
103 $tempMembership = new CRM_Member_DAO_Membership();
104 $tempMembership->id
= $membership->id
;
105 $tempMembership->find(TRUE);
106 $membership = $tempMembership;
109 //get the log start date.
110 //it is set during renewal of membership.
111 $logStartDate = CRM_Utils_Array
::value('log_start_date', $params);
112 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : CRM_Utils_Date
::isoToMysql($membership->start_date
);
113 $values = self
::getStatusANDTypeValues($membership->id
);
115 $membershipLog = array(
116 'membership_id' => $membership->id
,
117 'status_id' => $membership->status_id
,
118 'start_date' => $logStartDate,
119 'end_date' => CRM_Utils_Date
::isoToMysql($membership->end_date
),
120 'modified_date' => date('Ymd'),
121 'membership_type_id' => $values[$membership->id
]['membership_type_id'],
122 'max_related' => $membership->max_related
,
125 $session = CRM_Core_Session
::singleton();
126 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
127 if ($session->get('userID')) {
128 $membershipLog['modified_id'] = $session->get('userID');
130 elseif (!empty($ids['userId'])) {
131 $membershipLog['modified_id'] = $ids['userId'];
134 $membershipLog['modified_id'] = $membership->contact_id
;
137 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
139 // reset the group contact cache since smart groups might be affected due to this
140 CRM_Contact_BAO_GroupContactCache
::remove();
143 if ($membership->status_id
!= $oldStatus) {
144 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
145 $activityParam = array(
146 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
147 'source_contact_id' => $membershipLog['modified_id'],
148 'target_contact_id' => $membership->contact_id
,
149 'source_record_id' => $membership->id
,
150 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Change Membership Status'),
153 'activity_date_time' => date('Y-m-d H:i:s'),
155 civicrm_api3('activity', 'create', $activityParam);
157 if (isset($membership->membership_type_id
) && $membership->membership_type_id
!= $oldType) {
158 $membershipTypes = CRM_Member_BAO_Membership
::buildOptions('membership_type_id', 'get');
159 $activityParam = array(
160 'subject' => "Type changed from {$membershipTypes[$oldType]} to {$membershipTypes[$membership->membership_type_id]}",
161 'source_contact_id' => $membershipLog['modified_id'],
162 'target_contact_id' => $membership->contact_id
,
163 'source_record_id' => $membership->id
,
164 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Change Membership Type'),
167 'activity_date_time' => date('Y-m-d H:i:s'),
169 civicrm_api3('activity', 'create', $activityParam);
171 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
174 CRM_Utils_Hook
::post('create', 'Membership', $membership->id
, $membership);
181 * Fetch the object and store the values in the values array.
183 * @param array $params
184 * Input parameters to find object.
185 * @param array $values
186 * Output values of the object.
187 * @param bool $active
188 * Do you want only active memberships to.
190 * @param bool $relatedMemberships
192 * @return CRM_Member_BAO_Membership|null
193 * The found object or null
195 public static function &getValues(&$params, &$values, $active = FALSE, $relatedMemberships = FALSE) {
196 if (empty($params)) {
199 $membership = new CRM_Member_BAO_Membership();
201 $membership->copyValues($params);
203 $memberships = array();
204 while ($membership->fetch()) {
206 (!CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
207 $membership->status_id
,
214 CRM_Core_DAO
::storeValues($membership, $values[$membership->id
]);
215 $memberships[$membership->id
] = $membership;
216 if ($relatedMemberships && !empty($membership->owner_membership_id
)) {
217 $values['owner_membership_ids'][] = $membership->owner_membership_id
;
225 * Takes an associative array and creates a membership object.
227 * @param array $params
228 * (reference ) an assoc array of name/value pairs.
230 * The array that holds all the db ids.
231 * @param bool $skipRedirect
232 * @param string $activityType
234 * @throws CRM_Core_Exception
236 * @return CRM_Member_BAO_Membership|CRM_Core_Error
238 public static function create(&$params, &$ids, $skipRedirect = FALSE, $activityType = 'Membership Signup') {
239 // always calculate status if is_override/skipStatusCal is not true.
240 // giving respect to is_override during import. CRM-4012
242 // To skip status calculation we should use 'skipStatusCal'.
243 // eg pay later membership, membership update cron CRM-3984
245 if (empty($params['is_override']) && empty($params['skipStatusCal'])) {
246 $dates = array('start_date', 'end_date', 'join_date');
247 // Declare these out of courtesy as IDEs don't pick up the setting of them below.
248 $start_date = $end_date = $join_date = NULL;
249 foreach ($dates as $date) {
250 $
$date = $params[$date] = CRM_Utils_Date
::processDate(CRM_Utils_Array
::value($date, $params), NULL, TRUE, 'Ymd');
253 //fix for CRM-3570, during import exclude the statuses those having is_admin = 1
254 $excludeIsAdmin = CRM_Utils_Array
::value('exclude_is_admin', $params, FALSE);
256 //CRM-3724 always skip is_admin if is_override != true.
257 if (!$excludeIsAdmin && empty($params['is_override'])) {
258 $excludeIsAdmin = TRUE;
261 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($start_date, $end_date, $join_date,
262 'today', $excludeIsAdmin, CRM_Utils_Array
::value('membership_type_id', $params), $params
264 if (empty($calcStatus)) {
265 // Redirect the form in case of error
266 // @todo this redirect in the BAO layer is really bad & should be moved to the form layer
267 // however since we have no idea how (if) this is triggered we can't safely move / remove it
268 // NB I tried really hard to trigger this error from backoffice membership form in order to test it
269 // and am convinced form validation is complete on that form WRT this error.
270 $errorParams = array(
271 'message_title' => ts('No valid membership status for given dates.'),
272 'legacy_redirect_path' => 'civicrm/contact/view',
273 'legacy_redirect_query' => "reset=1&force=1&cid={$params['contact_id']}&selectedChild=member",
275 throw new CRM_Core_Exception(ts('The membership cannot be saved because the status cannot be calculated.'), 0, $errorParams);
277 $params['status_id'] = $calcStatus['id'];
280 // data cleanup only: all verifications on number of related memberships are done upstream in:
281 // CRM_Member_BAO_Membership::createRelatedMemberships()
282 // CRM_Contact_BAO_Relationship::relatedMemberships()
283 if (isset($params['owner_membership_id'])) {
284 unset($params['max_related']);
287 // if membership allows related, default max_related to value in membership_type
288 if (!array_key_exists('max_related', $params) && !empty($params['membership_type_id'])) {
289 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($params['membership_type_id']);
290 if (isset($membershipType['relationship_type_id'])) {
291 $params['max_related'] = CRM_Utils_Array
::value('max_related', $membershipType);
296 $transaction = new CRM_Core_Transaction();
298 $membership = self
::add($params, $ids);
300 if (is_a($membership, 'CRM_Core_Error')) {
301 $transaction->rollback();
305 // add custom field values
306 if (!empty($params['custom']) && is_array($params['custom'])
308 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_membership', $membership->id
);
311 $params['membership_id'] = $membership->id
;
312 if (isset($ids['membership'])) {
313 $ids['contribution'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment',
320 $params['skipLineItem'] = TRUE;
322 //record contribution for this membership
323 if (!empty($params['contribution_status_id']) && empty($params['relate_contribution_id'])) {
324 $memInfo = array_merge($params, array('membership_id' => $membership->id
));
325 $params['contribution'] = self
::recordMembershipContribution($memInfo, $ids);
328 if (!empty($params['lineItems'])) {
329 $params['line_item'] = $params['lineItems'];
332 //do cleanup line items if membership edit the Membership type.
333 if (empty($ids['contribution']) && !empty($ids['membership'])) {
334 CRM_Price_BAO_LineItem
::deleteLineItems($ids['membership'], 'civicrm_membership');
337 if (!empty($params['line_item']) && empty($ids['contribution'])) {
338 CRM_Price_BAO_LineItem
::processPriceSet($membership->id
, $params['line_item'], CRM_Utils_Array
::value('contribution', $params));
341 //insert payment record for this membership
342 if (!empty($params['relate_contribution_id'])) {
343 CRM_Member_BAO_MembershipPayment
::create(array(
344 'membership_id' => $membership->id
,
345 'contribution_id' => $params['relate_contribution_id'],
349 // add activity record only during create mode and renew mode
350 // also add activity if status changed CRM-3984 and CRM-2521
351 if (empty($ids['membership']) ||
352 $activityType == 'Membership Renewal' ||
!empty($params['createActivity'])
354 if (!empty($ids['membership'])) {
356 CRM_Core_DAO
::commonRetrieveAll('CRM_Member_DAO_Membership',
360 array('contact_id', 'membership_type_id', 'source')
363 $membership->contact_id
= $data[$membership->id
]['contact_id'];
364 $membership->membership_type_id
= $data[$membership->id
]['membership_type_id'];
365 $membership->source
= CRM_Utils_Array
::value('source', $data[$membership->id
]);
368 // since we are going to create activity record w/
369 // individual contact as a target in case of on behalf signup,
370 // so get the copy of organization id, CRM-5551
371 $realMembershipContactId = $membership->contact_id
;
373 // create activity source = individual, target = org CRM-4027
374 $targetContactID = NULL;
375 if (!empty($params['is_for_organization'])) {
376 $targetContactID = $membership->contact_id
;
377 $membership->contact_id
= CRM_Utils_Array
::value('userId', $ids);
380 if (empty($membership->contact_id
) && (!empty($membership->owner_membership_id
))) {
381 $membership->contact_id
= $realMembershipContactId;
384 if (!empty($ids['membership']) && $activityType != 'Membership Signup') {
385 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $targetContactID);
387 elseif (empty($ids['membership'])) {
388 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $targetContactID);
391 // we might created activity record w/ individual
392 // contact as target so update membership object w/
393 // original organization id, CRM-5551
394 $membership->contact_id
= $realMembershipContactId;
397 $transaction->commit();
399 self
::createRelatedMemberships($params, $membership);
401 // do not add to recent items for import, CRM-4399
402 if (empty($params['skipRecentView'])) {
403 $url = CRM_Utils_System
::url('civicrm/contact/view/membership',
404 "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
406 if (empty($membership->membership_type_id
)) {
407 // 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 * Retrieve DB object based on input parameters.
508 * It also stores all the retrieved values in the default array.
510 * @param array $params
511 * (reference ) an assoc array of name/value pairs.
512 * @param array $defaults
513 * (reference ) an assoc array to hold the name / value pairs.
514 * in a hierarchical manner
516 * @return CRM_Member_BAO_Membership
518 public static function retrieve(&$params, &$defaults) {
519 $membership = new CRM_Member_DAO_Membership();
521 $membership->copyValues($params);
523 if ($membership->find(TRUE)) {
524 CRM_Core_DAO
::storeValues($membership, $defaults);
526 //get the membership status and type values.
527 $statusANDType = self
::getStatusANDTypeValues($membership->id
);
532 $defaults[$fld] = CRM_Utils_Array
::value($fld, $statusANDType[$membership->id
]);
534 if (!empty($statusANDType[$membership->id
]['is_current_member'])) {
535 $defaults['active'] = TRUE;
547 * Get membership status and membership type values.
549 * @param int $membershipId
550 * Membership id of values to return.
553 * Array of key value pairs
555 public static function getStatusANDTypeValues($membershipId) {
557 if (!$membershipId) {
561 SELECT membership.id as id,
562 status.id as status_id,
563 status.label as status,
564 status.is_current_member as is_current_member,
565 type.id as membership_type_id,
566 type.name as membership_type,
567 type.relationship_type_id as relationship_type_id
568 FROM civicrm_membership membership
569 INNER JOIN civicrm_membership_status status ON ( status.id = membership.status_id )
570 INNER JOIN civicrm_membership_type type ON ( type.id = membership.membership_type_id )
571 WHERE membership.id = %1';
572 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($membershipId, 'Positive')));
577 'membership_type_id',
579 'relationship_type_id',
581 while ($dao->fetch()) {
582 foreach ($properties as $property) {
583 $values[$dao->id
][$property] = $dao->$property;
593 * Wrapper for most delete calls. Use this unless you JUST want to delete related memberships w/o deleting the parent.
595 * @param int $membershipId
596 * Membership id that needs to be deleted.
599 * Id of deleted Membership on success, false otherwise.
601 public static function del($membershipId) {
602 //delete related first and then delete parent.
603 self
::deleteRelatedMemberships($membershipId);
604 return self
::deleteMembership($membershipId);
610 * @param int $membershipId
611 * Membership id that needs to be deleted.
614 * Id of deleted Membership on success, false otherwise.
616 public static function deleteMembership($membershipId) {
617 // CRM-12147, retrieve membership data before we delete it for hooks
618 $params = array('id' => $membershipId);
619 $memValues = array();
620 $memberships = self
::getValues($params, $memValues);
622 $membership = $memberships[$membershipId];
624 CRM_Utils_Hook
::pre('delete', 'Membership', $membershipId, $memValues);
626 $transaction = new CRM_Core_Transaction();
629 //delete activity record
630 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
633 $deleteActivity = FALSE;
634 $membershipActivities = array(
636 'Membership Renewal',
637 'Change Membership Status',
638 'Change Membership Type',
639 'Membership Renewal Reminder',
641 foreach ($membershipActivities as $membershipActivity) {
642 $activityId = array_search($membershipActivity, $activityTypes);
644 $params['activity_type_id'][] = $activityId;
645 $deleteActivity = TRUE;
648 if ($deleteActivity) {
649 $params['source_record_id'] = $membershipId;
650 CRM_Activity_BAO_Activity
::deleteActivity($params);
652 self
::deleteMembershipPayment($membershipId);
654 $results = $membership->delete();
655 $transaction->commit();
657 CRM_Utils_Hook
::post('delete', 'Membership', $membership->id
, $membership);
659 // delete the recently created Membership
660 $membershipRecent = array(
661 'id' => $membershipId,
662 'type' => 'Membership',
664 CRM_Utils_Recent
::del($membershipRecent);
670 * Delete related memberships.
672 * @param int $ownerMembershipId
673 * @param int $contactId
677 public static function deleteRelatedMemberships($ownerMembershipId, $contactId = NULL) {
678 if (!$ownerMembershipId && !$contactId) {
682 $membership = new CRM_Member_DAO_Membership();
683 $membership->owner_membership_id
= $ownerMembershipId;
686 $membership->contact_id
= $contactId;
690 while ($membership->fetch()) {
691 //delete related first and then delete parent.
692 self
::deleteRelatedMemberships($membership->id
);
693 self
::deleteMembership($membership->id
);
699 * Obtain active/inactive memberships from the list of memberships passed to it.
701 * @param array $memberships
702 * Membership records.
703 * @param string $status
704 * Active or inactive.
707 * array of memberships based on status
709 public static function activeMembers($memberships, $status = 'active') {
711 if ($status == 'active') {
712 foreach ($memberships as $f => $v) {
713 if (!empty($v['active'])) {
719 elseif ($status == 'inactive') {
720 foreach ($memberships as $f => $v) {
721 if (empty($v['active'])) {
731 * Build Membership Block in Contribution Pages.
733 * @param CRM_Core_Form $form
738 * Contact checked for having a current membership for a particular membership.
739 * @param bool $formItems
740 * @param int $selectedMembershipTypeID
741 * Selected membership id.
742 * @param bool $thankPage
744 * @param null $isTest
747 * Is this a separate membership payment
749 public static function buildMembershipBlock(
754 $selectedMembershipTypeID = NULL,
759 $separateMembershipPayment = FALSE;
760 if ($form->_membershipBlock
) {
761 $form->_currentMemberships
= array();
763 $membershipBlock = $form->_membershipBlock
;
764 $membershipTypeIds = $membershipTypes = $radio = array();
765 $membershipPriceset = (!empty($form->_priceSetId
) && $form->_useForMember
) ?
TRUE : FALSE;
767 $allowAutoRenewMembership = $autoRenewOption = FALSE;
768 $autoRenewMembershipTypeOptions = array();
770 $paymentProcessor = CRM_Core_PseudoConstant
::paymentProcessor(FALSE, FALSE, 'is_recur = 1');
772 $separateMembershipPayment = CRM_Utils_Array
::value('is_separate_payment', $membershipBlock);
774 if ($membershipPriceset) {
775 foreach ($form->_priceSet
['fields'] as $pField) {
776 if (empty($pField['options'])) {
779 foreach ($pField['options'] as $opId => $opValues) {
780 if (empty($opValues['membership_type_id'])) {
783 $membershipTypeIds[$opValues['membership_type_id']] = $opValues['membership_type_id'];
787 elseif (!empty($membershipBlock['membership_types'])) {
788 $membershipTypeIds = explode(',', $membershipBlock['membership_types']);
791 if (!empty($membershipTypeIds)) {
792 //set status message if wrong membershipType is included in membershipBlock
793 if (isset($form->_mid
) && !$membershipPriceset) {
794 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
798 if (!in_array($membershipTypeID, $membershipTypeIds)) {
799 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');
803 $membershipTypeValues = self
::buildMembershipTypeValues($form, $membershipTypeIds);
804 $form->_membershipTypeValues
= $membershipTypeValues;
806 foreach ($membershipTypeIds as $value) {
807 $memType = $membershipTypeValues[$value];
808 if ($selectedMembershipTypeID != NULL) {
809 if ($memType['id'] == $selectedMembershipTypeID) {
810 $form->assign('minimum_fee',
811 CRM_Utils_Array
::value('minimum_fee', $memType)
813 $form->assign('membership_name', $memType['name']);
814 if (!$thankPage && $cid) {
815 $membership = new CRM_Member_DAO_Membership();
816 $membership->contact_id
= $cid;
817 $membership->membership_type_id
= $memType['id'];
818 if ($membership->find(TRUE)) {
819 $form->assign('renewal_mode', TRUE);
820 $memType['current_membership'] = $membership->end_date
;
821 $form->_currentMemberships
[$membership->membership_type_id
] = $membership->membership_type_id
;
824 $membershipTypes[] = $memType;
827 elseif ($memType['is_active']) {
828 $javascriptMethod = NULL;
829 $allowAutoRenewOpt = 1;
830 if (is_array($form->_paymentProcessors
)) {
831 foreach ($form->_paymentProcessors
as $id => $val) {
832 if (!$val['is_recur']) {
833 $allowAutoRenewOpt = 0;
839 $javascriptMethod = array('onclick' => "return showHideAutoRenew( this.value );");
840 $autoRenewMembershipTypeOptions["autoRenewMembershipType_{$value}"] = (int) $allowAutoRenewOpt * CRM_Utils_Array
::value($value, CRM_Utils_Array
::value('auto_renew', $form->_membershipBlock
));;
842 if ($allowAutoRenewOpt) {
843 $allowAutoRenewMembership = TRUE;
846 //add membership type.
847 $radio[$memType['id']] = $form->createElement('radio', NULL, NULL, NULL,
848 $memType['id'], $javascriptMethod
851 $membership = new CRM_Member_DAO_Membership();
852 $membership->contact_id
= $cid;
853 $membership->membership_type_id
= $memType['id'];
855 //show current membership, skip pending and cancelled membership records,
856 //because we take first membership record id for renewal
857 $membership->whereAdd('status_id != 5 AND status_id !=6');
859 if (!is_null($isTest)) {
860 $membership->is_test
= $isTest;
864 $membership->orderBy('end_date DESC');
866 if ($membership->find(TRUE)) {
867 if (!$membership->end_date
) {
868 unset($radio[$memType['id']]);
869 $form->assign('islifetime', TRUE);
872 $form->assign('renewal_mode', TRUE);
873 $form->_currentMemberships
[$membership->membership_type_id
] = $membership->membership_type_id
;
874 $memType['current_membership'] = $membership->end_date
;
876 $endDate = $memType['current_membership'];
877 $form->_defaultMemTypeId
= $memType['id'];
879 if ($memType['current_membership'] < $endDate) {
880 $endDate = $memType['current_membership'];
881 $form->_defaultMemTypeId
= $memType['id'];
885 $membershipTypes[] = $memType;
890 $form->assign('showRadio', $formItems);
892 if (!$membershipPriceset) {
893 if (!$membershipBlock['is_required']) {
894 $form->assign('showRadioNoThanks', TRUE);
895 $radio[''] = $form->createElement('radio', NULL, NULL, NULL, 'no_thanks', NULL);
896 $form->addGroup($radio, 'selectMembership', NULL);
898 elseif ($membershipBlock['is_required'] && count($radio) == 1) {
899 $temp = array_keys($radio);
900 $form->add('hidden', 'selectMembership', $temp[0], array('id' => 'selectMembership'));
901 $form->assign('singleMembership', TRUE);
902 $form->assign('showRadio', FALSE);
905 $form->addGroup($radio, 'selectMembership', NULL);
908 $form->addRule('selectMembership', ts('Please select one of the memberships.'), 'required');
911 $autoRenewOption = CRM_Price_BAO_PriceSet
::checkAutoRenewForPriceSet($form->_priceSetId
);
912 $form->assign('autoRenewOption', $autoRenewOption);
915 if (!$form->_values
['is_pay_later'] && is_array($form->_paymentProcessors
) && ($allowAutoRenewMembership ||
$autoRenewOption)) {
916 $form->addElement('checkbox', 'auto_renew', ts('Please renew my membership automatically.'));
921 $form->assign('membershipBlock', $membershipBlock);
922 $form->assign('membershipTypes', $membershipTypes);
923 $form->assign('allowAutoRenewMembership', $allowAutoRenewMembership);
924 $form->assign('autoRenewMembershipTypeOptions', json_encode($autoRenewMembershipTypeOptions));
926 //give preference to user submitted auto_renew value.
927 $takeUserSubmittedAutoRenew = (!empty($_POST) ||
$form->isSubmitted()) ?
TRUE : FALSE;
928 $form->assign('takeUserSubmittedAutoRenew', $takeUserSubmittedAutoRenew);
931 return $separateMembershipPayment;
935 * Return Membership Block info in Contribution Pages.
938 * Contribution page id.
942 public static function getMembershipBlock($pageID) {
943 $membershipBlock = array();
944 $dao = new CRM_Member_DAO_MembershipBlock();
945 $dao->entity_table
= 'civicrm_contribution_page';
947 $dao->entity_id
= $pageID;
949 if ($dao->find(TRUE)) {
950 CRM_Core_DAO
::storeValues($dao, $membershipBlock);
951 if (!empty($membershipBlock['membership_types'])) {
952 $membershipTypes = unserialize($membershipBlock['membership_types']);
953 if (!is_array($membershipTypes)) {
954 return $membershipBlock;
957 foreach ($membershipTypes as $key => $value) {
958 $membershipBlock['auto_renew'][$key] = $value;
959 $memTypes[$key] = $key;
961 $membershipBlock['membership_types'] = implode(',', $memTypes);
968 return $membershipBlock;
972 * Return a current membership of given contact.
974 * NB: if more than one membership meets criteria, a randomly selected one is returned.
976 * @param int $contactID
978 * @param int $memType
979 * Membership type, null to retrieve all types.
981 * @param int $membershipId
982 * If provided, then determine if it is current.
983 * @param bool $onlySameParentOrg
984 * True if only Memberships with same parent org as the $memType wanted, false otherwise.
988 public static function getContactMembership($contactID, $memType, $isTest, $membershipId = NULL, $onlySameParentOrg = FALSE) {
989 $dao = new CRM_Member_DAO_Membership();
991 $dao->id
= $membershipId;
993 $dao->contact_id
= $contactID;
994 $dao->membership_type_id
= $memType;
996 //fetch proper membership record.
998 $dao->is_test
= $isTest;
1001 $dao->whereAdd('is_test IS NULL OR is_test = 0');
1004 //avoid pending membership as current membership: CRM-3027
1005 $statusIds[] = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
1006 if (!$membershipId) {
1008 $statusIds[] = array_search(
1010 CRM_Member_PseudoConstant
::membershipStatus(
1012 " name = 'Cancelled' ",
1019 $dao->whereAdd('status_id NOT IN ( ' . implode(',', $statusIds) . ')');
1021 // order by start date to find most recent membership first, CRM-4545
1022 $dao->orderBy('start_date DESC');
1025 if ($onlySameParentOrg && $memType) {
1026 // require the same parent org as the $memType
1027 $params = array('id' => $memType);
1028 $membershipType = array();
1029 if (CRM_Member_BAO_MembershipType
::retrieve($params, $membershipType)) {
1030 $memberTypesSameParentOrg = CRM_Member_BAO_MembershipType
::getMembershipTypesByOrg($membershipType['member_of_contact_id']);
1031 $memberTypesSameParentOrgList = implode(',', array_keys($memberTypesSameParentOrg));
1032 $dao->whereAdd('membership_type_id IN (' . $memberTypesSameParentOrgList . ')');
1036 if ($dao->find(TRUE)) {
1037 $membership = array();
1038 CRM_Core_DAO
::storeValues($dao, $membership);
1039 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
1040 $membership['status_id'],
1041 'is_current_member', 'id'
1047 if ($onlySameParentOrg && $memType) {
1048 // see if there is a membership that has same parent as $memType but different parent than $membershipID
1049 if ($dao->id
&& CRM_Core_Permission
::check('edit memberships')) {
1050 // CRM-10016, This is probably a backend renewal, and make sure we return the same membership thats being renewed.
1057 unset($dao->membership_type_id
);
1058 if ($dao->find(TRUE)) {
1059 $membership = array();
1060 CRM_Core_DAO
::storeValues($dao, $membership);
1061 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
1062 $membership['status_id'],
1063 'is_current_member', 'id'
1072 * Combine all the importable fields from the lower levels object.
1074 * @param string $contactType
1076 * @param bool $status
1079 * array of importable Fields
1081 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
1082 if (!self
::$_importableFields) {
1083 if (!self
::$_importableFields) {
1084 self
::$_importableFields = array();
1088 $fields = array('' => array('title' => '- ' . ts('do not import') . ' -'));
1091 $fields = array('' => array('title' => '- ' . ts('Membership Fields') . ' -'));
1094 $tmpFields = CRM_Member_DAO_Membership
::import();
1095 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
1097 // Using new Dedupe rule.
1098 $ruleParams = array(
1099 'contact_type' => $contactType,
1100 'used' => 'Unsupervised',
1102 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
1104 $tmpContactField = array();
1105 if (is_array($fieldsArray)) {
1106 foreach ($fieldsArray as $value) {
1107 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
1112 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
1113 $tmpContactField[trim($value)] = CRM_Utils_Array
::value(trim($value), $contactFields);
1115 $title = $tmpContactField[trim($value)]['title'] . " " . ts('(match to contact)');
1118 $title = $tmpContactField[trim($value)]['title'];
1120 $tmpContactField[trim($value)]['title'] = $title;
1123 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
1124 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " " . ts('(match to contact)');
1126 $tmpFields['membership_contact_id']['title'] = $tmpFields['membership_contact_id']['title'] . " " . ts('(match to contact)');;
1128 $fields = array_merge($fields, $tmpContactField);
1129 $fields = array_merge($fields, $tmpFields);
1130 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1131 self
::$_importableFields = $fields;
1133 return self
::$_importableFields;
1137 * Get all exportable fields.
1139 * @return array return array of all exportable fields
1141 public static function &exportableFields() {
1142 $expFieldMembership = CRM_Member_DAO_Membership
::export();
1144 $expFieldsMemType = CRM_Member_DAO_MembershipType
::export();
1145 $fields = array_merge($expFieldMembership, $expFieldsMemType);
1146 $fields = array_merge($fields, $expFieldMembership);
1147 $membershipStatus = array(
1148 'membership_status' => array(
1149 'title' => 'Membership Status',
1150 'name' => 'membership_status',
1151 'type' => CRM_Utils_Type
::T_STRING
,
1152 'where' => 'civicrm_membership_status.name',
1155 //CRM-6161 fix for customdata export
1156 $fields = array_merge($fields, $membershipStatus, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1161 * Get membership joins/renewals for a specified membership type.
1163 * Specifically, retrieves a count of memberships whose "Membership
1164 * Signup" or "Membership Renewal" activity falls in the given date range.
1165 * Dates match the pattern "yyyy-mm-dd".
1167 * @param int $membershipTypeId
1168 * Membership type id.
1169 * @param int $startDate
1170 * Date on which to start counting.
1171 * @param int $endDate
1172 * Date on which to end counting.
1173 * @param bool|int $isTest if true, membership is for a test site
1174 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1177 * the number of members of type $membershipTypeId whose
1178 * start_date is between $startDate and $endDate
1180 public static function getMembershipStarts($membershipTypeId, $startDate, $endDate, $isTest = 0, $isOwner = 0) {
1182 $testClause = 'membership.is_test = 1';
1184 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1187 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1188 self
::_getActTypes();
1191 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1196 SELECT COUNT(DISTINCT membership.id) as member_count
1197 FROM civicrm_membership membership
1198 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id in (%1, %2))
1199 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1200 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1201 WHERE membership.membership_type_id = %3
1202 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1205 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1208 1 => array(self
::$_signupActType, 'Integer'),
1209 2 => array(self
::$_renewalActType, 'Integer'),
1210 3 => array($membershipTypeId, 'Integer'),
1213 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1214 return (int) $memberCount;
1218 * Get a count of membership for a specified membership type, optionally for a specified date.
1220 * 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 bool $isProcessSeparateMembershipTransaction
1304 * @param int $defaultContributionTypeID
1305 * @param array $membershipLineItems
1306 * Line items specific to membership payment that is separate to contribution.
1307 * @param bool $isPayLater
1309 * @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 = $paymentResult = 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 if ($isProcessSeparateMembershipTransaction) {
1333 // If we have 2 transactions only one can use the invoice id.
1334 $membershipParams['invoiceID'] .= '-2';
1337 $paymentResult = CRM_Contribute_BAO_Contribution_Utils
::processConfirm($form, $membershipParams,
1338 $premiumParams, $contactID,
1345 if (is_a($result[1], 'CRM_Core_Error')) {
1346 $errors[1] = CRM_Core_Error
::getMessages($paymentResult[1]);
1349 if (is_a($paymentResult, 'CRM_Core_Error')) {
1350 $errors[1] = CRM_Core_Error
::getMessages($paymentResult);
1352 elseif (!empty($paymentResult['contribution'])) {
1353 //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
1354 $membershipContribution = $paymentResult['contribution'];
1355 // Save the contribution ID so that I can be used in email receipts
1356 // For example, if you need to generate a tax receipt for the donation only.
1357 $form->_values
['contribution_other_id'] = $membershipContribution->id
;
1361 if ($isProcessSeparateMembershipTransaction) {
1363 $form->_lineItem
= $membershipLineItems;
1364 if (empty($form->_params
['auto_renew']) && !empty($membershipParams['is_recur'])) {
1365 unset($membershipParams['is_recur']);
1367 $membershipContribution = self
::processSecondaryFinancialTransaction($contactID, $form, $membershipParams, $isTest, $membershipLineItems, CRM_Utils_Array
::value('minimum_fee', $membershipDetails, 0), CRM_Utils_Array
::value('financial_type_id', $membershipDetails));
1369 catch (CRM_Core_Exception
$e) {
1370 $errors[2] = $e->getMessage();
1371 $membershipContribution = NULL;
1376 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1377 $membershipContributionID = $membershipContribution->id
;
1380 //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
1381 if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
1382 $form->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
1384 //@todo it should no longer be possible for it to get to this point & membership to not be an array
1385 if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
1386 $typesTerms = CRM_Utils_Array
::value('types_terms', $membershipParams, array());
1387 foreach ($membershipTypeIDs as $memType) {
1388 $numTerms = CRM_Utils_Array
::value($memType, $typesTerms, 1);
1389 $createdMemberships[$memType] = self
::createOrRenewMembership($membershipParams, $contactID, $customFieldsFormatted, $membershipID, $memType, $isTest, $numTerms, $membershipContribution, $form);
1391 if ($form->_priceSetId
&& !empty($form->_useForMember
) && !empty($form->_lineItem
)) {
1392 foreach ($form->_lineItem
[$form->_priceSetId
] as & $priceFieldOp) {
1393 if (!empty($priceFieldOp['membership_type_id']) &&
1394 isset($createdMemberships[$priceFieldOp['membership_type_id']])
1396 $membershipOb = $createdMemberships[$priceFieldOp['membership_type_id']];
1397 $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date
::customFormat($membershipOb->start_date
, '%B %E%f, %Y') : '-';
1398 $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date
::customFormat($membershipOb->end_date
, '%B %E%f, %Y') : '-';
1401 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1404 $form->_values
['lineItem'] = $form->_lineItem
;
1405 $form->assign('lineItem', $form->_lineItem
);
1409 if (!empty($errors)) {
1410 $message = self
::compileErrorMessage($errors);
1411 throw new CRM_Core_Exception($message);
1413 $form->_params
['createdMembershipIDs'] = array();
1415 // CRM-7851 - Moved after processing Payment Errors
1416 //@todo - the reasoning for this being here seems a little outdated
1417 foreach ($createdMemberships as $createdMembership) {
1418 CRM_Core_BAO_CustomValueTable
::postProcess(
1420 'civicrm_membership',
1421 $createdMembership->id
,
1424 $form->_params
['createdMembershipIDs'][] = $createdMembership->id
;
1426 if (count($createdMemberships) == 1) {
1427 //presumably this is only relevant for exactly 1 membership
1428 $form->_params
['membershipID'] = $createdMembership->id
;
1431 //CRM-15232: Check if membership is created and on the basis of it use
1432 //membership receipt template to send payment receipt
1433 if (count($createdMemberships)) {
1434 $form->_values
['isMembership'] = TRUE;
1436 if ($form->_contributeMode
== 'notify') {
1437 if ($form->_values
['is_monetary'] && $form->_amount
> 0.0 && !$form->_params
['is_pay_later']) {
1438 // call postProcess hook before leaving
1439 $form->postProcessHook();
1440 // this does not return
1441 $payment = CRM_Core_Payment
::singleton($form->_mode
, $form->_paymentProcessor
, $form);
1442 $payment->doTransferCheckout($form->_params
, 'contribute');
1446 if (isset($membershipContributionID)) {
1447 $form->_values
['contribution_id'] = $membershipContributionID;
1450 if ($form->_contributeMode
== 'direct') {
1451 if (CRM_Utils_Array
::value('contribution_status_id', $paymentResult) == 1) {
1453 civicrm_api3('contribution', 'completetransaction', array(
1454 'id' => $paymentResult['contribution']->id
,
1455 'trxn_id' => $paymentResult['contribution']->trxn_id
,
1456 'is_transactional' => FALSE,
1459 catch (CiviCRM_API3_Exception
$e) {
1460 // if for any reason it is already completed this will fail - e.g extensions hacking around core not completing transactions prior to CRM-15296
1461 // so let's be gentle here
1462 CRM_Core_Error
::debug_log_message('contribution ' . $membershipContribution->id
. ' not completed with trxn_id ' . $membershipContribution->trxn_id
. ' and message ' . $e->getMessage());
1468 //finally send an email receipt
1469 CRM_Contribute_BAO_ContributionPage
::sendMail($contactID,
1477 * Function for updating a membership record's contribution_recur_id.
1479 * @param CRM_Member_DAO_Membership $membership
1480 * @param \CRM_Contribute_BAO_Contribution|\CRM_Contribute_DAO_Contribution $contribution
1482 static public function updateRecurMembership(CRM_Member_DAO_Membership
$membership, CRM_Contribute_BAO_Contribution
$contribution) {
1484 if (empty($contribution->contribution_recur_id
)) {
1489 1 => array($contribution->contribution_recur_id
, 'Integer'),
1490 2 => array($membership->id
, 'Integer'),
1493 $sql = "UPDATE civicrm_membership SET contribution_recur_id = %1 WHERE id = %2";
1494 CRM_Core_DAO
::executeQuery($sql, $params);
1498 * A wrapper for renewing memberships from a form.
1501 * - including the form in the membership processing adds complexity
1502 * as the forms are being forced to pretend similarity
1503 * Try to call the renewMembership directly
1504 * @todo - this form method needs to have the interaction with the form layer removed from it
1505 * as a BAO function. Note that the api now supports membership renewals & it is not clear this function does anything
1506 * not done by the membership.create api (with a lot less unit tests)
1508 * This method will renew / create the membership depending on
1509 * whether the given contact has a membership or not. And will add
1510 * the modified dates for membership and in the log table.
1512 * @param int $contactID
1513 * Id of the contact.
1514 * @param int $membershipTypeID
1515 * Id of the new membership type.
1516 * @param bool $is_test
1517 * If this is test contribution or live contribution.
1518 * @param CRM_Core_Form $form
1520 * @param null $changeToday
1521 * @param int $modifiedID
1522 * Individual contact id in case of On Behalf signup (CRM-4027 ).
1523 * @param null $customFieldsFormatted
1524 * @param int $numRenewTerms
1525 * How many membership terms are being added to end date (default is 1).
1526 * @param int $membershipID
1527 * Membership ID, this should always be passed in & optionality should be removed.
1529 * @param bool $isPending
1530 * Is the transaction pending. We are working towards this ALWAYS being true and completion being done
1531 * in the complete transaction function, called by all types of payment processor (removing assumptions
1532 * about what they do & always doing a pending + a complete at the appropriate time).
1534 * @return CRM_Member_BAO_Membership|CRM_Core_Error
1536 public static function renewMembershipFormWrapper(
1543 $customFieldsFormatted,
1548 $statusFormat = '%Y-%m-%d';
1551 //@todo would be better to make $membershipID a compulsory function param & make form layer responsible for extracting it
1552 if (!$membershipID && isset($form->_membershipId
)) {
1553 $membershipID = $form->_membershipId
;
1556 //get all active statuses of membership.
1557 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1559 $membershipTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipTypeID);
1561 // check is it pending. - CRM-4555
1562 list($contributionRecurID, $changeToday, $membershipSource, $isPayLater, $campaignId) = self
::extractFormValues($form, $changeToday);
1563 list($membership, $renewalMode, $dates) = self
::renewMembership($contactID, $membershipTypeID, $is_test,
1564 $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $isPending, $allStatus,
1565 $membershipTypeDetails, $contributionRecurID, $format, $membershipSource, $ids, $statusFormat, $isPayLater, $campaignId);
1566 $form->set('renewal_mode', $renewalMode);
1567 if (!empty($dates)) {
1568 $form->assign('mem_start_date',
1569 CRM_Utils_Date
::customFormat($dates['start_date'], $format)
1571 $form->assign('mem_end_date',
1572 CRM_Utils_Date
::customFormat($dates['end_date'], $format)
1580 * Method to fix membership status of stale membership.
1582 * This method first checks if the membership is stale. If it is,
1583 * then status will be updated based on existing start and end
1584 * dates and log will be added for the status change.
1586 * @param array $currentMembership
1587 * Reference to the array.
1588 * containing all values of
1589 * the current membership
1590 * @param array $changeToday
1591 * Array of month, day, year.
1592 * values in case today needs
1593 * to be customised, null otherwise
1595 public static function fixMembershipStatusBeforeRenew(&$currentMembership, $changeToday) {
1598 $today = CRM_Utils_Date
::processDate($changeToday, NULL, FALSE, 'Y-m-d');
1601 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
1602 CRM_Utils_Array
::value('start_date', $currentMembership),
1603 CRM_Utils_Array
::value('end_date', $currentMembership),
1604 CRM_Utils_Array
::value('join_date', $currentMembership),
1607 $currentMembership['membership_type_id'],
1611 if (empty($status) ||
1612 empty($status['id'])
1614 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.'));
1617 $currentMembership['today_date'] = $today;
1619 if ($status['id'] !== $currentMembership['status_id']) {
1620 $memberDAO = new CRM_Member_DAO_Membership();
1621 $memberDAO->id
= $currentMembership['id'];
1622 $memberDAO->find(TRUE);
1624 $memberDAO->status_id
= $status['id'];
1625 $memberDAO->join_date
= CRM_Utils_Date
::isoToMysql($memberDAO->join_date
);
1626 $memberDAO->start_date
= CRM_Utils_Date
::isoToMysql($memberDAO->start_date
);
1627 $memberDAO->end_date
= CRM_Utils_Date
::isoToMysql($memberDAO->end_date
);
1629 CRM_Core_DAO
::storeValues($memberDAO, $currentMembership);
1632 $currentMembership['is_current_member'] = CRM_Core_DAO
::getFieldValue(
1633 'CRM_Member_DAO_MembershipStatus',
1634 $currentMembership['status_id'],
1640 'membership_id' => $currentMembership['id'],
1641 'status_id' => $status['id'],
1642 'start_date' => CRM_Utils_Date
::customFormat(
1643 $currentMembership['start_date'],
1646 'end_date' => CRM_Utils_Date
::customFormat(
1647 $currentMembership['end_date'],
1650 'modified_date' => CRM_Utils_Date
::customFormat(
1651 $currentMembership['today_date'],
1654 'membership_type_id' => $currentMembership['membership_type_id'],
1655 'max_related' => CRM_Utils_Array
::value('max_related', $currentMembership, 0),
1658 $session = CRM_Core_Session
::singleton();
1659 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
1660 if ($session->get('userID')) {
1661 $logParams['modified_id'] = $session->get('userID');
1664 $logParams['modified_id'] = $currentMembership['contact_id'];
1666 CRM_Member_BAO_MembershipLog
::add($logParams, CRM_Core_DAO
::$_nullArray);
1671 * Get the contribution page id from the membership record.
1673 * @param int $membershipID
1676 * contribution page id
1678 public static function getContributionPageId($membershipID) {
1680 SELECT c.contribution_page_id as pageID
1681 FROM civicrm_membership_payment mp, civicrm_contribution c
1682 WHERE mp.contribution_id = c.id
1683 AND c.contribution_page_id IS NOT NULL
1684 AND mp.membership_id = " . CRM_Utils_Type
::escape($membershipID, 'Integer')
1685 . " ORDER BY mp.id DESC";
1687 return CRM_Core_DAO
::singleValueQuery($query,
1688 CRM_Core_DAO
::$_nullArray
1693 * Updated related memberships.
1695 * @param int $ownerMembershipId
1696 * Owner Membership Id.
1697 * @param array $params
1698 * Formatted array of key => value.
1700 public static function updateRelatedMemberships($ownerMembershipId, $params) {
1701 $membership = new CRM_Member_DAO_Membership();
1702 $membership->owner_membership_id
= $ownerMembershipId;
1703 $membership->find();
1705 while ($membership->fetch()) {
1706 $relatedMembership = new CRM_Member_DAO_Membership();
1707 $relatedMembership->id
= $membership->id
;
1708 $relatedMembership->copyValues($params);
1709 $relatedMembership->save();
1710 $relatedMembership->free();
1713 $membership->free();
1717 * Get list of membership fields for profile.
1719 * For now we only allow custom membership fields to be in
1723 * FIXME: This param is ignored
1726 * the list of membership fields
1728 public static function getMembershipFields($mode = NULL) {
1729 $fields = CRM_Member_DAO_Membership
::export();
1731 unset($fields['membership_contact_id']);
1732 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1734 $membershipType = CRM_Member_DAO_MembershipType
::export();
1736 $membershipStatus = CRM_Member_DAO_MembershipStatus
::export();
1738 $fields = array_merge($fields, $membershipType, $membershipStatus);
1744 * Get the sort name of a contact for a particular membership.
1747 * Id of the membership.
1749 * @return null|string
1750 * sort name of the contact if found
1752 public static function sortName($id) {
1753 $id = CRM_Utils_Type
::escape($id, 'Integer');
1756 SELECT civicrm_contact.sort_name
1757 FROM civicrm_membership, civicrm_contact
1758 WHERE civicrm_membership.contact_id = civicrm_contact.id
1759 AND civicrm_membership.id = {$id}
1761 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1765 * Create memberships for related contacts, taking into account the maximum related memberships.
1767 * @param array $params
1768 * Array of key - value pairs.
1769 * @param CRM_Core_DAO $dao
1770 * Membership object.
1772 * @param bool $reset
1774 * @return array|null
1775 * Membership details, if created.
1777 * @throws \CRM_Core_Exception
1779 public static function createRelatedMemberships(&$params, &$dao, $reset = FALSE) {
1780 static $relatedContactIds = array();
1782 // not sure why a static var is in use here - we need a way to reset it from the test suite
1783 $relatedContactIds = array();
1787 $membership = new CRM_Member_DAO_Membership();
1788 $membership->id
= $dao->id
;
1790 // required since create method doesn't return all the
1791 // parameters in the returned membership object
1792 if (!$membership->find(TRUE)) {
1795 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1796 // FIXME : While updating/ renewing the
1797 // membership, if the relationship is PAST then
1798 // the membership of the related contact must be
1800 // For that, getting Membership Status for which
1801 // is_current_member is 0. It works for the
1802 // generated data as there is only one membership
1803 // status having is_current_member = 0.
1804 // But this wont work exactly if there will be
1805 // more than one status having is_current_member = 0.
1806 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
1807 $membershipStatus->is_current_member
= 0;
1808 if ($membershipStatus->find(TRUE)) {
1809 $expiredStatusId = $membershipStatus->id
;
1812 $expiredStatusId = array_search('Expired', CRM_Member_PseudoConstant
::membershipStatus());
1815 $allRelatedContacts = array();
1816 $relatedContacts = array();
1817 if (!is_a($membership, 'CRM_Core_Error')) {
1818 $allRelatedContacts = CRM_Member_BAO_Membership
::checkMembershipRelationship($membership->id
,
1819 $membership->contact_id
,
1820 CRM_Utils_Array
::value('action', $params)
1824 // check for loops. CRM-4213
1825 // remove repeated related contacts, which already inherited membership.
1826 $relatedContactIds[$membership->contact_id
] = TRUE;
1827 foreach ($allRelatedContacts as $cid => $status) {
1828 if (empty($relatedContactIds[$cid])) {
1829 $relatedContactIds[$cid] = TRUE;
1831 //don't create membership again for owner contact.
1832 $nestedRelationship = FALSE;
1833 if ($membership->owner_membership_id
) {
1834 $nestedRelMembership = new CRM_Member_DAO_Membership();
1835 $nestedRelMembership->id
= $membership->owner_membership_id
;
1836 $nestedRelMembership->contact_id
= $cid;
1837 $nestedRelationship = $nestedRelMembership->find(TRUE);
1838 $nestedRelMembership->free();
1840 if (!$nestedRelationship) {
1841 $relatedContacts[$cid] = $status;
1846 //lets cleanup related membership if any.
1847 if (empty($relatedContacts)) {
1848 self
::deleteRelatedMemberships($membership->id
);
1851 // Edit the params array
1852 unset($params['id']);
1853 // Reminder should be sent only to the direct membership
1854 unset($params['reminder_date']);
1855 // unset the custom value ids
1856 if (is_array(CRM_Utils_Array
::value('custom', $params))) {
1857 foreach ($params['custom'] as $k => $v) {
1858 unset($params['custom'][$k]['id']);
1861 if (!isset($params['membership_type_id'])) {
1862 $params['membership_type_id'] = $membership->membership_type_id
;
1865 // max_related should be set in the parent membership
1866 unset($params['max_related']);
1867 // Number of inherited memberships available - NULL is interpreted as unlimited, '0' as none
1868 $available = ($membership->max_related
== NULL ? PHP_INT_MAX
: $membership->max_related
);
1869 // will be used to queue potential memberships to be created.
1872 foreach ($relatedContacts as $contactId => $relationshipStatus) {
1873 //use existing membership record.
1874 $relMembership = new CRM_Member_DAO_Membership();
1875 $relMembership->contact_id
= $contactId;
1876 $relMembership->owner_membership_id
= $membership->id
;
1877 $relMemIds = array();
1878 if ($relMembership->find(TRUE)) {
1879 $params['id'] = $relMemIds['membership'] = $relMembership->id
;
1881 $params['contact_id'] = $contactId;
1882 $params['owner_membership_id'] = $membership->id
;
1884 // set status_id as it might have been changed for
1885 // past relationship
1886 $params['status_id'] = $membership->status_id
;
1888 if ($deceasedStatusId &&
1889 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'is_deceased')
1891 $params['status_id'] = $deceasedStatusId;
1893 elseif ((CRM_Utils_Array
::value('action', $params) & CRM_Core_Action
::UPDATE
) &&
1894 ($relationshipStatus == CRM_Contact_BAO_Relationship
::PAST
)
1896 $params['status_id'] = $expiredStatusId;
1899 //don't calculate status again in create( );
1900 $params['skipStatusCal'] = TRUE;
1902 //do create activity if we changed status.
1903 if ($params['status_id'] != $relMembership->status_id
) {
1904 $params['createActivity'] = TRUE;
1907 // we should not created contribution record for related contacts, CRM-3371
1908 unset($params['contribution_status_id']);
1910 if (($params['status_id'] == $deceasedStatusId) ||
($params['status_id'] == $expiredStatusId)) {
1911 // related membership is not active so does not count towards maximum
1912 CRM_Member_BAO_Membership
::create($params, $relMemIds);
1915 // related membership already exists, so this is just an update
1916 if (isset($params['id'])) {
1917 if ($available > 0) {
1918 CRM_Member_BAO_Membership
::create($params, $relMemIds);
1922 // we have run out of inherited memberships, so delete extras
1923 self
::deleteMembership($params['id']);
1925 // we need to first check if there will remain inherited memberships, so queue it up
1932 // now go over the queue and create any available related memberships
1934 while (($available > 0) && ($params = each($queue))) {
1935 CRM_Member_BAO_Membership
::create($params['value'], $relMemIds);
1942 * Delete the record that are associated with this Membership Payment.
1944 * @param int $membershipId
1947 * $membershipPayment deleted membership payment object
1949 public static function deleteMembershipPayment($membershipId) {
1951 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
1952 $membershipPayment->membership_id
= $membershipId;
1953 $membershipPayment->find();
1955 while ($membershipPayment->fetch()) {
1956 CRM_Contribute_BAO_Contribution
::deleteContribution($membershipPayment->contribution_id
);
1957 CRM_Utils_Hook
::pre('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1958 $membershipPayment->delete();
1959 CRM_Utils_Hook
::post('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1961 return $membershipPayment;
1965 * @param CRM_Core_Form $form
1966 * @param int $membershipTypeID
1970 public static function &buildMembershipTypeValues(&$form, $membershipTypeID = NULL) {
1971 $whereClause = " WHERE domain_id = " . CRM_Core_Config
::domainID();
1973 if (is_array($membershipTypeID)) {
1974 $allIDs = implode(',', $membershipTypeID);
1975 $whereClause .= " AND id IN ( $allIDs )";
1977 elseif (is_numeric($membershipTypeID) &&
1978 $membershipTypeID > 0
1980 $whereClause .= " AND id = $membershipTypeID";
1985 FROM civicrm_membership_type
1988 $dao = CRM_Core_DAO
::executeQuery($query);
1990 $membershipTypeValues = array();
1991 $membershipTypeFields = array(
1997 'financial_type_id',
1999 'member_of_contact_id',
2000 'relationship_type_id',
2001 'relationship_direction',
2005 while ($dao->fetch()) {
2006 $membershipTypeValues[$dao->id
] = array();
2007 foreach ($membershipTypeFields as $mtField) {
2008 $membershipTypeValues[$dao->id
][$mtField] = $dao->$mtField;
2013 CRM_Utils_Hook
::membershipTypeValues($form, $membershipTypeValues);
2015 if (is_numeric($membershipTypeID) &&
2016 $membershipTypeID > 0
2018 return $membershipTypeValues[$membershipTypeID];
2021 return $membershipTypeValues;
2026 * Get membership record count for a Contact.
2028 * @param int $contactID
2029 * @param bool $activeOnly
2031 * @return null|string
2033 public static function getContactMembershipCount($contactID, $activeOnly = FALSE) {
2034 $select = "SELECT count(*) FROM civicrm_membership ";
2035 $where = "WHERE civicrm_membership.contact_id = {$contactID} AND civicrm_membership.is_test = 0 ";
2037 // CRM-6627, all status below 3 (active, pending, grace) are considered active
2039 $select .= " INNER JOIN civicrm_membership_status ON civicrm_membership.status_id = civicrm_membership_status.id ";
2040 $where .= " and civicrm_membership_status.is_current_member = 1";
2043 $query = $select . $where;
2044 return CRM_Core_DAO
::singleValueQuery($query);
2048 * Check whether payment processor supports cancellation of membership subscription.
2053 * @param bool $isNotCancelled
2057 public static function isCancelSubscriptionSupported($mid, $isNotCancelled = TRUE) {
2058 $cacheKeyString = "$mid";
2059 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2061 static $supportsCancel = array();
2063 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2064 $supportsCancel[$cacheKeyString] = FALSE;
2065 $isCancelled = FALSE;
2067 if ($isNotCancelled) {
2068 $isCancelled = self
::isSubscriptionCancelled($mid);
2071 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($mid, 'membership', 'obj');
2072 if (!empty($paymentObject)) {
2073 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2076 return $supportsCancel[$cacheKeyString];
2080 * Check whether subscription is already cancelled.
2086 * contribution status
2088 public static function isSubscriptionCancelled($mid) {
2090 SELECT cr.contribution_status_id
2091 FROM civicrm_contribution_recur cr
2092 LEFT JOIN civicrm_membership mem ON ( cr.id = mem.contribution_recur_id )
2093 WHERE mem.id = %1 LIMIT 1";
2094 $params = array(1 => array($mid, 'Integer'));
2095 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2096 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
2097 if ($status == 'Cancelled') {
2104 * Get membership joins for a specified membership type.
2106 * Specifically, retrieves a count of still current memberships whose
2107 * join_date and start_date are within a specified date range. Dates match
2108 * the pattern "yyyy-mm-dd".
2110 * @param int $membershipTypeId
2111 * Membership type id.
2112 * @param int $startDate
2113 * Date on which to start counting.
2114 * @param int $endDate
2115 * Date on which to end counting.
2116 * @param bool|int $isTest if true, membership is for a test site
2119 * the number of members of type $membershipTypeId
2120 * whose join_date is between $startDate and $endDate and
2121 * whose start_date is between $startDate and $endDate
2123 public static function getMembershipJoins($membershipTypeId, $startDate, $endDate, $isTest = 0) {
2124 $testClause = 'membership.is_test = 1';
2126 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
2128 if (!self
::$_signupActType) {
2129 self
::_getActTypes();
2132 if (!self
::$_signupActType) {
2137 SELECT COUNT(DISTINCT membership.id) as member_count
2138 FROM civicrm_membership membership
2139 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
2140 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
2141 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
2142 WHERE membership.membership_type_id = %2
2143 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
2147 1 => array(self
::$_signupActType, 'Integer'),
2148 2 => array($membershipTypeId, 'Integer'),
2151 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
2153 return (int) $memberCount;
2157 * Get membership renewals for a specified membership type.
2159 * Specifically, retrieves a count of still current memberships
2160 * whose join_date is before and start_date is within a specified date
2161 * range. Dates match the pattern "yyyy-mm-dd".
2163 * @param int $membershipTypeId
2164 * Membership type id.
2165 * @param int $startDate
2166 * Date on which to start counting.
2167 * @param int $endDate
2168 * Date on which to end counting.
2169 * @param bool|int $isTest if true, membership is for a test site
2172 * returns the number of members of type $membershipTypeId
2173 * whose join_date is before $startDate and
2174 * whose start_date is between $startDate and $endDate
2176 public static function getMembershipRenewals($membershipTypeId, $startDate, $endDate, $isTest = 0) {
2177 $testClause = 'membership.is_test = 1';
2179 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
2181 if (!self
::$_renewalActType) {
2182 self
::_getActTypes();
2185 if (!self
::$_renewalActType) {
2190 SELECT COUNT(DISTINCT membership.id) as member_count
2191 FROM civicrm_membership membership
2192 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
2193 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
2194 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
2195 WHERE membership.membership_type_id = %2
2196 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
2200 1 => array(self
::$_renewalActType, 'Integer'),
2201 2 => array($membershipTypeId, 'Integer'),
2203 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
2205 return (int) $memberCount;
2209 * Where a second separate financial transaction is supported we will process it here.
2211 * @param int $contactID
2212 * @param CRM_Contribute_Form_Contribution_Confirm $form
2213 * @param array $tempParams
2214 * @param bool $isTest
2215 * @param array $lineItems
2216 * @param $minimumFee
2217 * @param int $financialTypeID
2219 * @throws CRM_Core_Exception
2221 * @return CRM_Contribute_BAO_Contribution
2223 public static function processSecondaryFinancialTransaction($contactID, &$form, $tempParams, $isTest, $lineItems, $minimumFee, $financialTypeID) {
2224 $financialType = new CRM_Financial_DAO_FinancialType();
2225 $financialType->id
= $financialTypeID;
2226 if (!$financialType->find(TRUE)) {
2227 CRM_Core_Error
::fatal(ts("Could not find a system table"));
2229 $tempParams['amount'] = $minimumFee;
2230 $tempParams['invoiceID'] = md5(uniqid(rand(), TRUE));
2233 if ($form->_values
['is_monetary'] && !$form->_params
['is_pay_later'] && $minimumFee > 0.0) {
2234 $payment = CRM_Core_Payment
::singleton($form->_mode
, $form->_paymentProcessor
, $form);
2236 if ($form->_contributeMode
== 'express') {
2237 $result = $payment->doExpressCheckout($tempParams);
2238 if (is_a($result, 'CRM_Core_Error')) {
2239 throw new CRM_Core_Exception(CRM_Core_Error
::getMessages($result));
2243 $result = $payment->doPayment($tempParams, 'contribute');
2247 //assign receive date when separate membership payment
2248 //and contribution amount not selected.
2249 if ($form->_amount
== 0) {
2250 $now = date('YmdHis');
2251 $form->_params
['receive_date'] = $now;
2252 $receiveDate = CRM_Utils_Date
::mysqlToIso($now);
2253 $form->set('params', $form->_params
);
2254 $form->assign('receive_date', $receiveDate);
2257 $form->set('membership_trx_id', $result['trxn_id']);
2258 $form->set('membership_amount', $minimumFee);
2260 $form->assign('membership_trx_id', $result['trxn_id']);
2261 $form->assign('membership_amount', $minimumFee);
2263 // we don't need to create the user twice, so lets disable cms_create_account
2264 // irrespective of the value, CRM-2888
2265 $tempParams['cms_create_account'] = 0;
2267 //CRM-16165, scenarios are
2268 // 1) If contribution is_pay_later and if contribution amount is > 0.0 we set pending = TRUE, vice-versa FALSE
2269 // 2) If not pay later but auto-renewal membership is chosen then pending = TRUE as it later triggers
2270 // pending recurring contribution, vice-versa FALSE
2271 $pending = $form->_params
['is_pay_later'] ?
(($minimumFee > 0.0) ?
TRUE : FALSE) : (!empty($form->_params
['auto_renew']) ?
TRUE : FALSE);
2273 //set this variable as we are not creating pledge for
2274 //separate membership payment contribution.
2275 //so for differentiating membership contribution from
2276 //main contribution.
2277 $form->_params
['separate_membership_payment'] = 1;
2278 $membershipContribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($form,
2289 return $membershipContribution;
2293 * Create linkages between membership & contribution - note this is the wrong place for this code but this is a
2294 * refactoring step. This should be BAO functionality
2295 * @param $membership
2296 * @param $membershipContribution
2298 public static function linkMembershipPayment($membership, $membershipContribution) {
2299 CRM_Member_BAO_MembershipPayment
::create(array(
2300 'membership_id' => $membership->id
,
2301 'contribution_id' => $membershipContribution->id
,
2306 * @param array $membershipParams
2307 * @param int $contactID
2308 * @param $customFieldsFormatted
2309 * @param int $membershipID
2311 * @param bool $isTest
2312 * @param int $numTerms
2313 * @param $membershipContribution
2314 * @param CRM_Core_Form $form
2318 public static function createOrRenewMembership($membershipParams, $contactID, $customFieldsFormatted, $membershipID, $memType, $isTest, $numTerms, $membershipContribution, &$form) {
2319 if (!empty($membershipContribution)) {
2320 $pendingStatus = CRM_Core_OptionGroup
::getValue('contribution_status', 'Pending', 'name');
2321 $pending = ($membershipContribution->contribution_status_id
== $pendingStatus) ?
TRUE : FALSE;
2323 $membership = self
::renewMembershipFormWrapper($contactID, $memType,
2324 $isTest, $form, NULL,
2325 CRM_Utils_Array
::value('cms_contactID', $membershipParams),
2326 $customFieldsFormatted, $numTerms,
2328 self
::extractPendingFormValue($form, $memType, $pending)
2331 if (!empty($membershipContribution)) {
2332 // update recurring id for membership record
2333 self
::updateRecurMembership($membership, $membershipContribution);
2335 self
::linkMembershipPayment($membership, $membershipContribution);
2341 * Turn array of errors into message string.
2343 * @param array $errors
2347 public static function compileErrorMessage($errors) {
2348 foreach ($errors as $error) {
2349 if (is_string($error)) {
2350 $message[] = $error;
2353 return ts('Payment Processor Error message') . ': ' . implode('<br/>', $message);
2357 * Determine if the form has a pending status.
2359 * This is an interim refactoring step. This information should be extracted at the form layer.
2363 * @param CRM_Core_Form $form
2364 * @param int $membershipID
2368 public static function extractPendingFormValue($form, $membershipID, $pending = FALSE) {
2369 $membershipTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipID);
2370 //@todo this is a BAO function & should not inspect the form - the form should do this
2371 // & pass required params to the BAO
2372 if (CRM_Utils_Array
::value('minimum_fee', $membershipTypeDetails) > 0.0) {
2373 if (((isset($form->_contributeMode
) && $form->_contributeMode
== 'notify') ||
!empty($form->_params
['is_pay_later'])
2375 (($form->_values
['is_monetary'] && $form->_amount
> 0.0) ||
2376 CRM_Utils_Array
::value('record_contribution', $form->_params
)
2386 * Extract relevant values from the form so we can separate form logic from BAO logcis.
2388 * @param CRM_Core_Form $form
2389 * @param $changeToday
2393 public static function extractFormValues($form, $changeToday) {
2394 $contributionRecurID = isset($form->_params
['contributionRecurID']) ?
$form->_params
['contributionRecurID'] : NULL;
2396 //we renew expired membership, CRM-6277
2397 if (!$changeToday) {
2398 if ($form->get('renewalDate')) {
2399 $changeToday = $form->get('renewalDate');
2401 elseif (get_class($form) == 'CRM_Contribute_Form_Contribution_Confirm') {
2402 $changeToday = date('YmdHis');
2406 $membershipSource = NULL;
2407 if (!empty($form->_params
['membership_source'])) {
2408 $membershipSource = $form->_params
['membership_source'];
2410 elseif (isset($form->_values
['title']) && !empty($form->_values
['title'])) {
2411 $membershipSource = ts('Online Contribution:') . ' ' . $form->_values
['title'];
2414 if (isset($form->_params
)) {
2415 $isPayLater = CRM_Utils_Array
::value('is_pay_later', $form->_params
);
2418 if (isset($form->_values
) && is_array($form->_values
) && !empty($form->_values
)) {
2419 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_params
);
2420 if (!array_key_exists('campaign_id', $form->_params
)) {
2421 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_values
);
2424 return array($contributionRecurID, $changeToday, $membershipSource, $isPayLater, $campaignId);
2428 * @param int $contactID
2429 * @param int $membershipTypeID
2430 * @param bool $is_test
2431 * @param $changeToday
2432 * @param int $modifiedID
2433 * @param $customFieldsFormatted
2434 * @param $numRenewTerms
2435 * @param int $membershipID
2438 * @param array $membershipTypeDetails
2439 * @param int $contributionRecurID
2441 * @param $membershipSource
2443 * @param $statusFormat
2444 * @param $isPayLater
2445 * @param int $campaignId
2447 * @throws CRM_Core_Exception
2450 public static function renewMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $allStatus, $membershipTypeDetails, $contributionRecurID, $format, $membershipSource, $ids, $statusFormat, $isPayLater, $campaignId) {
2451 $renewalMode = $updateStatusId = FALSE;
2453 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
2454 // is the same as the parent org of an existing membership of the contact
2455 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($contactID, $membershipTypeID,
2456 $is_test, $membershipID, TRUE
2458 if ($currentMembership) {
2459 $activityType = 'Membership Renewal';
2460 $renewalMode = TRUE;
2462 // Do NOT do anything.
2463 //1. membership with status : PENDING/CANCELLED (CRM-2395)
2464 //2. Paylater/IPN renew. CRM-4556.
2465 if ($pending ||
in_array($currentMembership['status_id'], array(
2466 array_search('Pending', $allStatus),
2468 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
2471 $membership = new CRM_Member_DAO_Membership();
2472 $membership->id
= $currentMembership['id'];
2473 $membership->find(TRUE);
2475 // CRM-8141 create a membership_log entry so that we will know the membership_type_id to change to when payment completed
2477 // note that we are logging the requested new membership_type_id that may be different than current membership_type_id
2478 // it will be used when payment is received to update the membership_type_id to what was paid for
2480 'membership_id' => $membership->id
,
2481 'status_id' => $membership->status_id
,
2482 'start_date' => CRM_Utils_Date
::customFormat(
2483 $membership->start_date
,
2486 'end_date' => CRM_Utils_Date
::customFormat(
2487 $membership->end_date
,
2490 'modified_date' => CRM_Utils_Date
::customFormat(
2494 'membership_type_id' => $membershipTypeID,
2495 'max_related' => !empty($membershipTypeDetails['max_related']) ?
$membershipTypeDetails['max_related'] : NULL,
2497 $session = CRM_Core_Session
::singleton();
2498 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
2499 if ($session->get('userID')) {
2500 $logParams['modified_id'] = $session->get('userID');
2503 $logParams['modified_id'] = $membership->contact_id
;
2505 CRM_Member_BAO_MembershipLog
::add($logParams, CRM_Core_DAO
::$_nullArray);
2507 if (!empty($contributionRecurID)) {
2508 CRM_Core_DAO
::setFieldValue('CRM_Member_DAO_Membership', $membership->id
,
2509 'contribution_recur_id', $contributionRecurID
2513 return array($membership, $renewalMode, $dates);
2516 // Check and fix the membership if it is STALE
2517 self
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
2519 // Now Renew the membership
2520 if (!$currentMembership['is_current_member']) {
2521 // membership is not CURRENT
2523 // CRM-7297 Membership Upsell - calculate dates based on new membership type
2524 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($currentMembership['id'],
2530 $currentMembership['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
2531 $currentMembership['start_date'] = CRM_Utils_Array
::value('start_date', $dates);
2532 $currentMembership['end_date'] = CRM_Utils_Array
::value('end_date', $dates);
2533 $currentMembership['is_test'] = $is_test;
2535 if (!empty($membershipSource)) {
2536 $currentMembership['source'] = $membershipSource;
2539 $currentMembership['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
2540 $currentMembership['id'],
2545 if (!empty($currentMembership['id'])) {
2546 $ids['membership'] = $currentMembership['id'];
2548 $memParams = $currentMembership;
2549 $memParams['membership_type_id'] = $membershipTypeID;
2551 //set the log start date.
2552 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
2556 // CURRENT Membership
2557 $membership = new CRM_Member_DAO_Membership();
2558 $membership->id
= $currentMembership['id'];
2559 $membership->find(TRUE);
2560 // CRM-7297 Membership Upsell - calculate dates based on new membership type
2561 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
2567 // Insert renewed dates for CURRENT membership
2568 $memParams = array();
2569 $memParams['join_date'] = CRM_Utils_Date
::isoToMysql($membership->join_date
);
2570 $memParams['start_date'] = CRM_Utils_Date
::isoToMysql($membership->start_date
);
2571 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $dates);
2572 $memParams['membership_type_id'] = $membershipTypeID;
2574 //set the log start date.
2575 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
2576 if (empty($membership->source
)) {
2577 if (!empty($membershipSource)) {
2578 $memParams['source'] = $membershipSource;
2581 $memParams['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
2582 $currentMembership['id'],
2588 if (!empty($currentMembership['id'])) {
2589 $ids['membership'] = $currentMembership['id'];
2594 $updateStatusId = array_search('Pending', $allStatus);
2600 $activityType = 'Membership Signup';
2602 'contact_id' => $contactID,
2603 'membership_type_id' => $membershipTypeID,
2607 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
2609 $memParams['join_date'] = CRM_Utils_Array
::value('join_date', $dates);
2610 $memParams['start_date'] = CRM_Utils_Array
::value('start_date', $dates);
2611 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $dates);
2613 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(CRM_Utils_Date
::customFormat($dates['start_date'],
2616 CRM_Utils_Date
::customFormat($dates['end_date'],
2619 CRM_Utils_Date
::customFormat($dates['join_date'],
2627 $updateStatusId = CRM_Utils_Array
::value('id', $status);
2630 // if IPN/Pay-Later set status to: PENDING
2631 $updateStatusId = array_search('Pending', $allStatus);
2634 if (!empty($membershipSource)) {
2635 $memParams['source'] = $membershipSource;
2637 $memParams['contribution_recur_id'] = $contributionRecurID;
2639 $memParams['is_test'] = $is_test;
2640 $memParams['is_pay_later'] = $isPayLater;
2644 //if we decided status here and want to skip status
2645 //calculation in create( ); then need to pass 'skipStatusCal'.
2646 if ($updateStatusId) {
2647 $memParams['status_id'] = $updateStatusId;
2648 $memParams['skipStatusCal'] = TRUE;
2651 //since we are renewing,
2652 //make status override false.
2653 $memParams['is_override'] = FALSE;
2655 //CRM-4027, create log w/ individual contact.
2657 $ids['userId'] = $modifiedID;
2658 $memParams['is_for_organization'] = TRUE;
2661 $ids['userId'] = $contactID;
2664 //inherit campaign from contrib page.
2665 if (isset($campaignId)) {
2666 $memParams['campaign_id'] = $campaignId;
2669 $memParams['custom'] = $customFieldsFormatted;
2670 $membership = self
::create($memParams, $ids, FALSE, $activityType);
2672 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
2673 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
2674 $membership->find(TRUE);
2676 return array($membership, $renewalMode, $dates);
2680 * Process price set and line items.
2682 * @param int $membershipId
2683 * @param array $lineItem
2685 public function processPriceSet($membershipId, $lineItem) {
2686 //FIXME : need to move this too
2687 if (!$membershipId ||
!is_array($lineItem)
2688 || CRM_Utils_System
::isNull($lineItem)
2693 foreach ($lineItem as $priceSetId => $values) {
2697 foreach ($values as $line) {
2698 $line['entity_table'] = 'civicrm_membership';
2699 $line['entity_id'] = $membershipId;
2700 CRM_Price_BAO_LineItem
::create($line);
2706 * Retrieve the contribution id for the associated Membership id.
2707 * @todo we should get this off the line item
2709 * @param int $membershipId
2715 public static function getMembershipContributionId($membershipId) {
2717 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
2718 $membershipPayment->membership_id
= $membershipId;
2719 if ($membershipPayment->find(TRUE)) {
2720 return $membershipPayment->contribution_id
;
2726 * The function checks and updates the status of all membership records for a given domain using the
2727 * calc_membership_status and update_contact_membership APIs.
2730 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
2734 public static function updateAllMembershipStatus() {
2736 //get all active statuses of membership, CRM-3984
2737 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2738 $statusLabels = CRM_Member_PseudoConstant
::membershipStatus(NULL, NULL, 'label');
2739 $allTypes = CRM_Member_PseudoConstant
::membershipType();
2741 // get only memberships with active membership types
2743 SELECT civicrm_membership.id as membership_id,
2744 civicrm_membership.is_override as is_override,
2745 civicrm_membership.membership_type_id as membership_type_id,
2746 civicrm_membership.status_id as status_id,
2747 civicrm_membership.join_date as join_date,
2748 civicrm_membership.start_date as start_date,
2749 civicrm_membership.end_date as end_date,
2750 civicrm_membership.source as source,
2751 civicrm_contact.id as contact_id,
2752 civicrm_contact.is_deceased as is_deceased,
2753 civicrm_membership.owner_membership_id as owner_membership_id,
2754 civicrm_membership.contribution_recur_id as recur_id
2755 FROM civicrm_membership
2756 INNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )
2757 INNER JOIN civicrm_membership_type ON
2758 (civicrm_membership.membership_type_id = civicrm_membership_type.id AND civicrm_membership_type.is_active = 1)
2759 WHERE civicrm_membership.is_test = 0";
2762 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2767 $smarty = CRM_Core_Smarty
::singleton();
2769 while ($dao->fetch()) {
2773 // Put common parameters into array for easy access
2774 $memberParams = array(
2775 'id' => $dao->membership_id
,
2776 'status_id' => $dao->status_id
,
2777 'contact_id' => $dao->contact_id
,
2778 'membership_type_id' => $dao->membership_type_id
,
2779 'membership_type' => $allTypes[$dao->membership_type_id
],
2780 'join_date' => $dao->join_date
,
2781 'start_date' => $dao->start_date
,
2782 'end_date' => $dao->end_date
,
2783 'source' => $dao->source
,
2784 'skipStatusCal' => TRUE,
2785 'skipRecentView' => TRUE,
2788 $smarty->assign_by_ref('memberParams', $memberParams);
2790 //update membership record to Deceased if contact is deceased
2791 if ($dao->is_deceased
) {
2792 // check for 'Deceased' membership status, CRM-5636
2793 $deceaseStatusId = array_search('Deceased', $allStatus);
2794 if (!$deceaseStatusId) {
2795 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'))));
2798 //process only when status change.
2799 if ($dao->status_id
!= $deceaseStatusId) {
2800 //take all params that need to save.
2801 $deceasedMembership = $memberParams;
2802 $deceasedMembership['status_id'] = $deceaseStatusId;
2803 $deceasedMembership['createActivity'] = TRUE;
2804 $deceasedMembership['version'] = 3;
2806 //since there is change in status.
2807 $statusChange = array('status_id' => $deceaseStatusId);
2808 $smarty->append_by_ref('memberParams', $statusChange, TRUE);
2810 $deceasedMembership['contact_id'],
2811 $deceasedMembership['membership_type_id'],
2812 $deceasedMembership['membership_type'],
2813 $deceasedMembership['join_date'],
2814 $deceasedMembership['start_date'],
2815 $deceasedMembership['end_date'],
2816 $deceasedMembership['source']
2819 //process membership record.
2820 civicrm_api('membership', 'create', $deceasedMembership);
2825 //we fetch related, since we need to check for deceased
2826 //now further processing is handle w/ main membership record.
2827 if ($dao->owner_membership_id
) {
2831 //update membership records where status is NOT - Pending OR Cancelled.
2832 //as well as membership is not override.
2833 //skipping Expired membership records -> reduced extra processing( kiran )
2834 if (!$dao->is_override
&&
2835 !in_array($dao->status_id
, array(
2836 array_search('Pending', $allStatus),
2840 CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)
2842 array_search('Expired', $allStatus),
2846 // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses
2847 //get the membership status as per id.
2848 $newStatus = civicrm_api('membership_status', 'calc',
2850 'membership_id' => $dao->membership_id
,
2852 'ignore_admin_only' => FALSE,
2855 $statusId = CRM_Utils_Array
::value('id', $newStatus);
2857 //process only when status change.
2859 $statusId != $dao->status_id
2861 //take all params that need to save.
2862 $memParams = $memberParams;
2863 $memParams['status_id'] = $statusId;
2864 $memParams['createActivity'] = TRUE;
2865 $memParams['version'] = 3;
2867 // Unset columns which should remain unchanged from their current saved
2868 // values. This avoids race condition in which these values may have
2869 // been changed by other processes.
2871 $memParams['contact_id'],
2872 $memParams['membership_type_id'],
2873 $memParams['membership_type'],
2874 $memParams['join_date'],
2875 $memParams['start_date'],
2876 $memParams['end_date'],
2877 $memParams['source']
2879 //since there is change in status.
2880 $statusChange = array('status_id' => $statusId);
2881 $smarty->append_by_ref('memberParams', $statusChange, TRUE);
2883 //process member record.
2884 civicrm_api('membership', 'create', $memParams);
2889 $result['is_error'] = 0;
2890 $result['messages'] = ts('Processed %1 membership records. Updated %2 records.', array(
2898 * Returns the membership types for a particular contact
2899 * who has lifetime membership without end date.
2901 * @param int $contactID
2902 * @param bool $isTest
2903 * @param bool $onlyLifeTime
2907 public static function getAllContactMembership($contactID, $isTest = FALSE, $onlyLifeTime = FALSE) {
2908 $contactMembershipType = array();
2910 return $contactMembershipType;
2913 $dao = new CRM_Member_DAO_Membership();
2914 $dao->contact_id
= $contactID;
2915 $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
2916 $dao->whereAdd("status_id != $pendingStatusId");
2919 $dao->is_test
= $isTest;
2922 $dao->whereAdd('is_test IS NULL OR is_test = 0');
2925 if ($onlyLifeTime) {
2926 $dao->whereAdd('end_date IS NULL');
2930 while ($dao->fetch()) {
2931 $membership = array();
2932 CRM_Core_DAO
::storeValues($dao, $membership);
2933 $contactMembershipType[$dao->membership_type_id
] = $membership;
2935 return $contactMembershipType;
2939 * Record contribution record associated with membership.
2941 * @param array $params
2942 * Array of submitted params.
2944 * (param in process of being removed - try to use params) array of ids.
2946 * @return CRM_Contribute_BAO_Contribution
2948 public static function recordMembershipContribution(&$params, $ids = array()) {
2949 $membershipId = $params['membership_id'];
2950 $contributionParams = array();
2951 $config = CRM_Core_Config
::singleton();
2952 $contributionParams['currency'] = $config->defaultCurrency
;
2953 $contributionParams['receipt_date'] = (CRM_Utils_Array
::value('receipt_date', $params)) ?
$params['receipt_date'] : 'null';
2954 $contributionParams['source'] = CRM_Utils_Array
::value('contribution_source', $params);
2955 $contributionParams['non_deductible_amount'] = 'null';
2956 $contributionParams['payment_processor'] = CRM_Utils_Array
::value('payment_processor_id', $params);
2957 $contributionSoftParams = CRM_Utils_Array
::value('soft_credit', $params);
2958 $recordContribution = array(
2962 'financial_type_id',
2963 'payment_instrument_id',
2967 'contribution_status_id',
2975 foreach ($recordContribution as $f) {
2976 $contributionParams[$f] = CRM_Utils_Array
::value($f, $params);
2979 // make entry in batch entity batch table
2980 if (!empty($params['batch_id'])) {
2981 $contributionParams['batch_id'] = $params['batch_id'];
2984 if (!empty($params['contribution_contact_id'])) {
2985 // deal with possibility of a different person paying for contribution
2986 $contributionParams['contact_id'] = $params['contribution_contact_id'];
2989 if (!empty($params['processPriceSet']) &&
2990 !empty($params['lineItems'])
2992 $contributionParams['line_item'] = CRM_Utils_Array
::value('lineItems', $params, NULL);
2995 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
2997 //CRM-13981, create new soft-credit record as to record payment from different person for this membership
2998 if (!empty($contributionSoftParams)) {
2999 if (!empty($params['batch_id'])) {
3000 foreach ($contributionSoftParams as $contributionSoft) {
3001 $contributionSoft['contribution_id'] = $contribution->id
;
3002 $contributionSoft['currency'] = $contribution->currency
;
3003 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoft);
3007 $contributionSoftParams['contribution_id'] = $contribution->id
;
3008 $contributionSoftParams['currency'] = $contribution->currency
;
3009 $contributionSoftParams['amount'] = $contribution->total_amount
;
3010 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoftParams);
3014 // store contribution id
3015 $params['contribution_id'] = $contribution->id
;
3017 //insert payment record for this membership
3018 if (empty($ids['contribution']) ||
!empty($params['is_recur'])) {
3019 CRM_Member_BAO_MembershipPayment
::create(array(
3020 'membership_id' => $membershipId,
3021 'contribution_id' => $contribution->id
,
3024 return $contribution;
3028 * Record line items for default membership.
3030 * @param CRM_Core_Form $qf
3031 * @param array $membershipType
3032 * Array with membership type and organization.
3033 * @param int $priceSetId
3036 public static function createLineItems(&$qf, $membershipType, &$priceSetId) {
3037 $qf->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
3039 $qf->_priceSet
= $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
3041 $editedFieldParams = array(
3042 'price_set_id' => $priceSetId,
3043 'name' => $membershipType[0],
3045 $editedResults = array();
3046 CRM_Price_BAO_PriceField
::retrieve($editedFieldParams, $editedResults);
3048 if (!empty($editedResults)) {
3049 unset($qf->_priceSet
['fields']);
3050 $qf->_priceSet
['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
3051 unset($qf->_priceSet
['fields'][$editedResults['id']]['options']);
3052 $fid = $editedResults['id'];
3053 $editedFieldParams = array(
3054 'price_field_id' => $editedResults['id'],
3055 'membership_type_id' => $membershipType[1],
3057 $editedResults = array();
3058 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $editedResults);
3059 $qf->_priceSet
['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
3060 if (!empty($qf->_params
['total_amount'])) {
3061 $qf->_priceSet
['fields'][$fid]['options'][$editedResults['id']]['amount'] = $qf->_params
['total_amount'];
3065 $fieldID = key($qf->_priceSet
['fields']);
3066 $qf->_params
['price_' . $fieldID] = CRM_Utils_Array
::value('id', $editedResults);
3070 * @todo document me - I seem a bit out of date....
3072 public static function _getActTypes() {
3073 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
3074 self
::$_renewalActType = CRM_Utils_Array
::key('Membership Renewal', $activityTypes);
3075 self
::$_signupActType = CRM_Utils_Array
::key('Membership Signup', $activityTypes);
3079 * Get all Cancelled Membership(s) for a contact
3081 * @param int $contactID
3083 * @param bool $isTest
3087 * Array of membership type
3089 public static function getContactsCancelledMembership($contactID, $isTest = FALSE) {
3093 $query = 'SELECT membership_type_id FROM civicrm_membership WHERE contact_id = %1 AND status_id = %2 AND is_test = %3';
3094 $queryParams = array(
3095 1 => array($contactID, 'Integer'),
3100 CRM_Member_PseudoConstant
::membershipStatus(
3102 " name = 'Cancelled' ",
3110 3 => array($isTest, 'Boolean'),
3113 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
3114 $cancelledMembershipIds = array();
3115 while ($dao->fetch()) {
3116 $cancelledMembershipIds[] = $dao->membership_type_id
;
3118 return $cancelledMembershipIds;