3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
35 class CRM_Member_BAO_Membership
extends CRM_Member_DAO_Membership
{
38 * Static field for all the membership information that we can potentially import
43 static $_importableFields = NULL;
45 static $_renewalActType = NULL;
47 static $_signupActType = NULL;
52 * @return \CRM_Member_DAO_Membership
57 public function __construct() {
58 parent
::__construct();
62 * Takes an associative array and creates a membership object
64 * the function extracts all the params it needs to initialize the created
65 * membership object. The params array could contain additional unused name/value
68 * @param array $params
69 * (reference ) an assoc array of name/value pairs.
71 * The array that holds all the db ids.
73 * @return CRM_Member_BAO_Membership object
76 public static function add(&$params, $ids = array()) {
77 $oldStatus = $oldType = NULL;
78 $params['id'] = CRM_Utils_Array
::value('id', $params, CRM_Utils_Array
::value('membership', $ids));
80 CRM_Utils_Hook
::pre('edit', 'Membership', $params['id'], $params);
83 CRM_Utils_Hook
::pre('create', 'Membership', $params['id'], $params);
86 // we do this after the hooks are called in case it has been altered
88 $membershipObj = new CRM_Member_DAO_Membership();
89 $membershipObj->id
= $id;
90 $membershipObj->find();
91 while ($membershipObj->fetch()) {
92 $oldStatus = $membershipObj->status_id
;
93 $oldType = $membershipObj->membership_type_id
;
97 if (array_key_exists('is_override', $params) && !$params['is_override']) {
98 $params['is_override'] = 'null';
101 $membership = new CRM_Member_BAO_Membership();
102 $membership->copyValues($params);
103 $membership->id
= $id;
108 if (empty($membership->contact_id
) ||
empty($membership->status_id
)) {
109 // this means we are in renewal mode and are just updating the membership
110 // record or this is an API update call and all fields are not present in the update record
111 // however the hooks dont care and want all data CRM-7784
112 $tempMembership = new CRM_Member_DAO_Membership();
113 $tempMembership->id
= $membership->id
;
114 $tempMembership->find(TRUE);
115 $membership = $tempMembership;
118 //get the log start date.
119 //it is set during renewal of membership.
120 $logStartDate = CRM_Utils_Array
::value('log_start_date', $params);
121 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : CRM_Utils_Date
::isoToMysql($membership->start_date
);
122 $values = self
::getStatusANDTypeValues($membership->id
);
124 $membershipLog = array(
125 'membership_id' => $membership->id
,
126 'status_id' => $membership->status_id
,
127 'start_date' => $logStartDate,
128 'end_date' => CRM_Utils_Date
::isoToMysql($membership->end_date
),
129 'modified_date' => date('Ymd'),
130 'membership_type_id' => $values[$membership->id
]['membership_type_id'],
131 'max_related' => $membership->max_related
,
134 $session = CRM_Core_Session
::singleton();
135 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
136 if ($session->get('userID')) {
137 $membershipLog['modified_id'] = $session->get('userID');
139 elseif (!empty($ids['userId'])) {
140 $membershipLog['modified_id'] = $ids['userId'];
143 $membershipLog['modified_id'] = $membership->contact_id
;
146 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
148 // reset the group contact cache since smart groups might be affected due to this
149 CRM_Contact_BAO_GroupContactCache
::remove();
152 if ($membership->status_id
!= $oldStatus) {
153 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
154 $activityParam = array(
155 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
156 'source_contact_id' => $membershipLog['modified_id'],
157 'target_contact_id' => $membership->contact_id
,
158 'source_record_id' => $membership->id
,
159 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Change Membership Status'),
162 'activity_date_time' => date('Y-m-d H:i:s'),
164 civicrm_api3('activity', 'create', $activityParam);
166 if (isset($membership->membership_type_id
) && $membership->membership_type_id
!= $oldType) {
167 $membershipTypes = CRM_Member_BAO_Membership
::buildOptions('membership_type_id', 'get');
168 $activityParam = array(
169 'subject' => "Type changed from {$membershipTypes[$oldType]} to {$membershipTypes[$membership->membership_type_id]}",
170 'source_contact_id' => $membershipLog['modified_id'],
171 'target_contact_id' => $membership->contact_id
,
172 'source_record_id' => $membership->id
,
173 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Change Membership Type'),
176 'activity_date_time' => date('Y-m-d H:i:s'),
178 civicrm_api3('activity', 'create', $activityParam);
180 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
183 CRM_Utils_Hook
::post('create', 'Membership', $membership->id
, $membership);
190 * Given the list of params in the params array, fetch the object
191 * and store the values in the values array
193 * @param array $params
194 * Input parameters to find object.
195 * @param array $values
196 * Output values of the object.
197 * @param bool $active
198 * Do you want only active memberships to.
201 * @return CRM_Member_BAO_Membership|null the found object or null
204 public static function &getValues(&$params, &$values, $active = FALSE) {
205 if (empty($params)) {
208 $membership = new CRM_Member_BAO_Membership();
210 $membership->copyValues($params);
212 $memberships = array();
213 while ($membership->fetch()) {
215 (!CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
216 $membership->status_id
,
223 CRM_Core_DAO
::storeValues($membership, $values[$membership->id
]);
224 $memberships[$membership->id
] = $membership;
231 * Takes an associative array and creates a membership object
233 * @param array $params
234 * (reference ) an assoc array of name/value pairs.
236 * The array that holds all the db ids.
237 * @param bool $skipRedirect
238 * @param string $activityType
240 * @throws CRM_Core_Exception
242 * @return CRM_Member_BAO_Membership object
245 public static function create(&$params, &$ids, $skipRedirect = FALSE, $activityType = 'Membership Signup') {
246 // always calculate status if is_override/skipStatusCal is not true.
247 // giving respect to is_override during import. CRM-4012
249 // To skip status calculation we should use 'skipStatusCal'.
250 // eg pay later membership, membership update cron CRM-3984
252 if (empty($params['is_override']) && empty($params['skipStatusCal'])) {
253 $dates = array('start_date', 'end_date', 'join_date');
254 $start_date = $end_date = $join_date = NULL; // declare these out of courtesy as IDEs don't pick up the setting of them below
255 foreach ($dates as $date) {
256 $
$date = $params[$date] = CRM_Utils_Date
::processDate(CRM_Utils_Array
::value($date, $params), NULL, TRUE, 'Ymd');
259 //fix for CRM-3570, during import exclude the statuses those having is_admin = 1
260 $excludeIsAdmin = CRM_Utils_Array
::value('exclude_is_admin', $params, FALSE);
262 //CRM-3724 always skip is_admin if is_override != true.
263 if (!$excludeIsAdmin && empty($params['is_override'])) {
264 $excludeIsAdmin = TRUE;
267 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($start_date, $end_date, $join_date,
268 'today', $excludeIsAdmin, CRM_Utils_Array
::value('membership_type_id', $params), $params
270 if (empty($calcStatus)) {
271 // Redirect the form in case of error
272 // @todo this redirect in the BAO layer is really bad & should be moved to the form layer
273 // however since we have no idea how (if) this is triggered we can't safely move / remove it
274 // NB I tried really hard to trigger this error from backoffice membership form in order to test it
275 // and am convinced form validation is complete on that form WRT this error.
276 $errorParams = array(
277 'message_title' => ts('No valid membership status for given dates.'),
278 'legacy_redirect_path' => 'civicrm/contact/view',
279 'legacy_redirect_query' => "reset=1&force=1&cid={$params['contact_id']}&selectedChild=member",
281 throw new CRM_Core_Exception(ts('The membership cannot be saved because the status cannot be calculated.'), 0, $errorParams);
283 $params['status_id'] = $calcStatus['id'];
286 // data cleanup only: all verifications on number of related memberships are done upstream in:
287 // CRM_Member_BAO_Membership::createRelatedMemberships()
288 // CRM_Contact_BAO_Relationship::relatedMemberships()
289 if (isset($params['owner_membership_id'])) {
290 unset($params['max_related']);
293 // if membership allows related, default max_related to value in membership_type
294 if (!array_key_exists('max_related', $params) && !empty($params['membership_type_id'])) {
295 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($params['membership_type_id']);
296 if (isset($membershipType['relationship_type_id'])) {
297 $params['max_related'] = CRM_Utils_Array
::value('max_related', $membershipType);
302 $transaction = new CRM_Core_Transaction();
304 $membership = self
::add($params, $ids);
306 if (is_a($membership, 'CRM_Core_Error')) {
307 $transaction->rollback();
311 // add custom field values
312 if (!empty($params['custom']) && is_array($params['custom'])
314 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_membership', $membership->id
);
317 $params['membership_id'] = $membership->id
;
318 if (isset($ids['membership'])) {
319 $ids['contribution'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment',
326 $params['skipLineItem'] = TRUE;
328 //record contribution for this membership
329 if (!empty($params['contribution_status_id']) && empty($params['relate_contribution_id'])) {
330 $memInfo = array_merge($params, array('membership_id' => $membership->id
));
331 $params['contribution'] = self
::recordMembershipContribution($memInfo, $ids);
334 if (!empty($params['lineItems'])) {
335 $params['line_item'] = $params['lineItems'];
338 //do cleanup line items if membership edit the Membership type.
339 if (empty($ids['contribution']) && !empty($ids['membership'])) {
340 CRM_Price_BAO_LineItem
::deleteLineItems($ids['membership'], 'civicrm_membership');
343 if (!empty($params['line_item']) && empty($ids['contribution'])) {
344 CRM_Price_BAO_LineItem
::processPriceSet($membership->id
, $params['line_item'], CRM_Utils_Array
::value('contribution', $params));
347 //insert payment record for this membership
348 if (!empty($params['relate_contribution_id'])) {
349 CRM_Member_BAO_MembershipPayment
::create(array(
350 'membership_id' => $membership->id
,
351 'contribution_id' => $params['relate_contribution_id']
355 // add activity record only during create mode and renew mode
356 // also add activity if status changed CRM-3984 and CRM-2521
357 if (empty($ids['membership']) ||
358 $activityType == 'Membership Renewal' ||
!empty($params['createActivity'])
360 if (!empty($ids['membership'])) {
362 CRM_Core_DAO
::commonRetrieveAll('CRM_Member_DAO_Membership',
366 array('contact_id', 'membership_type_id', 'source')
369 $membership->contact_id
= $data[$membership->id
]['contact_id'];
370 $membership->membership_type_id
= $data[$membership->id
]['membership_type_id'];
371 $membership->source
= CRM_Utils_Array
::value('source', $data[$membership->id
]);
374 // since we are going to create activity record w/
375 // individual contact as a target in case of on behalf signup,
376 // so get the copy of organization id, CRM-5551
377 $realMembershipContactId = $membership->contact_id
;
379 // create activity source = individual, target = org CRM-4027
380 $targetContactID = NULL;
381 if (!empty($params['is_for_organization'])) {
382 $targetContactID = $membership->contact_id
;
383 $membership->contact_id
= CRM_Utils_Array
::value('userId', $ids);
386 if (empty($membership->contact_id
) && (!empty($membership->owner_membership_id
))) {
387 $membership->contact_id
= $realMembershipContactId;
390 if (!empty($ids['membership']) && $activityType != 'Membership Signup') {
391 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $targetContactID);
393 elseif (empty($ids['membership'])) {
394 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $targetContactID);
397 // we might created activity record w/ individual
398 // contact as target so update membership object w/
399 // original organization id, CRM-5551
400 $membership->contact_id
= $realMembershipContactId;
403 $transaction->commit();
405 self
::createRelatedMemberships($params, $membership);
407 // do not add to recent items for import, CRM-4399
408 if (empty($params['skipRecentView'])) {
409 $url = CRM_Utils_System
::url('civicrm/contact/view/membership',
410 "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
412 if (empty($membership->membership_type_id
)) {// ie in an update situation
413 $membership->find(TRUE);
415 $membershipTypes = CRM_Member_PseudoConstant
::membershipType();
416 $title = CRM_Contact_BAO_Contact
::displayName($membership->contact_id
) . ' - ' . ts('Membership Type:') . ' ' . $membershipTypes[$membership->membership_type_id
];
418 $recentOther = array();
419 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::UPDATE
)) {
420 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
421 "action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
424 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::DELETE
)) {
425 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
426 "action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
430 // add the recently created Membership
431 CRM_Utils_Recent
::add($title,
435 $membership->contact_id
,
445 * Check the membership extended through relationship
447 * @param int $membershipId
449 * @param int $contactId
454 * @return Array array of contact_id of all related contacts.
457 public static function checkMembershipRelationship($membershipId, $contactId, $action = CRM_Core_Action
::ADD
) {
459 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $membershipId, 'membership_type_id');
461 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipTypeID);
462 $relationships = array();
463 if (isset($membershipType['relationship_type_id'])) {
464 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
465 CRM_Contact_BAO_Relationship
::CURRENT
467 if ($action & CRM_Core_Action
::UPDATE
) {
468 $pastRelationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
469 CRM_Contact_BAO_Relationship
::PAST
471 $relationships = array_merge($relationships, $pastRelationships);
475 if (!empty($relationships)) {
476 // check for each contact relationships
477 foreach ($relationships as $values) {
478 //get details of the relationship type
479 $relType = array('id' => $values['civicrm_relationship_type_id']);
480 $relValues = array();
481 CRM_Contact_BAO_RelationshipType
::retrieve($relType, $relValues);
482 // Check if contact's relationship type exists in membership type
483 $relTypeDirs = array();
484 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_type_id']);
485 $relDirections = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_direction']);
486 $bidirectional = FALSE;
487 foreach ($relTypeIds as $key => $value) {
488 $relTypeDirs[] = $value . '_' . $relDirections[$key];
489 if (in_array($value, $relType) &&
490 $relValues['name_a_b'] == $relValues['name_b_a']
492 $bidirectional = TRUE;
496 $relTypeDir = $values['civicrm_relationship_type_id'] . '_' . $values['rtype'];
497 if ($bidirectional ||
in_array($relTypeDir, $relTypeDirs)) {
498 // $values['status'] is going to have value for
499 // current or past relationships.
500 $contacts[$values['cid']] = $values['status'];
505 // Sort by contact_id ascending
511 * Takes a bunch of params that are needed to match certain criteria and
512 * retrieves the relevant objects. We'll tweak this function to be more
513 * full featured over a period of time. This is the inverse function of
514 * create. It also stores all the retrieved values in the default array
516 * @param array $params
517 * (reference ) an assoc array of name/value pairs.
518 * @param array $defaults
519 * (reference ) an assoc array to hold the name / value pairs.
520 * in a hierarchical manner
522 * @return CRM_Member_BAO_Membership object
525 public static function retrieve(&$params, &$defaults) {
526 $membership = new CRM_Member_DAO_Membership();
528 $membership->copyValues($params);
530 if ($membership->find(TRUE)) {
531 CRM_Core_DAO
::storeValues($membership, $defaults);
533 //get the membership status and type values.
534 $statusANDType = self
::getStatusANDTypeValues($membership->id
);
539 $defaults[$fld] = CRM_Utils_Array
::value($fld, $statusANDType[$membership->id
]);
541 if (!empty($statusANDType[$membership->id
]['is_current_member'])) {
542 $defaults['active'] = TRUE;
555 * get membership status and membership type values
557 * @param int $membershipId
558 * Membership id of values to return.
560 * @return array of key value pairs
562 public static function getStatusANDTypeValues($membershipId) {
564 if (!$membershipId) {
568 SELECT membership.id as id,
569 status.id as status_id,
570 status.label as status,
571 status.is_current_member as is_current_member,
572 type.id as membership_type_id,
573 type.name as membership_type,
574 type.relationship_type_id as relationship_type_id
575 FROM civicrm_membership membership
576 INNER JOIN civicrm_membership_status status ON ( status.id = membership.status_id )
577 INNER JOIN civicrm_membership_type type ON ( type.id = membership.membership_type_id )
578 WHERE membership.id = %1';
579 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($membershipId, 'Positive')));
584 'membership_type_id',
586 'relationship_type_id'
588 while ($dao->fetch()) {
589 foreach ($properties as $property) {
590 $values[$dao->id
][$property] = $dao->$property;
599 * Wrapper for most delete calls. Use this unless you JUST want to delete related memberships w/o deleting the parent.
601 * @param int $membershipId
602 * Membership id that needs to be deleted.
606 * @return $results no of deleted Membership on success, false otherwise
608 public static function del($membershipId) {
609 //delete related first and then delete parent.
610 self
::deleteRelatedMemberships($membershipId);
611 return self
::deleteMembership($membershipId);
617 * @param int $membershipId
618 * Membership id that needs to be deleted.
622 * @return $results no of deleted Membership on success, false otherwise
624 public static function deleteMembership($membershipId) {
625 // CRM-12147, retrieve membership data before we delete it for hooks
626 $params = array('id' => $membershipId);
627 $memValues = array();
628 $memberships = self
::getValues($params, $memValues);
630 $membership = $memberships[$membershipId];
632 CRM_Utils_Hook
::pre('delete', 'Membership', $membershipId, $memValues);
634 $transaction = new CRM_Core_Transaction();
637 //delete activity record
638 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
641 $deleteActivity = FALSE;
642 $membershipActivities = array(
644 'Membership Renewal',
645 'Change Membership Status',
646 'Change Membership Type',
647 'Membership Renewal Reminder'
649 foreach ($membershipActivities as $membershipActivity) {
650 $activityId = array_search($membershipActivity, $activityTypes);
652 $params['activity_type_id'][] = $activityId;
653 $deleteActivity = TRUE;
656 if ($deleteActivity) {
657 $params['source_record_id'] = $membershipId;
658 CRM_Activity_BAO_Activity
::deleteActivity($params);
660 self
::deleteMembershipPayment($membershipId);
662 $results = $membership->delete();
663 $transaction->commit();
665 CRM_Utils_Hook
::post('delete', 'Membership', $membership->id
, $membership);
667 // delete the recently created Membership
668 $membershipRecent = array(
669 'id' => $membershipId,
670 'type' => 'Membership',
672 CRM_Utils_Recent
::del($membershipRecent);
678 * Delete related memberships
680 * @param int $ownerMembershipId
681 * @param int $contactId
686 public static function deleteRelatedMemberships($ownerMembershipId, $contactId = NULL) {
687 if (!$ownerMembershipId && !$contactId) {
691 $membership = new CRM_Member_DAO_Membership();
692 $membership->owner_membership_id
= $ownerMembershipId;
695 $membership->contact_id
= $contactId;
699 while ($membership->fetch()) {
700 //delete related first and then delete parent.
701 self
::deleteRelatedMemberships($membership->id
);
702 self
::deleteMembership($membership->id
);
708 * Obtain active/inactive memberships from the list of memberships passed to it.
710 * @param array $memberships
711 * Membership records.
712 * @param string $status
713 * Active or inactive.
715 * @return array $actives array of memberships based on status
718 public static function activeMembers($memberships, $status = 'active') {
720 if ($status == 'active') {
721 foreach ($memberships as $f => $v) {
722 if (!empty($v['active'])) {
728 elseif ($status == 'inactive') {
729 foreach ($memberships as $f => $v) {
730 if (empty($v['active'])) {
740 * Build Membership Block in Contribution Pages
742 * @param CRM_Core_Form $form
747 * Contact checked for having a current membership for a particular membership.
748 * @param bool $formItems
749 * @param int $selectedMembershipTypeID
750 * Selected membership id.
751 * @param bool $thankPage
753 * @param null $isTest
755 * @return bool Is this a separate membership payment
759 static function buildMembershipBlock(
764 $selectedMembershipTypeID = NULL,
769 $separateMembershipPayment = FALSE;
770 if ($form->_membershipBlock
) {
771 $form->_currentMemberships
= array();
773 $membershipBlock = $form->_membershipBlock
;
774 $membershipTypeIds = $membershipTypes = $radio = array();
775 $membershipPriceset = (!empty($form->_priceSetId
) && $form->_useForMember
) ?
TRUE : FALSE;
777 $allowAutoRenewMembership = $autoRenewOption = FALSE;
778 $autoRenewMembershipTypeOptions = array();
780 $paymentProcessor = CRM_Core_PseudoConstant
::paymentProcessor(FALSE, FALSE, 'is_recur = 1');
782 $separateMembershipPayment = CRM_Utils_Array
::value('is_separate_payment', $membershipBlock);
784 if ($membershipPriceset) {
785 foreach ($form->_priceSet
['fields'] as $pField) {
786 if (empty($pField['options'])) {
789 foreach ($pField['options'] as $opId => $opValues) {
790 if (empty($opValues['membership_type_id'])) {
793 $membershipTypeIds[$opValues['membership_type_id']] = $opValues['membership_type_id'];
797 elseif (!empty($membershipBlock['membership_types'])) {
798 $membershipTypeIds = explode(',', $membershipBlock['membership_types']);
801 if (!empty($membershipTypeIds)) {
802 //set status message if wrong membershipType is included in membershipBlock
803 if (isset($form->_mid
) && !$membershipPriceset) {
804 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
808 if (!in_array($membershipTypeID, $membershipTypeIds)) {
809 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');
813 $membershipTypeValues = self
::buildMembershipTypeValues($form, $membershipTypeIds);
814 $form->_membershipTypeValues
= $membershipTypeValues;
816 foreach ($membershipTypeIds as $value) {
817 $memType = $membershipTypeValues[$value];
818 if ($selectedMembershipTypeID != NULL) {
819 if ($memType['id'] == $selectedMembershipTypeID) {
820 $form->assign('minimum_fee',
821 CRM_Utils_Array
::value('minimum_fee', $memType)
823 $form->assign('membership_name', $memType['name']);
824 if (!$thankPage && $cid) {
825 $membership = new CRM_Member_DAO_Membership();
826 $membership->contact_id
= $cid;
827 $membership->membership_type_id
= $memType['id'];
828 if ($membership->find(TRUE)) {
829 $form->assign('renewal_mode', TRUE);
830 $memType['current_membership'] = $membership->end_date
;
831 $form->_currentMemberships
[$membership->membership_type_id
] = $membership->membership_type_id
;
834 $membershipTypes[] = $memType;
837 elseif ($memType['is_active']) {
838 $javascriptMethod = NULL;
839 $allowAutoRenewOpt = 1;
840 if (is_array($form->_paymentProcessors
)) {
841 foreach ($form->_paymentProcessors
as $id => $val) {
842 if (!$val['is_recur']) {
843 $allowAutoRenewOpt = 0;
849 $javascriptMethod = array('onclick' => "return showHideAutoRenew( this.value );");
850 $autoRenewMembershipTypeOptions["autoRenewMembershipType_{$value}"] = (int) $allowAutoRenewOpt * CRM_Utils_Array
::value($value, CRM_Utils_Array
::value('auto_renew', $form->_membershipBlock
));;
852 if ($allowAutoRenewOpt) {
853 $allowAutoRenewMembership = TRUE;
856 //add membership type.
857 $radio[$memType['id']] = $form->createElement('radio', NULL, NULL, NULL,
858 $memType['id'], $javascriptMethod
861 $membership = new CRM_Member_DAO_Membership();
862 $membership->contact_id
= $cid;
863 $membership->membership_type_id
= $memType['id'];
865 //show current membership, skip pending and cancelled membership records,
866 //because we take first membership record id for renewal
867 $membership->whereAdd('status_id != 5 AND status_id !=6');
869 if (!is_null($isTest)) {
870 $membership->is_test
= $isTest;
874 $membership->orderBy('end_date DESC');
876 if ($membership->find(TRUE)) {
877 if (!$membership->end_date
) {
878 unset($radio[$memType['id']]);
879 $form->assign('islifetime', TRUE);
882 $form->assign('renewal_mode', TRUE);
883 $form->_currentMemberships
[$membership->membership_type_id
] = $membership->membership_type_id
;
884 $memType['current_membership'] = $membership->end_date
;
886 $endDate = $memType['current_membership'];
887 $form->_defaultMemTypeId
= $memType['id'];
889 if ($memType['current_membership'] < $endDate) {
890 $endDate = $memType['current_membership'];
891 $form->_defaultMemTypeId
= $memType['id'];
895 $membershipTypes[] = $memType;
900 $form->assign('showRadio', $formItems);
902 if (!$membershipPriceset) {
903 if (!$membershipBlock['is_required']) {
904 $form->assign('showRadioNoThanks', TRUE);
905 $radio[''] = $form->createElement('radio', NULL, NULL, NULL, 'no_thanks', NULL);
906 $form->addGroup($radio, 'selectMembership', NULL);
908 elseif ($membershipBlock['is_required'] && count($radio) == 1) {
909 $temp = array_keys($radio);
910 $form->add('hidden', 'selectMembership', $temp[0], array('id' => 'selectMembership'));
911 $form->assign('singleMembership', TRUE);
912 $form->assign('showRadio', FALSE);
915 $form->addGroup($radio, 'selectMembership', NULL);
918 $form->addRule('selectMembership', ts('Please select one of the memberships.'), 'required');
921 $autoRenewOption = CRM_Price_BAO_PriceSet
::checkAutoRenewForPriceSet($form->_priceSetId
);
922 $form->assign('autoRenewOption', $autoRenewOption);
925 if (!$form->_values
['is_pay_later'] && is_array($form->_paymentProcessors
) && ($allowAutoRenewMembership ||
$autoRenewOption)) {
926 $form->addElement('checkbox', 'auto_renew', ts('Please renew my membership automatically.'));
931 $form->assign('membershipBlock', $membershipBlock);
932 $form->assign('membershipTypes', $membershipTypes);
933 $form->assign('allowAutoRenewMembership', $allowAutoRenewMembership);
934 $form->assign('autoRenewMembershipTypeOptions', json_encode($autoRenewMembershipTypeOptions));
936 //give preference to user submitted auto_renew value.
937 $takeUserSubmittedAutoRenew = (!empty($_POST) ||
$form->isSubmitted()) ?
TRUE : FALSE;
938 $form->assign('takeUserSubmittedAutoRenew', $takeUserSubmittedAutoRenew);
941 return $separateMembershipPayment;
945 * Return Membership Block info in Contribution Pages
948 * Contribution page id.
954 public static function getMembershipBlock($pageID) {
955 $membershipBlock = array();
956 $dao = new CRM_Member_DAO_MembershipBlock();
957 $dao->entity_table
= 'civicrm_contribution_page';
959 $dao->entity_id
= $pageID;
961 if ($dao->find(TRUE)) {
962 CRM_Core_DAO
::storeValues($dao, $membershipBlock);
963 if (!empty($membershipBlock['membership_types'])) {
964 $membershipTypes = unserialize($membershipBlock['membership_types']);
965 if (!is_array($membershipTypes)) {
966 return $membershipBlock;
969 foreach ($membershipTypes as $key => $value) {
970 $membershipBlock['auto_renew'][$key] = $value;
971 $memTypes[$key] = $key;
973 $membershipBlock['membership_types'] = implode(',', $memTypes);
980 return $membershipBlock;
984 * Return a current membership of given contact
985 * NB: if more than one membership meets criteria, a randomly selected one is returned.
987 * @param int $contactID
989 * @param int $memType
990 * Membership type, null to retrieve all types.
992 * @param int $membershipId
993 * If provided, then determine if it is current.
994 * @param bool $onlySameParentOrg
995 * True if only Memberships with same parent org as the $memType wanted, false otherwise.
1000 public static function getContactMembership($contactID, $memType, $isTest, $membershipId = NULL, $onlySameParentOrg = FALSE) {
1001 $dao = new CRM_Member_DAO_Membership();
1002 if ($membershipId) {
1003 $dao->id
= $membershipId;
1005 $dao->contact_id
= $contactID;
1006 $dao->membership_type_id
= $memType;
1008 //fetch proper membership record.
1010 $dao->is_test
= $isTest;
1013 $dao->whereAdd('is_test IS NULL OR is_test = 0');
1016 //avoid pending membership as current membership: CRM-3027
1017 $statusIds[] = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
1018 if (!$membershipId) {
1020 $statusIds[] = array_search(
1022 CRM_Member_PseudoConstant
::membershipStatus(
1024 " name = 'Cancelled' ",
1031 $dao->whereAdd('status_id NOT IN ( ' . implode(',', $statusIds) . ')');
1033 // order by start date to find most recent membership first, CRM-4545
1034 $dao->orderBy('start_date DESC');
1037 if ($onlySameParentOrg && $memType) {
1038 // require the same parent org as the $memType
1039 $params = array('id' => $memType);
1040 $membershipType = array();
1041 if (CRM_Member_BAO_MembershipType
::retrieve($params, $membershipType)) {
1042 $memberTypesSameParentOrg = CRM_Member_BAO_MembershipType
::getMembershipTypesByOrg($membershipType['member_of_contact_id']);
1043 $memberTypesSameParentOrgList = implode(',', array_keys($memberTypesSameParentOrg));
1044 $dao->whereAdd('membership_type_id IN (' . $memberTypesSameParentOrgList . ')');
1048 if ($dao->find(TRUE)) {
1049 $membership = array();
1050 CRM_Core_DAO
::storeValues($dao, $membership);
1051 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
1052 $membership['status_id'],
1053 'is_current_member', 'id'
1059 if ($onlySameParentOrg && $memType) {
1060 // see if there is a membership that has same parent as $memType but different parent than $membershipID
1061 if ($dao->id
&& CRM_Core_Permission
::check('edit memberships')) {
1062 // CRM-10016, This is probably a backend renewal, and make sure we return the same membership thats being renewed.
1069 unset($dao->membership_type_id
);
1070 if ($dao->find(TRUE)) {
1071 $membership = array();
1072 CRM_Core_DAO
::storeValues($dao, $membership);
1073 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
1074 $membership['status_id'],
1075 'is_current_member', 'id'
1084 * Combine all the importable fields from the lower levels object
1086 * @param string $contactType
1088 * @param bool $status
1090 * @return array array of importable Fields
1093 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
1094 if (!self
::$_importableFields) {
1095 if (!self
::$_importableFields) {
1096 self
::$_importableFields = array();
1100 $fields = array('' => array('title' => '- ' . ts('do not import') . ' -'));
1103 $fields = array('' => array('title' => '- ' . ts('Membership Fields') . ' -'));
1106 $tmpFields = CRM_Member_DAO_Membership
::import();
1107 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
1109 // Using new Dedupe rule.
1110 $ruleParams = array(
1111 'contact_type' => $contactType,
1112 'used' => 'Unsupervised',
1114 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
1116 $tmpContactField = array();
1117 if (is_array($fieldsArray)) {
1118 foreach ($fieldsArray as $value) {
1119 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
1124 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
1125 $tmpContactField[trim($value)] = CRM_Utils_Array
::value(trim($value), $contactFields);
1127 $title = $tmpContactField[trim($value)]['title'] . " " . ts('(match to contact)');
1130 $title = $tmpContactField[trim($value)]['title'];
1132 $tmpContactField[trim($value)]['title'] = $title;
1135 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
1136 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " " . ts('(match to contact)');
1138 $tmpFields['membership_contact_id']['title'] = $tmpFields['membership_contact_id']['title'] . " " . ts('(match to contact)');;
1140 $fields = array_merge($fields, $tmpContactField);
1141 $fields = array_merge($fields, $tmpFields);
1142 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1143 self
::$_importableFields = $fields;
1145 return self
::$_importableFields;
1149 * Get all exportable fields
1151 * @retun array return array of all exportable fields
1154 public static function &exportableFields() {
1155 $expFieldMembership = CRM_Member_DAO_Membership
::export();
1157 $expFieldsMemType = CRM_Member_DAO_MembershipType
::export();
1158 $fields = array_merge($expFieldMembership, $expFieldsMemType);
1159 $fields = array_merge($fields, $expFieldMembership);
1160 $membershipStatus = array(
1161 'membership_status' => array(
1162 'title' => 'Membership Status',
1163 'name' => 'membership_status',
1164 'type' => CRM_Utils_Type
::T_STRING
,
1165 'where' => 'civicrm_membership_status.name',
1168 //CRM-6161 fix for customdata export
1169 $fields = array_merge($fields, $membershipStatus, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1174 * Get membership joins/renewals for a specified membership
1175 * type. Specifically, retrieves a count of memberships whose "Membership
1176 * Signup" or "Membership Renewal" activity falls in the given date range.
1177 * Dates match the pattern "yyyy-mm-dd".
1179 * @param int $membershipTypeId
1180 * Membership type id.
1181 * @param int $startDate
1182 * Date on which to start counting.
1183 * @param int $endDate
1184 * Date on which to end counting.
1185 * @param bool|int $isTest if true, membership is for a test site
1186 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1188 * @return integer the number of members of type $membershipTypeId whose
1189 * start_date is between $startDate and $endDate
1192 public static function getMembershipStarts($membershipTypeId, $startDate, $endDate, $isTest = 0, $isOwner = 0) {
1194 $testClause = 'membership.is_test = 1';
1196 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1199 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1200 self
::_getActTypes();
1203 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1208 SELECT COUNT(DISTINCT membership.id) as member_count
1209 FROM civicrm_membership membership
1210 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id in (%1, %2))
1211 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1212 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1213 WHERE membership.membership_type_id = %3
1214 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1217 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1220 1 => array(self
::$_signupActType, 'Integer'),
1221 2 => array(self
::$_renewalActType, 'Integer'),
1222 3 => array($membershipTypeId, 'Integer'),
1225 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1226 return (int) $memberCount;
1230 * Get a count of membership for a specified membership type,
1231 * optionally for a specified date. The date must have the form yyyy-mm-dd.
1233 * If $date is omitted, this function counts as a member anyone whose
1234 * membership status_id indicates they're a current member.
1235 * If $date is given, this function counts as a member anyone who:
1236 * -- Has a start_date before $date and end_date after $date, or
1237 * -- Has a start_date before $date and is currently a member, as indicated
1238 * by the the membership's status_id.
1239 * The second condition takes care of records that have no end_date. These
1240 * are assumed to be lifetime memberships.
1242 * @param int $membershipTypeId
1243 * Membership type id.
1244 * @param string $date
1245 * The date for which to retrieve the count.
1246 * @param bool|int $isTest if true, membership is for a test site
1247 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1249 * @return returns the number of members of type $membershipTypeId as of
1252 public static function getMembershipCount($membershipTypeId, $date = NULL, $isTest = 0, $isOwner = 0) {
1253 if (!CRM_Utils_Rule
::date($date)) {
1254 CRM_Core_Error
::fatal(ts('Invalid date "%1" (must have form yyyy-mm-dd).', array(1 => $date)));
1258 1 => array($membershipTypeId, 'Integer'),
1259 2 => array($isTest, 'Boolean'),
1261 $query = "SELECT count(civicrm_membership.id ) as member_count
1262 FROM civicrm_membership left join civicrm_membership_status on ( civicrm_membership.status_id = civicrm_membership_status.id )
1263 WHERE civicrm_membership.membership_type_id = %1
1264 AND civicrm_membership.contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)
1265 AND civicrm_membership.is_test = %2";
1267 $query .= " AND civicrm_membership_status.is_current_member = 1";
1270 $query .= " AND civicrm_membership.start_date <= '$date' AND civicrm_membership_status.is_current_member = 1";
1273 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1274 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1275 return (int) $memberCount;
1279 * Function check the status of the membership before adding membership for a contact
1281 * @param int $contactId
1286 public static function statusAvailabilty($contactId) {
1287 $membership = new CRM_Member_DAO_MembershipStatus();
1288 $membership->whereAdd('is_active=1');
1289 return $membership->count();
1293 * Process the Memberships
1295 * @param array $membershipParams
1296 * Array of membership fields.
1297 * @param int $contactID
1299 * @param CRM_Contribute_Form_Contribution_Confirm $form
1300 * Confirmation form object.
1302 * @param array $premiumParams
1303 * @param null $customFieldsFormatted
1304 * @param null $includeFieldTypes
1306 * @param array $membershipDetails
1308 * @param array $membershipTypeIDs
1310 * @param bool $isPaidMembership
1311 * @param array $membershipID
1313 * @param $isProcessSeparateMembershipTransaction
1315 * @param int $defaultContributionTypeID
1316 * @param array $membershipLineItems
1317 * Line items specific to membership payment that is separate to contribution.
1318 * @throws CRM_Core_Exception
1322 public static function postProcessMembership(
1323 $membershipParams, $contactID, &$form, $premiumParams,
1324 $customFieldsFormatted = NULL, $includeFieldTypes = NULL, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID,
1325 $isProcessSeparateMembershipTransaction, $defaultContributionTypeID, $membershipLineItems, $isPayLater) {
1326 $result = $membershipContribution = NULL;
1327 $isTest = CRM_Utils_Array
::value('is_test', $membershipParams, FALSE);
1328 $errors = $createdMemberships = array();
1330 //@todo move this into the calling function & pass in the correct financialTypeID
1331 if (isset($paymentParams['financial_type'])) {
1332 $financialTypeID = $paymentParams['financial_type'];
1335 $financialTypeID = $defaultContributionTypeID;
1338 if (CRM_Utils_Array
::value('membership_source', $form->_params
)) {
1339 $membershipParams['contribution_source'] = $form->_params
['membership_source'];
1342 if ($isPaidMembership) {
1343 $result = CRM_Contribute_BAO_Contribution_Utils
::processConfirm($form, $membershipParams,
1344 $premiumParams, $contactID,
1351 if (is_a($result[1], 'CRM_Core_Error')) {
1352 $errors[1] = CRM_Core_Error
::getMessages($result[1]);
1354 elseif (!empty($result[1])) {
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'] = $result[1]->id
;
1358 //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
1359 $membershipContribution = $result[1];
1363 if ($isProcessSeparateMembershipTransaction) {
1365 $lineItems = $form->_lineItem
= $membershipLineItems;
1366 $membershipContribution = self
::processSecondaryFinancialTransaction($contactID, $form, $membershipParams, $isTest, $membershipLineItems, CRM_Utils_Array
::value('minimum_fee', $membershipDetails, 0), CRM_Utils_Array
::value('financial_type_id', $membershipDetails));
1368 catch (CRM_Core_Exception
$e) {
1369 $errors[2] = $e->getMessage();
1370 $membershipContribution = NULL;
1375 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1376 $membershipContributionID = $membershipContribution->id
;
1379 //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
1380 if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
1381 $form->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
1383 //@todo it should no longer be possible for it to get to this point & membership to not be an array
1384 if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
1385 $typesTerms = CRM_Utils_Array
::value('types_terms', $membershipParams, array());
1386 foreach ($membershipTypeIDs as $memType) {
1387 $numTerms = CRM_Utils_Array
::value($memType, $typesTerms, 1);
1388 $createdMemberships[$memType] = self
::createOrRenewMembership($membershipParams, $contactID, $customFieldsFormatted, $membershipID, $memType, $isTest, $numTerms, $membershipContribution, $form);
1390 if ($form->_priceSetId
&& !empty($form->_useForMember
) && !empty($form->_lineItem
)) {
1391 foreach ($form->_lineItem
[$form->_priceSetId
] as & $priceFieldOp) {
1392 if (!empty($priceFieldOp['membership_type_id']) &&
1393 isset($createdMemberships[$priceFieldOp['membership_type_id']])
1395 $membershipOb = $createdMemberships[$priceFieldOp['membership_type_id']];
1396 $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date
::customFormat($membershipOb->start_date
, '%B %E%f, %Y') : '-';
1397 $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date
::customFormat($membershipOb->end_date
, '%B %E%f, %Y') : '-';
1400 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1403 $form->_values
['lineItem'] = $form->_lineItem
;
1404 $form->assign('lineItem', $form->_lineItem
);
1408 if (!empty($errors)) {
1409 $message = self
::compileErrorMessage($errors);
1410 throw new CRM_Core_Exception($message);
1412 $form->_params
['createdMembershipIDs'] = array();
1414 // CRM-7851 - Moved after processing Payment Errors
1415 //@todo - the reasoning for this being here seems a little outdated
1416 foreach ($createdMemberships as $createdMembership) {
1417 CRM_Core_BAO_CustomValueTable
::postProcess(
1419 CRM_Core_DAO
::$_nullArray,
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 reciept template to send payment reciept
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 // Do not send an email if Recurring transaction is done via Direct Mode
1451 // Email will we sent when the IPN is received.
1452 if (!empty($form->_params
['is_recur']) && $form->_contributeMode
== 'direct') {
1453 if (!empty($membershipContribution->trxn_id
)) {
1455 civicrm_api3('contribution', 'completetransaction', array(
1456 'id' => $membershipContribution->id
,
1457 'trxn_id' => $membershipContribution->trxn_id
1460 catch (CiviCRM_API3_Exception
$e) {
1461 // if for any reason it is already completed this will fail - e.g extensions hacking around core not completing transactions prior to CRM-15296
1462 // so let's be gentle here
1463 CRM_Core_Error
::debug_log_message('contribution ' . $membershipContribution->id
. ' not completed with trxn_id ' . $membershipContribution->trxn_id
. ' and message ' . $e->getMessage());
1469 //finally send an email receipt
1470 CRM_Contribute_BAO_ContributionPage
::sendMail($contactID,
1478 * Function for updating a membership record's contribution_recur_id
1480 * @param object CRM_Member_DAO_Membership $membership
1481 * @param \CRM_Contribute_BAO_Contribution|\CRM_Contribute_DAO_Contribution $contribution
1486 static public function updateRecurMembership(
1487 CRM_Member_DAO_Membership
$membership,
1488 CRM_Contribute_BAO_Contribution
$contribution) {
1490 if (empty($contribution->contribution_recur_id
)) {
1495 1 => array($contribution->contribution_recur_id
, 'Integer'),
1496 2 => array($membership->id
, 'Integer'),
1499 $sql = "UPDATE civicrm_membership SET contribution_recur_id = %1 WHERE id = %2";
1500 CRM_Core_DAO
::executeQuery($sql, $params);
1505 * A wrapper for renewing memberships from a form - including the form in the membership processing adds complexity
1506 * as the forms are being forced to pretend similarity
1507 * Try to call the renewMembership directly
1508 * @todo - this form method needs to have the interaction with the form layer removed from it
1509 * as a BAO function. Note that the api now supports membership renewals & it is not clear this function does anything
1510 * not done by the membership.create api (with a lot less unit tests)
1512 * This method will renew / create the membership depending on
1513 * whether the given contact has a membership or not. And will add
1514 * the modified dates for membership and in the log table.
1516 * @param int $contactID
1517 * Id of the contact.
1518 * @param int $membershipTypeID
1519 * Id of the new membership type.
1520 * @param bool $is_test
1521 * If this is test contribution or live contribution.
1522 * @param CRM_Core_Form $form
1524 * @param null $changeToday
1525 * @param int $modifiedID
1526 * Individual contact id in case of On Behalf signup (CRM-4027 ).
1527 * @param null $customFieldsFormatted
1528 * @param int $numRenewTerms
1529 * How many membership terms are being added to end date (default is 1).
1530 * @param int $membershipID
1531 * Membership ID, this should always be passed in & optionality should be removed.
1533 * @throws CRM_Core_Exception
1537 static function renewMembershipFormWrapper(
1542 $changeToday = NULL,
1544 $customFieldsFormatted = NULL,
1546 $membershipID = NULL
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($pending, $contributionRecurID, $changeToday, $membershipSource, $isPayLater, $campaignId) = self
::extractFormValues($form, $changeToday, $membershipTypeDetails);
1563 list($membership, $renewalMode, $dates) = self
::renewMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $allStatus, $membershipTypeDetails, $contributionRecurID, $format, $membershipSource, $ids, $statusFormat, $isPayLater, $campaignId);
1564 $form->set('renewal_mode', $renewalMode);
1565 if (!empty($dates)) {
1566 $form->assign('mem_start_date',
1567 CRM_Utils_Date
::customFormat($dates['start_date'], $format)
1569 $form->assign('mem_end_date',
1570 CRM_Utils_Date
::customFormat($dates['end_date'], $format)
1578 * Method to fix membership status of stale membership
1580 * This method first checks if the membership is stale. If it is,
1581 * then status will be updated based on existing start and end
1582 * dates and log will be added for the status change.
1584 * @param array $currentMembership
1585 * Reference to the array.
1586 * containing all values of
1587 * the current membership
1588 * @param array $changeToday
1589 * Array of month, day, year.
1590 * values in case today needs
1591 * to be customised, null otherwise
1596 public static function fixMembershipStatusBeforeRenew(&$currentMembership, $changeToday) {
1599 $today = CRM_Utils_Date
::processDate($changeToday, NULL, FALSE, 'Y-m-d');
1602 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
1603 CRM_Utils_Array
::value('start_date', $currentMembership),
1604 CRM_Utils_Array
::value('end_date', $currentMembership),
1605 CRM_Utils_Array
::value('join_date', $currentMembership),
1608 $currentMembership['membership_type_id'],
1612 if (empty($status) ||
1613 empty($status['id'])
1615 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.'));
1618 $currentMembership['today_date'] = $today;
1620 if ($status['id'] !== $currentMembership['status_id']) {
1621 $memberDAO = new CRM_Member_DAO_Membership();
1622 $memberDAO->id
= $currentMembership['id'];
1623 $memberDAO->find(TRUE);
1625 $memberDAO->status_id
= $status['id'];
1626 $memberDAO->join_date
= CRM_Utils_Date
::isoToMysql($memberDAO->join_date
);
1627 $memberDAO->start_date
= CRM_Utils_Date
::isoToMysql($memberDAO->start_date
);
1628 $memberDAO->end_date
= CRM_Utils_Date
::isoToMysql($memberDAO->end_date
);
1630 CRM_Core_DAO
::storeValues($memberDAO, $currentMembership);
1633 $currentMembership['is_current_member'] = CRM_Core_DAO
::getFieldValue(
1634 'CRM_Member_DAO_MembershipStatus',
1635 $currentMembership['status_id'],
1641 'membership_id' => $currentMembership['id'],
1642 'status_id' => $status['id'],
1643 'start_date' => CRM_Utils_Date
::customFormat(
1644 $currentMembership['start_date'],
1647 'end_date' => CRM_Utils_Date
::customFormat(
1648 $currentMembership['end_date'],
1651 'modified_date' => CRM_Utils_Date
::customFormat(
1652 $currentMembership['today_date'],
1655 'membership_type_id' => $currentMembership['membership_type_id'],
1656 'max_related' => $currentMembership['max_related'],
1659 $session = CRM_Core_Session
::singleton();
1660 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
1661 if ($session->get('userID')) {
1662 $logParams['modified_id'] = $session->get('userID');
1665 $logParams['modified_id'] = $currentMembership['contact_id'];
1667 CRM_Member_BAO_MembershipLog
::add($logParams, CRM_Core_DAO
::$_nullArray);
1672 * Get the contribution page id from the membership record
1674 * @param int membershipId membership id
1676 * @return int $contributionPageId contribution page id
1679 public static function getContributionPageId($membershipID) {
1681 SELECT c.contribution_page_id as pageID
1682 FROM civicrm_membership_payment mp, civicrm_contribution c
1683 WHERE mp.contribution_id = c.id
1684 AND c.contribution_page_id IS NOT NULL
1685 AND mp.membership_id = " . CRM_Utils_Type
::escape($membershipID, 'Integer')
1686 . " ORDER BY mp.id DESC";
1688 return CRM_Core_DAO
::singleValueQuery($query,
1689 CRM_Core_DAO
::$_nullArray
1694 * Updated related memberships
1696 * @param int $ownerMembershipId
1697 * Owner Membership Id.
1698 * @param array $params
1699 * Formatted array of key => value.
1702 public static function updateRelatedMemberships($ownerMembershipId, $params) {
1703 $membership = new CRM_Member_DAO_Membership();
1704 $membership->owner_membership_id
= $ownerMembershipId;
1705 $membership->find();
1707 while ($membership->fetch()) {
1708 $relatedMembership = new CRM_Member_DAO_Membership();
1709 $relatedMembership->id
= $membership->id
;
1710 $relatedMembership->copyValues($params);
1711 $relatedMembership->save();
1712 $relatedMembership->free();
1715 $membership->free();
1719 * Get list of membership fields for profile
1720 * For now we only allow custom membership fields to be in
1725 * @return array 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 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
1766 * takes into account the maximum related memberships
1768 * @param array $params
1769 * Array of key - value pairs.
1770 * @param CRM_Core_DAO $dao
1771 * Membership object.
1773 * @return null|array array of memberships if created
1776 public static function createRelatedMemberships(&$params, &$dao, $reset = FALSE) {
1777 static $relatedContactIds = array();
1779 // not sure why a static var is in use here - we need a way to reset it from the test suite
1780 $relatedContactIds = array();
1784 $membership = new CRM_Member_DAO_Membership();
1785 $membership->id
= $dao->id
;
1787 // required since create method doesn't return all the
1788 // parameters in the returned membership object
1789 if (!$membership->find(TRUE)) {
1792 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1793 // FIXME : While updating/ renewing the
1794 // membership, if the relationship is PAST then
1795 // the membership of the related contact must be
1797 // For that, getting Membership Status for which
1798 // is_current_member is 0. It works for the
1799 // generated data as there is only one membership
1800 // status having is_current_member = 0.
1801 // But this wont work exactly if there will be
1802 // more than one status having is_current_member = 0.
1803 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
1804 $membershipStatus->is_current_member
= 0;
1805 if ($membershipStatus->find(TRUE)) {
1806 $expiredStatusId = $membershipStatus->id
;
1809 $expiredStatusId = array_search('Expired', CRM_Member_PseudoConstant
::membershipStatus());
1812 $allRelatedContacts = array();
1813 $relatedContacts = array();
1814 if (!is_a($membership, 'CRM_Core_Error')) {
1815 $allRelatedContacts = CRM_Member_BAO_Membership
::checkMembershipRelationship($membership->id
,
1816 $membership->contact_id
,
1817 CRM_Utils_Array
::value('action', $params)
1821 // check for loops. CRM-4213
1822 // remove repeated related contacts, which already inherited membership.
1823 $relatedContactIds[$membership->contact_id
] = TRUE;
1824 foreach ($allRelatedContacts as $cid => $status) {
1825 if (empty($relatedContactIds[$cid])) {
1826 $relatedContactIds[$cid] = TRUE;
1828 //don't create membership again for owner contact.
1829 $nestedRelationship = FALSE;
1830 if ($membership->owner_membership_id
) {
1831 $nestedRelMembership = new CRM_Member_DAO_Membership();
1832 $nestedRelMembership->id
= $membership->owner_membership_id
;
1833 $nestedRelMembership->contact_id
= $cid;
1834 $nestedRelationship = $nestedRelMembership->find(TRUE);
1835 $nestedRelMembership->free();
1837 if (!$nestedRelationship) {
1838 $relatedContacts[$cid] = $status;
1843 //lets cleanup related membership if any.
1844 if (empty($relatedContacts)) {
1845 self
::deleteRelatedMemberships($membership->id
);
1848 // Edit the params array
1849 unset($params['id']);
1850 // Reminder should be sent only to the direct membership
1851 unset($params['reminder_date']);
1852 // unset the custom value ids
1853 if (is_array(CRM_Utils_Array
::value('custom', $params))) {
1854 foreach ($params['custom'] as $k => $v) {
1855 unset($params['custom'][$k]['id']);
1858 if (!isset($params['membership_type_id'])) {
1859 $params['membership_type_id'] = $membership->membership_type_id
;
1862 // max_related should be set in the parent membership
1863 unset($params['max_related']);
1864 // Number of inherited memberships available - NULL is interpreted as unlimited, '0' as none
1865 $available = ($membership->max_related
== NULL ? PHP_INT_MAX
: $membership->max_related
);
1866 $queue = array(); // will be used to queue potential memberships to be created
1868 foreach ($relatedContacts as $contactId => $relationshipStatus) {
1869 //use existing membership record.
1870 $relMembership = new CRM_Member_DAO_Membership();
1871 $relMembership->contact_id
= $contactId;
1872 $relMembership->owner_membership_id
= $membership->id
;
1873 $relMemIds = array();
1874 if ($relMembership->find(TRUE)) {
1875 $params['id'] = $relMemIds['membership'] = $relMembership->id
;
1877 $params['contact_id'] = $contactId;
1878 $params['owner_membership_id'] = $membership->id
;
1880 // set status_id as it might have been changed for
1881 // past relationship
1882 $params['status_id'] = $membership->status_id
;
1884 if ($deceasedStatusId &&
1885 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'is_deceased')
1887 $params['status_id'] = $deceasedStatusId;
1889 elseif ((CRM_Utils_Array
::value('action', $params) & CRM_Core_Action
::UPDATE
) &&
1890 ($relationshipStatus == CRM_Contact_BAO_Relationship
::PAST
)
1892 $params['status_id'] = $expiredStatusId;
1895 //don't calculate status again in create( );
1896 $params['skipStatusCal'] = TRUE;
1898 //do create activity if we changed status.
1899 if ($params['status_id'] != $relMembership->status_id
) {
1900 $params['createActivity'] = TRUE;
1903 // we should not created contribution record for related contacts, CRM-3371
1904 unset($params['contribution_status_id']);
1906 if (($params['status_id'] == $deceasedStatusId) ||
($params['status_id'] == $expiredStatusId)) {
1907 // related membership is not active so does not count towards maximum
1908 CRM_Member_BAO_Membership
::create($params, $relMemIds);
1911 // related membership already exists, so this is just an update
1912 if (isset($params['id'])) {
1913 if ($available > 0) {
1914 CRM_Member_BAO_Membership
::create($params, $relMemIds);
1917 else { // we have run out of inherited memberships, so delete extras
1918 self
::deleteMembership($params['id']);
1920 // we need to first check if there will remain inherited memberships, so queue it up
1927 // now go over the queue and create any available related memberships
1929 while (($available > 0) && ($params = each($queue))) {
1930 CRM_Member_BAO_Membership
::create($params['value'], $relMemIds);
1937 * Delete the record that are associated with this Membership Payment
1939 * @param int $membershipId
1942 * @return boolean true if deleted false otherwise
1944 public static function deleteMembershipPayment($membershipId) {
1946 $membesrshipPayment = new CRM_Member_DAO_MembershipPayment();
1947 $membesrshipPayment->membership_id
= $membershipId;
1948 $membesrshipPayment->find();
1950 while ($membesrshipPayment->fetch()) {
1951 CRM_Contribute_BAO_Contribution
::deleteContribution($membesrshipPayment->contribution_id
);
1952 CRM_Utils_Hook
::pre('delete', 'MembershipPayment', $membesrshipPayment->id
, $membesrshipPayment);
1953 $membesrshipPayment->delete();
1954 CRM_Utils_Hook
::post('delete', 'MembershipPayment', $membesrshipPayment->id
, $membesrshipPayment);
1956 return $membesrshipPayment;
1960 * @param CRM_Core_Form $form
1961 * @param int $membershipTypeID
1965 public static function &buildMembershipTypeValues(&$form, $membershipTypeID = NULL) {
1966 $whereClause = " WHERE domain_id = " . CRM_Core_Config
::domainID();
1968 if (is_array($membershipTypeID)) {
1969 $allIDs = implode(',', $membershipTypeID);
1970 $whereClause .= " AND id IN ( $allIDs )";
1972 elseif (is_numeric($membershipTypeID) &&
1973 $membershipTypeID > 0
1975 $whereClause .= " AND id = $membershipTypeID";
1980 FROM civicrm_membership_type
1983 $dao = CRM_Core_DAO
::executeQuery($query);
1985 $membershipTypeValues = array();
1986 $membershipTypeFields = array(
1992 'financial_type_id',
1994 'member_of_contact_id',
1995 'relationship_type_id',
1996 'relationship_direction',
2000 while ($dao->fetch()) {
2001 $membershipTypeValues[$dao->id
] = array();
2002 foreach ($membershipTypeFields as $mtField) {
2003 $membershipTypeValues[$dao->id
][$mtField] = $dao->$mtField;
2008 CRM_Utils_Hook
::membershipTypeValues($form, $membershipTypeValues);
2010 if (is_numeric($membershipTypeID) &&
2011 $membershipTypeID > 0
2013 return $membershipTypeValues[$membershipTypeID];
2016 return $membershipTypeValues;
2021 * Get membership record count for a Contact
2023 * @param int $contactID
2024 * @param bool $activeOnly
2026 * @return null|string
2029 public static function getContactMembershipCount($contactID, $activeOnly = FALSE) {
2030 $select = "SELECT count(*) FROM civicrm_membership ";
2031 $where = "WHERE civicrm_membership.contact_id = {$contactID} AND civicrm_membership.is_test = 0 ";
2033 // CRM-6627, all status below 3 (active, pending, grace) are considered active
2035 $select .= " INNER JOIN civicrm_membership_status ON civicrm_membership.status_id = civicrm_membership_status.id ";
2036 $where .= " and civicrm_membership_status.is_current_member = 1";
2039 $query = $select . $where;
2040 return CRM_Core_DAO
::singleValueQuery($query);
2044 * Check whether payment processor supports
2045 * cancellation of membership subscription
2050 * @param bool $isNotCancelled
2055 public static function isCancelSubscriptionSupported($mid, $isNotCancelled = TRUE) {
2056 $cacheKeyString = "$mid";
2057 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2059 static $supportsCancel = array();
2061 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2062 $supportsCancel[$cacheKeyString] = FALSE;
2063 $isCancelled = FALSE;
2065 if ($isNotCancelled) {
2066 $isCancelled = self
::isSubscriptionCancelled($mid);
2069 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($mid, 'membership', 'obj');
2070 if (!empty($paymentObject)) {
2071 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2074 return $supportsCancel[$cacheKeyString];
2078 * Check whether subscription is already cancelled
2083 * @return string $status contribution status
2086 public static function isSubscriptionCancelled($mid) {
2088 SELECT cr.contribution_status_id
2089 FROM civicrm_contribution_recur cr
2090 LEFT JOIN civicrm_membership mem ON ( cr.id = mem.contribution_recur_id )
2091 WHERE mem.id = %1 LIMIT 1";
2092 $params = array(1 => array($mid, 'Integer'));
2093 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2094 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
2095 if ($status == 'Cancelled') {
2102 * Get membership joins for a specified membership
2103 * type. Specifically, retrieves a count of still current memberships whose
2104 * join_date and start_date are within a specified date range. Dates match
2105 * the pattern "yyyy-mm-dd".
2107 * @param int $membershipTypeId
2108 * Membership type id.
2109 * @param int $startDate
2110 * Date on which to start counting.
2111 * @param int $endDate
2112 * Date on which to end counting.
2113 * @param bool|int $isTest if true, membership is for a test site
2115 * @return returns the number of members of type $membershipTypeId
2116 * whose join_date is between $startDate and $endDate and
2117 * whose start_date is between $startDate and $endDate
2119 public static function getMembershipJoins($membershipTypeId, $startDate, $endDate, $isTest = 0) {
2120 $testClause = 'membership.is_test = 1';
2122 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
2124 if (!self
::$_signupActType) {
2125 self
::_getActTypes();
2128 if (!self
::$_signupActType) {
2133 SELECT COUNT(DISTINCT membership.id) as member_count
2134 FROM civicrm_membership membership
2135 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
2136 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
2137 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
2138 WHERE membership.membership_type_id = %2
2139 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
2143 1 => array(self
::$_signupActType, 'Integer'),
2144 2 => array($membershipTypeId, 'Integer'),
2147 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
2149 return (int) $memberCount;
2153 * Get membership renewals for a specified membership
2154 * type. Specifically, retrieves a count of still current memberships
2155 * whose join_date is before and start_date is within a specified date
2156 * range. Dates match the pattern "yyyy-mm-dd".
2158 * @param int $membershipTypeId
2159 * Membership type id.
2160 * @param int $startDate
2161 * Date on which to start counting.
2162 * @param int $endDate
2163 * Date on which to end counting.
2164 * @param bool|int $isTest if true, membership is for a test site
2166 * @return integer returns the number of members of type $membershipTypeId
2167 * whose join_date is before $startDate and
2168 * whose start_date is between $startDate and $endDate
2170 public static function getMembershipRenewals($membershipTypeId, $startDate, $endDate, $isTest = 0) {
2171 $testClause = 'membership.is_test = 1';
2173 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
2175 if (!self
::$_renewalActType) {
2176 self
::_getActTypes();
2179 if (!self
::$_renewalActType) {
2184 SELECT COUNT(DISTINCT membership.id) as member_count
2185 FROM civicrm_membership membership
2186 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
2187 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
2188 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
2189 WHERE membership.membership_type_id = %2
2190 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
2194 1 => array(self
::$_renewalActType, 'Integer'),
2195 2 => array($membershipTypeId, 'Integer'),
2197 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
2199 return (int) $memberCount;
2203 * Where a second separate financial transaction is supported we will process it here
2205 * @param int $contactID
2206 * @param CRM_Contribute_Form_Contribution_Confirm $form
2207 * @param array $tempParams
2209 * @param array $lineItems
2210 * @param $minimumFee
2211 * @param int $financialTypeID
2213 * @throws CRM_Core_Exception
2215 * @return CRM_Contribute_BAO_Contribution
2217 public static function processSecondaryFinancialTransaction($contactID, &$form, $tempParams, $isTest, $lineItems, $minimumFee, $financialTypeID) {
2218 $contributionType = new CRM_Financial_DAO_FinancialType();
2219 $contributionType->id
= $financialTypeID;
2220 if (!$contributionType->find(TRUE)) {
2221 CRM_Core_Error
::fatal(ts("Could not find a system table"));
2223 $tempParams['amount'] = $minimumFee;
2224 $tempParams['invoiceID'] = md5(uniqid(rand(), TRUE));
2227 if ($form->_values
['is_monetary'] && !$form->_params
['is_pay_later'] && $minimumFee > 0.0) {
2228 $payment = CRM_Core_Payment
::singleton($form->_mode
, $form->_paymentProcessor
, $form);
2230 if ($form->_contributeMode
== 'express') {
2231 $result = $payment->doExpressCheckout($tempParams);
2234 $result = $payment->doDirectPayment($tempParams);
2238 if (is_a($result, 'CRM_Core_Error')) {
2239 throw new CRM_Core_Exception(CRM_Core_Error
::getMessages($result));
2242 //assign receive date when separate membership payment
2243 //and contribution amount not selected.
2244 if ($form->_amount
== 0) {
2245 $now = date('YmdHis');
2246 $form->_params
['receive_date'] = $now;
2247 $receiveDate = CRM_Utils_Date
::mysqlToIso($now);
2248 $form->set('params', $form->_params
);
2249 $form->assign('receive_date', $receiveDate);
2252 $form->set('membership_trx_id', $result['trxn_id']);
2253 $form->set('membership_amount', $minimumFee);
2255 $form->assign('membership_trx_id', $result['trxn_id']);
2256 $form->assign('membership_amount', $minimumFee);
2258 // we don't need to create the user twice, so lets disable cms_create_account
2259 // irrespective of the value, CRM-2888
2260 $tempParams['cms_create_account'] = 0;
2262 $pending = $form->_params
['is_pay_later'] ?
(($minimumFee > 0.0) ?
TRUE : FALSE) : FALSE;
2264 //set this variable as we are not creating pledge for
2265 //separate membership payment contribution.
2266 //so for differentiating membership contribution from
2267 //main contribution.
2268 $form->_params
['separate_membership_payment'] = 1;
2269 $membershipContribution = CRM_Contribute_Form_Contribution_Confirm
::processContribution($form,
2279 return $membershipContribution;
2284 * Create linkages between membership & contribution - note this is the wrong place for this code but this is a
2285 * refactoring step. This should be BAO functionality
2286 * @param $membership
2287 * @param $membershipContribution
2289 public static function linkMembershipPayment($membership, $membershipContribution) {
2290 CRM_Member_BAO_MembershipPayment
::create(array(
2291 'membership_id' => $membership->id
,
2292 'contribution_id' => $membershipContribution->id
2297 * @param array $membershipParams
2298 * @param int $contactID
2299 * @param $customFieldsFormatted
2300 * @param int $membershipID
2304 * @param $membershipContribution
2305 * @param CRM_Core_Form $form
2309 public static function createOrRenewMembership($membershipParams, $contactID, $customFieldsFormatted, $membershipID, $memType, $isTest, $numTerms, $membershipContribution, &$form) {
2310 $membership = self
::renewMembershipFormWrapper($contactID, $memType,
2311 $isTest, $form, NULL,
2312 CRM_Utils_Array
::value('cms_contactID', $membershipParams),
2313 $customFieldsFormatted, $numTerms,
2317 if (!empty($membershipContribution)) {
2318 // update recurring id for membership record
2319 self
::updateRecurMembership($membership, $membershipContribution);
2321 self
::linkMembershipPayment($membership, $membershipContribution);
2327 * Turn array of errors into message string
2329 * @param array $errors
2334 public static function compileErrorMessage($errors) {
2335 foreach ($errors as $error) {
2336 if (is_string($error)) {
2337 $message[] = $error;
2340 return ts('Payment Processor Error message') . ': ' . implode('<br/>', $message);
2344 * Extract relevant values from the form so we can separate form logic from BAO logcis
2345 * @param CRM_Core_Form $form
2346 * @param $changeToday
2347 * @param $membershipTypeDetails
2351 public static function extractFormValues($form, $changeToday, $membershipTypeDetails) {
2353 //@todo this is a BAO function & should not inspect the form - the form should do this
2354 // & pass required params to the BAO
2355 if (CRM_Utils_Array
::value('minimum_fee', $membershipTypeDetails) > 0.0) {
2356 if (((isset($form->_contributeMode
) && $form->_contributeMode
== 'notify') ||
!empty($form->_params
['is_pay_later']) ||
2357 (!empty($form->_params
['is_recur']) && $form->_contributeMode
== 'direct'
2360 (($form->_values
['is_monetary'] && $form->_amount
> 0.0) ||
!empty($form->_params
['separate_membership_payment']) ||
2361 CRM_Utils_Array
::value('record_contribution', $form->_params
)
2367 $contributionRecurID = isset($form->_params
['contributionRecurID']) ?
$form->_params
['contributionRecurID'] : NULL;
2369 //we renew expired membership, CRM-6277
2370 if (!$changeToday) {
2371 if ($form->get('renewalDate')) {
2372 $changeToday = $form->get('renewalDate');
2374 elseif (get_class($form) == 'CRM_Contribute_Form_Contribution_Confirm') {
2375 $changeToday = date('YmdHis');
2379 $membershipSource = NULL;
2380 if (!empty($form->_params
['membership_source'])) {
2381 $membershipSource = $form->_params
['membership_source'];
2383 elseif (isset($form->_values
['title']) && !empty($form->_values
['title'])) {
2384 $membershipSource = ts('Online Contribution:') . ' ' . $form->_values
['title'];
2387 if (isset($form->_params
)) {
2388 $isPayLater = CRM_Utils_Array
::value('is_pay_later', $form->_params
);
2391 if (isset($form->_values
) && is_array($form->_values
) && !empty($form->_values
)) {
2392 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_params
);
2393 if (!array_key_exists('campaign_id', $form->_params
)) {
2394 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_values
);
2397 return array($pending, $contributionRecurID, $changeToday, $membershipSource, $isPayLater, $campaignId);
2401 * @param int $contactID
2402 * @param int $membershipTypeID
2403 * @param bool $is_test
2404 * @param $changeToday
2405 * @param int $modifiedID
2406 * @param $customFieldsFormatted
2407 * @param $numRenewTerms
2408 * @param int $membershipID
2411 * @param array $membershipTypeDetails
2412 * @param int $contributionRecurID
2414 * @param $membershipSource
2416 * @param $statusFormat
2417 * @param $isPayLater
2418 * @param int $campaignId
2420 * @throws CRM_Core_Exception
2423 public static function renewMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $allStatus, $membershipTypeDetails, $contributionRecurID, $format, $membershipSource, $ids, $statusFormat, $isPayLater, $campaignId) {
2424 $renewalMode = $updateStatusId = FALSE;
2426 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
2427 // is the same as the parent org of an existing membership of the contact
2428 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($contactID, $membershipTypeID,
2429 $is_test, $membershipID, TRUE
2431 if ($currentMembership) {
2432 $activityType = 'Membership Renewal';
2433 $renewalMode = TRUE;
2435 // Do NOT do anything.
2436 //1. membership with status : PENDING/CANCELLED (CRM-2395)
2437 //2. Paylater/IPN renew. CRM-4556.
2438 if ($pending ||
in_array($currentMembership['status_id'], array(
2439 array_search('Pending', $allStatus),
2441 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
2444 $membership = new CRM_Member_DAO_Membership();
2445 $membership->id
= $currentMembership['id'];
2446 $membership->find(TRUE);
2448 // CRM-8141 create a membership_log entry so that we will know the membership_type_id to change to when payment completed
2450 // note that we are logging the requested new membership_type_id that may be different than current membership_type_id
2451 // it will be used when payment is received to update the membership_type_id to what was paid for
2453 'membership_id' => $membership->id
,
2454 'status_id' => $membership->status_id
,
2455 'start_date' => CRM_Utils_Date
::customFormat(
2456 $membership->start_date
,
2459 'end_date' => CRM_Utils_Date
::customFormat(
2460 $membership->end_date
,
2463 'modified_date' => CRM_Utils_Date
::customFormat(
2467 'membership_type_id' => $membershipTypeID,
2468 'max_related' => !empty($membershipTypeDetails['max_related']) ?
$membershipTypeDetails['max_related'] : NULL,
2470 $session = CRM_Core_Session
::singleton();
2471 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
2472 if ($session->get('userID')) {
2473 $logParams['modified_id'] = $session->get('userID');
2476 $logParams['modified_id'] = $membership->contact_id
;
2478 CRM_Member_BAO_MembershipLog
::add($logParams, CRM_Core_DAO
::$_nullArray);
2480 if (!empty($contributionRecurID)) {
2481 CRM_Core_DAO
::setFieldValue('CRM_Member_DAO_Membership', $membership->id
,
2482 'contribution_recur_id', $contributionRecurID
2486 return array($membership, $renewalMode, $dates);
2489 // Check and fix the membership if it is STALE
2490 self
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
2492 // Now Renew the membership
2493 if (!$currentMembership['is_current_member']) {
2494 // membership is not CURRENT
2496 // CRM-7297 Membership Upsell - calculate dates based on new membership type
2497 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($currentMembership['id'],
2503 $currentMembership['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
2504 $currentMembership['start_date'] = CRM_Utils_Array
::value('start_date', $dates);
2505 $currentMembership['end_date'] = CRM_Utils_Array
::value('end_date', $dates);
2506 $currentMembership['is_test'] = $is_test;
2508 if (!empty($membershipSource)) {
2509 $currentMembership['source'] = $membershipSource;
2512 $currentMembership['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
2513 $currentMembership['id'],
2518 if (!empty($currentMembership['id'])) {
2519 $ids['membership'] = $currentMembership['id'];
2521 $memParams = $currentMembership;
2522 $memParams['membership_type_id'] = $membershipTypeID;
2524 //set the log start date.
2525 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
2529 // CURRENT Membership
2530 $membership = new CRM_Member_DAO_Membership();
2531 $membership->id
= $currentMembership['id'];
2532 $membership->find(TRUE);
2533 // CRM-7297 Membership Upsell - calculate dates based on new membership type
2534 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
2540 // Insert renewed dates for CURRENT membership
2541 $memParams = array();
2542 $memParams['join_date'] = CRM_Utils_Date
::isoToMysql($membership->join_date
);
2543 $memParams['start_date'] = CRM_Utils_Date
::isoToMysql($membership->start_date
);
2544 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $dates);
2545 $memParams['membership_type_id'] = $membershipTypeID;
2547 //set the log start date.
2548 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
2549 if (empty($membership->source
)) {
2550 if (!empty($membershipSource)) {
2551 $memParams['source'] = $membershipSource;
2554 $memParams['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
2555 $currentMembership['id'],
2561 if (!empty($currentMembership['id'])) {
2562 $ids['membership'] = $currentMembership['id'];
2567 $updateStatusId = array_search('Pending', $allStatus);
2573 $activityType = 'Membership Signup';
2575 'contact_id' => $contactID,
2576 'membership_type_id' => $membershipTypeID,
2580 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
2582 $memParams['join_date'] = CRM_Utils_Array
::value('join_date', $dates);
2583 $memParams['start_date'] = CRM_Utils_Array
::value('start_date', $dates);
2584 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $dates);
2586 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(CRM_Utils_Date
::customFormat($dates['start_date'],
2589 CRM_Utils_Date
::customFormat($dates['end_date'],
2592 CRM_Utils_Date
::customFormat($dates['join_date'],
2600 $updateStatusId = CRM_Utils_Array
::value('id', $status);
2603 // if IPN/Pay-Later set status to: PENDING
2604 $updateStatusId = array_search('Pending', $allStatus);
2607 if (!empty($membershipSource)) {
2608 $memParams['source'] = $membershipSource;
2610 $memParams['contribution_recur_id'] = $contributionRecurID;
2612 $memParams['is_test'] = $is_test;
2613 $memParams['is_pay_later'] = $isPayLater;
2617 //if we decided status here and want to skip status
2618 //calculation in create( ); then need to pass 'skipStatusCal'.
2619 if ($updateStatusId) {
2620 $memParams['status_id'] = $updateStatusId;
2621 $memParams['skipStatusCal'] = TRUE;
2624 //since we are renewing,
2625 //make status override false.
2626 $memParams['is_override'] = FALSE;
2628 //CRM-4027, create log w/ individual contact.
2630 $ids['userId'] = $modifiedID;
2631 $memParams['is_for_organization'] = TRUE;
2634 $ids['userId'] = $contactID;
2637 //inherit campaign from contrib page.
2638 if (isset($campaignId)) {
2639 $memParams['campaign_id'] = $campaignId;
2642 $memParams['custom'] = $customFieldsFormatted;
2643 $membership = self
::create($memParams, $ids, FALSE, $activityType);
2645 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
2646 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
2647 $membership->find(TRUE);
2649 return array($membership, $renewalMode, $dates);
2653 * Process price set and line items.
2656 * @param int $membershipId
2661 public function processPriceSet($membershipId, $lineItem) {
2662 //FIXME : need to move this too
2663 if (!$membershipId ||
!is_array($lineItem)
2664 || CRM_Utils_System
::isNull($lineItem)
2669 foreach ($lineItem as $priceSetId => $values) {
2673 foreach ($values as $line) {
2674 $line['entity_table'] = 'civicrm_membership';
2675 $line['entity_id'] = $membershipId;
2676 CRM_Price_BAO_LineItem
::create($line);
2682 * Retrieve the contribution id for the associated Membership id
2683 * @todo we should get this off the line item
2685 * @param int $membershipId
2688 * @return integer contribution id
2690 public static function getMembershipContributionId($membershipId) {
2692 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
2693 $membershipPayment->membership_id
= $membershipId;
2694 if ($membershipPayment->find(TRUE)) {
2695 return $membershipPayment->contribution_id
;
2701 * The function checks and updates the status of all membership records for a given domain using the
2702 * calc_membership_status and update_contact_membership APIs.
2705 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
2707 * @return array $result
2709 public static function updateAllMembershipStatus() {
2711 //get all active statuses of membership, CRM-3984
2712 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2713 $statusLabels = CRM_Member_PseudoConstant
::membershipStatus(NULL, NULL, 'label');
2714 $allTypes = CRM_Member_PseudoConstant
::membershipType();
2716 // get only memberships with active membership types
2718 SELECT civicrm_membership.id as membership_id,
2719 civicrm_membership.is_override as is_override,
2720 civicrm_membership.membership_type_id as membership_type_id,
2721 civicrm_membership.status_id as status_id,
2722 civicrm_membership.join_date as join_date,
2723 civicrm_membership.start_date as start_date,
2724 civicrm_membership.end_date as end_date,
2725 civicrm_membership.source as source,
2726 civicrm_contact.id as contact_id,
2727 civicrm_contact.is_deceased as is_deceased,
2728 civicrm_membership.owner_membership_id as owner_membership_id,
2729 civicrm_membership.contribution_recur_id as recur_id
2730 FROM civicrm_membership
2731 INNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )
2732 INNER JOIN civicrm_membership_type ON
2733 (civicrm_membership.membership_type_id = civicrm_membership_type.id AND civicrm_membership_type.is_active = 1)
2734 WHERE civicrm_membership.is_test = 0";
2737 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2742 $smarty = CRM_Core_Smarty
::singleton();
2744 while ($dao->fetch()) {
2748 // Put common parameters into array for easy access
2749 $memberParams = array(
2750 'id' => $dao->membership_id
,
2751 'status_id' => $dao->status_id
,
2752 'contact_id' => $dao->contact_id
,
2753 'membership_type_id' => $dao->membership_type_id
,
2754 'membership_type' => $allTypes[$dao->membership_type_id
],
2755 'join_date' => $dao->join_date
,
2756 'start_date' => $dao->start_date
,
2757 'end_date' => $dao->end_date
,
2758 'source' => $dao->source
,
2759 'skipStatusCal' => TRUE,
2760 'skipRecentView' => TRUE,
2763 $smarty->assign_by_ref('memberParams', $memberParams);
2765 //update membership record to Deceased if contact is deceased
2766 if ($dao->is_deceased
) {
2767 // check for 'Deceased' membership status, CRM-5636
2768 $deceaseStatusId = array_search('Deceased', $allStatus);
2769 if (!$deceaseStatusId) {
2770 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'))));
2773 //process only when status change.
2774 if ($dao->status_id
!= $deceaseStatusId) {
2775 //take all params that need to save.
2776 $deceasedMembership = $memberParams;
2777 $deceasedMembership['status_id'] = $deceaseStatusId;
2778 $deceasedMembership['createActivity'] = TRUE;
2779 $deceasedMembership['version'] = 3;
2781 //since there is change in status.
2782 $statusChange = array('status_id' => $deceaseStatusId);
2783 $smarty->append_by_ref('memberParams', $statusChange, TRUE);
2785 $deceasedMembership['contact_id'],
2786 $deceasedMembership['membership_type_id'],
2787 $deceasedMembership['membership_type'],
2788 $deceasedMembership['join_date'],
2789 $deceasedMembership['start_date'],
2790 $deceasedMembership['end_date'],
2791 $deceasedMembership['source']
2794 //process membership record.
2795 civicrm_api('membership', 'create', $deceasedMembership);
2800 //we fetch related, since we need to check for deceased
2801 //now further processing is handle w/ main membership record.
2802 if ($dao->owner_membership_id
) {
2806 //update membership records where status is NOT - Pending OR Cancelled.
2807 //as well as membership is not override.
2808 //skipping Expired membership records -> reduced extra processing( kiran )
2809 if (!$dao->is_override
&&
2810 !in_array($dao->status_id
, array(
2811 array_search('Pending', $allStatus),
2815 CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)
2817 array_search('Expired', $allStatus),
2821 // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses
2822 //get the membership status as per id.
2823 $newStatus = civicrm_api('membership_status', 'calc',
2825 'membership_id' => $dao->membership_id
,
2827 'ignore_admin_only' => FALSE
2830 $statusId = CRM_Utils_Array
::value('id', $newStatus);
2832 //process only when status change.
2834 $statusId != $dao->status_id
2836 //take all params that need to save.
2837 $memParams = $memberParams;
2838 $memParams['status_id'] = $statusId;
2839 $memParams['createActivity'] = TRUE;
2840 $memParams['version'] = 3;
2842 // Unset columns which should remain unchanged from their current saved
2843 // values. This avoids race condition in which these values may have
2844 // been changed by other processes.
2846 $memParams['contact_id'],
2847 $memParams['membership_type_id'],
2848 $memParams['membership_type'],
2849 $memParams['join_date'],
2850 $memParams['start_date'],
2851 $memParams['end_date'],
2852 $memParams['source']
2854 //since there is change in status.
2855 $statusChange = array('status_id' => $statusId);
2856 $smarty->append_by_ref('memberParams', $statusChange, TRUE);
2858 //process member record.
2859 civicrm_api('membership', 'create', $memParams);
2864 $result['is_error'] = 0;
2865 $result['messages'] = ts('Processed %1 membership records. Updated %2 records.', array(
2873 * The function returns the membershiptypes for a particular contact
2874 * who has lifetime membership without end date.
2876 * @param int $contactID
2877 * @param bool $isTest
2878 * @param bool $onlyLifeTime
2882 public static function getAllContactMembership($contactID, $isTest = FALSE, $onlyLifeTime = FALSE) {
2883 $contactMembershipType = array();
2885 return $contactMembershipType;
2888 $dao = new CRM_Member_DAO_Membership();
2889 $dao->contact_id
= $contactID;
2890 $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
2891 $dao->whereAdd("status_id != $pendingStatusId");
2894 $dao->is_test
= $isTest;
2897 $dao->whereAdd('is_test IS NULL OR is_test = 0');
2900 if ($onlyLifeTime) {
2901 $dao->whereAdd('end_date IS NULL');
2905 while ($dao->fetch()) {
2906 $membership = array();
2907 CRM_Core_DAO
::storeValues($dao, $membership);
2908 $contactMembershipType[$dao->membership_type_id
] = $membership;
2910 return $contactMembershipType;
2914 * Record contribution record associated with membership
2916 * @param array $params
2917 * Array of submitted params.
2919 * (param in process of being removed - try to use params) array of ids.
2921 * @return CRM_Contribute_BAO_Contribution
2924 public static function recordMembershipContribution(&$params, $ids = array()) {
2925 $membershipId = $params['membership_id'];
2926 $contributionParams = array();
2927 $config = CRM_Core_Config
::singleton();
2928 $contributionParams['currency'] = $config->defaultCurrency
;
2929 $contributionParams['receipt_date'] = (CRM_Utils_Array
::value('receipt_date', $params)) ?
$params['receipt_date'] : 'null';
2930 $contributionParams['source'] = CRM_Utils_Array
::value('contribution_source', $params);
2931 $contributionParams['non_deductible_amount'] = 'null';
2932 $contributionParams['payment_processor'] = CRM_Utils_Array
::value('payment_processor_id', $params);
2933 $contributionSoftParams = CRM_Utils_Array
::value('soft_credit', $params);
2934 $recordContribution = array(
2938 'financial_type_id',
2939 'payment_instrument_id',
2943 'contribution_status_id',
2951 foreach ($recordContribution as $f) {
2952 $contributionParams[$f] = CRM_Utils_Array
::value($f, $params);
2955 // make entry in batch entity batch table
2956 if (!empty($params['batch_id'])) {
2957 $contributionParams['batch_id'] = $params['batch_id'];
2960 if (!empty($params['contribution_contact_id'])) {
2961 // deal with possibility of a different person paying for contribution
2962 $contributionParams['contact_id'] = $params['contribution_contact_id'];
2965 if (!empty($params['processPriceSet']) &&
2966 !empty($params['lineItems'])
2968 $contributionParams['line_item'] = CRM_Utils_Array
::value('lineItems', $params, NULL);
2971 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
2973 //CRM-13981, create new soft-credit record as to record payment from different person for this membership
2974 if (!empty($contributionSoftParams)) {
2975 if (!empty($params['batch_id'])) {
2976 foreach ($contributionSoftParams as $contributionSoft) {
2977 $contributionSoft['contribution_id'] = $contribution->id
;
2978 $contributionSoft['currency'] = $contribution->currency
;
2979 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoft);
2983 $contributionSoftParams['contribution_id'] = $contribution->id
;
2984 $contributionSoftParams['currency'] = $contribution->currency
;
2985 $contributionSoftParams['amount'] = $contribution->total_amount
;
2986 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoftParams);
2990 // store contribution id
2991 $params['contribution_id'] = $contribution->id
;
2993 //insert payment record for this membership
2994 if (empty($ids['contribution']) ||
!empty($params['is_recur'])) {
2995 CRM_Member_BAO_MembershipPayment
::create(array(
2996 'membership_id' => $membershipId,
2997 'contribution_id' => $contribution->id
3000 return $contribution;
3004 * Record line items for default membership
3006 * @param CRM_Core_Form $qf
3007 * @param array $membershipType
3008 * Array with membership type and organization.
3009 * @param int $priceSetId
3013 public static function createLineItems(&$qf, $membershipType, &$priceSetId) {
3014 $qf->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
3016 $qf->_priceSet
= $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
3018 $editedFieldParams = array(
3019 'price_set_id' => $priceSetId,
3020 'name' => $membershipType[0],
3022 $editedResults = array();
3023 CRM_Price_BAO_PriceField
::retrieve($editedFieldParams, $editedResults);
3025 if (!empty($editedResults)) {
3026 unset($qf->_priceSet
['fields']);
3027 $qf->_priceSet
['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
3028 unset($qf->_priceSet
['fields'][$editedResults['id']]['options']);
3029 $fid = $editedResults['id'];
3030 $editedFieldParams = array(
3031 'price_field_id' => $editedResults['id'],
3032 'membership_type_id' => $membershipType[1],
3034 $editedResults = array();
3035 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $editedResults);
3036 $qf->_priceSet
['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
3037 if (!empty($qf->_params
['total_amount'])) {
3038 $qf->_priceSet
['fields'][$fid]['options'][$editedResults['id']]['amount'] = $qf->_params
['total_amount'];
3042 $fieldID = key($qf->_priceSet
['fields']);
3043 $qf->_params
['price_' . $fieldID] = CRM_Utils_Array
::value('id', $editedResults);
3047 * @todo document me - I seem a bit out of date....
3049 public static function _getActTypes() {
3050 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
3051 self
::$_renewalActType = CRM_Utils_Array
::key('Membership Renewal', $activityTypes);
3052 self
::$_signupActType = CRM_Utils_Array
::key('Membership Signup', $activityTypes);
3056 * Get all Cancelled Membership(s) for a contact
3058 * @param int $contactID
3060 * @param bool $isTest
3063 * @return array of membership type
3066 public static function getContactsCancelledMembership($contactID, $isTest = FALSE) {
3070 $query = 'SELECT membership_type_id FROM civicrm_membership WHERE contact_id = %1 AND status_id = %2 AND is_test = %3';
3071 $queryParams = array(
3072 1 => array($contactID, 'Integer'),
3077 CRM_Member_PseudoConstant
::membershipStatus(
3079 " name = 'Cancelled' ",
3087 3 => array($isTest, 'Boolean'),
3090 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
3091 $cancelledMembershipIds = array();
3092 while ($dao->fetch()) {
3093 $cancelledMembershipIds[] = $dao->membership_type_id
;
3095 return $cancelledMembershipIds;