3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
35 class CRM_Member_BAO_Membership
extends CRM_Member_DAO_Membership
{
38 * Static field for all the membership information that we can potentially import.
42 static $_importableFields = NULL;
44 static $_renewalActType = NULL;
46 static $_signupActType = NULL;
51 * @return \CRM_Member_DAO_Membership
55 public function __construct() {
56 parent
::__construct();
60 * Takes an associative array and creates a membership object.
62 * the function extracts all the params it needs to initialize the created
63 * membership object. The params array could contain additional unused name/value
66 * @param array $params
67 * (reference ) an assoc array of name/value pairs.
69 * The array that holds all the db ids.
71 * @return CRM_Member_BAO_Membership
73 public static function add(&$params, $ids = array()) {
74 $oldStatus = $oldType = NULL;
75 $params['id'] = CRM_Utils_Array
::value('id', $params, CRM_Utils_Array
::value('membership', $ids));
77 CRM_Utils_Hook
::pre('edit', 'Membership', $params['id'], $params);
80 CRM_Utils_Hook
::pre('create', 'Membership', NULL, $params);
83 // we do this after the hooks are called in case it has been altered
85 $membershipObj = new CRM_Member_DAO_Membership();
86 $membershipObj->id
= $id;
87 $membershipObj->find();
88 while ($membershipObj->fetch()) {
89 $oldStatus = $membershipObj->status_id
;
90 $oldType = $membershipObj->membership_type_id
;
94 if (array_key_exists('is_override', $params) && !$params['is_override']) {
95 $params['is_override'] = 'null';
98 $membership = new CRM_Member_BAO_Membership();
99 $membership->copyValues($params);
100 $membership->id
= $id;
105 if (empty($membership->contact_id
) ||
empty($membership->status_id
)) {
106 // this means we are in renewal mode and are just updating the membership
107 // record or this is an API update call and all fields are not present in the update record
108 // however the hooks don't care and want all data CRM-7784
109 $tempMembership = new CRM_Member_DAO_Membership();
110 $tempMembership->id
= $membership->id
;
111 $tempMembership->find(TRUE);
112 $membership = $tempMembership;
115 //get the log start date.
116 //it is set during renewal of membership.
117 $logStartDate = CRM_Utils_Array
::value('log_start_date', $params);
118 $logStartDate = ($logStartDate) ? CRM_Utils_Date
::isoToMysql($logStartDate) : CRM_Utils_Date
::isoToMysql($membership->start_date
);
119 $values = self
::getStatusANDTypeValues($membership->id
);
121 $membershipLog = array(
122 'membership_id' => $membership->id
,
123 'status_id' => $membership->status_id
,
124 'start_date' => $logStartDate,
125 'end_date' => CRM_Utils_Date
::isoToMysql($membership->end_date
),
126 'modified_date' => date('Ymd'),
127 'membership_type_id' => $values[$membership->id
]['membership_type_id'],
128 'max_related' => $membership->max_related
,
131 $session = CRM_Core_Session
::singleton();
132 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
133 if ($session->get('userID')) {
134 $membershipLog['modified_id'] = $session->get('userID');
136 elseif (!empty($ids['userId'])) {
137 $membershipLog['modified_id'] = $ids['userId'];
140 $membershipLog['modified_id'] = $membership->contact_id
;
143 CRM_Member_BAO_MembershipLog
::add($membershipLog, CRM_Core_DAO
::$_nullArray);
145 // reset the group contact cache since smart groups might be affected due to this
146 CRM_Contact_BAO_GroupContactCache
::remove();
149 if ($membership->status_id
!= $oldStatus) {
150 $allStatus = CRM_Member_BAO_Membership
::buildOptions('status_id', 'get');
151 $activityParam = array(
152 'subject' => "Status changed from {$allStatus[$oldStatus]} to {$allStatus[$membership->status_id]}",
153 'source_contact_id' => $membershipLog['modified_id'],
154 'target_contact_id' => $membership->contact_id
,
155 'source_record_id' => $membership->id
,
156 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Change Membership Status'),
159 'activity_date_time' => date('Y-m-d H:i:s'),
161 civicrm_api3('activity', 'create', $activityParam);
163 if (isset($membership->membership_type_id
) && $membership->membership_type_id
!= $oldType) {
164 $membershipTypes = CRM_Member_BAO_Membership
::buildOptions('membership_type_id', 'get');
165 $activityParam = array(
166 'subject' => "Type changed from {$membershipTypes[$oldType]} to {$membershipTypes[$membership->membership_type_id]}",
167 'source_contact_id' => $membershipLog['modified_id'],
168 'target_contact_id' => $membership->contact_id
,
169 'source_record_id' => $membership->id
,
170 'activity_type_id' => CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Change Membership Type'),
173 'activity_date_time' => date('Y-m-d H:i:s'),
175 civicrm_api3('activity', 'create', $activityParam);
177 CRM_Utils_Hook
::post('edit', 'Membership', $membership->id
, $membership);
180 CRM_Utils_Hook
::post('create', 'Membership', $membership->id
, $membership);
187 * Given the list of params in the params array, fetch the object
188 * and store the values in the values array
190 * @param array $params
191 * Input parameters to find object.
192 * @param array $values
193 * Output values of the object.
194 * @param bool $active
195 * Do you want only active memberships to.
198 * @return CRM_Member_BAO_Membership|null the found object or null
200 public static function &getValues(&$params, &$values, $active = FALSE) {
201 if (empty($params)) {
204 $membership = new CRM_Member_BAO_Membership();
206 $membership->copyValues($params);
208 $memberships = array();
209 while ($membership->fetch()) {
211 (!CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
212 $membership->status_id
,
219 CRM_Core_DAO
::storeValues($membership, $values[$membership->id
]);
220 $memberships[$membership->id
] = $membership;
227 * Takes an associative array and creates a membership object.
229 * @param array $params
230 * (reference ) an assoc array of name/value pairs.
232 * The array that holds all the db ids.
233 * @param bool $skipRedirect
234 * @param string $activityType
236 * @throws CRM_Core_Exception
238 * @return CRM_Member_BAO_Membership|CRM_Core_Error
240 public static function create(&$params, &$ids, $skipRedirect = FALSE, $activityType = 'Membership Signup') {
241 // always calculate status if is_override/skipStatusCal is not true.
242 // giving respect to is_override during import. CRM-4012
244 // To skip status calculation we should use 'skipStatusCal'.
245 // eg pay later membership, membership update cron CRM-3984
247 if (empty($params['is_override']) && empty($params['skipStatusCal'])) {
248 $dates = array('start_date', 'end_date', 'join_date');
249 $start_date = $end_date = $join_date = NULL; // declare these out of courtesy as IDEs don't pick up the setting of them below
250 foreach ($dates as $date) {
251 $
$date = $params[$date] = CRM_Utils_Date
::processDate(CRM_Utils_Array
::value($date, $params), NULL, TRUE, 'Ymd');
254 //fix for CRM-3570, during import exclude the statuses those having is_admin = 1
255 $excludeIsAdmin = CRM_Utils_Array
::value('exclude_is_admin', $params, FALSE);
257 //CRM-3724 always skip is_admin if is_override != true.
258 if (!$excludeIsAdmin && empty($params['is_override'])) {
259 $excludeIsAdmin = TRUE;
262 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($start_date, $end_date, $join_date,
263 'today', $excludeIsAdmin, CRM_Utils_Array
::value('membership_type_id', $params), $params
265 if (empty($calcStatus)) {
266 // Redirect the form in case of error
267 // @todo this redirect in the BAO layer is really bad & should be moved to the form layer
268 // however since we have no idea how (if) this is triggered we can't safely move / remove it
269 // NB I tried really hard to trigger this error from backoffice membership form in order to test it
270 // and am convinced form validation is complete on that form WRT this error.
271 $errorParams = array(
272 'message_title' => ts('No valid membership status for given dates.'),
273 'legacy_redirect_path' => 'civicrm/contact/view',
274 'legacy_redirect_query' => "reset=1&force=1&cid={$params['contact_id']}&selectedChild=member",
276 throw new CRM_Core_Exception(ts('The membership cannot be saved because the status cannot be calculated.'), 0, $errorParams);
278 $params['status_id'] = $calcStatus['id'];
281 // data cleanup only: all verifications on number of related memberships are done upstream in:
282 // CRM_Member_BAO_Membership::createRelatedMemberships()
283 // CRM_Contact_BAO_Relationship::relatedMemberships()
284 if (isset($params['owner_membership_id'])) {
285 unset($params['max_related']);
288 // if membership allows related, default max_related to value in membership_type
289 if (!array_key_exists('max_related', $params) && !empty($params['membership_type_id'])) {
290 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($params['membership_type_id']);
291 if (isset($membershipType['relationship_type_id'])) {
292 $params['max_related'] = CRM_Utils_Array
::value('max_related', $membershipType);
297 $transaction = new CRM_Core_Transaction();
299 $membership = self
::add($params, $ids);
301 if (is_a($membership, 'CRM_Core_Error')) {
302 $transaction->rollback();
306 // add custom field values
307 if (!empty($params['custom']) && is_array($params['custom'])
309 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_membership', $membership->id
);
312 $params['membership_id'] = $membership->id
;
313 if (isset($ids['membership'])) {
314 $ids['contribution'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipPayment',
321 $params['skipLineItem'] = TRUE;
323 //record contribution for this membership
324 if (!empty($params['contribution_status_id']) && empty($params['relate_contribution_id'])) {
325 $memInfo = array_merge($params, array('membership_id' => $membership->id
));
326 $params['contribution'] = self
::recordMembershipContribution($memInfo, $ids);
329 if (!empty($params['lineItems'])) {
330 $params['line_item'] = $params['lineItems'];
333 //do cleanup line items if membership edit the Membership type.
334 if (empty($ids['contribution']) && !empty($ids['membership'])) {
335 CRM_Price_BAO_LineItem
::deleteLineItems($ids['membership'], 'civicrm_membership');
338 if (!empty($params['line_item']) && empty($ids['contribution'])) {
339 CRM_Price_BAO_LineItem
::processPriceSet($membership->id
, $params['line_item'], CRM_Utils_Array
::value('contribution', $params));
342 //insert payment record for this membership
343 if (!empty($params['relate_contribution_id'])) {
344 CRM_Member_BAO_MembershipPayment
::create(array(
345 'membership_id' => $membership->id
,
346 'contribution_id' => $params['relate_contribution_id'],
350 // add activity record only during create mode and renew mode
351 // also add activity if status changed CRM-3984 and CRM-2521
352 if (empty($ids['membership']) ||
353 $activityType == 'Membership Renewal' ||
!empty($params['createActivity'])
355 if (!empty($ids['membership'])) {
357 CRM_Core_DAO
::commonRetrieveAll('CRM_Member_DAO_Membership',
361 array('contact_id', 'membership_type_id', 'source')
364 $membership->contact_id
= $data[$membership->id
]['contact_id'];
365 $membership->membership_type_id
= $data[$membership->id
]['membership_type_id'];
366 $membership->source
= CRM_Utils_Array
::value('source', $data[$membership->id
]);
369 // since we are going to create activity record w/
370 // individual contact as a target in case of on behalf signup,
371 // so get the copy of organization id, CRM-5551
372 $realMembershipContactId = $membership->contact_id
;
374 // create activity source = individual, target = org CRM-4027
375 $targetContactID = NULL;
376 if (!empty($params['is_for_organization'])) {
377 $targetContactID = $membership->contact_id
;
378 $membership->contact_id
= CRM_Utils_Array
::value('userId', $ids);
381 if (empty($membership->contact_id
) && (!empty($membership->owner_membership_id
))) {
382 $membership->contact_id
= $realMembershipContactId;
385 if (!empty($ids['membership']) && $activityType != 'Membership Signup') {
386 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $targetContactID);
388 elseif (empty($ids['membership'])) {
389 CRM_Activity_BAO_Activity
::addActivity($membership, $activityType, $targetContactID);
392 // we might created activity record w/ individual
393 // contact as target so update membership object w/
394 // original organization id, CRM-5551
395 $membership->contact_id
= $realMembershipContactId;
398 $transaction->commit();
400 self
::createRelatedMemberships($params, $membership);
402 // do not add to recent items for import, CRM-4399
403 if (empty($params['skipRecentView'])) {
404 $url = CRM_Utils_System
::url('civicrm/contact/view/membership',
405 "action=view&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
407 if (empty($membership->membership_type_id
)) {// ie in an update situation
408 $membership->find(TRUE);
410 $membershipTypes = CRM_Member_PseudoConstant
::membershipType();
411 $title = CRM_Contact_BAO_Contact
::displayName($membership->contact_id
) . ' - ' . ts('Membership Type:') . ' ' . $membershipTypes[$membership->membership_type_id
];
413 $recentOther = array();
414 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::UPDATE
)) {
415 $recentOther['editUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
416 "action=update&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
419 if (CRM_Core_Permission
::checkActionPermission('CiviMember', CRM_Core_Action
::DELETE
)) {
420 $recentOther['deleteUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
421 "action=delete&reset=1&id={$membership->id}&cid={$membership->contact_id}&context=home"
425 // add the recently created Membership
426 CRM_Utils_Recent
::add($title,
430 $membership->contact_id
,
440 * Check the membership extended through relationship.
442 * @param int $membershipId
444 * @param int $contactId
450 * array of contact_id of all related contacts.
452 public static function checkMembershipRelationship($membershipId, $contactId, $action = CRM_Core_Action
::ADD
) {
454 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $membershipId, 'membership_type_id');
456 $membershipType = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipTypeID);
457 $relationships = array();
458 if (isset($membershipType['relationship_type_id'])) {
459 $relationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
460 CRM_Contact_BAO_Relationship
::CURRENT
462 if ($action & CRM_Core_Action
::UPDATE
) {
463 $pastRelationships = CRM_Contact_BAO_Relationship
::getRelationship($contactId,
464 CRM_Contact_BAO_Relationship
::PAST
466 $relationships = array_merge($relationships, $pastRelationships);
470 if (!empty($relationships)) {
471 // check for each contact relationships
472 foreach ($relationships as $values) {
473 //get details of the relationship type
474 $relType = array('id' => $values['civicrm_relationship_type_id']);
475 $relValues = array();
476 CRM_Contact_BAO_RelationshipType
::retrieve($relType, $relValues);
477 // Check if contact's relationship type exists in membership type
478 $relTypeDirs = array();
479 $relTypeIds = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_type_id']);
480 $relDirections = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $membershipType['relationship_direction']);
481 $bidirectional = FALSE;
482 foreach ($relTypeIds as $key => $value) {
483 $relTypeDirs[] = $value . '_' . $relDirections[$key];
484 if (in_array($value, $relType) &&
485 $relValues['name_a_b'] == $relValues['name_b_a']
487 $bidirectional = TRUE;
491 $relTypeDir = $values['civicrm_relationship_type_id'] . '_' . $values['rtype'];
492 if ($bidirectional ||
in_array($relTypeDir, $relTypeDirs)) {
493 // $values['status'] is going to have value for
494 // current or past relationships.
495 $contacts[$values['cid']] = $values['status'];
500 // Sort by contact_id ascending
506 * Retrieve DB object based on input parameters.
508 * It also stores all the retrieved values in the default array.
510 * @param array $params
511 * (reference ) an assoc array of name/value pairs.
512 * @param array $defaults
513 * (reference ) an assoc array to hold the name / value pairs.
514 * in a hierarchical manner
516 * @return CRM_Member_BAO_Membership
518 public static function retrieve(&$params, &$defaults) {
519 $membership = new CRM_Member_DAO_Membership();
521 $membership->copyValues($params);
523 if ($membership->find(TRUE)) {
524 CRM_Core_DAO
::storeValues($membership, $defaults);
526 //get the membership status and type values.
527 $statusANDType = self
::getStatusANDTypeValues($membership->id
);
532 $defaults[$fld] = CRM_Utils_Array
::value($fld, $statusANDType[$membership->id
]);
534 if (!empty($statusANDType[$membership->id
]['is_current_member'])) {
535 $defaults['active'] = TRUE;
548 * get membership status and membership type values
550 * @param int $membershipId
551 * Membership id of values to return.
554 * Array of key value pairs
556 public static function getStatusANDTypeValues($membershipId) {
558 if (!$membershipId) {
562 SELECT membership.id as id,
563 status.id as status_id,
564 status.label as status,
565 status.is_current_member as is_current_member,
566 type.id as membership_type_id,
567 type.name as membership_type,
568 type.relationship_type_id as relationship_type_id
569 FROM civicrm_membership membership
570 INNER JOIN civicrm_membership_status status ON ( status.id = membership.status_id )
571 INNER JOIN civicrm_membership_type type ON ( type.id = membership.membership_type_id )
572 WHERE membership.id = %1';
573 $dao = CRM_Core_DAO
::executeQuery($sql, array(1 => array($membershipId, 'Positive')));
578 'membership_type_id',
580 'relationship_type_id',
582 while ($dao->fetch()) {
583 foreach ($properties as $property) {
584 $values[$dao->id
][$property] = $dao->$property;
593 * Wrapper for most delete calls. Use this unless you JUST want to delete related memberships w/o deleting the parent.
595 * @param int $membershipId
596 * Membership id that needs to be deleted.
599 * @return int $results id of deleted Membership on success, false otherwise
601 public static function del($membershipId) {
602 //delete related first and then delete parent.
603 self
::deleteRelatedMemberships($membershipId);
604 return self
::deleteMembership($membershipId);
610 * @param int $membershipId
611 * Membership id that needs to be deleted.
614 * @return int $results id of deleted Membership on success, false otherwise
616 public static function deleteMembership($membershipId) {
617 // CRM-12147, retrieve membership data before we delete it for hooks
618 $params = array('id' => $membershipId);
619 $memValues = array();
620 $memberships = self
::getValues($params, $memValues);
622 $membership = $memberships[$membershipId];
624 CRM_Utils_Hook
::pre('delete', 'Membership', $membershipId, $memValues);
626 $transaction = new CRM_Core_Transaction();
629 //delete activity record
630 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
633 $deleteActivity = FALSE;
634 $membershipActivities = array(
636 'Membership Renewal',
637 'Change Membership Status',
638 'Change Membership Type',
639 'Membership Renewal Reminder',
641 foreach ($membershipActivities as $membershipActivity) {
642 $activityId = array_search($membershipActivity, $activityTypes);
644 $params['activity_type_id'][] = $activityId;
645 $deleteActivity = TRUE;
648 if ($deleteActivity) {
649 $params['source_record_id'] = $membershipId;
650 CRM_Activity_BAO_Activity
::deleteActivity($params);
652 self
::deleteMembershipPayment($membershipId);
654 $results = $membership->delete();
655 $transaction->commit();
657 CRM_Utils_Hook
::post('delete', 'Membership', $membership->id
, $membership);
659 // delete the recently created Membership
660 $membershipRecent = array(
661 'id' => $membershipId,
662 'type' => 'Membership',
664 CRM_Utils_Recent
::del($membershipRecent);
670 * Delete related memberships.
672 * @param int $ownerMembershipId
673 * @param int $contactId
677 public static function deleteRelatedMemberships($ownerMembershipId, $contactId = NULL) {
678 if (!$ownerMembershipId && !$contactId) {
682 $membership = new CRM_Member_DAO_Membership();
683 $membership->owner_membership_id
= $ownerMembershipId;
686 $membership->contact_id
= $contactId;
690 while ($membership->fetch()) {
691 //delete related first and then delete parent.
692 self
::deleteRelatedMemberships($membership->id
);
693 self
::deleteMembership($membership->id
);
699 * Obtain active/inactive memberships from the list of memberships passed to it.
701 * @param array $memberships
702 * Membership records.
703 * @param string $status
704 * Active or inactive.
707 * array of memberships based on status
709 public static function activeMembers($memberships, $status = 'active') {
711 if ($status == 'active') {
712 foreach ($memberships as $f => $v) {
713 if (!empty($v['active'])) {
719 elseif ($status == 'inactive') {
720 foreach ($memberships as $f => $v) {
721 if (empty($v['active'])) {
731 * Build Membership Block in Contribution Pages.
733 * @param CRM_Core_Form $form
738 * Contact checked for having a current membership for a particular membership.
739 * @param bool $formItems
740 * @param int $selectedMembershipTypeID
741 * Selected membership id.
742 * @param bool $thankPage
744 * @param null $isTest
747 * Is this a separate membership payment
750 public static function buildMembershipBlock(
755 $selectedMembershipTypeID = NULL,
760 $separateMembershipPayment = FALSE;
761 if ($form->_membershipBlock
) {
762 $form->_currentMemberships
= array();
764 $membershipBlock = $form->_membershipBlock
;
765 $membershipTypeIds = $membershipTypes = $radio = array();
766 $membershipPriceset = (!empty($form->_priceSetId
) && $form->_useForMember
) ?
TRUE : FALSE;
768 $allowAutoRenewMembership = $autoRenewOption = FALSE;
769 $autoRenewMembershipTypeOptions = array();
771 $paymentProcessor = CRM_Core_PseudoConstant
::paymentProcessor(FALSE, FALSE, 'is_recur = 1');
773 $separateMembershipPayment = CRM_Utils_Array
::value('is_separate_payment', $membershipBlock);
775 if ($membershipPriceset) {
776 foreach ($form->_priceSet
['fields'] as $pField) {
777 if (empty($pField['options'])) {
780 foreach ($pField['options'] as $opId => $opValues) {
781 if (empty($opValues['membership_type_id'])) {
784 $membershipTypeIds[$opValues['membership_type_id']] = $opValues['membership_type_id'];
788 elseif (!empty($membershipBlock['membership_types'])) {
789 $membershipTypeIds = explode(',', $membershipBlock['membership_types']);
792 if (!empty($membershipTypeIds)) {
793 //set status message if wrong membershipType is included in membershipBlock
794 if (isset($form->_mid
) && !$membershipPriceset) {
795 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
799 if (!in_array($membershipTypeID, $membershipTypeIds)) {
800 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');
804 $membershipTypeValues = self
::buildMembershipTypeValues($form, $membershipTypeIds);
805 $form->_membershipTypeValues
= $membershipTypeValues;
807 foreach ($membershipTypeIds as $value) {
808 $memType = $membershipTypeValues[$value];
809 if ($selectedMembershipTypeID != NULL) {
810 if ($memType['id'] == $selectedMembershipTypeID) {
811 $form->assign('minimum_fee',
812 CRM_Utils_Array
::value('minimum_fee', $memType)
814 $form->assign('membership_name', $memType['name']);
815 if (!$thankPage && $cid) {
816 $membership = new CRM_Member_DAO_Membership();
817 $membership->contact_id
= $cid;
818 $membership->membership_type_id
= $memType['id'];
819 if ($membership->find(TRUE)) {
820 $form->assign('renewal_mode', TRUE);
821 $memType['current_membership'] = $membership->end_date
;
822 $form->_currentMemberships
[$membership->membership_type_id
] = $membership->membership_type_id
;
825 $membershipTypes[] = $memType;
828 elseif ($memType['is_active']) {
829 $javascriptMethod = NULL;
830 $allowAutoRenewOpt = 1;
831 if (is_array($form->_paymentProcessors
)) {
832 foreach ($form->_paymentProcessors
as $id => $val) {
833 if (!$val['is_recur']) {
834 $allowAutoRenewOpt = 0;
840 $javascriptMethod = array('onclick' => "return showHideAutoRenew( this.value );");
841 $autoRenewMembershipTypeOptions["autoRenewMembershipType_{$value}"] = (int) $allowAutoRenewOpt * CRM_Utils_Array
::value($value, CRM_Utils_Array
::value('auto_renew', $form->_membershipBlock
));;
843 if ($allowAutoRenewOpt) {
844 $allowAutoRenewMembership = TRUE;
847 //add membership type.
848 $radio[$memType['id']] = $form->createElement('radio', NULL, NULL, NULL,
849 $memType['id'], $javascriptMethod
852 $membership = new CRM_Member_DAO_Membership();
853 $membership->contact_id
= $cid;
854 $membership->membership_type_id
= $memType['id'];
856 //show current membership, skip pending and cancelled membership records,
857 //because we take first membership record id for renewal
858 $membership->whereAdd('status_id != 5 AND status_id !=6');
860 if (!is_null($isTest)) {
861 $membership->is_test
= $isTest;
865 $membership->orderBy('end_date DESC');
867 if ($membership->find(TRUE)) {
868 if (!$membership->end_date
) {
869 unset($radio[$memType['id']]);
870 $form->assign('islifetime', TRUE);
873 $form->assign('renewal_mode', TRUE);
874 $form->_currentMemberships
[$membership->membership_type_id
] = $membership->membership_type_id
;
875 $memType['current_membership'] = $membership->end_date
;
877 $endDate = $memType['current_membership'];
878 $form->_defaultMemTypeId
= $memType['id'];
880 if ($memType['current_membership'] < $endDate) {
881 $endDate = $memType['current_membership'];
882 $form->_defaultMemTypeId
= $memType['id'];
886 $membershipTypes[] = $memType;
891 $form->assign('showRadio', $formItems);
893 if (!$membershipPriceset) {
894 if (!$membershipBlock['is_required']) {
895 $form->assign('showRadioNoThanks', TRUE);
896 $radio[''] = $form->createElement('radio', NULL, NULL, NULL, 'no_thanks', NULL);
897 $form->addGroup($radio, 'selectMembership', NULL);
899 elseif ($membershipBlock['is_required'] && count($radio) == 1) {
900 $temp = array_keys($radio);
901 $form->add('hidden', 'selectMembership', $temp[0], array('id' => 'selectMembership'));
902 $form->assign('singleMembership', TRUE);
903 $form->assign('showRadio', FALSE);
906 $form->addGroup($radio, 'selectMembership', NULL);
909 $form->addRule('selectMembership', ts('Please select one of the memberships.'), 'required');
912 $autoRenewOption = CRM_Price_BAO_PriceSet
::checkAutoRenewForPriceSet($form->_priceSetId
);
913 $form->assign('autoRenewOption', $autoRenewOption);
916 if (!$form->_values
['is_pay_later'] && is_array($form->_paymentProcessors
) && ($allowAutoRenewMembership ||
$autoRenewOption)) {
917 $form->addElement('checkbox', 'auto_renew', ts('Please renew my membership automatically.'));
922 $form->assign('membershipBlock', $membershipBlock);
923 $form->assign('membershipTypes', $membershipTypes);
924 $form->assign('allowAutoRenewMembership', $allowAutoRenewMembership);
925 $form->assign('autoRenewMembershipTypeOptions', json_encode($autoRenewMembershipTypeOptions));
927 //give preference to user submitted auto_renew value.
928 $takeUserSubmittedAutoRenew = (!empty($_POST) ||
$form->isSubmitted()) ?
TRUE : FALSE;
929 $form->assign('takeUserSubmittedAutoRenew', $takeUserSubmittedAutoRenew);
932 return $separateMembershipPayment;
936 * Return Membership Block info in Contribution Pages.
939 * Contribution page id.
944 public static function getMembershipBlock($pageID) {
945 $membershipBlock = array();
946 $dao = new CRM_Member_DAO_MembershipBlock();
947 $dao->entity_table
= 'civicrm_contribution_page';
949 $dao->entity_id
= $pageID;
951 if ($dao->find(TRUE)) {
952 CRM_Core_DAO
::storeValues($dao, $membershipBlock);
953 if (!empty($membershipBlock['membership_types'])) {
954 $membershipTypes = unserialize($membershipBlock['membership_types']);
955 if (!is_array($membershipTypes)) {
956 return $membershipBlock;
959 foreach ($membershipTypes as $key => $value) {
960 $membershipBlock['auto_renew'][$key] = $value;
961 $memTypes[$key] = $key;
963 $membershipBlock['membership_types'] = implode(',', $memTypes);
970 return $membershipBlock;
974 * Return a current membership of given contact.
975 * NB: if more than one membership meets criteria, a randomly selected one is returned.
977 * @param int $contactID
979 * @param int $memType
980 * Membership type, null to retrieve all types.
982 * @param int $membershipId
983 * If provided, then determine if it is current.
984 * @param bool $onlySameParentOrg
985 * True if only Memberships with same parent org as the $memType wanted, false otherwise.
989 public static function getContactMembership($contactID, $memType, $isTest, $membershipId = NULL, $onlySameParentOrg = FALSE) {
990 $dao = new CRM_Member_DAO_Membership();
992 $dao->id
= $membershipId;
994 $dao->contact_id
= $contactID;
995 $dao->membership_type_id
= $memType;
997 //fetch proper membership record.
999 $dao->is_test
= $isTest;
1002 $dao->whereAdd('is_test IS NULL OR is_test = 0');
1005 //avoid pending membership as current membership: CRM-3027
1006 $statusIds[] = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
1007 if (!$membershipId) {
1009 $statusIds[] = array_search(
1011 CRM_Member_PseudoConstant
::membershipStatus(
1013 " name = 'Cancelled' ",
1020 $dao->whereAdd('status_id NOT IN ( ' . implode(',', $statusIds) . ')');
1022 // order by start date to find most recent membership first, CRM-4545
1023 $dao->orderBy('start_date DESC');
1026 if ($onlySameParentOrg && $memType) {
1027 // require the same parent org as the $memType
1028 $params = array('id' => $memType);
1029 $membershipType = array();
1030 if (CRM_Member_BAO_MembershipType
::retrieve($params, $membershipType)) {
1031 $memberTypesSameParentOrg = CRM_Member_BAO_MembershipType
::getMembershipTypesByOrg($membershipType['member_of_contact_id']);
1032 $memberTypesSameParentOrgList = implode(',', array_keys($memberTypesSameParentOrg));
1033 $dao->whereAdd('membership_type_id IN (' . $memberTypesSameParentOrgList . ')');
1037 if ($dao->find(TRUE)) {
1038 $membership = array();
1039 CRM_Core_DAO
::storeValues($dao, $membership);
1040 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
1041 $membership['status_id'],
1042 'is_current_member', 'id'
1048 if ($onlySameParentOrg && $memType) {
1049 // see if there is a membership that has same parent as $memType but different parent than $membershipID
1050 if ($dao->id
&& CRM_Core_Permission
::check('edit memberships')) {
1051 // CRM-10016, This is probably a backend renewal, and make sure we return the same membership thats being renewed.
1058 unset($dao->membership_type_id
);
1059 if ($dao->find(TRUE)) {
1060 $membership = array();
1061 CRM_Core_DAO
::storeValues($dao, $membership);
1062 $membership['is_current_member'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
1063 $membership['status_id'],
1064 'is_current_member', 'id'
1073 * Combine all the importable fields from the lower levels object.
1075 * @param string $contactType
1077 * @param bool $status
1080 * array of importable Fields
1082 public static function &importableFields($contactType = 'Individual', $status = TRUE) {
1083 if (!self
::$_importableFields) {
1084 if (!self
::$_importableFields) {
1085 self
::$_importableFields = array();
1089 $fields = array('' => array('title' => '- ' . ts('do not import') . ' -'));
1092 $fields = array('' => array('title' => '- ' . ts('Membership Fields') . ' -'));
1095 $tmpFields = CRM_Member_DAO_Membership
::import();
1096 $contactFields = CRM_Contact_BAO_Contact
::importableFields($contactType, NULL);
1098 // Using new Dedupe rule.
1099 $ruleParams = array(
1100 'contact_type' => $contactType,
1101 'used' => 'Unsupervised',
1103 $fieldsArray = CRM_Dedupe_BAO_Rule
::dedupeRuleFields($ruleParams);
1105 $tmpContactField = array();
1106 if (is_array($fieldsArray)) {
1107 foreach ($fieldsArray as $value) {
1108 $customFieldId = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_CustomField',
1113 $value = $customFieldId ?
'custom_' . $customFieldId : $value;
1114 $tmpContactField[trim($value)] = CRM_Utils_Array
::value(trim($value), $contactFields);
1116 $title = $tmpContactField[trim($value)]['title'] . " " . ts('(match to contact)');
1119 $title = $tmpContactField[trim($value)]['title'];
1121 $tmpContactField[trim($value)]['title'] = $title;
1124 $tmpContactField['external_identifier'] = $contactFields['external_identifier'];
1125 $tmpContactField['external_identifier']['title'] = $contactFields['external_identifier']['title'] . " " . ts('(match to contact)');
1127 $tmpFields['membership_contact_id']['title'] = $tmpFields['membership_contact_id']['title'] . " " . ts('(match to contact)');;
1129 $fields = array_merge($fields, $tmpContactField);
1130 $fields = array_merge($fields, $tmpFields);
1131 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1132 self
::$_importableFields = $fields;
1134 return self
::$_importableFields;
1138 * Get all exportable fields.
1140 * @retun array return array of all exportable fields
1142 public static function &exportableFields() {
1143 $expFieldMembership = CRM_Member_DAO_Membership
::export();
1145 $expFieldsMemType = CRM_Member_DAO_MembershipType
::export();
1146 $fields = array_merge($expFieldMembership, $expFieldsMemType);
1147 $fields = array_merge($fields, $expFieldMembership);
1148 $membershipStatus = array(
1149 'membership_status' => array(
1150 'title' => 'Membership Status',
1151 'name' => 'membership_status',
1152 'type' => CRM_Utils_Type
::T_STRING
,
1153 'where' => 'civicrm_membership_status.name',
1156 //CRM-6161 fix for customdata export
1157 $fields = array_merge($fields, $membershipStatus, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1162 * Get membership joins/renewals for a specified membership
1163 * type. Specifically, retrieves a count of memberships whose "Membership
1164 * Signup" or "Membership Renewal" activity falls in the given date range.
1165 * Dates match the pattern "yyyy-mm-dd".
1167 * @param int $membershipTypeId
1168 * Membership type id.
1169 * @param int $startDate
1170 * Date on which to start counting.
1171 * @param int $endDate
1172 * Date on which to end counting.
1173 * @param bool|int $isTest if true, membership is for a test site
1174 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1177 * the number of members of type $membershipTypeId whose
1178 * start_date is between $startDate and $endDate
1180 public static function getMembershipStarts($membershipTypeId, $startDate, $endDate, $isTest = 0, $isOwner = 0) {
1182 $testClause = 'membership.is_test = 1';
1184 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
1187 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1188 self
::_getActTypes();
1191 if (!self
::$_signupActType ||
!self
::$_renewalActType) {
1196 SELECT COUNT(DISTINCT membership.id) as member_count
1197 FROM civicrm_membership membership
1198 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id in (%1, %2))
1199 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
1200 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
1201 WHERE membership.membership_type_id = %3
1202 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
1205 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1208 1 => array(self
::$_signupActType, 'Integer'),
1209 2 => array(self
::$_renewalActType, 'Integer'),
1210 3 => array($membershipTypeId, 'Integer'),
1213 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1214 return (int) $memberCount;
1218 * Get a count of membership for a specified membership type,
1219 * optionally for a specified date. The date must have the form yyyy-mm-dd.
1221 * If $date is omitted, this function counts as a member anyone whose
1222 * membership status_id indicates they're a current member.
1223 * If $date is given, this function counts as a member anyone who:
1224 * -- Has a start_date before $date and end_date after $date, or
1225 * -- Has a start_date before $date and is currently a member, as indicated
1226 * by the the membership's status_id.
1227 * The second condition takes care of records that have no end_date. These
1228 * are assumed to be lifetime memberships.
1230 * @param int $membershipTypeId
1231 * Membership type id.
1232 * @param string $date
1233 * The date for which to retrieve the count.
1234 * @param bool|int $isTest if true, membership is for a test site
1235 * @param bool|int $isOwner if true, only retrieve membership records for owners //LCD
1238 * the number of members of type $membershipTypeId as of $date.
1240 public static function getMembershipCount($membershipTypeId, $date = NULL, $isTest = 0, $isOwner = 0) {
1241 if (!CRM_Utils_Rule
::date($date)) {
1242 CRM_Core_Error
::fatal(ts('Invalid date "%1" (must have form yyyy-mm-dd).', array(1 => $date)));
1246 1 => array($membershipTypeId, 'Integer'),
1247 2 => array($isTest, 'Boolean'),
1249 $query = "SELECT count(civicrm_membership.id ) as member_count
1250 FROM civicrm_membership left join civicrm_membership_status on ( civicrm_membership.status_id = civicrm_membership_status.id )
1251 WHERE civicrm_membership.membership_type_id = %1
1252 AND civicrm_membership.contact_id NOT IN (SELECT id FROM civicrm_contact WHERE is_deleted = 1)
1253 AND civicrm_membership.is_test = %2";
1255 $query .= " AND civicrm_membership_status.is_current_member = 1";
1258 $query .= " AND civicrm_membership.start_date <= '$date' AND civicrm_membership_status.is_current_member = 1";
1261 $query .= ($isOwner) ?
' AND owner_membership_id IS NULL' : '';
1262 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
1263 return (int) $memberCount;
1267 * Function check the status of the membership before adding membership for a contact.
1269 * @param int $contactId
1274 public static function statusAvailabilty($contactId) {
1275 $membership = new CRM_Member_DAO_MembershipStatus();
1276 $membership->whereAdd('is_active=1');
1277 return $membership->count();
1281 * Process the Memberships.
1283 * @param array $membershipParams
1284 * Array of membership fields.
1285 * @param int $contactID
1287 * @param CRM_Contribute_Form_Contribution_Confirm $form
1288 * Confirmation form object.
1290 * @param array $premiumParams
1291 * @param null $customFieldsFormatted
1292 * @param null $includeFieldTypes
1294 * @param array $membershipDetails
1296 * @param array $membershipTypeIDs
1298 * @param bool $isPaidMembership
1299 * @param array $membershipID
1301 * @param $isProcessSeparateMembershipTransaction
1303 * @param int $defaultContributionTypeID
1304 * @param array $membershipLineItems
1305 * Line items specific to membership payment that is separate to contribution.
1306 * @throws CRM_Core_Exception
1310 public static function postProcessMembership(
1311 $membershipParams, $contactID, &$form, $premiumParams,
1312 $customFieldsFormatted = NULL, $includeFieldTypes = NULL, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID,
1313 $isProcessSeparateMembershipTransaction, $defaultContributionTypeID, $membershipLineItems, $isPayLater) {
1314 $result = $membershipContribution = NULL;
1315 $isTest = CRM_Utils_Array
::value('is_test', $membershipParams, FALSE);
1316 $errors = $createdMemberships = array();
1318 //@todo move this into the calling function & pass in the correct financialTypeID
1319 if (isset($paymentParams['financial_type'])) {
1320 $financialTypeID = $paymentParams['financial_type'];
1323 $financialTypeID = $defaultContributionTypeID;
1326 if (CRM_Utils_Array
::value('membership_source', $form->_params
)) {
1327 $membershipParams['contribution_source'] = $form->_params
['membership_source'];
1330 if ($isPaidMembership) {
1331 $result = CRM_Contribute_BAO_Contribution_Utils
::processConfirm($form, $membershipParams,
1332 $premiumParams, $contactID,
1339 if (is_a($result[1], 'CRM_Core_Error')) {
1340 $errors[1] = CRM_Core_Error
::getMessages($result[1]);
1342 elseif (!empty($result[1])) {
1343 // Save the contribution ID so that I can be used in email receipts
1344 // For example, if you need to generate a tax receipt for the donation only.
1345 $form->_values
['contribution_other_id'] = $result[1]->id
;
1346 //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
1347 $membershipContribution = $result[1];
1351 if ($isProcessSeparateMembershipTransaction) {
1353 $lineItems = $form->_lineItem
= $membershipLineItems;
1354 $membershipContribution = self
::processSecondaryFinancialTransaction($contactID, $form, $membershipParams, $isTest, $membershipLineItems, CRM_Utils_Array
::value('minimum_fee', $membershipDetails, 0), CRM_Utils_Array
::value('financial_type_id', $membershipDetails));
1356 catch (CRM_Core_Exception
$e) {
1357 $errors[2] = $e->getMessage();
1358 $membershipContribution = NULL;
1363 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1364 $membershipContributionID = $membershipContribution->id
;
1367 //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
1368 if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
1369 $form->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
1371 //@todo it should no longer be possible for it to get to this point & membership to not be an array
1372 if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
1373 $typesTerms = CRM_Utils_Array
::value('types_terms', $membershipParams, array());
1374 foreach ($membershipTypeIDs as $memType) {
1375 $numTerms = CRM_Utils_Array
::value($memType, $typesTerms, 1);
1376 $createdMemberships[$memType] = self
::createOrRenewMembership($membershipParams, $contactID, $customFieldsFormatted, $membershipID, $memType, $isTest, $numTerms, $membershipContribution, $form);
1378 if ($form->_priceSetId
&& !empty($form->_useForMember
) && !empty($form->_lineItem
)) {
1379 foreach ($form->_lineItem
[$form->_priceSetId
] as & $priceFieldOp) {
1380 if (!empty($priceFieldOp['membership_type_id']) &&
1381 isset($createdMemberships[$priceFieldOp['membership_type_id']])
1383 $membershipOb = $createdMemberships[$priceFieldOp['membership_type_id']];
1384 $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date
::customFormat($membershipOb->start_date
, '%B %E%f, %Y') : '-';
1385 $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date
::customFormat($membershipOb->end_date
, '%B %E%f, %Y') : '-';
1388 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1391 $form->_values
['lineItem'] = $form->_lineItem
;
1392 $form->assign('lineItem', $form->_lineItem
);
1396 if (!empty($errors)) {
1397 $message = self
::compileErrorMessage($errors);
1398 throw new CRM_Core_Exception($message);
1400 $form->_params
['createdMembershipIDs'] = array();
1402 // CRM-7851 - Moved after processing Payment Errors
1403 //@todo - the reasoning for this being here seems a little outdated
1404 foreach ($createdMemberships as $createdMembership) {
1405 CRM_Core_BAO_CustomValueTable
::postProcess(
1407 CRM_Core_DAO
::$_nullArray,
1408 'civicrm_membership',
1409 $createdMembership->id
,
1412 $form->_params
['createdMembershipIDs'][] = $createdMembership->id
;
1414 if (count($createdMemberships) == 1) {
1415 //presumably this is only relevant for exactly 1 membership
1416 $form->_params
['membershipID'] = $createdMembership->id
;
1419 //CRM-15232: Check if membership is created and on the basis of it use
1420 //membership reciept template to send payment reciept
1421 if (count($createdMemberships)) {
1422 $form->_values
['isMembership'] = TRUE;
1424 if ($form->_contributeMode
== 'notify') {
1425 if ($form->_values
['is_monetary'] && $form->_amount
> 0.0 && !$form->_params
['is_pay_later']) {
1426 // call postProcess hook before leaving
1427 $form->postProcessHook();
1428 // this does not return
1429 $payment = CRM_Core_Payment
::singleton($form->_mode
, $form->_paymentProcessor
, $form);
1430 $payment->doTransferCheckout($form->_params
, 'contribute');
1434 if (isset($membershipContributionID)) {
1435 $form->_values
['contribution_id'] = $membershipContributionID;
1438 // Do not send an email if Recurring transaction is done via Direct Mode
1439 // Email will we sent when the IPN is received.
1440 if (!empty($form->_params
['is_recur']) && $form->_contributeMode
== 'direct') {
1441 if (!empty($membershipContribution->trxn_id
)) {
1443 civicrm_api3('contribution', 'completetransaction', array(
1444 'id' => $membershipContribution->id
,
1445 'trxn_id' => $membershipContribution->trxn_id
,
1448 catch (CiviCRM_API3_Exception
$e) {
1449 // if for any reason it is already completed this will fail - e.g extensions hacking around core not completing transactions prior to CRM-15296
1450 // so let's be gentle here
1451 CRM_Core_Error
::debug_log_message('contribution ' . $membershipContribution->id
. ' not completed with trxn_id ' . $membershipContribution->trxn_id
. ' and message ' . $e->getMessage());
1457 //finally send an email receipt
1458 CRM_Contribute_BAO_ContributionPage
::sendMail($contactID,
1466 * Function for updating a membership record's contribution_recur_id
1468 * @param CRM_Member_DAO_Membership $membership
1469 * @param \CRM_Contribute_BAO_Contribution|\CRM_Contribute_DAO_Contribution $contribution
1473 static public function updateRecurMembership(CRM_Member_DAO_Membership
$membership, CRM_Contribute_BAO_Contribution
$contribution) {
1475 if (empty($contribution->contribution_recur_id
)) {
1480 1 => array($contribution->contribution_recur_id
, 'Integer'),
1481 2 => array($membership->id
, 'Integer'),
1484 $sql = "UPDATE civicrm_membership SET contribution_recur_id = %1 WHERE id = %2";
1485 CRM_Core_DAO
::executeQuery($sql, $params);
1490 * A wrapper for renewing memberships from a form - including the form in the membership processing adds complexity
1491 * as the forms are being forced to pretend similarity
1492 * Try to call the renewMembership directly
1493 * @todo - this form method needs to have the interaction with the form layer removed from it
1494 * as a BAO function. Note that the api now supports membership renewals & it is not clear this function does anything
1495 * not done by the membership.create api (with a lot less unit tests)
1497 * This method will renew / create the membership depending on
1498 * whether the given contact has a membership or not. And will add
1499 * the modified dates for membership and in the log table.
1501 * @param int $contactID
1502 * Id of the contact.
1503 * @param int $membershipTypeID
1504 * Id of the new membership type.
1505 * @param bool $is_test
1506 * If this is test contribution or live contribution.
1507 * @param CRM_Core_Form $form
1509 * @param null $changeToday
1510 * @param int $modifiedID
1511 * Individual contact id in case of On Behalf signup (CRM-4027 ).
1512 * @param null $customFieldsFormatted
1513 * @param int $numRenewTerms
1514 * How many membership terms are being added to end date (default is 1).
1515 * @param int $membershipID
1516 * Membership ID, this should always be passed in & optionality should be removed.
1518 * @throws CRM_Core_Exception
1521 public static function renewMembershipFormWrapper(
1526 $changeToday = NULL,
1528 $customFieldsFormatted = NULL,
1530 $membershipID = NULL
1532 $statusFormat = '%Y-%m-%d';
1535 //@todo would be better to make $membershipID a compulsory function param & make form layer responsible for extracting it
1536 if (!$membershipID && isset($form->_membershipId
)) {
1537 $membershipID = $form->_membershipId
;
1540 //get all active statuses of membership.
1541 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
1543 $membershipTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($membershipTypeID);
1545 // check is it pending. - CRM-4555
1546 list($pending, $contributionRecurID, $changeToday, $membershipSource, $isPayLater, $campaignId) = self
::extractFormValues($form, $changeToday, $membershipTypeDetails);
1547 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);
1548 $form->set('renewal_mode', $renewalMode);
1549 if (!empty($dates)) {
1550 $form->assign('mem_start_date',
1551 CRM_Utils_Date
::customFormat($dates['start_date'], $format)
1553 $form->assign('mem_end_date',
1554 CRM_Utils_Date
::customFormat($dates['end_date'], $format)
1562 * Method to fix membership status of stale membership.
1564 * This method first checks if the membership is stale. If it is,
1565 * then status will be updated based on existing start and end
1566 * dates and log will be added for the status change.
1568 * @param array $currentMembership
1569 * Reference to the array.
1570 * containing all values of
1571 * the current membership
1572 * @param array $changeToday
1573 * Array of month, day, year.
1574 * values in case today needs
1575 * to be customised, null otherwise
1579 public static function fixMembershipStatusBeforeRenew(&$currentMembership, $changeToday) {
1582 $today = CRM_Utils_Date
::processDate($changeToday, NULL, FALSE, 'Y-m-d');
1585 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(
1586 CRM_Utils_Array
::value('start_date', $currentMembership),
1587 CRM_Utils_Array
::value('end_date', $currentMembership),
1588 CRM_Utils_Array
::value('join_date', $currentMembership),
1591 $currentMembership['membership_type_id'],
1595 if (empty($status) ||
1596 empty($status['id'])
1598 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.'));
1601 $currentMembership['today_date'] = $today;
1603 if ($status['id'] !== $currentMembership['status_id']) {
1604 $memberDAO = new CRM_Member_DAO_Membership();
1605 $memberDAO->id
= $currentMembership['id'];
1606 $memberDAO->find(TRUE);
1608 $memberDAO->status_id
= $status['id'];
1609 $memberDAO->join_date
= CRM_Utils_Date
::isoToMysql($memberDAO->join_date
);
1610 $memberDAO->start_date
= CRM_Utils_Date
::isoToMysql($memberDAO->start_date
);
1611 $memberDAO->end_date
= CRM_Utils_Date
::isoToMysql($memberDAO->end_date
);
1613 CRM_Core_DAO
::storeValues($memberDAO, $currentMembership);
1616 $currentMembership['is_current_member'] = CRM_Core_DAO
::getFieldValue(
1617 'CRM_Member_DAO_MembershipStatus',
1618 $currentMembership['status_id'],
1624 'membership_id' => $currentMembership['id'],
1625 'status_id' => $status['id'],
1626 'start_date' => CRM_Utils_Date
::customFormat(
1627 $currentMembership['start_date'],
1630 'end_date' => CRM_Utils_Date
::customFormat(
1631 $currentMembership['end_date'],
1634 'modified_date' => CRM_Utils_Date
::customFormat(
1635 $currentMembership['today_date'],
1638 'membership_type_id' => $currentMembership['membership_type_id'],
1639 'max_related' => $currentMembership['max_related'],
1642 $session = CRM_Core_Session
::singleton();
1643 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
1644 if ($session->get('userID')) {
1645 $logParams['modified_id'] = $session->get('userID');
1648 $logParams['modified_id'] = $currentMembership['contact_id'];
1650 CRM_Member_BAO_MembershipLog
::add($logParams, CRM_Core_DAO
::$_nullArray);
1655 * Get the contribution page id from the membership record.
1657 * @param int $membershipID
1660 * contribution page id
1662 public static function getContributionPageId($membershipID) {
1664 SELECT c.contribution_page_id as pageID
1665 FROM civicrm_membership_payment mp, civicrm_contribution c
1666 WHERE mp.contribution_id = c.id
1667 AND c.contribution_page_id IS NOT NULL
1668 AND mp.membership_id = " . CRM_Utils_Type
::escape($membershipID, 'Integer')
1669 . " ORDER BY mp.id DESC";
1671 return CRM_Core_DAO
::singleValueQuery($query,
1672 CRM_Core_DAO
::$_nullArray
1677 * Updated related memberships.
1679 * @param int $ownerMembershipId
1680 * Owner Membership Id.
1681 * @param array $params
1682 * Formatted array of key => value.
1684 public static function updateRelatedMemberships($ownerMembershipId, $params) {
1685 $membership = new CRM_Member_DAO_Membership();
1686 $membership->owner_membership_id
= $ownerMembershipId;
1687 $membership->find();
1689 while ($membership->fetch()) {
1690 $relatedMembership = new CRM_Member_DAO_Membership();
1691 $relatedMembership->id
= $membership->id
;
1692 $relatedMembership->copyValues($params);
1693 $relatedMembership->save();
1694 $relatedMembership->free();
1697 $membership->free();
1701 * Get list of membership fields for profile.
1702 * For now we only allow custom membership fields to be in
1706 * FIXME: This param is ignored
1709 * the list of membership fields
1711 public static function getMembershipFields($mode = NULL) {
1712 $fields = CRM_Member_DAO_Membership
::export();
1714 unset($fields['membership_contact_id']);
1715 $fields = array_merge($fields, CRM_Core_BAO_CustomField
::getFieldsForImport('Membership'));
1717 $membershipType = CRM_Member_DAO_MembershipType
::export();
1719 $membershipStatus = CRM_Member_DAO_MembershipStatus
::export();
1721 $fields = array_merge($fields, $membershipType, $membershipStatus);
1727 * Get the sort name of a contact for a particular membership.
1730 * Id of the membership.
1732 * @return null|string
1733 * sort name of the contact if found
1735 public static function sortName($id) {
1736 $id = CRM_Utils_Type
::escape($id, 'Integer');
1739 SELECT civicrm_contact.sort_name
1740 FROM civicrm_membership, civicrm_contact
1741 WHERE civicrm_membership.contact_id = civicrm_contact.id
1742 AND civicrm_membership.id = {$id}
1744 return CRM_Core_DAO
::singleValueQuery($query, CRM_Core_DAO
::$_nullArray);
1748 * Create memberships for related contacts.
1749 * takes into account the maximum related memberships
1751 * @param array $params
1752 * Array of key - value pairs.
1753 * @param CRM_Core_DAO $dao
1754 * Membership object.
1756 * @return null|array
1757 * array of memberships if created
1759 public static function createRelatedMemberships(&$params, &$dao, $reset = FALSE) {
1760 static $relatedContactIds = array();
1762 // not sure why a static var is in use here - we need a way to reset it from the test suite
1763 $relatedContactIds = array();
1767 $membership = new CRM_Member_DAO_Membership();
1768 $membership->id
= $dao->id
;
1770 // required since create method doesn't return all the
1771 // parameters in the returned membership object
1772 if (!$membership->find(TRUE)) {
1775 $deceasedStatusId = array_search('Deceased', CRM_Member_PseudoConstant
::membershipStatus());
1776 // FIXME : While updating/ renewing the
1777 // membership, if the relationship is PAST then
1778 // the membership of the related contact must be
1780 // For that, getting Membership Status for which
1781 // is_current_member is 0. It works for the
1782 // generated data as there is only one membership
1783 // status having is_current_member = 0.
1784 // But this wont work exactly if there will be
1785 // more than one status having is_current_member = 0.
1786 $membershipStatus = new CRM_Member_DAO_MembershipStatus();
1787 $membershipStatus->is_current_member
= 0;
1788 if ($membershipStatus->find(TRUE)) {
1789 $expiredStatusId = $membershipStatus->id
;
1792 $expiredStatusId = array_search('Expired', CRM_Member_PseudoConstant
::membershipStatus());
1795 $allRelatedContacts = array();
1796 $relatedContacts = array();
1797 if (!is_a($membership, 'CRM_Core_Error')) {
1798 $allRelatedContacts = CRM_Member_BAO_Membership
::checkMembershipRelationship($membership->id
,
1799 $membership->contact_id
,
1800 CRM_Utils_Array
::value('action', $params)
1804 // check for loops. CRM-4213
1805 // remove repeated related contacts, which already inherited membership.
1806 $relatedContactIds[$membership->contact_id
] = TRUE;
1807 foreach ($allRelatedContacts as $cid => $status) {
1808 if (empty($relatedContactIds[$cid])) {
1809 $relatedContactIds[$cid] = TRUE;
1811 //don't create membership again for owner contact.
1812 $nestedRelationship = FALSE;
1813 if ($membership->owner_membership_id
) {
1814 $nestedRelMembership = new CRM_Member_DAO_Membership();
1815 $nestedRelMembership->id
= $membership->owner_membership_id
;
1816 $nestedRelMembership->contact_id
= $cid;
1817 $nestedRelationship = $nestedRelMembership->find(TRUE);
1818 $nestedRelMembership->free();
1820 if (!$nestedRelationship) {
1821 $relatedContacts[$cid] = $status;
1826 //lets cleanup related membership if any.
1827 if (empty($relatedContacts)) {
1828 self
::deleteRelatedMemberships($membership->id
);
1831 // Edit the params array
1832 unset($params['id']);
1833 // Reminder should be sent only to the direct membership
1834 unset($params['reminder_date']);
1835 // unset the custom value ids
1836 if (is_array(CRM_Utils_Array
::value('custom', $params))) {
1837 foreach ($params['custom'] as $k => $v) {
1838 unset($params['custom'][$k]['id']);
1841 if (!isset($params['membership_type_id'])) {
1842 $params['membership_type_id'] = $membership->membership_type_id
;
1845 // max_related should be set in the parent membership
1846 unset($params['max_related']);
1847 // Number of inherited memberships available - NULL is interpreted as unlimited, '0' as none
1848 $available = ($membership->max_related
== NULL ? PHP_INT_MAX
: $membership->max_related
);
1849 $queue = array(); // will be used to queue potential memberships to be created
1851 foreach ($relatedContacts as $contactId => $relationshipStatus) {
1852 //use existing membership record.
1853 $relMembership = new CRM_Member_DAO_Membership();
1854 $relMembership->contact_id
= $contactId;
1855 $relMembership->owner_membership_id
= $membership->id
;
1856 $relMemIds = array();
1857 if ($relMembership->find(TRUE)) {
1858 $params['id'] = $relMemIds['membership'] = $relMembership->id
;
1860 $params['contact_id'] = $contactId;
1861 $params['owner_membership_id'] = $membership->id
;
1863 // set status_id as it might have been changed for
1864 // past relationship
1865 $params['status_id'] = $membership->status_id
;
1867 if ($deceasedStatusId &&
1868 CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactId, 'is_deceased')
1870 $params['status_id'] = $deceasedStatusId;
1872 elseif ((CRM_Utils_Array
::value('action', $params) & CRM_Core_Action
::UPDATE
) &&
1873 ($relationshipStatus == CRM_Contact_BAO_Relationship
::PAST
)
1875 $params['status_id'] = $expiredStatusId;
1878 //don't calculate status again in create( );
1879 $params['skipStatusCal'] = TRUE;
1881 //do create activity if we changed status.
1882 if ($params['status_id'] != $relMembership->status_id
) {
1883 $params['createActivity'] = TRUE;
1886 // we should not created contribution record for related contacts, CRM-3371
1887 unset($params['contribution_status_id']);
1889 if (($params['status_id'] == $deceasedStatusId) ||
($params['status_id'] == $expiredStatusId)) {
1890 // related membership is not active so does not count towards maximum
1891 CRM_Member_BAO_Membership
::create($params, $relMemIds);
1894 // related membership already exists, so this is just an update
1895 if (isset($params['id'])) {
1896 if ($available > 0) {
1897 CRM_Member_BAO_Membership
::create($params, $relMemIds);
1901 // we have run out of inherited memberships, so delete extras
1902 self
::deleteMembership($params['id']);
1904 // we need to first check if there will remain inherited memberships, so queue it up
1911 // now go over the queue and create any available related memberships
1913 while (($available > 0) && ($params = each($queue))) {
1914 CRM_Member_BAO_Membership
::create($params['value'], $relMemIds);
1921 * Delete the record that are associated with this Membership Payment.
1923 * @param int $membershipId
1926 * $membershipPayment deleted membership payment object
1928 public static function deleteMembershipPayment($membershipId) {
1930 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
1931 $membershipPayment->membership_id
= $membershipId;
1932 $membershipPayment->find();
1934 while ($membershipPayment->fetch()) {
1935 CRM_Contribute_BAO_Contribution
::deleteContribution($membershipPayment->contribution_id
);
1936 CRM_Utils_Hook
::pre('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1937 $membershipPayment->delete();
1938 CRM_Utils_Hook
::post('delete', 'MembershipPayment', $membershipPayment->id
, $membershipPayment);
1940 return $membershipPayment;
1944 * @param CRM_Core_Form $form
1945 * @param int $membershipTypeID
1949 public static function &buildMembershipTypeValues(&$form, $membershipTypeID = NULL) {
1950 $whereClause = " WHERE domain_id = " . CRM_Core_Config
::domainID();
1952 if (is_array($membershipTypeID)) {
1953 $allIDs = implode(',', $membershipTypeID);
1954 $whereClause .= " AND id IN ( $allIDs )";
1956 elseif (is_numeric($membershipTypeID) &&
1957 $membershipTypeID > 0
1959 $whereClause .= " AND id = $membershipTypeID";
1964 FROM civicrm_membership_type
1967 $dao = CRM_Core_DAO
::executeQuery($query);
1969 $membershipTypeValues = array();
1970 $membershipTypeFields = array(
1976 'financial_type_id',
1978 'member_of_contact_id',
1979 'relationship_type_id',
1980 'relationship_direction',
1984 while ($dao->fetch()) {
1985 $membershipTypeValues[$dao->id
] = array();
1986 foreach ($membershipTypeFields as $mtField) {
1987 $membershipTypeValues[$dao->id
][$mtField] = $dao->$mtField;
1992 CRM_Utils_Hook
::membershipTypeValues($form, $membershipTypeValues);
1994 if (is_numeric($membershipTypeID) &&
1995 $membershipTypeID > 0
1997 return $membershipTypeValues[$membershipTypeID];
2000 return $membershipTypeValues;
2005 * Get membership record count for a Contact.
2007 * @param int $contactID
2008 * @param bool $activeOnly
2010 * @return null|string
2012 public static function getContactMembershipCount($contactID, $activeOnly = FALSE) {
2013 $select = "SELECT count(*) FROM civicrm_membership ";
2014 $where = "WHERE civicrm_membership.contact_id = {$contactID} AND civicrm_membership.is_test = 0 ";
2016 // CRM-6627, all status below 3 (active, pending, grace) are considered active
2018 $select .= " INNER JOIN civicrm_membership_status ON civicrm_membership.status_id = civicrm_membership_status.id ";
2019 $where .= " and civicrm_membership_status.is_current_member = 1";
2022 $query = $select . $where;
2023 return CRM_Core_DAO
::singleValueQuery($query);
2027 * Check whether payment processor supports
2028 * cancellation of membership subscription
2033 * @param bool $isNotCancelled
2037 public static function isCancelSubscriptionSupported($mid, $isNotCancelled = TRUE) {
2038 $cacheKeyString = "$mid";
2039 $cacheKeyString .= $isNotCancelled ?
'_1' : '_0';
2041 static $supportsCancel = array();
2043 if (!array_key_exists($cacheKeyString, $supportsCancel)) {
2044 $supportsCancel[$cacheKeyString] = FALSE;
2045 $isCancelled = FALSE;
2047 if ($isNotCancelled) {
2048 $isCancelled = self
::isSubscriptionCancelled($mid);
2051 $paymentObject = CRM_Financial_BAO_PaymentProcessor
::getProcessorForEntity($mid, 'membership', 'obj');
2052 if (!empty($paymentObject)) {
2053 $supportsCancel[$cacheKeyString] = $paymentObject->isSupported('cancelSubscription') && !$isCancelled;
2056 return $supportsCancel[$cacheKeyString];
2060 * Check whether subscription is already cancelled.
2066 * contribution status
2068 public static function isSubscriptionCancelled($mid) {
2070 SELECT cr.contribution_status_id
2071 FROM civicrm_contribution_recur cr
2072 LEFT JOIN civicrm_membership mem ON ( cr.id = mem.contribution_recur_id )
2073 WHERE mem.id = %1 LIMIT 1";
2074 $params = array(1 => array($mid, 'Integer'));
2075 $statusId = CRM_Core_DAO
::singleValueQuery($sql, $params);
2076 $status = CRM_Contribute_PseudoConstant
::contributionStatus($statusId, 'name');
2077 if ($status == 'Cancelled') {
2084 * Get membership joins for a specified membership
2085 * type. Specifically, retrieves a count of still current memberships whose
2086 * join_date and start_date are within a specified date range. Dates match
2087 * the pattern "yyyy-mm-dd".
2089 * @param int $membershipTypeId
2090 * Membership type id.
2091 * @param int $startDate
2092 * Date on which to start counting.
2093 * @param int $endDate
2094 * Date on which to end counting.
2095 * @param bool|int $isTest if true, membership is for a test site
2098 * the number of members of type $membershipTypeId
2099 * whose join_date is between $startDate and $endDate and
2100 * whose start_date is between $startDate and $endDate
2102 public static function getMembershipJoins($membershipTypeId, $startDate, $endDate, $isTest = 0) {
2103 $testClause = 'membership.is_test = 1';
2105 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
2107 if (!self
::$_signupActType) {
2108 self
::_getActTypes();
2111 if (!self
::$_signupActType) {
2116 SELECT COUNT(DISTINCT membership.id) as member_count
2117 FROM civicrm_membership membership
2118 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
2119 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
2120 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
2121 WHERE membership.membership_type_id = %2
2122 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
2126 1 => array(self
::$_signupActType, 'Integer'),
2127 2 => array($membershipTypeId, 'Integer'),
2130 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
2132 return (int) $memberCount;
2136 * Get membership renewals for a specified membership
2137 * type. Specifically, retrieves a count of still current memberships
2138 * whose join_date is before and start_date is within a specified date
2139 * range. Dates match the pattern "yyyy-mm-dd".
2141 * @param int $membershipTypeId
2142 * Membership type id.
2143 * @param int $startDate
2144 * Date on which to start counting.
2145 * @param int $endDate
2146 * Date on which to end counting.
2147 * @param bool|int $isTest if true, membership is for a test site
2150 * returns the number of members of type $membershipTypeId
2151 * whose join_date is before $startDate and
2152 * whose start_date is between $startDate and $endDate
2154 public static function getMembershipRenewals($membershipTypeId, $startDate, $endDate, $isTest = 0) {
2155 $testClause = 'membership.is_test = 1';
2157 $testClause = '( membership.is_test IS NULL OR membership.is_test = 0 )';
2159 if (!self
::$_renewalActType) {
2160 self
::_getActTypes();
2163 if (!self
::$_renewalActType) {
2168 SELECT COUNT(DISTINCT membership.id) as member_count
2169 FROM civicrm_membership membership
2170 INNER JOIN civicrm_activity activity ON (activity.source_record_id = membership.id AND activity.activity_type_id = %1)
2171 INNER JOIN civicrm_membership_status status ON ( membership.status_id = status.id AND status.is_current_member = 1 )
2172 INNER JOIN civicrm_contact contact ON ( contact.id = membership.contact_id AND contact.is_deleted = 0 )
2173 WHERE membership.membership_type_id = %2
2174 AND activity.activity_date_time >= '$startDate' AND activity.activity_date_time <= '$endDate 23:59:59'
2178 1 => array(self
::$_renewalActType, 'Integer'),
2179 2 => array($membershipTypeId, 'Integer'),
2181 $memberCount = CRM_Core_DAO
::singleValueQuery($query, $params);
2183 return (int) $memberCount;
2187 * Where a second separate financial transaction is supported we will process it here.
2189 * @param int $contactID
2190 * @param CRM_Contribute_Form_Contribution_Confirm $form
2191 * @param array $tempParams
2193 * @param array $lineItems
2194 * @param $minimumFee
2195 * @param int $financialTypeID
2197 * @throws CRM_Core_Exception
2199 * @return CRM_Contribute_BAO_Contribution
2201 public static function processSecondaryFinancialTransaction($contactID, &$form, $tempParams, $isTest, $lineItems, $minimumFee, $financialTypeID) {
2202 $financialType = new CRM_Financial_DAO_FinancialType();
2203 $financialType->id
= $financialTypeID;
2204 if (!$financialType->find(TRUE)) {
2205 CRM_Core_Error
::fatal(ts("Could not find a system table"));
2207 $tempParams['amount'] = $minimumFee;
2208 $tempParams['invoiceID'] = md5(uniqid(rand(), TRUE));
2211 if ($form->_values
['is_monetary'] && !$form->_params
['is_pay_later'] && $minimumFee > 0.0) {
2212 $payment = CRM_Core_Payment
::singleton($form->_mode
, $form->_paymentProcessor
, $form);
2214 if ($form->_contributeMode
== 'express') {
2215 $result = $payment->doExpressCheckout($tempParams);
2216 if (is_a($result, 'CRM_Core_Error')) {
2217 throw new CRM_Core_Exception(CRM_Core_Error
::getMessages($result));
2221 $result = $payment->doPayment($tempParams, 'contribute');
2225 //assign receive date when separate membership payment
2226 //and contribution amount not selected.
2227 if ($form->_amount
== 0) {
2228 $now = date('YmdHis');
2229 $form->_params
['receive_date'] = $now;
2230 $receiveDate = CRM_Utils_Date
::mysqlToIso($now);
2231 $form->set('params', $form->_params
);
2232 $form->assign('receive_date', $receiveDate);
2235 $form->set('membership_trx_id', $result['trxn_id']);
2236 $form->set('membership_amount', $minimumFee);
2238 $form->assign('membership_trx_id', $result['trxn_id']);
2239 $form->assign('membership_amount', $minimumFee);
2241 // we don't need to create the user twice, so lets disable cms_create_account
2242 // irrespective of the value, CRM-2888
2243 $tempParams['cms_create_account'] = 0;
2245 $pending = $form->_params
['is_pay_later'] ?
(($minimumFee > 0.0) ?
TRUE : FALSE) : FALSE;
2247 //set this variable as we are not creating pledge for
2248 //separate membership payment contribution.
2249 //so for differentiating membership contribution from
2250 //main contribution.
2251 $form->_params
['separate_membership_payment'] = 1;
2252 $membershipContribution = CRM_Contribute_Form_Contribution_Confirm
::processContribution($form,
2262 return $membershipContribution;
2266 * Create linkages between membership & contribution - note this is the wrong place for this code but this is a
2267 * refactoring step. This should be BAO functionality
2268 * @param $membership
2269 * @param $membershipContribution
2271 public static function linkMembershipPayment($membership, $membershipContribution) {
2272 CRM_Member_BAO_MembershipPayment
::create(array(
2273 'membership_id' => $membership->id
,
2274 'contribution_id' => $membershipContribution->id
,
2279 * @param array $membershipParams
2280 * @param int $contactID
2281 * @param $customFieldsFormatted
2282 * @param int $membershipID
2286 * @param $membershipContribution
2287 * @param CRM_Core_Form $form
2291 public static function createOrRenewMembership($membershipParams, $contactID, $customFieldsFormatted, $membershipID, $memType, $isTest, $numTerms, $membershipContribution, &$form) {
2292 $membership = self
::renewMembershipFormWrapper($contactID, $memType,
2293 $isTest, $form, NULL,
2294 CRM_Utils_Array
::value('cms_contactID', $membershipParams),
2295 $customFieldsFormatted, $numTerms,
2299 if (!empty($membershipContribution)) {
2300 // update recurring id for membership record
2301 self
::updateRecurMembership($membership, $membershipContribution);
2303 self
::linkMembershipPayment($membership, $membershipContribution);
2309 * Turn array of errors into message string.
2311 * @param array $errors
2315 public static function compileErrorMessage($errors) {
2316 foreach ($errors as $error) {
2317 if (is_string($error)) {
2318 $message[] = $error;
2321 return ts('Payment Processor Error message') . ': ' . implode('<br/>', $message);
2325 * Extract relevant values from the form so we can separate form logic from BAO logcis.
2327 * @param CRM_Core_Form $form
2328 * @param $changeToday
2329 * @param $membershipTypeDetails
2333 public static function extractFormValues($form, $changeToday, $membershipTypeDetails) {
2335 //@todo this is a BAO function & should not inspect the form - the form should do this
2336 // & pass required params to the BAO
2337 if (CRM_Utils_Array
::value('minimum_fee', $membershipTypeDetails) > 0.0) {
2338 if (((isset($form->_contributeMode
) && $form->_contributeMode
== 'notify') ||
!empty($form->_params
['is_pay_later']) ||
2339 (!empty($form->_params
['is_recur']) && $form->_contributeMode
== 'direct'
2342 (($form->_values
['is_monetary'] && $form->_amount
> 0.0) ||
!empty($form->_params
['separate_membership_payment']) ||
2343 CRM_Utils_Array
::value('record_contribution', $form->_params
)
2349 $contributionRecurID = isset($form->_params
['contributionRecurID']) ?
$form->_params
['contributionRecurID'] : NULL;
2351 //we renew expired membership, CRM-6277
2352 if (!$changeToday) {
2353 if ($form->get('renewalDate')) {
2354 $changeToday = $form->get('renewalDate');
2356 elseif (get_class($form) == 'CRM_Contribute_Form_Contribution_Confirm') {
2357 $changeToday = date('YmdHis');
2361 $membershipSource = NULL;
2362 if (!empty($form->_params
['membership_source'])) {
2363 $membershipSource = $form->_params
['membership_source'];
2365 elseif (isset($form->_values
['title']) && !empty($form->_values
['title'])) {
2366 $membershipSource = ts('Online Contribution:') . ' ' . $form->_values
['title'];
2369 if (isset($form->_params
)) {
2370 $isPayLater = CRM_Utils_Array
::value('is_pay_later', $form->_params
);
2373 if (isset($form->_values
) && is_array($form->_values
) && !empty($form->_values
)) {
2374 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_params
);
2375 if (!array_key_exists('campaign_id', $form->_params
)) {
2376 $campaignId = CRM_Utils_Array
::value('campaign_id', $form->_values
);
2379 return array($pending, $contributionRecurID, $changeToday, $membershipSource, $isPayLater, $campaignId);
2383 * @param int $contactID
2384 * @param int $membershipTypeID
2385 * @param bool $is_test
2386 * @param $changeToday
2387 * @param int $modifiedID
2388 * @param $customFieldsFormatted
2389 * @param $numRenewTerms
2390 * @param int $membershipID
2393 * @param array $membershipTypeDetails
2394 * @param int $contributionRecurID
2396 * @param $membershipSource
2398 * @param $statusFormat
2399 * @param $isPayLater
2400 * @param int $campaignId
2402 * @throws CRM_Core_Exception
2405 public static function renewMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $allStatus, $membershipTypeDetails, $contributionRecurID, $format, $membershipSource, $ids, $statusFormat, $isPayLater, $campaignId) {
2406 $renewalMode = $updateStatusId = FALSE;
2408 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
2409 // is the same as the parent org of an existing membership of the contact
2410 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($contactID, $membershipTypeID,
2411 $is_test, $membershipID, TRUE
2413 if ($currentMembership) {
2414 $activityType = 'Membership Renewal';
2415 $renewalMode = TRUE;
2417 // Do NOT do anything.
2418 //1. membership with status : PENDING/CANCELLED (CRM-2395)
2419 //2. Paylater/IPN renew. CRM-4556.
2420 if ($pending ||
in_array($currentMembership['status_id'], array(
2421 array_search('Pending', $allStatus),
2423 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
2426 $membership = new CRM_Member_DAO_Membership();
2427 $membership->id
= $currentMembership['id'];
2428 $membership->find(TRUE);
2430 // CRM-8141 create a membership_log entry so that we will know the membership_type_id to change to when payment completed
2432 // note that we are logging the requested new membership_type_id that may be different than current membership_type_id
2433 // it will be used when payment is received to update the membership_type_id to what was paid for
2435 'membership_id' => $membership->id
,
2436 'status_id' => $membership->status_id
,
2437 'start_date' => CRM_Utils_Date
::customFormat(
2438 $membership->start_date
,
2441 'end_date' => CRM_Utils_Date
::customFormat(
2442 $membership->end_date
,
2445 'modified_date' => CRM_Utils_Date
::customFormat(
2449 'membership_type_id' => $membershipTypeID,
2450 'max_related' => !empty($membershipTypeDetails['max_related']) ?
$membershipTypeDetails['max_related'] : NULL,
2452 $session = CRM_Core_Session
::singleton();
2453 // If we have an authenticated session, set modified_id to that user's contact_id, else set to membership.contact_id
2454 if ($session->get('userID')) {
2455 $logParams['modified_id'] = $session->get('userID');
2458 $logParams['modified_id'] = $membership->contact_id
;
2460 CRM_Member_BAO_MembershipLog
::add($logParams, CRM_Core_DAO
::$_nullArray);
2462 if (!empty($contributionRecurID)) {
2463 CRM_Core_DAO
::setFieldValue('CRM_Member_DAO_Membership', $membership->id
,
2464 'contribution_recur_id', $contributionRecurID
2468 return array($membership, $renewalMode, $dates);
2471 // Check and fix the membership if it is STALE
2472 self
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
2474 // Now Renew the membership
2475 if (!$currentMembership['is_current_member']) {
2476 // membership is not CURRENT
2478 // CRM-7297 Membership Upsell - calculate dates based on new membership type
2479 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($currentMembership['id'],
2485 $currentMembership['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
2486 $currentMembership['start_date'] = CRM_Utils_Array
::value('start_date', $dates);
2487 $currentMembership['end_date'] = CRM_Utils_Array
::value('end_date', $dates);
2488 $currentMembership['is_test'] = $is_test;
2490 if (!empty($membershipSource)) {
2491 $currentMembership['source'] = $membershipSource;
2494 $currentMembership['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
2495 $currentMembership['id'],
2500 if (!empty($currentMembership['id'])) {
2501 $ids['membership'] = $currentMembership['id'];
2503 $memParams = $currentMembership;
2504 $memParams['membership_type_id'] = $membershipTypeID;
2506 //set the log start date.
2507 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
2511 // CURRENT Membership
2512 $membership = new CRM_Member_DAO_Membership();
2513 $membership->id
= $currentMembership['id'];
2514 $membership->find(TRUE);
2515 // CRM-7297 Membership Upsell - calculate dates based on new membership type
2516 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
2522 // Insert renewed dates for CURRENT membership
2523 $memParams = array();
2524 $memParams['join_date'] = CRM_Utils_Date
::isoToMysql($membership->join_date
);
2525 $memParams['start_date'] = CRM_Utils_Date
::isoToMysql($membership->start_date
);
2526 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $dates);
2527 $memParams['membership_type_id'] = $membershipTypeID;
2529 //set the log start date.
2530 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
2531 if (empty($membership->source
)) {
2532 if (!empty($membershipSource)) {
2533 $memParams['source'] = $membershipSource;
2536 $memParams['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
2537 $currentMembership['id'],
2543 if (!empty($currentMembership['id'])) {
2544 $ids['membership'] = $currentMembership['id'];
2549 $updateStatusId = array_search('Pending', $allStatus);
2555 $activityType = 'Membership Signup';
2557 'contact_id' => $contactID,
2558 'membership_type_id' => $membershipTypeID,
2562 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
2564 $memParams['join_date'] = CRM_Utils_Array
::value('join_date', $dates);
2565 $memParams['start_date'] = CRM_Utils_Array
::value('start_date', $dates);
2566 $memParams['end_date'] = CRM_Utils_Array
::value('end_date', $dates);
2568 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(CRM_Utils_Date
::customFormat($dates['start_date'],
2571 CRM_Utils_Date
::customFormat($dates['end_date'],
2574 CRM_Utils_Date
::customFormat($dates['join_date'],
2582 $updateStatusId = CRM_Utils_Array
::value('id', $status);
2585 // if IPN/Pay-Later set status to: PENDING
2586 $updateStatusId = array_search('Pending', $allStatus);
2589 if (!empty($membershipSource)) {
2590 $memParams['source'] = $membershipSource;
2592 $memParams['contribution_recur_id'] = $contributionRecurID;
2594 $memParams['is_test'] = $is_test;
2595 $memParams['is_pay_later'] = $isPayLater;
2599 //if we decided status here and want to skip status
2600 //calculation in create( ); then need to pass 'skipStatusCal'.
2601 if ($updateStatusId) {
2602 $memParams['status_id'] = $updateStatusId;
2603 $memParams['skipStatusCal'] = TRUE;
2606 //since we are renewing,
2607 //make status override false.
2608 $memParams['is_override'] = FALSE;
2610 //CRM-4027, create log w/ individual contact.
2612 $ids['userId'] = $modifiedID;
2613 $memParams['is_for_organization'] = TRUE;
2616 $ids['userId'] = $contactID;
2619 //inherit campaign from contrib page.
2620 if (isset($campaignId)) {
2621 $memParams['campaign_id'] = $campaignId;
2624 $memParams['custom'] = $customFieldsFormatted;
2625 $membership = self
::create($memParams, $ids, FALSE, $activityType);
2627 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
2628 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
2629 $membership->find(TRUE);
2631 return array($membership, $renewalMode, $dates);
2635 * Process price set and line items.
2637 * @param int $membershipId
2642 public function processPriceSet($membershipId, $lineItem) {
2643 //FIXME : need to move this too
2644 if (!$membershipId ||
!is_array($lineItem)
2645 || CRM_Utils_System
::isNull($lineItem)
2650 foreach ($lineItem as $priceSetId => $values) {
2654 foreach ($values as $line) {
2655 $line['entity_table'] = 'civicrm_membership';
2656 $line['entity_id'] = $membershipId;
2657 CRM_Price_BAO_LineItem
::create($line);
2663 * Retrieve the contribution id for the associated Membership id.
2664 * @todo we should get this off the line item
2666 * @param int $membershipId
2672 public static function getMembershipContributionId($membershipId) {
2674 $membershipPayment = new CRM_Member_DAO_MembershipPayment();
2675 $membershipPayment->membership_id
= $membershipId;
2676 if ($membershipPayment->find(TRUE)) {
2677 return $membershipPayment->contribution_id
;
2683 * The function checks and updates the status of all membership records for a given domain using the
2684 * calc_membership_status and update_contact_membership APIs.
2687 * Sending renewal reminders has been migrated from this job to the Scheduled Reminders function as of 4.3.
2691 public static function updateAllMembershipStatus() {
2693 //get all active statuses of membership, CRM-3984
2694 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2695 $statusLabels = CRM_Member_PseudoConstant
::membershipStatus(NULL, NULL, 'label');
2696 $allTypes = CRM_Member_PseudoConstant
::membershipType();
2698 // get only memberships with active membership types
2700 SELECT civicrm_membership.id as membership_id,
2701 civicrm_membership.is_override as is_override,
2702 civicrm_membership.membership_type_id as membership_type_id,
2703 civicrm_membership.status_id as status_id,
2704 civicrm_membership.join_date as join_date,
2705 civicrm_membership.start_date as start_date,
2706 civicrm_membership.end_date as end_date,
2707 civicrm_membership.source as source,
2708 civicrm_contact.id as contact_id,
2709 civicrm_contact.is_deceased as is_deceased,
2710 civicrm_membership.owner_membership_id as owner_membership_id,
2711 civicrm_membership.contribution_recur_id as recur_id
2712 FROM civicrm_membership
2713 INNER JOIN civicrm_contact ON ( civicrm_membership.contact_id = civicrm_contact.id )
2714 INNER JOIN civicrm_membership_type ON
2715 (civicrm_membership.membership_type_id = civicrm_membership_type.id AND civicrm_membership_type.is_active = 1)
2716 WHERE civicrm_membership.is_test = 0";
2719 $dao = CRM_Core_DAO
::executeQuery($query, $params);
2724 $smarty = CRM_Core_Smarty
::singleton();
2726 while ($dao->fetch()) {
2730 // Put common parameters into array for easy access
2731 $memberParams = array(
2732 'id' => $dao->membership_id
,
2733 'status_id' => $dao->status_id
,
2734 'contact_id' => $dao->contact_id
,
2735 'membership_type_id' => $dao->membership_type_id
,
2736 'membership_type' => $allTypes[$dao->membership_type_id
],
2737 'join_date' => $dao->join_date
,
2738 'start_date' => $dao->start_date
,
2739 'end_date' => $dao->end_date
,
2740 'source' => $dao->source
,
2741 'skipStatusCal' => TRUE,
2742 'skipRecentView' => TRUE,
2745 $smarty->assign_by_ref('memberParams', $memberParams);
2747 //update membership record to Deceased if contact is deceased
2748 if ($dao->is_deceased
) {
2749 // check for 'Deceased' membership status, CRM-5636
2750 $deceaseStatusId = array_search('Deceased', $allStatus);
2751 if (!$deceaseStatusId) {
2752 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'))));
2755 //process only when status change.
2756 if ($dao->status_id
!= $deceaseStatusId) {
2757 //take all params that need to save.
2758 $deceasedMembership = $memberParams;
2759 $deceasedMembership['status_id'] = $deceaseStatusId;
2760 $deceasedMembership['createActivity'] = TRUE;
2761 $deceasedMembership['version'] = 3;
2763 //since there is change in status.
2764 $statusChange = array('status_id' => $deceaseStatusId);
2765 $smarty->append_by_ref('memberParams', $statusChange, TRUE);
2767 $deceasedMembership['contact_id'],
2768 $deceasedMembership['membership_type_id'],
2769 $deceasedMembership['membership_type'],
2770 $deceasedMembership['join_date'],
2771 $deceasedMembership['start_date'],
2772 $deceasedMembership['end_date'],
2773 $deceasedMembership['source']
2776 //process membership record.
2777 civicrm_api('membership', 'create', $deceasedMembership);
2782 //we fetch related, since we need to check for deceased
2783 //now further processing is handle w/ main membership record.
2784 if ($dao->owner_membership_id
) {
2788 //update membership records where status is NOT - Pending OR Cancelled.
2789 //as well as membership is not override.
2790 //skipping Expired membership records -> reduced extra processing( kiran )
2791 if (!$dao->is_override
&&
2792 !in_array($dao->status_id
, array(
2793 array_search('Pending', $allStatus),
2797 CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)
2799 array_search('Expired', $allStatus),
2803 // CRM-7248: added excludeIsAdmin param to the following fn call to prevent moving to admin statuses
2804 //get the membership status as per id.
2805 $newStatus = civicrm_api('membership_status', 'calc',
2807 'membership_id' => $dao->membership_id
,
2809 'ignore_admin_only' => FALSE,
2812 $statusId = CRM_Utils_Array
::value('id', $newStatus);
2814 //process only when status change.
2816 $statusId != $dao->status_id
2818 //take all params that need to save.
2819 $memParams = $memberParams;
2820 $memParams['status_id'] = $statusId;
2821 $memParams['createActivity'] = TRUE;
2822 $memParams['version'] = 3;
2824 // Unset columns which should remain unchanged from their current saved
2825 // values. This avoids race condition in which these values may have
2826 // been changed by other processes.
2828 $memParams['contact_id'],
2829 $memParams['membership_type_id'],
2830 $memParams['membership_type'],
2831 $memParams['join_date'],
2832 $memParams['start_date'],
2833 $memParams['end_date'],
2834 $memParams['source']
2836 //since there is change in status.
2837 $statusChange = array('status_id' => $statusId);
2838 $smarty->append_by_ref('memberParams', $statusChange, TRUE);
2840 //process member record.
2841 civicrm_api('membership', 'create', $memParams);
2846 $result['is_error'] = 0;
2847 $result['messages'] = ts('Processed %1 membership records. Updated %2 records.', array(
2855 * Returns the membership types for a particular contact
2856 * who has lifetime membership without end date.
2858 * @param int $contactID
2859 * @param bool $isTest
2860 * @param bool $onlyLifeTime
2864 public static function getAllContactMembership($contactID, $isTest = FALSE, $onlyLifeTime = FALSE) {
2865 $contactMembershipType = array();
2867 return $contactMembershipType;
2870 $dao = new CRM_Member_DAO_Membership();
2871 $dao->contact_id
= $contactID;
2872 $pendingStatusId = array_search('Pending', CRM_Member_PseudoConstant
::membershipStatus());
2873 $dao->whereAdd("status_id != $pendingStatusId");
2876 $dao->is_test
= $isTest;
2879 $dao->whereAdd('is_test IS NULL OR is_test = 0');
2882 if ($onlyLifeTime) {
2883 $dao->whereAdd('end_date IS NULL');
2887 while ($dao->fetch()) {
2888 $membership = array();
2889 CRM_Core_DAO
::storeValues($dao, $membership);
2890 $contactMembershipType[$dao->membership_type_id
] = $membership;
2892 return $contactMembershipType;
2896 * Record contribution record associated with membership.
2898 * @param array $params
2899 * Array of submitted params.
2901 * (param in process of being removed - try to use params) array of ids.
2903 * @return CRM_Contribute_BAO_Contribution
2905 public static function recordMembershipContribution(&$params, $ids = array()) {
2906 $membershipId = $params['membership_id'];
2907 $contributionParams = array();
2908 $config = CRM_Core_Config
::singleton();
2909 $contributionParams['currency'] = $config->defaultCurrency
;
2910 $contributionParams['receipt_date'] = (CRM_Utils_Array
::value('receipt_date', $params)) ?
$params['receipt_date'] : 'null';
2911 $contributionParams['source'] = CRM_Utils_Array
::value('contribution_source', $params);
2912 $contributionParams['non_deductible_amount'] = 'null';
2913 $contributionParams['payment_processor'] = CRM_Utils_Array
::value('payment_processor_id', $params);
2914 $contributionSoftParams = CRM_Utils_Array
::value('soft_credit', $params);
2915 $recordContribution = array(
2919 'financial_type_id',
2920 'payment_instrument_id',
2924 'contribution_status_id',
2932 foreach ($recordContribution as $f) {
2933 $contributionParams[$f] = CRM_Utils_Array
::value($f, $params);
2936 // make entry in batch entity batch table
2937 if (!empty($params['batch_id'])) {
2938 $contributionParams['batch_id'] = $params['batch_id'];
2941 if (!empty($params['contribution_contact_id'])) {
2942 // deal with possibility of a different person paying for contribution
2943 $contributionParams['contact_id'] = $params['contribution_contact_id'];
2946 if (!empty($params['processPriceSet']) &&
2947 !empty($params['lineItems'])
2949 $contributionParams['line_item'] = CRM_Utils_Array
::value('lineItems', $params, NULL);
2952 $contribution = CRM_Contribute_BAO_Contribution
::create($contributionParams, $ids);
2954 //CRM-13981, create new soft-credit record as to record payment from different person for this membership
2955 if (!empty($contributionSoftParams)) {
2956 if (!empty($params['batch_id'])) {
2957 foreach ($contributionSoftParams as $contributionSoft) {
2958 $contributionSoft['contribution_id'] = $contribution->id
;
2959 $contributionSoft['currency'] = $contribution->currency
;
2960 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoft);
2964 $contributionSoftParams['contribution_id'] = $contribution->id
;
2965 $contributionSoftParams['currency'] = $contribution->currency
;
2966 $contributionSoftParams['amount'] = $contribution->total_amount
;
2967 CRM_Contribute_BAO_ContributionSoft
::add($contributionSoftParams);
2971 // store contribution id
2972 $params['contribution_id'] = $contribution->id
;
2974 //insert payment record for this membership
2975 if (empty($ids['contribution']) ||
!empty($params['is_recur'])) {
2976 CRM_Member_BAO_MembershipPayment
::create(array(
2977 'membership_id' => $membershipId,
2978 'contribution_id' => $contribution->id
,
2981 return $contribution;
2985 * Record line items for default membership.
2987 * @param CRM_Core_Form $qf
2988 * @param array $membershipType
2989 * Array with membership type and organization.
2990 * @param int $priceSetId
2993 public static function createLineItems(&$qf, $membershipType, &$priceSetId) {
2994 $qf->_priceSetId
= $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', 'default_membership_type_amount', 'id', 'name');
2996 $qf->_priceSet
= $priceSets = current(CRM_Price_BAO_PriceSet
::getSetDetail($priceSetId));
2998 $editedFieldParams = array(
2999 'price_set_id' => $priceSetId,
3000 'name' => $membershipType[0],
3002 $editedResults = array();
3003 CRM_Price_BAO_PriceField
::retrieve($editedFieldParams, $editedResults);
3005 if (!empty($editedResults)) {
3006 unset($qf->_priceSet
['fields']);
3007 $qf->_priceSet
['fields'][$editedResults['id']] = $priceSets['fields'][$editedResults['id']];
3008 unset($qf->_priceSet
['fields'][$editedResults['id']]['options']);
3009 $fid = $editedResults['id'];
3010 $editedFieldParams = array(
3011 'price_field_id' => $editedResults['id'],
3012 'membership_type_id' => $membershipType[1],
3014 $editedResults = array();
3015 CRM_Price_BAO_PriceFieldValue
::retrieve($editedFieldParams, $editedResults);
3016 $qf->_priceSet
['fields'][$fid]['options'][$editedResults['id']] = $priceSets['fields'][$fid]['options'][$editedResults['id']];
3017 if (!empty($qf->_params
['total_amount'])) {
3018 $qf->_priceSet
['fields'][$fid]['options'][$editedResults['id']]['amount'] = $qf->_params
['total_amount'];
3022 $fieldID = key($qf->_priceSet
['fields']);
3023 $qf->_params
['price_' . $fieldID] = CRM_Utils_Array
::value('id', $editedResults);
3027 * @todo document me - I seem a bit out of date....
3029 public static function _getActTypes() {
3030 $activityTypes = CRM_Core_PseudoConstant
::activityType(TRUE, FALSE, FALSE, 'name');
3031 self
::$_renewalActType = CRM_Utils_Array
::key('Membership Renewal', $activityTypes);
3032 self
::$_signupActType = CRM_Utils_Array
::key('Membership Signup', $activityTypes);
3036 * Get all Cancelled Membership(s) for a contact
3038 * @param int $contactID
3040 * @param bool $isTest
3044 * Array of membership type
3046 public static function getContactsCancelledMembership($contactID, $isTest = FALSE) {
3050 $query = 'SELECT membership_type_id FROM civicrm_membership WHERE contact_id = %1 AND status_id = %2 AND is_test = %3';
3051 $queryParams = array(
3052 1 => array($contactID, 'Integer'),
3057 CRM_Member_PseudoConstant
::membershipStatus(
3059 " name = 'Cancelled' ",
3067 3 => array($isTest, 'Boolean'),
3070 $dao = CRM_Core_DAO
::executeQuery($query, $queryParams);
3071 $cancelledMembershipIds = array();
3072 while ($dao->fetch()) {
3073 $cancelledMembershipIds[] = $dao->membership_type_id
;
3075 return $cancelledMembershipIds;