3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * This class generates form components for offline membership form.
21 class CRM_Member_Form_Membership
extends CRM_Member_Form
{
23 protected $_memType = NULL;
25 protected $_onlinePendingContributionId;
29 public $_contributeMode = 'direct';
31 protected $_recurMembershipTypes;
33 protected $_memTypeSelected;
36 * Display name of the member.
40 protected $_memberDisplayName = NULL;
43 * email of the person paying for the membership (used for receipts)
46 protected $_memberEmail = NULL;
49 * Contact ID of the member.
53 public $_contactID = NULL;
56 * Display name of the person paying for the membership (used for receipts)
60 protected $_contributorDisplayName = NULL;
63 * Email of the person paying for the membership (used for receipts).
67 protected $_contributorEmail;
70 * email of the person paying for the membership (used for receipts)
74 protected $_contributorContactID = NULL;
77 * ID of the person the receipt is to go to.
81 protected $_receiptContactId = NULL;
84 * Keep a class variable for ALL membership IDs so
85 * postProcess hook function can do something with it
89 protected $_membershipIDs = [];
92 * Set entity fields to be assigned to the form.
94 protected function setEntityFields() {
95 $this->entityFields
= [
97 'name' => 'join_date',
98 'description' => ts('Member Since'),
101 'name' => 'start_date',
102 'description' => ts('Start Date'),
105 'name' => 'end_date',
106 'description' => ts('End Date'),
112 * Set the delete message.
114 * We do this from the constructor in order to do a translation.
116 public function setDeleteMessage() {
117 $this->deleteMessage
= '<span class="font-red bold">'
118 . ts('WARNING: Deleting this membership will also delete any related payment (contribution) records.' . ts('This action cannot be undone.')
120 . ts('Consider modifying the membership status instead if you want to maintain an audit trail and avoid losing payment data. You can set the status to Cancelled by editing the membership and clicking the Status Override checkbox.')
122 . ts("Click 'Delete' if you want to continue.") . '</p>');
126 * Overriding this entity trait function as not yet tested.
128 * We continue to rely on legacy handling.
130 public function addCustomDataToForm() {}
133 * Overriding this entity trait function as not yet tested.
135 * We continue to rely on legacy handling.
137 public function addFormButtons() {}
140 * Get selected membership type from the form values.
142 * @param array $priceSet
143 * @param array $params
146 * @throws \CRM_Core_Exception
148 public static function getSelectedMemberships($priceSet, $params) {
149 $memTypeSelected = [];
150 $priceFieldIDS = self
::getPriceFieldIDs($params, $priceSet);
151 if (isset($params['membership_type_id']) && !empty($params['membership_type_id'][1])) {
152 $memTypeSelected = [$params['membership_type_id'][1] => $params['membership_type_id'][1]];
155 foreach ($priceFieldIDS as $priceFieldId) {
156 if ($id = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id')) {
157 $memTypeSelected[$id] = $id;
161 return $memTypeSelected;
165 * Extract price set fields and values from $params.
167 * @param array $params
168 * @param array $priceSet
172 public static function getPriceFieldIDs($params, $priceSet) {
174 if (isset($priceSet['fields']) && is_array($priceSet['fields'])) {
175 foreach ($priceSet['fields'] as $fieldId => $field) {
176 if (!empty($params['price_' . $fieldId])) {
177 if (is_array($params['price_' . $fieldId])) {
178 foreach ($params['price_' . $fieldId] as $priceFldVal => $isSet) {
180 $priceFieldIDS[] = $priceFldVal;
184 elseif (!$field['is_enter_qty']) {
185 $priceFieldIDS[] = $params['price_' . $fieldId];
190 return $priceFieldIDS;
194 * Form preProcess function.
196 * @throws \CRM_Core_Exception
197 * @throws \CiviCRM_API3_Exception
199 public function preProcess() {
200 // This string makes up part of the class names, differentiating them (not sure why) from the membership fields.
201 $this->assign('formClass', 'membership');
202 parent
::preProcess();
205 $this->_priceSetId
= $_GET['priceSetId'] ??
NULL;
206 $this->set('priceSetId', $this->_priceSetId
);
207 $this->assign('priceSetId', $this->_priceSetId
);
209 if ($this->_action
& CRM_Core_Action
::DELETE
) {
210 $contributionID = CRM_Member_BAO_Membership
::getMembershipContributionId($this->_id
);
211 // check delete permission for contribution
212 if ($this->_id
&& $contributionID && !CRM_Core_Permission
::checkActionPermission('CiviContribute', $this->_action
)) {
213 CRM_Core_Error
::statusBounce(ts("This Membership is linked to a contribution. You must have 'delete in CiviContribute' permission in order to delete this record."));
217 if ($this->_action
& CRM_Core_Action
::ADD
) {
218 if ($this->_contactID
) {
219 //check whether contact has a current membership so we can alert user that they may want to do a renewal instead
220 $contactMemberships = [];
221 $memParams = ['contact_id' => $this->_contactID
];
222 CRM_Member_BAO_Membership
::getValues($memParams, $contactMemberships, TRUE);
224 foreach ($contactMemberships as $mem) {
225 $cMemTypes[] = $mem['membership_type_id'];
227 if (count($cMemTypes) > 0) {
228 $memberorgs = CRM_Member_BAO_MembershipType
::getMemberOfContactByMemTypes($cMemTypes);
230 foreach ($contactMemberships as $mem) {
231 $mem['member_of_contact_id'] = $memberorgs[$mem['membership_type_id']] ??
NULL;
232 if (!empty($mem['membership_end_date'])) {
233 $mem['membership_end_date'] = CRM_Utils_Date
::customFormat($mem['membership_end_date']);
235 $mem['membership_type'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
236 $mem['membership_type_id'],
239 $mem['membership_status'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipStatus',
243 $mem['renewUrl'] = CRM_Utils_System
::url('civicrm/contact/view/membership',
244 "reset=1&action=renew&cid={$this->_contactID}&id={$mem['id']}&context=membership&selectedChild=member"
245 . ($this->_mode ?
'&mode=live' : '')
247 $mem['membershipTab'] = CRM_Utils_System
::url('civicrm/contact/view',
248 "reset=1&force=1&cid={$this->_contactID}&selectedChild=member"
250 $mems_by_org[$mem['member_of_contact_id']] = $mem;
252 $this->assign('existingContactMemberships', $mems_by_org);
256 // In standalone mode we don't have a contact id yet so lookup will be done client-side with this script:
257 $resources = CRM_Core_Resources
::singleton();
258 $resources->addScriptFile('civicrm', 'templates/CRM/Member/Form/MembershipStandalone.js');
260 'typeorgs' => CRM_Member_BAO_MembershipType
::getMembershipTypeOrganization(),
261 'memtypes' => CRM_Core_PseudoConstant
::get('CRM_Member_BAO_Membership', 'membership_type_id'),
262 'statuses' => CRM_Core_PseudoConstant
::get('CRM_Member_BAO_Membership', 'status_id'),
264 $resources->addSetting(['existingMems' => $passthru]);
268 if (!$this->_memType
) {
269 $params = CRM_Utils_Request
::exportValues();
270 if (!empty($params['membership_type_id'][1])) {
271 $this->_memType
= $params['membership_type_id'][1];
275 // Add custom data to form
276 CRM_Custom_Form_CustomData
::addToForm($this, $this->_memType
);
278 // CRM-4395, get the online pending contribution id.
279 $this->_onlinePendingContributionId
= NULL;
280 if (!$this->_mode
&& $this->_id
&& ($this->_action
& CRM_Core_Action
::UPDATE
)) {
281 $this->_onlinePendingContributionId
= CRM_Contribute_BAO_Contribution
::checkOnlinePendingContribution($this->_id
,
285 $this->assign('onlinePendingContributionId', $this->_onlinePendingContributionId
);
287 $this->setPageTitle(ts('Membership'));
291 * Set default values for the form.
293 public function setDefaultValues() {
295 if ($this->_priceSetId
) {
296 return CRM_Price_BAO_PriceSet
::setDefaultPriceSet($this, $defaults);
299 $defaults = parent
::setDefaultValues();
301 //setting default join date and receive date
302 if ($this->_action
== CRM_Core_Action
::ADD
) {
303 $defaults['receive_date'] = date('Y-m-d H:i:s');
306 $defaults['num_terms'] = 1;
308 if (!empty($defaults['id'])) {
309 if ($this->_onlinePendingContributionId
) {
310 $defaults['record_contribution'] = $this->_onlinePendingContributionId
;
313 $contributionId = CRM_Core_DAO
::singleValueQuery("
314 SELECT contribution_id
315 FROM civicrm_membership_payment
316 WHERE membership_id = $this->_id
317 ORDER BY contribution_id
320 if ($contributionId) {
321 $defaults['record_contribution'] = $contributionId;
326 if ($this->_contactID
) {
327 $defaults['contact_id'] = $this->_contactID
;
331 //set Soft Credit Type to Gift by default
332 $scTypes = CRM_Core_OptionGroup
::values('soft_credit_type');
333 $defaults['soft_credit_type_id'] = CRM_Utils_Array
::value(ts('Gift'), array_flip($scTypes));
336 if (empty($defaults['payment_instrument_id'])) {
337 $defaults['payment_instrument_id'] = key(CRM_Core_OptionGroup
::values('payment_instrument', FALSE, FALSE, FALSE, 'AND is_default = 1'));
340 // User must explicitly choose to send a receipt in both add and update mode.
341 $defaults['send_receipt'] = 0;
343 if ($this->_action
& CRM_Core_Action
::UPDATE
) {
344 // in this mode by default uncheck this checkbox
345 unset($defaults['record_contribution']);
348 $subscriptionCancelled = FALSE;
349 if (!empty($defaults['id'])) {
350 $subscriptionCancelled = CRM_Member_BAO_Membership
::isSubscriptionCancelled($this->_id
);
353 $alreadyAutoRenew = FALSE;
354 if (!empty($defaults['contribution_recur_id']) && !$subscriptionCancelled) {
355 $defaults['auto_renew'] = 1;
356 $alreadyAutoRenew = TRUE;
358 $this->assign('alreadyAutoRenew', $alreadyAutoRenew);
360 $this->assign('member_is_test', CRM_Utils_Array
::value('member_is_test', $defaults));
362 $this->assign('membership_status_id', CRM_Utils_Array
::value('status_id', $defaults));
364 if (!empty($defaults['is_pay_later'])) {
365 $this->assign('is_pay_later', TRUE);
368 $defaults = $this->getBillingDefaults($defaults);
369 // hack to simplify credit card entry for testing
370 // $defaults['credit_card_type'] = 'Visa';
371 // $defaults['credit_card_number'] = '4807731747657838';
372 // $defaults['cvv2'] = '000';
373 // $defaults['credit_card_exp_date'] = array( 'Y' => '2012', 'M' => '05' );
376 //setting default join date if there is no join date
377 if (empty($defaults['join_date'])) {
378 $defaults['join_date'] = date('Y-m-d');
381 if (!empty($defaults['membership_end_date'])) {
382 $this->assign('endDate', $defaults['membership_end_date']);
389 * Build the form object.
391 * @throws \CRM_Core_Exception
393 public function buildQuickForm() {
395 $this->buildQuickEntityForm();
396 $this->assign('currency_symbol', CRM_Core_BAO_Country
::defaultCurrencySymbol());
397 $isUpdateToExistingRecurringMembership = $this->isUpdateToExistingRecurringMembership();
398 // build price set form.
399 $buildPriceSet = FALSE;
400 if ($this->_priceSetId ||
!empty($_POST['price_set_id'])) {
401 if (!empty($_POST['price_set_id'])) {
402 $buildPriceSet = TRUE;
404 $getOnlyPriceSetElements = TRUE;
405 if (!$this->_priceSetId
) {
406 $this->_priceSetId
= $_POST['price_set_id'];
407 $getOnlyPriceSetElements = FALSE;
410 $this->set('priceSetId', $this->_priceSetId
);
411 CRM_Price_BAO_PriceSet
::buildPriceSet($this);
413 $optionsMembershipTypes = [];
414 foreach ($this->_priceSet
['fields'] as $pField) {
415 if (empty($pField['options'])) {
418 foreach ($pField['options'] as $opId => $opValues) {
419 $optionsMembershipTypes[$opId] = CRM_Utils_Array
::value('membership_type_id', $opValues, 0);
423 $this->assign('autoRenewOption', CRM_Price_BAO_PriceSet
::checkAutoRenewForPriceSet($this->_priceSetId
));
425 $this->assign('optionsMembershipTypes', $optionsMembershipTypes);
426 $this->assign('contributionType', CRM_Utils_Array
::value('financial_type_id', $this->_priceSet
));
428 // get only price set form elements.
429 if ($getOnlyPriceSetElements) {
434 // use to build form during form rule.
435 $this->assign('buildPriceSet', $buildPriceSet);
437 if ($this->_action
& CRM_Core_Action
::ADD
) {
438 $buildPriceSet = FALSE;
439 $priceSets = CRM_Price_BAO_PriceSet
::getAssoc(FALSE, 'CiviMember');
440 if (!empty($priceSets)) {
441 $buildPriceSet = TRUE;
444 if ($buildPriceSet) {
445 $this->add('select', 'price_set_id', ts('Choose price set'),
447 '' => ts('Choose price set'),
449 NULL, ['onchange' => "buildAmount( this.value );"]
452 $this->assign('hasPriceSets', $buildPriceSet);
455 if ($this->_action
& CRM_Core_Action
::DELETE
) {
459 'name' => ts('Delete'),
460 'spacing' => ' ',
465 'name' => ts('Cancel'),
471 $contactField = $this->addEntityRef('contact_id', ts('Member'), ['create' => TRUE, 'api' => ['extra' => ['email']]], TRUE);
472 if ($this->_context
!== 'standalone') {
473 $contactField->freeze();
476 $selOrgMemType[0][0] = $selMemTypeOrg[0] = ts('- select -');
478 // Throw status bounce when no Membership type or priceset is present
479 if (CRM_Financial_BAO_FinancialType
::isACLFinancialTypeStatus()
480 && empty($this->allMembershipTypeDetails
) && empty($priceSets)
482 CRM_Core_Error
::statusBounce(ts('You do not have all the permissions needed for this page.'));
484 // retrieve all memberships
485 $allMembershipInfo = [];
486 foreach ($this->allMembershipTypeDetails
as $key => $values) {
487 if ($this->_mode
&& empty($values['minimum_fee'])) {
491 $memberOfContactId = $values['member_of_contact_id'] ??
NULL;
492 if (empty($selMemTypeOrg[$memberOfContactId])) {
493 $selMemTypeOrg[$memberOfContactId] = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact',
499 $selOrgMemType[$memberOfContactId][0] = ts('- select -');
501 if (empty($selOrgMemType[$memberOfContactId][$key])) {
502 $selOrgMemType[$memberOfContactId][$key] = $values['name'] ??
NULL;
505 $totalAmount = $values['minimum_fee'] ??
NULL;
506 //CRM-18827 - override the default value if total_amount is submitted
507 if (!empty($this->_submitValues
['total_amount'])) {
508 $totalAmount = $this->_submitValues
['total_amount'];
510 // build membership info array, which is used when membership type is selected to:
511 // - set the payment information block
512 // - set the max related block
513 $allMembershipInfo[$key] = [
514 'financial_type_id' => $values['financial_type_id'] ??
NULL,
515 'total_amount' => CRM_Utils_Money
::format($totalAmount, NULL, '%a'),
516 'total_amount_numeric' => $totalAmount,
517 'auto_renew' => $values['auto_renew'] ??
NULL,
518 'has_related' => isset($values['relationship_type_id']),
519 'max_related' => $values['max_related'] ??
NULL,
523 $this->assign('allMembershipInfo', json_encode($allMembershipInfo));
525 // show organization by default, if only one organization in
527 if (count($selMemTypeOrg) == 2) {
528 unset($selMemTypeOrg[0], $selOrgMemType[0][0]);
530 //sort membership organization and type, CRM-6099
531 natcasesort($selMemTypeOrg);
532 foreach ($selOrgMemType as $index => $orgMembershipType) {
533 natcasesort($orgMembershipType);
534 $selOrgMemType[$index] = $orgMembershipType;
538 'onChange' => "buildMaxRelated(this.value,true); CRM.buildCustomData('Membership', this.value);",
541 if (!empty($this->_recurPaymentProcessors
)) {
542 $memTypeJs['onChange'] = "" . $memTypeJs['onChange'] . " buildAutoRenew(this.value, null, '{$this->_mode}');";
545 $this->add('text', 'max_related', ts('Max related'),
546 CRM_Core_DAO
::getAttribute('CRM_Member_DAO_Membership', 'max_related')
549 $sel = &$this->addElement('hierselect',
550 'membership_type_id',
551 ts('Membership Organization and Type'),
555 $sel->setOptions([$selMemTypeOrg, $selOrgMemType]);
557 if ($this->_action
& CRM_Core_Action
::ADD
) {
558 $this->add('number', 'num_terms', ts('Number of Terms'), ['size' => 6]);
561 $this->add('text', 'source', ts('Source'),
562 CRM_Core_DAO
::getAttribute('CRM_Member_DAO_Membership', 'source')
565 //CRM-7362 --add campaigns.
568 $campaignId = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $this->_id
, 'campaign_id');
570 CRM_Campaign_BAO_Campaign
::addCampaign($this, $campaignId);
573 $this->add('select', 'status_id', ts('Membership Status'),
574 ['' => ts('- select -')] + CRM_Member_PseudoConstant
::membershipStatus(NULL, NULL, 'label')
577 $statusOverride = $this->addElement('select', 'is_override', ts('Status Override?'),
578 CRM_Member_StatusOverrideTypes
::getSelectOptions()
581 $this->add('datepicker', 'status_override_end_date', ts('Status Override End Date'), '', FALSE, ['minDate' => time(), 'time' => FALSE]);
583 $this->addElement('checkbox', 'record_contribution', ts('Record Membership Payment?'));
585 $this->add('text', 'total_amount', ts('Amount'));
586 $this->addRule('total_amount', ts('Please enter a valid amount.'), 'money');
588 $this->add('datepicker', 'receive_date', ts('Received'), [], FALSE, ['time' => TRUE]);
590 $this->add('select', 'payment_instrument_id',
591 ts('Payment Method'),
592 ['' => ts('- select -')] + CRM_Contribute_PseudoConstant
::paymentInstrument(),
593 FALSE, ['onChange' => "return showHideByValue('payment_instrument_id','4','checkNumber','table-row','select',false);"]
595 $this->add('text', 'trxn_id', ts('Transaction ID'));
596 $this->addRule('trxn_id', ts('Transaction ID already exists in Database.'),
598 'CRM_Contribute_DAO_Contribution',
604 $this->add('select', 'contribution_status_id',
605 ts('Payment Status'), CRM_Contribute_BAO_Contribution_Utils
::getContributionStatuses('membership')
607 $this->add('text', 'check_number', ts('Check Number'),
608 CRM_Core_DAO
::getAttribute('CRM_Contribute_DAO_Contribution', 'check_number')
612 //add field for amount to allow an amount to be entered that differs from minimum
613 $this->add('text', 'total_amount', ts('Amount'));
615 $this->add('select', 'financial_type_id',
616 ts('Financial Type'),
617 ['' => ts('- select -')] + CRM_Financial_BAO_FinancialType
::getAvailableFinancialTypes($financialTypes, $this->_action
)
620 $this->addElement('checkbox', 'is_different_contribution_contact', ts('Record Payment from a Different Contact?'));
622 $this->addSelect('soft_credit_type_id', ['entity' => 'contribution_soft']);
623 $this->addEntityRef('soft_credit_contact_id', ts('Payment From'), ['create' => TRUE]);
625 $this->addElement('checkbox',
627 ts('Send Confirmation and Receipt?'), NULL,
628 ['onclick' => "showEmailOptions()"]
631 $this->add('select', 'from_email_address', ts('Receipt From'), $this->_fromEmails
);
633 $this->add('textarea', 'receipt_text', ts('Receipt Message'));
635 // Retrieve the name and email of the contact - this will be the TO for receipt email
636 if ($this->_contactID
) {
637 list($this->_memberDisplayName
,
639 ) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($this->_contactID
);
641 $this->assign('emailExists', $this->_memberEmail
);
642 $this->assign('displayName', $this->_memberDisplayName
);
645 if ($isUpdateToExistingRecurringMembership && CRM_Member_BAO_Membership
::isCancelSubscriptionSupported($this->_id
)) {
646 $this->assign('cancelAutoRenew',
647 CRM_Utils_System
::url('civicrm/contribute/unsubscribe', "reset=1&mid={$this->_id}")
651 $this->assign('isRecur', $isUpdateToExistingRecurringMembership);
653 $this->addFormRule(['CRM_Member_Form_Membership', 'formRule'], $this);
654 $mailingInfo = Civi
::settings()->get('mailing_backend');
655 $this->assign('isEmailEnabledForSite', ($mailingInfo['outBound_option'] != 2));
657 parent
::buildQuickForm();
663 * @param array $params
664 * (ref.) an assoc array of name/value pairs.
666 * @param array $files
667 * @param CRM_Member_Form_Membership $self
670 * mixed true or array of errors
672 * @throws \CRM_Core_Exception
673 * @throws CiviCRM_API3_Exception
675 public static function formRule($params, $files, $self) {
678 $priceSetId = self
::getPriceSetID($params);
679 $priceSetDetails = self
::getPriceSetDetails($params);
681 $selectedMemberships = self
::getSelectedMemberships($priceSetDetails[$priceSetId], $params);
683 if (!empty($params['price_set_id'])) {
684 CRM_Price_BAO_PriceField
::priceSetValidation($priceSetId, $params, $errors);
686 $priceFieldIDS = self
::getPriceFieldIDs($params, $priceSetDetails[$priceSetId]);
688 if (!empty($priceFieldIDS)) {
689 $ids = implode(',', $priceFieldIDS);
691 $count = CRM_Price_BAO_PriceSet
::getMembershipCount($ids);
692 foreach ($count as $occurrence) {
693 if ($occurrence > 1) {
694 $errors['_qf_default'] = ts('Select at most one option associated with the same membership type.');
698 // Return error if empty $self->_memTypeSelected
699 if (empty($errors) && empty($selectedMemberships)) {
700 $errors['_qf_default'] = ts('Select at least one membership option.');
702 if (!$self->_mode
&& empty($params['record_contribution'])) {
703 $errors['record_contribution'] = ts('Record Membership Payment is required when you use a price set.');
707 if (empty($params['membership_type_id'][1])) {
708 $errors['membership_type_id'] = ts('Please select a membership type.');
710 $numterms = $params['num_terms'] ??
NULL;
711 if ($numterms && intval($numterms) != $numterms) {
712 $errors['num_terms'] = ts('Please enter an integer for the number of terms.');
715 if (($self->_mode ||
isset($params['record_contribution'])) && empty($params['financial_type_id'])) {
716 $errors['financial_type_id'] = ts('Please enter the financial Type.');
720 if (!empty($errors) && (count($selectedMemberships) > 1)) {
721 $memberOfContacts = CRM_Member_BAO_MembershipType
::getMemberOfContactByMemTypes($selectedMemberships);
722 $duplicateMemberOfContacts = array_count_values($memberOfContacts);
723 foreach ($duplicateMemberOfContacts as $countDuplicate) {
724 if ($countDuplicate > 1) {
725 $errors['_qf_default'] = ts('Please do not select more than one membership associated with the same organization.');
730 if (!empty($errors)) {
734 if (!empty($params['record_contribution']) && empty($params['payment_instrument_id'])) {
735 $errors['payment_instrument_id'] = ts('Payment Method is a required field.');
738 if (!empty($params['is_different_contribution_contact'])) {
739 if (empty($params['soft_credit_type_id'])) {
740 $errors['soft_credit_type_id'] = ts('Please Select a Soft Credit Type');
742 if (empty($params['soft_credit_contact_id'])) {
743 $errors['soft_credit_contact_id'] = ts('Please select a contact');
747 if (!empty($params['payment_processor_id'])) {
748 // validate payment instrument (e.g. credit card number)
749 CRM_Core_Payment_Form
::validatePaymentInstrument($params['payment_processor_id'], $params, $errors, NULL);
753 if (!empty($params['join_date'])) {
755 $joinDate = CRM_Utils_Date
::processDate($params['join_date']);
757 foreach ($selectedMemberships as $memType) {
759 if (!empty($params['start_date'])) {
760 $startDate = CRM_Utils_Date
::processDate($params['start_date']);
763 // if end date is set, ensure that start date is also set
764 // and that end date is later than start date
766 if (!empty($params['end_date'])) {
767 $endDate = CRM_Utils_Date
::processDate($params['end_date']);
770 $membershipDetails = CRM_Member_BAO_MembershipType
::getMembershipTypeDetails($memType);
772 if ($startDate && CRM_Utils_Array
::value('period_type', $membershipDetails) === 'rolling') {
773 if ($startDate < $joinDate) {
774 $errors['start_date'] = ts('Start date must be the same or later than Member since.');
779 if ($membershipDetails['duration_unit'] === 'lifetime') {
780 // Check if status is NOT cancelled or similar. For lifetime memberships, there is no automated
781 // process to update status based on end-date. The user must change the status now.
782 $result = civicrm_api3('MembershipStatus', 'get', [
784 'is_current_member' => 0,
786 $tmp_statuses = $result['values'];
788 foreach ($tmp_statuses as $cur_stat) {
789 $status_ids[] = $cur_stat['id'];
792 if (empty($params['status_id']) ||
in_array($params['status_id'], $status_ids) == FALSE) {
793 $errors['status_id'] = ts('Please enter a status that does NOT represent a current membership status.');
796 if (!empty($params['is_override']) && !CRM_Member_StatusOverrideTypes
::isPermanent($params['is_override'])) {
797 $errors['is_override'] = ts('Because you set an End Date for a lifetime membership, This must be set to "Override Permanently"');
802 $errors['start_date'] = ts('Start date must be set if end date is set.');
804 if ($endDate < $startDate) {
805 $errors['end_date'] = ts('End date must be the same or later than start date.');
810 // Default values for start and end dates if not supplied on the form.
811 $defaultDates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($memType,
818 $startDate = CRM_Utils_Array
::value('start_date',
823 $endDate = CRM_Utils_Array
::value('end_date',
828 //CRM-3724, check for availability of valid membership status.
829 if ((empty($params['is_override']) || CRM_Member_StatusOverrideTypes
::isNo($params['is_override'])) && !isset($errors['_qf_default'])) {
830 $calcStatus = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate($startDate,
838 if (empty($calcStatus)) {
839 $url = CRM_Utils_System
::url('civicrm/admin/member/membershipStatus', 'reset=1&action=browse');
840 $errors['_qf_default'] = ts('There is no valid Membership Status available for selected membership dates.');
841 $status = ts('Oops, it looks like there is no valid membership status available for the given membership dates. You can <a href="%1">Configure Membership Status Rules</a>.', [1 => $url]);
843 $status .= ' ' . ts('OR You can sign up by setting Status Override? to something other than "NO".');
845 CRM_Core_Session
::setStatus($status, ts('Membership Status Error'), 'error');
851 $errors['join_date'] = ts('Please enter the Member Since.');
854 if (!empty($params['is_override']) && CRM_Member_StatusOverrideTypes
::isOverridden($params['is_override']) && empty($params['status_id'])) {
855 $errors['status_id'] = ts('Please enter the Membership status.');
858 if (!empty($params['is_override']) && CRM_Member_StatusOverrideTypes
::isUntilDate($params['is_override'])) {
859 if (empty($params['status_override_end_date'])) {
860 $errors['status_override_end_date'] = ts('Please enter the Membership override end date.');
864 //total amount condition arise when membership type having no
866 if (isset($params['record_contribution'])) {
867 if (CRM_Utils_System
::isNull($params['total_amount'])) {
868 $errors['total_amount'] = ts('Please enter the contribution.');
872 // validate contribution status for 'Failed'.
873 if ($self->_onlinePendingContributionId
&& !empty($params['record_contribution']) &&
874 (CRM_Utils_Array
::value('contribution_status_id', $params) ==
875 array_search('Failed', CRM_Contribute_PseudoConstant
::contributionStatus(NULL, 'name'))
878 $errors['contribution_status_id'] = ts('Please select a valid payment status before updating.');
881 return empty($errors) ?
TRUE : $errors;
885 * Process the form submission.
887 * @throws \CRM_Core_Exception
888 * @throws \CiviCRM_API3_Exception
890 public function postProcess() {
891 if ($this->_action
& CRM_Core_Action
::DELETE
) {
892 CRM_Member_BAO_Membership
::del($this->_id
);
895 // get the submitted form values.
896 $this->_params
= $this->controller
->exportValues($this->_name
);
897 $this->prepareStatusOverrideValues();
901 $this->setUserContext();
905 * Prepares the values related to status override.
907 private function prepareStatusOverrideValues() {
908 $this->setOverrideDateValue();
909 $this->convertIsOverrideValue();
913 * Sets status override end date to empty value if
914 * the selected override option is not 'until date'.
916 private function setOverrideDateValue() {
917 if (!CRM_Member_StatusOverrideTypes
::isUntilDate(CRM_Utils_Array
::value('is_override', $this->_params
))) {
918 $this->_params
['status_override_end_date'] = '';
923 * Convert the value of selected (status override?)
924 * option to TRUE if it indicate an overridden status
925 * or FALSE otherwise.
927 private function convertIsOverrideValue() {
928 $this->_params
['is_override'] = CRM_Member_StatusOverrideTypes
::isOverridden($this->_params
['is_override']);
932 * Send email receipt.
934 * @param CRM_Core_Form $form
936 * @param array $formValues
937 * @param object $membership
939 * @param array $customValues
942 * true if mail was sent successfully
943 * @throws \CRM_Core_Exception
946 * This function is shared with Batch_Entry which has limited overlap
947 * & needs rationalising.
950 public static function emailReceipt(&$form, &$formValues, &$membership, $customValues = NULL) {
951 // retrieve 'from email id' for acknowledgement
952 $receiptFrom = $formValues['from_email_address'] ??
NULL;
954 // @todo figure out how much of the stuff below is genuinely shared with the batch form & a logical shared place.
955 if (!empty($formValues['payment_instrument_id'])) {
956 $paymentInstrument = CRM_Contribute_PseudoConstant
::paymentInstrument();
957 $formValues['paidBy'] = $paymentInstrument[$formValues['payment_instrument_id']];
960 $form->assign('customValues', $customValues);
963 // @todo move this outside shared code as Batch entry just doesn't
964 $form->assign('address', CRM_Utils_Address
::getFormattedBillingAddressFieldsFromParameters(
969 $date = CRM_Utils_Date
::format($form->_params
['credit_card_exp_date']);
970 $date = CRM_Utils_Date
::mysqlToIso($date);
971 $form->assign('credit_card_exp_date', $date);
972 $form->assign('credit_card_number',
973 CRM_Utils_System
::mungeCreditCard($form->_params
['credit_card_number'])
975 $form->assign('credit_card_type', $form->_params
['credit_card_type']);
976 $form->assign('contributeMode', 'direct');
977 $form->assign('isAmountzero', 0);
978 $form->assign('is_pay_later', 0);
979 $form->assign('isPrimary', 1);
982 $form->assign('module', 'Membership');
983 $form->assign('contactID', $formValues['contact_id']);
985 $form->assign('membershipID', CRM_Utils_Array
::value('membership_id', $form->_params
, CRM_Utils_Array
::value('membership_id', $form->_defaultValues
)));
987 if (!empty($formValues['contribution_id'])) {
988 $form->assign('contributionID', $formValues['contribution_id']);
990 elseif (isset($form->_onlinePendingContributionId
)) {
991 $form->assign('contributionID', $form->_onlinePendingContributionId
);
994 if (!empty($formValues['contribution_status_id'])) {
995 $form->assign('contributionStatusID', $formValues['contribution_status_id']);
996 $form->assign('contributionStatus', CRM_Contribute_PseudoConstant
::contributionStatus($formValues['contribution_status_id'], 'name'));
999 if (!empty($formValues['is_renew'])) {
1000 $form->assign('receiptType', 'membership renewal');
1003 $form->assign('receiptType', 'membership signup');
1005 $form->assign('receive_date', CRM_Utils_Array
::value('receive_date', $formValues));
1006 $form->assign('formValues', $formValues);
1008 if (empty($lineItem)) {
1009 $form->assign('mem_start_date', CRM_Utils_Date
::customFormat($membership->start_date
, '%B %E%f, %Y'));
1010 if (!CRM_Utils_System
::isNull($membership->end_date
)) {
1011 $form->assign('mem_end_date', CRM_Utils_Date
::customFormat($membership->end_date
, '%B %E%f, %Y'));
1013 $form->assign('membership_name', CRM_Member_PseudoConstant
::membershipType($membership->membership_type_id
));
1016 // @todo - if we have to figure out if this is for batch processing it doesn't belong in the shared function.
1017 $isBatchProcess = is_a($form, 'CRM_Batch_Form_Entry');
1018 if ((empty($form->_contributorDisplayName
) ||
empty($form->_contributorEmail
)) ||
$isBatchProcess) {
1019 // in this case the form is being called statically from the batch editing screen
1020 // having one class in the form layer call another statically is not greate
1021 // & we should aim to move this function to the BAO layer in future.
1022 // however, we can assume that the contact_id passed in by the batch
1023 // function will be the recipient
1024 list($form->_contributorDisplayName
, $form->_contributorEmail
)
1025 = CRM_Contact_BAO_Contact_Location
::getEmailDetails($formValues['contact_id']);
1026 if (empty($form->_receiptContactId
) ||
$isBatchProcess) {
1027 $form->_receiptContactId
= $formValues['contact_id'];
1030 // @todo determine isEmailPdf in calling function.
1031 $template = CRM_Core_Smarty
::singleton();
1032 $taxAmt = $template->get_template_vars('dataArray');
1033 $eventTaxAmt = $template->get_template_vars('totalTaxAmount');
1034 $prefixValue = Civi
::settings()->get('contribution_invoice_settings');
1035 $invoicing = $prefixValue['invoicing'] ??
NULL;
1036 if ((!empty($taxAmt) ||
isset($eventTaxAmt)) && (isset($invoicing) && isset($prefixValue['is_email_pdf']))) {
1040 $isEmailPdf = FALSE;
1043 list($mailSend, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate
::sendTemplate(
1045 'groupName' => 'msg_tpl_workflow_membership',
1046 'valueName' => 'membership_offline_receipt',
1047 'contactId' => $form->_receiptContactId
,
1048 'from' => $receiptFrom,
1049 'toName' => $form->_contributorDisplayName
,
1050 'toEmail' => $form->_contributorEmail
,
1051 'PDFFilename' => ts('receipt') . '.pdf',
1052 'isEmailPdf' => $isEmailPdf,
1053 'contributionId' => $formValues['contribution_id'],
1054 'isTest' => (bool) ($form->_action
& CRM_Core_Action
::PREVIEW
),
1064 * This is also accessed by unit tests.
1066 * @throws \CRM_Core_Exception
1067 * @throws \CiviCRM_API3_Exception
1069 public function submit() {
1070 $isTest = ($this->_mode
=== 'test') ?
1 : 0;
1071 $this->storeContactFields($this->_params
);
1072 $this->beginPostProcess();
1073 $joinDate = $startDate = $endDate = NULL;
1074 $membershipTypes = $membership = $calcDate = [];
1075 $membershipType = NULL;
1076 $paymentInstrumentID = $this->_paymentProcessor
['object']->getPaymentInstrumentID();
1077 $params = $softParams = $ids = [];
1080 $this->processBillingAddress();
1081 $formValues = $this->_params
;
1082 $formValues = $this->setPriceSetParameters($formValues);
1085 $ids['membership'] = $params['id'] = $this->_id
;
1088 // Set variables that we normally get from context.
1089 // In form mode these are set in preProcess.
1090 //TODO: set memberships, fixme
1091 $this->setContextVariables($formValues);
1093 $this->_memTypeSelected
= self
::getSelectedMemberships(
1097 if (empty($formValues['financial_type_id'])) {
1098 $formValues['financial_type_id'] = $this->_priceSet
['financial_type_id'];
1101 $config = CRM_Core_Config
::singleton();
1103 $membershipTypeValues = [];
1104 foreach ($this->_memTypeSelected
as $memType) {
1105 $membershipTypeValues[$memType]['membership_type_id'] = $memType;
1108 //take the required membership recur values.
1109 if ($this->_mode
&& !empty($formValues['auto_renew'])) {
1110 $params['is_recur'] = $formValues['is_recur'] = TRUE;
1113 foreach ($this->_memTypeSelected
as $memType) {
1114 $recurMembershipTypeValues = CRM_Utils_Array
::value($memType,
1115 $this->allMembershipTypeDetails
, []
1117 if (!$recurMembershipTypeValues['auto_renew']) {
1121 'frequency_interval' => 'duration_interval',
1122 'frequency_unit' => 'duration_unit',
1123 ] as $mapVal => $mapParam) {
1124 $membershipTypeValues[$memType][$mapVal] = $recurMembershipTypeValues[$mapParam];
1127 $formValues[$mapVal] = CRM_Utils_Array
::value($mapParam,
1128 $recurMembershipTypeValues
1136 $isQuickConfig = $this->_priceSet
['is_quick_config'];
1140 $lineItem = [$this->_priceSetId
=> []];
1142 // BEGIN Fix for dev/core/issues/860
1143 // Prepare fee block and call buildAmount hook - based on CRM_Price_BAO_PriceSet::buildPriceSet().
1144 CRM_Price_BAO_PriceSet
::applyACLFinancialTypeStatusToFeeBlock($this->_priceSet
['fields']);
1145 CRM_Utils_Hook
::buildAmount('membership', $this, $this->_priceSet
['fields']);
1146 // END Fix for dev/core/issues/860
1148 CRM_Price_BAO_PriceSet
::processAmount($this->_priceSet
['fields'],
1149 $formValues, $lineItem[$this->_priceSetId
], $this->_priceSetId
);
1151 if (!empty($formValues['tax_amount'])) {
1152 $params['tax_amount'] = $formValues['tax_amount'];
1154 $params['total_amount'] = $formValues['amount'] ??
NULL;
1155 if (!empty($lineItem[$this->_priceSetId
])) {
1156 foreach ($lineItem[$this->_priceSetId
] as &$li) {
1157 if (!empty($li['membership_type_id'])) {
1158 if (!empty($li['membership_num_terms'])) {
1159 $termsByType[$li['membership_type_id']] = $li['membership_num_terms'];
1163 ///CRM-11529 for quick config backoffice transactions
1164 //when financial_type_id is passed in form, update the
1165 //lineitems with the financial type selected in form
1166 $submittedFinancialType = $formValues['financial_type_id'] ??
NULL;
1167 if ($isQuickConfig && $submittedFinancialType) {
1168 $li['financial_type_id'] = $submittedFinancialType;
1173 $params['contact_id'] = $this->_contactID
;
1179 'status_override_end_date',
1183 foreach ($fields as $f) {
1184 $params[$f] = $formValues[$f] ??
NULL;
1188 // when is_override false ignore is_admin statuses during membership
1189 // status calculation. similarly we did fix for import in CRM-3570.
1190 if (empty($params['is_override'])) {
1191 $params['exclude_is_admin'] = TRUE;
1194 // process date params to mysql date format.
1196 'join_date' => 'joinDate',
1197 'start_date' => 'startDate',
1198 'end_date' => 'endDate',
1200 foreach ($dateTypes as $dateField => $dateVariable) {
1201 $
$dateVariable = CRM_Utils_Date
::processDate($formValues[$dateField]);
1204 $memTypeNumTerms = empty($termsByType) ? CRM_Utils_Array
::value('num_terms', $formValues) : NULL;
1207 foreach ($this->_memTypeSelected
as $memType) {
1208 if (empty($memTypeNumTerms)) {
1209 $memTypeNumTerms = CRM_Utils_Array
::value($memType, $termsByType, 1);
1211 $calcDates[$memType] = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($memType,
1212 $joinDate, $startDate, $endDate, $memTypeNumTerms
1216 foreach ($calcDates as $memType => $calcDate) {
1217 foreach (array_keys($dateTypes) as $d) {
1218 //first give priority to form values then calDates.
1219 $date = $formValues[$d] ??
NULL;
1221 $date = $calcDate[$d] ??
NULL;
1224 $membershipTypeValues[$memType][$d] = CRM_Utils_Date
::processDate($date);
1228 foreach ($this->_memTypeSelected
as $memType) {
1229 if (array_key_exists('max_related', $formValues)) {
1230 // max related memberships - take from form or inherit from membership type
1231 $membershipTypeValues[$memType]['max_related'] = $formValues['max_related'] ??
NULL;
1233 $membershipTypeValues[$memType]['custom'] = CRM_Core_BAO_CustomField
::postProcess($formValues,
1237 $membershipTypes[$memType] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_MembershipType',
1242 $membershipType = implode(', ', $membershipTypes);
1244 // Retrieve the name and email of the current user - this will be the FROM for the receipt email
1245 list($userName) = CRM_Contact_BAO_Contact_Location
::getEmailDetails(CRM_Core_Session
::getLoggedInContactID());
1247 //CRM-13981, allow different person as a soft-contributor of chosen type
1248 if ($this->_contributorContactID
!= $this->_contactID
) {
1249 $params['contribution_contact_id'] = $this->_contributorContactID
;
1250 if (!empty($formValues['soft_credit_type_id'])) {
1251 $softParams['soft_credit_type_id'] = $formValues['soft_credit_type_id'];
1252 $softParams['contact_id'] = $this->_contactID
;
1256 $pendingMembershipStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Member_BAO_Membership', 'status_id', 'Pending');
1258 if (!empty($formValues['record_contribution'])) {
1259 $recordContribution = [
1261 'financial_type_id',
1262 'payment_instrument_id',
1264 'contribution_status_id',
1272 foreach ($recordContribution as $f) {
1273 $params[$f] = $formValues[$f] ??
NULL;
1276 if (!$this->_onlinePendingContributionId
) {
1277 if (empty($formValues['source'])) {
1278 $params['contribution_source'] = ts('%1 Membership: Offline signup (by %2)', [
1279 1 => $membershipType,
1284 $params['contribution_source'] = $formValues['source'];
1288 $completedContributionStatusId = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Completed');
1289 if (empty($params['is_override']) &&
1290 CRM_Utils_Array
::value('contribution_status_id', $params) != $completedContributionStatusId
1292 $params['status_id'] = $pendingMembershipStatusId;
1293 $params['skipStatusCal'] = TRUE;
1294 $params['is_pay_later'] = 1;
1295 $this->assign('is_pay_later', 1);
1298 if (!empty($formValues['send_receipt'])) {
1299 $params['receipt_date'] = $formValues['receive_date'] ??
NULL;
1302 //insert financial type name in receipt.
1303 $formValues['contributionType_name'] = CRM_Core_DAO
::getFieldValue('CRM_Financial_DAO_FinancialType',
1304 $formValues['financial_type_id']
1308 // process line items, until no previous line items.
1309 if (!empty($lineItem)) {
1310 $params['lineItems'] = $lineItem;
1311 $params['processPriceSet'] = TRUE;
1313 $createdMemberships = [];
1315 $params['total_amount'] = CRM_Utils_Array
::value('total_amount', $formValues, 0);
1317 //CRM-20264 : Store CC type and number (last 4 digit) during backoffice or online payment
1318 $params['card_type_id'] = $this->_params
['card_type_id'] ??
NULL;
1319 $params['pan_truncation'] = $this->_params
['pan_truncation'] ??
NULL;
1321 if (!$isQuickConfig) {
1322 $params['financial_type_id'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet',
1328 $params['financial_type_id'] = $formValues['financial_type_id'] ??
NULL;
1331 //get the payment processor id as per mode. Try removing in favour of beginPostProcess.
1332 $params['payment_processor_id'] = $formValues['payment_processor_id'] = $this->_paymentProcessor
['id'];
1333 $params['register_date'] = date('YmdHis');
1335 // add all the additional payment params we need
1336 $formValues['amount'] = $params['total_amount'];
1337 // @todo this is a candidate for beginPostProcessFunction.
1338 $formValues['currencyID'] = $config->defaultCurrency
;
1339 $formValues['description'] = ts("Contribution submitted by a staff person using member's credit card for signup");
1340 $formValues['invoiceID'] = md5(uniqid(rand(), TRUE));
1341 $formValues['financial_type_id'] = $params['financial_type_id'];
1343 // at this point we've created a contact and stored its address etc
1344 // all the payment processors expect the name and address to be in the
1345 // so we copy stuff over to first_name etc.
1346 $paymentParams = $formValues;
1347 $paymentParams['contactID'] = $this->_contributorContactID
;
1348 //CRM-10377 if payment is by an alternate contact then we need to set that person
1349 // as the contact in the payment params
1350 if ($this->_contributorContactID
!= $this->_contactID
) {
1351 if (!empty($formValues['soft_credit_type_id'])) {
1352 $softParams['contact_id'] = $params['contact_id'];
1353 $softParams['soft_credit_type_id'] = $formValues['soft_credit_type_id'];
1356 if (!empty($formValues['send_receipt'])) {
1357 $paymentParams['email'] = $this->_contributorEmail
;
1360 // This is a candidate for shared beginPostProcess function.
1361 // @todo Do we need this now we have $this->formatParamsForPaymentProcessor() ?
1362 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $formValues, $paymentParams, TRUE);
1363 // CRM-7137 -for recurring membership,
1364 // we do need contribution and recurring records.
1366 if (!empty($paymentParams['is_recur'])) {
1367 $financialType = new CRM_Financial_DAO_FinancialType();
1368 $financialType->id
= $params['financial_type_id'];
1369 $financialType->find(TRUE);
1370 $this->_params
= $formValues;
1372 $contribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($this,
1376 'contact_id' => $this->_contributorContactID
,
1377 'line_item' => $lineItem,
1378 'is_test' => $isTest,
1379 'campaign_id' => $paymentParams['campaign_id'] ??
NULL,
1380 'contribution_page_id' => $formValues['contribution_page_id'] ??
NULL,
1381 'source' => CRM_Utils_Array
::value('source', $paymentParams, CRM_Utils_Array
::value('description', $paymentParams)),
1382 'thankyou_date' => $paymentParams['thankyou_date'] ??
NULL,
1383 'payment_instrument_id' => $paymentInstrumentID,
1391 //create new soft-credit record, CRM-13981
1393 $softParams['contribution_id'] = $contribution->id
;
1394 $softParams['currency'] = $contribution->currency
;
1395 $softParams['amount'] = $contribution->total_amount
;
1396 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
1399 $paymentParams['contactID'] = $this->_contactID
;
1400 $paymentParams['contributionID'] = $contribution->id
;
1401 $paymentParams['contributionTypeID'] = $contribution->financial_type_id
;
1402 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
1403 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
1404 $params['contribution_id'] = $paymentParams['contributionID'];
1405 $params['contribution_recur_id'] = $paymentParams['contributionRecurID'];
1407 $paymentStatus = NULL;
1409 if ($params['total_amount'] > 0.0) {
1410 $payment = $this->_paymentProcessor
['object'];
1412 $result = $payment->doPayment($paymentParams);
1413 $formValues = array_merge($formValues, $result);
1414 $paymentStatus = CRM_Core_PseudoConstant
::getName('CRM_Contribute_BAO_Contribution', 'contribution_status_id', $formValues['payment_status_id']);
1415 // Assign amount to template if payment was successful.
1416 $this->assign('amount', $params['total_amount']);
1418 catch (\Civi\Payment\Exception\PaymentProcessorException
$e) {
1419 if (!empty($paymentParams['contributionID'])) {
1420 CRM_Contribute_BAO_Contribution
::failPayment($paymentParams['contributionID'], $this->_contactID
,
1423 if (!empty($paymentParams['contributionRecurID'])) {
1424 CRM_Contribute_BAO_ContributionRecur
::deleteRecurContribution($paymentParams['contributionRecurID']);
1427 CRM_Core_Session
::singleton()->setStatus($e->getMessage());
1428 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contact/view/membership',
1429 "reset=1&action=add&cid={$this->_contactID}&context=membership&mode={$this->_mode}"
1435 if ($paymentStatus !== 'Completed') {
1436 $params['status_id'] = $pendingMembershipStatusId;
1437 $params['skipStatusCal'] = TRUE;
1438 // unset send-receipt option, since receipt will be sent when ipn is received.
1439 unset($formValues['send_receipt'], $formValues['send_receipt']);
1440 //as membership is pending set dates to null.
1442 'join_date' => 'joinDate',
1443 'start_date' => 'startDate',
1444 'end_date' => 'endDate',
1446 foreach ($memberDates as $dv) {
1448 foreach ($this->_memTypeSelected
as $memType) {
1449 $membershipTypeValues[$memType][$dv] = NULL;
1453 $now = date('YmdHis');
1454 $params['receive_date'] = date('Y-m-d H:i:s');
1455 $params['invoice_id'] = $formValues['invoiceID'];
1456 $params['contribution_source'] = ts('%1 Membership Signup: Credit card or direct debit (by %2)',
1457 [1 => $membershipType, 2 => $userName]
1459 $params['source'] = $formValues['source'] ?
$formValues['source'] : $params['contribution_source'];
1460 $params['trxn_id'] = $result['trxn_id'] ??
NULL;
1461 $params['is_test'] = ($this->_mode
=== 'live') ?
0 : 1;
1462 if (!empty($formValues['send_receipt'])) {
1463 $params['receipt_date'] = $now;
1466 $params['receipt_date'] = NULL;
1469 $this->set('params', $formValues);
1470 $this->assign('trxn_id', CRM_Utils_Array
::value('trxn_id', $result));
1471 $this->assign('receive_date',
1472 CRM_Utils_Date
::mysqlToIso($params['receive_date'])
1475 // required for creating membership for related contacts
1476 $params['action'] = $this->_action
;
1478 //create membership record.
1480 foreach ($this->_memTypeSelected
as $memType) {
1482 ($relateContribution = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
))
1484 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
1487 $membershipParams = array_merge($membershipTypeValues[$memType], $params);
1489 if (!empty($softParams) && empty($paymentParams['is_recur'])) {
1490 $membershipParams['soft_credit'] = $softParams;
1492 if (isset($result['fee_amount'])) {
1493 $membershipParams['fee_amount'] = $result['fee_amount'];
1495 // This is required to trigger the recording of the membership contribution in the
1496 // CRM_Member_BAO_Membership::Create function.
1497 // @todo stop setting this & 'teach' the create function to respond to something
1498 // appropriate as part of our 2-step always create the pending contribution & then finally add the payment
1500 // @see http://wiki.civicrm.org/confluence/pages/viewpage.action?pageId=261062657#Payments&AccountsRoadmap-Movetowardsalwaysusinga2-steppaymentprocess
1501 $membershipParams['contribution_status_id'] = $result['payment_status_id'] ??
NULL;
1502 if (!empty($paymentParams['is_recur'])) {
1503 // The earlier process created the line items (although we want to get rid of the earlier one in favour
1504 // of a single path!
1505 unset($membershipParams['lineItems']);
1507 $membershipParams['payment_instrument_id'] = $paymentInstrumentID;
1508 // @todo stop passing $ids (membership and userId only are set above)
1509 $membership = CRM_Member_BAO_Membership
::create($membershipParams, $ids);
1510 $params['contribution'] = $membershipParams['contribution'] ??
NULL;
1511 unset($params['lineItems']);
1512 $this->_membershipIDs
[] = $membership->id
;
1513 $createdMemberships[$memType] = $membership;
1519 $params['action'] = $this->_action
;
1520 if ($this->_onlinePendingContributionId
&& !empty($formValues['record_contribution'])) {
1522 // update membership as well as contribution object, CRM-4395
1523 $params['contribution_id'] = $this->_onlinePendingContributionId
;
1524 $params['componentId'] = $params['id'];
1525 $params['componentName'] = 'contribute';
1526 $result = CRM_Contribute_BAO_Contribution
::transitionComponents($params, TRUE);
1527 if (!empty($result) && !empty($params['contribution_id'])) {
1529 $lineItems = CRM_Price_BAO_LineItem
::getLineItemsByContributionID($params['contribution_id']);
1530 $itemId = key($lineItems);
1531 $priceSetId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceField', $lineItems[$itemId]['price_field_id'], 'price_set_id');
1533 $lineItems[$itemId]['unit_price'] = $params['total_amount'];
1534 $lineItems[$itemId]['line_total'] = $params['total_amount'];
1535 $lineItems[$itemId]['id'] = $itemId;
1536 $lineItem[$priceSetId] = $lineItems;
1537 $contributionBAO = new CRM_Contribute_BAO_Contribution();
1538 $contributionBAO->id
= $params['contribution_id'];
1539 $contributionBAO->contact_id
= $params['contact_id'];
1540 $contributionBAO->find();
1541 CRM_Price_BAO_LineItem
::processPriceSet($params['contribution_id'], $lineItem, $contributionBAO, 'civicrm_membership');
1543 //create new soft-credit record, CRM-13981
1545 $softParams['contribution_id'] = $params['contribution_id'];
1546 while ($contributionBAO->fetch()) {
1547 $softParams['currency'] = $contributionBAO->currency
;
1548 $softParams['amount'] = $contributionBAO->total_amount
;
1550 CRM_Contribute_BAO_ContributionSoft
::add($softParams);
1554 //carry updated membership object.
1555 $membership = new CRM_Member_DAO_Membership();
1556 $membership->id
= $this->_id
;
1557 $membership->find(TRUE);
1560 if ($membership->end_date
) {
1561 //display end date w/ status message.
1562 $endDate = $membership->end_date
;
1564 if (!in_array($membership->status_id
, [
1566 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
1567 array_search('Expired', CRM_Member_PseudoConstant
::membershipStatus()),
1573 // suppress form values in template.
1574 $this->assign('cancelled', $cancelled);
1576 $createdMemberships[] = $membership;
1580 foreach ($this->_memTypeSelected
as $memType) {
1581 if ($count && !empty($formValues['record_contribution']) &&
1582 ($relateContribution = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
))
1584 $membershipTypeValues[$memType]['relate_contribution_id'] = $relateContribution;
1587 // @todo figure out why recieve_date isn't being set right here.
1588 if (empty($params['receive_date'])) {
1589 $params['receive_date'] = date('Y-m-d H:i:s');
1591 $membershipParams = array_merge($params, $membershipTypeValues[$memType]);
1592 if (!empty($formValues['int_amount'])) {
1594 foreach ($formValues as $key => $value) {
1595 if (strstr($key, 'txt-price')) {
1596 $init_amount[$key] = $value;
1599 $membershipParams['init_amount'] = $init_amount;
1602 if (!empty($softParams)) {
1603 $membershipParams['soft_credit'] = $softParams;
1605 // @todo stop passing $ids (membership and userId only are set above)
1606 $membership = CRM_Member_BAO_Membership
::create($membershipParams, $ids);
1607 $params['contribution'] = $membershipParams['contribution'] ??
NULL;
1608 unset($params['lineItems']);
1609 // skip line item creation for next interation since line item(s) are already created.
1610 $params['skipLineItem'] = TRUE;
1612 $this->_membershipIDs
[] = $membership->id
;
1613 $createdMemberships[$memType] = $membership;
1618 $isRecur = $params['is_recur'] ??
NULL;
1619 if (($this->_action
& CRM_Core_Action
::UPDATE
)) {
1620 $this->addStatusMessage($this->getStatusMessageForUpdate($membership, $endDate));
1622 elseif (($this->_action
& CRM_Core_Action
::ADD
)) {
1623 $this->addStatusMessage($this->getStatusMessageForCreate($endDate, $membershipTypes, $createdMemberships,
1624 $isRecur, $calcDates));
1627 if (!empty($lineItem[$this->_priceSetId
])) {
1628 $invoicing = Civi
::settings()->get('invoicing');
1630 $totalTaxAmount = 0;
1631 foreach ($lineItem[$this->_priceSetId
] as & $priceFieldOp) {
1632 if (!empty($priceFieldOp['membership_type_id'])) {
1633 $priceFieldOp['start_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'] ? CRM_Utils_Date
::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['start_date'], '%B %E%f, %Y') : '-';
1634 $priceFieldOp['end_date'] = $membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'] ? CRM_Utils_Date
::customFormat($membershipTypeValues[$priceFieldOp['membership_type_id']]['end_date'], '%B %E%f, %Y') : '-';
1637 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1639 if ($invoicing && isset($priceFieldOp['tax_amount'])) {
1641 $totalTaxAmount +
= $priceFieldOp['tax_amount'];
1646 foreach ($lineItem[$this->_priceSetId
] as $key => $value) {
1647 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
1648 if (isset($dataArray[$value['tax_rate']])) {
1649 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] + CRM_Utils_Array
::value('tax_amount', $value);
1652 $dataArray[$value['tax_rate']] = $value['tax_amount'] ??
NULL;
1657 $this->assign('totalTaxAmount', $totalTaxAmount);
1658 // Not sure why would need this on Submit.... unless it's being used when sending mails in which case this is the wrong place
1659 $this->assign('taxTerm', $this->getSalesTaxTerm());
1661 $this->assign('dataArray', $dataArray);
1664 $this->assign('lineItem', !empty($lineItem) && !$isQuickConfig ?
$lineItem : FALSE);
1666 $receiptSend = FALSE;
1667 $contributionId = CRM_Member_BAO_Membership
::getMembershipContributionId($membership->id
);
1668 $membershipIds = $this->_membershipIDs
;
1669 if ($contributionId && !empty($membershipIds)) {
1670 $contributionDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails(
1671 CRM_Export_Form_Select
::MEMBER_EXPORT
, $this->_membershipIDs
);
1672 if ($contributionDetails[$membership->id
]['contribution_status'] === 'Completed') {
1673 $receiptSend = TRUE;
1677 $receiptSent = FALSE;
1678 if (!empty($formValues['send_receipt']) && $receiptSend) {
1679 $formValues['contact_id'] = $this->_contactID
;
1680 $formValues['contribution_id'] = $contributionId;
1681 // We really don't need a distinct receipt_text_signup vs receipt_text_renewal as they are
1682 // handled in the receipt. But by setting one we avoid breaking templates for now
1683 // although at some point we should switch in the templates.
1684 $formValues['receipt_text_signup'] = $formValues['receipt_text'];
1685 // send email receipt
1686 $this->assignBillingName();
1687 $mailSend = $this->emailMembershipReceipt($formValues, $membership);
1688 $receiptSent = TRUE;
1691 // finally set membership id if already not set
1693 $this->_id
= $membership->id
;
1696 $this->updateContributionOnMembershipTypeChange($params, $membership);
1697 if ($receiptSent && $mailSend) {
1698 $this->addStatusMessage(ts('A membership confirmation and receipt has been sent to %1.', [1 => $this->_contributorEmail
]));
1701 CRM_Core_Session
::setStatus($this->getStatusMessage(), ts('Complete'), 'success');
1702 $this->setStatusMessage($membership);
1706 * Update related contribution of a membership if update_contribution_on_membership_type_change
1707 * contribution setting is enabled and type is changed on edit
1709 * @param array $inputParams
1710 * submitted form values
1711 * @param CRM_Member_DAO_Membership $membership
1712 * Updated membership object
1714 * @throws \CRM_Core_Exception
1715 * @throws \CiviCRM_API3_Exception
1717 protected function updateContributionOnMembershipTypeChange($inputParams, $membership) {
1718 if (Civi
::settings()->get('update_contribution_on_membership_type_change') &&
1720 ($this->_action
& CRM_Core_Action
::UPDATE
) &&
1723 // if selected membership doesn't match with earlier membership
1724 !in_array($this->_memType
, $this->_memTypeSelected
)
1726 if (!empty($inputParams['is_recur'])) {
1727 CRM_Core_Session
::setStatus(ts('Associated recurring contribution cannot be updated on membership type change.', ts('Error'), 'error'));
1731 // fetch lineitems by updated membership ID
1732 $lineItems = CRM_Price_BAO_LineItem
::getLineItems($membership->id
, 'membership');
1733 // retrieve the related contribution ID
1734 $contributionID = CRM_Core_DAO
::getFieldValue(
1735 'CRM_Member_DAO_MembershipPayment',
1740 // get price fields of chosen price-set
1741 $priceSetDetails = CRM_Utils_Array
::value(
1743 CRM_Price_BAO_PriceSet
::getSetDetail(
1750 // add price field information in $inputParams
1751 self
::addPriceFieldByMembershipType($inputParams, $priceSetDetails['fields'], $membership->membership_type_id
);
1753 // update related contribution and financial records
1754 CRM_Price_BAO_LineItem
::changeFeeSelections(
1759 $priceSetDetails['fields'],
1762 CRM_Core_Session
::setStatus(ts('Associated contribution is updated on membership type change.'), ts('Success'), 'success');
1767 * Add selected price field information in $formValues
1769 * @param array $formValues
1770 * submitted form values
1771 * @param array $priceFields
1772 * Price fields of selected Priceset ID
1773 * @param int $membershipTypeID
1774 * Selected membership type ID
1777 public static function addPriceFieldByMembershipType(&$formValues, $priceFields, $membershipTypeID) {
1778 foreach ($priceFields as $priceFieldID => $priceField) {
1779 if (isset($priceField['options']) && count($priceField['options'])) {
1780 foreach ($priceField['options'] as $option) {
1781 if ($option['membership_type_id'] == $membershipTypeID) {
1782 $formValues["price_{$priceFieldID}"] = $option['id'];
1791 * Set context in session.
1793 protected function setUserContext() {
1794 $buttonName = $this->controller
->getButtonName();
1795 $session = CRM_Core_Session
::singleton();
1797 if ($this->_context
=== 'standalone') {
1798 if ($buttonName == $this->getButtonName('upload', 'new')) {
1799 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/member/add',
1800 'reset=1&action=add&context=standalone'
1804 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view',
1805 "reset=1&cid={$this->_contactID}&selectedChild=member"
1809 elseif ($buttonName == $this->getButtonName('upload', 'new')) {
1810 $session->replaceUserContext(CRM_Utils_System
::url('civicrm/contact/view/membership',
1811 "reset=1&action=add&context=membership&cid={$this->_contactID}"
1817 * Get status message for updating membership.
1819 * @param CRM_Member_BAO_Membership $membership
1820 * @param string $endDate
1824 protected function getStatusMessageForUpdate($membership, $endDate) {
1825 // End date can be modified by hooks, so if end date is set then use it.
1826 $endDate = ($membership->end_date
) ?
$membership->end_date
: $endDate;
1828 $statusMsg = ts('Membership for %1 has been updated.', [1 => $this->_memberDisplayName
]);
1829 if ($endDate && $endDate !== 'null') {
1830 $endDate = CRM_Utils_Date
::customFormat($endDate);
1831 $statusMsg .= ' ' . ts('The membership End Date is %1.', [1 => $endDate]);
1837 * Get status message for create action.
1839 * @param string $endDate
1840 * @param array $membershipTypes
1841 * @param array $createdMemberships
1842 * @param bool $isRecur
1843 * @param array $calcDates
1845 * @return array|string
1847 protected function getStatusMessageForCreate($endDate, $membershipTypes, $createdMemberships,
1848 $isRecur, $calcDates) {
1849 // FIX ME: fix status messages
1852 foreach ($membershipTypes as $memType => $membershipType) {
1853 $statusMsg[$memType] = ts('%1 membership for %2 has been added.', [
1854 1 => $membershipType,
1855 2 => $this->_memberDisplayName
,
1858 $membership = $createdMemberships[$memType];
1859 $memEndDate = ($membership->end_date
) ?
$membership->end_date
: $endDate;
1861 //get the end date from calculated dates.
1862 if (!$memEndDate && !$isRecur) {
1863 $memEndDate = $calcDates[$memType]['end_date'] ??
NULL;
1866 if ($memEndDate && $memEndDate !== 'null') {
1867 $memEndDate = CRM_Utils_Date
::customFormat($memEndDate);
1868 $statusMsg[$memType] .= ' ' . ts('The new membership End Date is %1.', [1 => $memEndDate]);
1871 $statusMsg = implode('<br/>', $statusMsg);
1876 * @param $membership
1878 protected function setStatusMessage($membership) {
1880 // display message when membership type is changed
1881 if (($this->_action
& CRM_Core_Action
::UPDATE
) && $this->_id
&& !in_array($this->_memType
, $this->_memTypeSelected
)) {
1882 $lineItem = CRM_Price_BAO_LineItem
::getLineItems($this->_id
, 'membership');
1883 $maxID = max(array_keys($lineItem));
1884 $lineItem = $lineItem[$maxID];
1885 $membershipTypeDetails = $this->allMembershipTypeDetails
[$membership->membership_type_id
];
1886 if ($membershipTypeDetails['financial_type_id'] != $lineItem['financial_type_id']) {
1887 CRM_Core_Session
::setStatus(
1888 ts('The financial types associated with the old and new membership types are different. You may want to edit the contribution associated with this membership to adjust its financial type.'),
1892 if ($membershipTypeDetails['minimum_fee'] != $lineItem['line_total']) {
1893 CRM_Core_Session
::setStatus(
1894 ts('The cost of the old and new membership types are different. You may want to edit the contribution associated with this membership to adjust its amount.'),
1903 * @throws \CRM_Core_Exception
1905 protected function isUpdateToExistingRecurringMembership() {
1907 if ($this->_action
& CRM_Core_Action
::UPDATE
1908 && CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership', $this->getEntityId(),
1909 'contribution_recur_id')
1910 && !CRM_Member_BAO_Membership
::isSubscriptionCancelled($this->getEntityId())) {
1918 * Send a receipt for the membership.
1920 * @param array $formValues
1921 * @param \CRM_Member_BAO_Membership $membership
1924 * @throws \CRM_Core_Exception
1926 protected function emailMembershipReceipt($formValues, $membership) {
1927 $customValues = $this->getCustomValuesForReceipt($formValues, $membership);
1929 return self
::emailReceipt($this, $formValues, $membership, $customValues);
1933 * Filter the custom values from the input parameters (for display in the email).
1935 * @todo figure out why the scary code this calls does & document.
1937 * @param array $formValues
1938 * @param \CRM_Member_BAO_Membership $membership
1941 protected function getCustomValuesForReceipt($formValues, $membership) {
1942 $customFields = $customValues = [];
1943 if (property_exists($this, '_groupTree')
1944 && !empty($this->_groupTree
)
1946 foreach ($this->_groupTree
as $groupID => $group) {
1947 if ($groupID === 'info') {
1950 foreach ($group['fields'] as $k => $field) {
1951 $field['title'] = $field['label'];
1952 $customFields["custom_{$k}"] = $field;
1957 $members = [['member_id', '=', $membership->id
, 0, 0]];
1958 // check whether its a test drive
1959 if ($this->_mode
=== 'test') {
1960 $members[] = ['member_test', '=', 1, 0, 0];
1963 CRM_Core_BAO_UFGroup
::getValues($formValues['contact_id'], $customFields, $customValues, FALSE, $members);
1964 return $customValues;