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 * form to process actions on the group aspect of Custom Data
21 class CRM_Contribute_Form_Contribution_Confirm
extends CRM_Contribute_Form_ContributionBase
{
24 * The id of the contact associated with this contribution.
32 * The id of the contribution object that is created when the form is submitted.
36 public $_contributionID;
38 public $submitOnce = TRUE;
43 * @param $contributionParams
45 * @param $contribution
46 * @param $isEmailReceipt
49 public static function handlePledge(&$form, $params, $contributionParams, $pledgeID, $contribution, $isEmailReceipt) {
51 //when user doing pledge payments.
52 //update the schedule when payment(s) are made
53 $amount = $params['amount'];
54 $pledgePaymentParams = [];
55 foreach ($params['pledge_amount'] as $paymentId => $dontCare) {
56 $scheduledAmount = CRM_Core_DAO
::getFieldValue(
57 'CRM_Pledge_DAO_PledgePayment',
63 $pledgePayment = ($amount >= $scheduledAmount) ?
$scheduledAmount : $amount;
64 if ($pledgePayment > 0) {
65 $pledgePaymentParams[] = [
67 'contribution_id' => $contribution->id
,
68 'status_id' => $contribution->contribution_status_id
,
69 'actual_amount' => $pledgePayment,
71 $amount -= $pledgePayment;
74 if ($amount > 0 && count($pledgePaymentParams)) {
75 $pledgePaymentParams[count($pledgePaymentParams) - 1]['actual_amount'] +
= $amount;
77 foreach ($pledgePaymentParams as $p) {
78 CRM_Pledge_BAO_PledgePayment
::add($p);
81 //update pledge status according to the new payment statuses
82 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID);
86 //when user creating pledge record.
88 $pledgeParams['contact_id'] = $contribution->contact_id
;
89 $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount
;
90 $pledgeParams['contribution_id'] = $contribution->id
;
91 $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id
;
92 $pledgeParams['financial_type_id'] = $contribution->financial_type_id
;
93 $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
94 $pledgeParams['installments'] = $params['pledge_installments'];
95 $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
96 if ($pledgeParams['frequency_unit'] === 'month') {
97 $pledgeParams['frequency_day'] = intval(date("d"));
100 $pledgeParams['frequency_day'] = 1;
102 $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
103 if (!empty($params['start_date'])) {
104 $pledgeParams['frequency_day'] = intval(date("d", strtotime($params['start_date'])));
105 $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date('Ymd', strtotime($params['start_date']));
107 $pledgeParams['status_id'] = $contribution->contribution_status_id
;
108 $pledgeParams['max_reminders'] = $form->_values
['max_reminders'];
109 $pledgeParams['initial_reminder_day'] = $form->_values
['initial_reminder_day'];
110 $pledgeParams['additional_reminder_day'] = $form->_values
['additional_reminder_day'];
111 $pledgeParams['is_test'] = $contribution->is_test
;
112 $pledgeParams['acknowledge_date'] = date('Ymd');
113 $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount'];
115 //inherit campaign from contirb page.
116 $pledgeParams['campaign_id'] = $contributionParams['campaign_id'] ??
NULL;
118 $pledge = CRM_Pledge_BAO_Pledge
::create($pledgeParams);
120 $form->_params
['pledge_id'] = $pledge->id
;
122 //send acknowledgment email. only when pledge is created
123 if ($pledge->id
&& $isEmailReceipt) {
124 //build params to send acknowledgment.
125 $pledgeParams['id'] = $pledge->id
;
126 $pledgeParams['receipt_from_name'] = $form->_values
['receipt_from_name'];
127 $pledgeParams['receipt_from_email'] = $form->_values
['receipt_from_email'];
129 //scheduled amount will be same as installment_amount.
130 $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
132 //get total pledge amount.
133 $pledgeParams['total_pledge_amount'] = $pledge->amount
;
135 CRM_Pledge_BAO_Pledge
::sendAcknowledgment($form, $pledgeParams);
143 * Set the parameters to be passed to contribution create function.
145 * @param array $params
146 * @param int $financialTypeID
147 * @param array $paymentProcessorOutcome
148 * @param string $receiptDate
149 * @param int $recurringContributionID
152 * @throws \CRM_Core_Exception
154 public static function getContributionParams(
155 $params, $financialTypeID,
156 $paymentProcessorOutcome, $receiptDate, $recurringContributionID) {
157 $contributionParams = [
158 'financial_type_id' => $financialTypeID,
159 'receive_date' => !empty($params['receive_date']) ? CRM_Utils_Date
::processDate($params['receive_date']) : date('YmdHis'),
160 'tax_amount' => $params['tax_amount'] ??
NULL,
161 'amount_level' => $params['amount_level'] ??
NULL,
162 'invoice_id' => $params['invoiceID'],
163 'currency' => $params['currencyID'],
164 'is_pay_later' => $params['is_pay_later'] ??
0,
165 //configure cancel reason, cancel date and thankyou date
166 //from 'contribution' type profile if included
167 'cancel_reason' => $params['cancel_reason'] ??
0,
168 'cancel_date' => isset($params['cancel_date']) ? CRM_Utils_Date
::format($params['cancel_date']) : NULL,
169 'thankyou_date' => isset($params['thankyou_date']) ? CRM_Utils_Date
::format($params['thankyou_date']) : NULL,
170 //setting to make available to hook - although seems wrong to set on form for BAO hook availability
171 'skipLineItem' => $params['skipLineItem'] ??
0,
174 if ($paymentProcessorOutcome) {
175 $contributionParams['payment_processor'] = $paymentProcessorOutcome['payment_processor'] ??
NULL;
177 if (!empty($params["is_email_receipt"])) {
178 $contributionParams +
= [
179 'receipt_date' => $receiptDate,
183 if ($recurringContributionID) {
184 $contributionParams['contribution_recur_id'] = $recurringContributionID;
187 $contributionParams['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
188 if (isset($contributionParams['invoice_id'])) {
189 $contributionParams['id'] = CRM_Core_DAO
::getFieldValue(
190 'CRM_Contribute_DAO_Contribution',
191 $contributionParams['invoice_id'],
197 return $contributionParams;
201 * Get non-deductible amount.
203 * This is a bit too much about wierd form interpretation to be this deep.
205 * @see https://issues.civicrm.org/jira/browse/CRM-11885
206 * if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep
209 * @param array $params
210 * @param CRM_Financial_BAO_FinancialType $financialType
211 * @param bool $online
212 * @param CRM_Contribute_Form_Contribution_Confirm $form
216 public static function getNonDeductibleAmount($params, $financialType, $online, $form) {
217 if (isset($params['non_deductible_amount']) && (!empty($params['non_deductible_amount']))) {
218 return $params['non_deductible_amount'];
220 $priceSetId = $params['priceSetId'] ??
NULL;
221 // return non-deductible amount if it is set at the price field option level
222 if ($priceSetId && !empty($form->_lineItem
)) {
223 $nonDeductibleAmount = CRM_Price_BAO_PriceSet
::getNonDeductibleAmountFromPriceSet($priceSetId, $form->_lineItem
);
226 if (!empty($nonDeductibleAmount)) {
227 return $nonDeductibleAmount;
230 if ($financialType->is_deductible
) {
231 if ($online && isset($params['selectProduct'])) {
232 $selectProduct = $params['selectProduct'] ??
NULL;
234 if (!$online && isset($params['product_name'][0])) {
235 $selectProduct = $params['product_name'][0];
237 // if there is a product - compare the value to the contribution amount
238 if (isset($selectProduct) &&
239 $selectProduct !== 'no_thanks'
241 $productDAO = new CRM_Contribute_DAO_Product();
242 $productDAO->id
= $selectProduct;
243 $productDAO->find(TRUE);
244 // product value exceeds contribution amount
245 if ($params['amount'] < $productDAO->price
) {
246 $nonDeductibleAmount = $params['amount'];
247 return $nonDeductibleAmount;
249 // product value does NOT exceed contribution amount
251 return $productDAO->price
;
254 // contribution is deductible - but there is no product
259 // contribution is NOT deductible
261 return $params['amount'];
267 * Set variables up before form is built.
269 public function preProcess() {
270 parent
::preProcess();
272 // lineItem isn't set until Register postProcess
273 $this->_lineItem
= $this->get('lineItem');
274 $this->_ccid
= $this->get('ccid');
276 $this->_params
= $this->controller
->exportValues('Main');
277 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
278 $this->_params
['amount'] = $this->get('amount');
279 if (isset($this->_params
['amount'])) {
280 $this->setFormAmountFields($this->_params
['priceSetId']);
283 if (!empty($this->get('tax_amount'))) {
284 CRM_Core_Error
::deprecatedWarning('tax_amount should be not passed in');
285 $this->_params
['tax_amount'] = $this->get('tax_amount');
287 $this->_useForMember
= $this->get('useForMember');
289 CRM_Contribute_Form_AbstractEditPayment
::formatCreditCardDetails($this->_params
);
291 $this->_params
['currencyID'] = CRM_Core_Config
::singleton()->defaultCurrency
;
293 if (!empty($this->_membershipBlock
)) {
294 $this->_params
['selectMembership'] = $this->get('selectMembership');
296 if (!empty($this->_paymentProcessor
) && $this->_paymentProcessor
['object']->supports('preApproval')) {
297 $preApprovalParams = $this->_paymentProcessor
['object']->getPreApprovalDetails($this->get('pre_approval_parameters'));
298 $this->_params
= array_merge($this->_params
, $preApprovalParams);
300 // We may have fetched some billing details from the getPreApprovalDetails function so we
301 // want to ensure we set this after that function has been called.
302 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $preApprovalParams, $this->_params
, FALSE);
305 $this->_params
['is_pay_later'] = $this->get('is_pay_later');
306 $this->assign('is_pay_later', $this->_params
['is_pay_later']);
307 if ($this->_params
['is_pay_later']) {
308 $this->assign('pay_later_receipt', $this->_values
['pay_later_receipt'] ??
NULL);
310 // if onbehalf-of-organization
311 if (!empty($this->_values
['onbehalf_profile_id']) && !empty($this->_params
['onbehalf']['organization_name'])) {
312 if (empty($this->_params
['org_option']) && empty($this->_params
['organization_id'])) {
313 $this->_params
['organization_id'] = $this->_params
['onbehalfof_id'] ??
NULL;
315 $this->_params
['organization_name'] = $this->_params
['onbehalf']['organization_name'];
322 'supplemental_address_1',
323 'supplemental_address_2',
324 'supplemental_address_3',
325 'postal_code_suffix',
331 $blocks = ['email', 'phone', 'im', 'url', 'openid'];
332 foreach ($this->_params
['onbehalf'] as $loc => $value) {
333 $field = $typeId = NULL;
334 if (strstr($loc, '-')) {
335 [$field, $locType] = explode('-', $loc);
338 if (in_array($field, $addressBlocks)) {
339 if ($locType === 'Primary') {
340 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
341 $locType = $defaultLocationType->id
;
344 if ($field === 'country') {
345 $value = CRM_Core_PseudoConstant
::countryIsoCode($value);
347 elseif ($field === 'state_province') {
348 $value = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($value);
352 if (isset($this->_params
['onbehalf_location']['address'])
353 && count($this->_params
['onbehalf_location']['address']) > 0
358 $this->_params
['onbehalf_location']['address'][$locType][$field] = $value;
359 if (empty($this->_params
['onbehalf_location']['address'][$locType]['is_primary'])) {
360 $this->_params
['onbehalf_location']['address'][$locType]['is_primary'] = $isPrimary;
362 $this->_params
['onbehalf_location']['address'][$locType]['location_type_id'] = $locType;
364 elseif (in_array($field, $blocks)) {
365 if (!$typeId ||
is_numeric($typeId)) {
366 $blockName = $fieldName = $field;
367 $locationType = 'location_type_id';
368 if ($locType === 'Primary') {
369 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
370 $locationValue = $defaultLocationType->id
;
373 $locationValue = $locType;
378 if ($field === 'url') {
379 $blockName = 'website';
380 $locationType = 'website_type_id';
381 [$field, $locationValue] = explode('-', $loc);
383 elseif ($field === 'im') {
385 $locTypeId = 'provider_id';
386 $typeId = $this->_params
['onbehalf']["{$loc}-provider_id"];
388 elseif ($field == 'phone') {
389 [$field, $locType, $typeId] = explode('-', $loc);
390 $locTypeId = 'phone_type_id';
392 //check if extension field exists
393 $extField = str_replace('phone', 'phone_ext', $loc);
394 if (isset($this->_params
['onbehalf'][$extField])) {
395 $phoneExtField = ['phone_ext' => $this->_params
['onbehalf'][$extField]];
400 if (isset($this->_params
['onbehalf_location'][$blockName])
401 && count($this->_params
['onbehalf_location'][$blockName]) > 0
405 if ($locationValue) {
407 $fieldName => $value,
408 $locationType => $locationValue,
409 'is_primary' => $isPrimary,
413 $blockValues = array_merge($blockValues, [$locTypeId => $typeId]);
415 if (!empty($phoneExtField)) {
416 $blockValues = array_merge($blockValues, $phoneExtField);
419 $this->_params
['onbehalf_location'][$blockName][] = $blockValues;
423 elseif (strstr($loc, 'custom')) {
424 if ($value && isset($this->_params
['onbehalf']["{$loc}_id"])) {
425 $value = $this->_params
['onbehalf']["{$loc}_id"];
427 $this->_params
['onbehalf_location']["{$loc}"] = $value;
430 if ($loc === 'contact_sub_type') {
431 $this->_params
['onbehalf_location'][$loc] = $value;
434 $this->_params
['onbehalf_location'][$field] = $value;
439 elseif (!empty($this->_values
['is_for_organization'])) {
440 // no on behalf of an organization, CRM-5519
441 // so reset loc blocks from main params.
447 if (isset($this->_params
[$blk])) {
448 unset($this->_params
[$blk]);
452 $this->setRecurringMembershipParams();
455 $params = $this->processPcp($this, $this->_params
);
456 $this->_params
= $params;
458 $this->_params
['invoiceID'] = $this->get('invoiceID');
460 //carry campaign from profile.
461 if (array_key_exists('contribution_campaign_id', $this->_params
)) {
462 $this->_params
['campaign_id'] = $this->_params
['contribution_campaign_id'];
465 // assign contribution page id to the template so we can add css class for it
466 $this->assign('contributionPageID', $this->_id
);
467 $this->assign('is_for_organization', $this->_params
['is_for_organization'] ??
NULL);
469 $this->set('params', $this->_params
);
473 * Build the form object.
475 public function buildQuickForm() {
476 // FIXME: Some of this code is identical to Thankyou.php and should be broken out into a shared function
477 $this->assignToTemplate();
479 $params = $this->_params
;
480 // make sure we have values for it
481 if (!empty($this->_values
['honoree_profile_id']) && !empty($params['soft_credit_type_id']) && empty($this->_ccid
)) {
483 $softCreditTypes = CRM_Core_OptionGroup
::values("soft_credit_type", FALSE);
485 $this->assign('soft_credit_type', $softCreditTypes[$params['soft_credit_type_id']]);
486 CRM_Contribute_BAO_ContributionSoft
::formatHonoreeProfileFields($this, $params['honor']);
488 $fieldTypes = ['Contact'];
489 $fieldTypes[] = CRM_Core_BAO_UFGroup
::getContactType($this->_values
['honoree_profile_id']);
490 $this->buildCustom($this->_values
['honoree_profile_id'], 'honoreeProfileFields', TRUE, 'honor', $fieldTypes);
492 $this->assign('receiptFromEmail', $this->_values
['receipt_from_email'] ??
NULL);
493 $this->assign('amount_block_is_active', $this->isFormSupportsNonMembershipContributions());
495 // Make a copy of line items array to use for display only
496 $tplLineItems = $this->_lineItem
;
497 if (CRM_Invoicing_Utils
::isInvoicingEnabled()) {
499 foreach ($tplLineItems ??
[] as $lineItems) {
500 foreach ($lineItems as $lineItem) {
501 $taxAmount +
= (float) ($lineItem['tax_amount'] ??
0);
505 $this->assign('totalTaxAmount', $taxAmount);
506 $this->assign('taxTerm', CRM_Invoicing_Utils
::getTaxTerm());
509 $isDisplayLineItems = $this->_priceSetId
&& !CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config');
510 $this->assign('isDisplayLineItems', $isDisplayLineItems);
512 if (!$isDisplayLineItems) {
513 // quickConfig is deprecated in favour of isDisplayLineItems. Lots of logic has been harnessed to quick config
514 // whereas isDisplayLineItems is specific & clear.
515 $this->assign('is_quick_config', 1);
516 $this->_params
['is_quick_config'] = 1;
519 $this->assignLineItemsToTemplate($tplLineItems);
522 if (!empty($params['selectProduct']) && $params['selectProduct'] !== 'no_thanks') {
523 $option = $params['options_' . $params['selectProduct']] ??
NULL;
524 $productID = $params['selectProduct'];
525 CRM_Contribute_BAO_Premium
::buildPremiumBlock($this, $this->_id
, FALSE,
528 $this->set('productID', $productID);
529 $this->set('option', $option);
531 if (CRM_Core_Component
::isEnabled('CiviMember') && empty($this->_ccid
)) {
532 if (isset($params['selectMembership']) &&
533 $params['selectMembership'] !== 'no_thanks'
535 $this->buildMembershipBlock(
536 $this->_membershipContactID
,
537 $params['selectMembership']
539 if (!empty($params['auto_renew'])) {
540 $this->assign('auto_renew', TRUE);
544 $this->assign('membershipBlock', FALSE);
547 if (empty($this->_ccid
)) {
548 $this->buildCustom($this->_values
['custom_pre_id'], 'customPre', TRUE);
549 $this->buildCustom($this->_values
['custom_post_id'], 'customPost', TRUE);
552 if (!empty($this->_values
['onbehalf_profile_id']) &&
553 !empty($params['onbehalf']) &&
554 ($this->_values
['is_for_organization'] == 2 ||
555 !empty($params['is_for_organization'])
556 ) && empty($this->_ccid
)
558 $fieldTypes = ['Contact', 'Organization'];
559 $contactSubType = CRM_Contact_BAO_ContactType
::subTypes('Organization');
560 $fieldTypes = array_merge($fieldTypes, $contactSubType);
561 if (is_array($this->_membershipBlock
) && !empty($this->_membershipBlock
)) {
562 $fieldTypes = array_merge($fieldTypes, ['Membership']);
565 $fieldTypes = array_merge($fieldTypes, ['Contribution']);
568 $this->buildCustom($this->_values
['onbehalf_profile_id'], 'onbehalfProfile', TRUE, 'onbehalf', $fieldTypes);
571 $this->_separateMembershipPayment
= $this->get('separateMembershipPayment');
572 $this->assign('is_separate_payment', $this->_separateMembershipPayment
);
574 $this->assign('priceSetID', $this->_priceSetId
);
576 // The concept of contributeMode is deprecated.
577 if ($this->_contributeMode
=== 'notify' ||
578 $this->_amount
<= 0.0 ||
$this->_params
['is_pay_later']
580 $contribButton = ts('Continue');
582 elseif (!empty($this->_ccid
)) {
583 $contribButton = ts('Make Payment');
586 $contribButton = ts('Make Contribution');
588 $this->assign('button', $contribButton);
590 $this->assign('continueText',
591 $this->getPaymentProcessorObject()->getText('contributionPageContinueText', [
592 'is_payment_to_existing' => !empty($this->_ccid
),
593 'amount' => $this->_amount
,
600 'name' => $contribButton,
601 'spacing' => ' ',
606 'name' => ts('Go Back'),
611 $fields = array_fill_keys(array_keys($this->_fields
), 1);
612 $fields["billing_state_province-{$this->_bltID}"] = $fields["billing_country-{$this->_bltID}"] = $fields["email-{$this->_bltID}"] = 1;
614 $contact = $this->_params
;
615 foreach ($fields as $name => $dontCare) {
616 // Recursively set defaults for nested fields
617 if (isset($contact[$name]) && is_array($contact[$name]) && ($name === 'onbehalf' ||
$name === 'honor')) {
618 foreach ($contact[$name] as $fieldName => $fieldValue) {
619 if (is_array($fieldValue) && $this->_fields
[$name][$fieldName]['html_type'] === 'CheckBox') {
620 foreach ($fieldValue as $key => $value) {
621 $defaults["{$name}[{$fieldName}][{$key}]"] = $value;
625 $defaults["{$name}[{$fieldName}]"] = $fieldValue;
629 elseif (isset($contact[$name])) {
630 $defaults[$name] = $contact[$name];
631 if (substr($name, 0, 7) === 'custom_') {
632 $timeField = "{$name}_time";
633 if (isset($contact[$timeField])) {
634 $defaults[$timeField] = $contact[$timeField];
636 if (isset($contact["{$name}_id"])) {
637 $defaults["{$name}_id"] = $contact["{$name}_id"];
640 elseif (in_array($name, [
644 ]) && !empty($contact[$name . '_custom'])
646 $defaults[$name . '_custom'] = $contact[$name . '_custom'];
651 $this->assign('useForMember', $this->get('useForMember'));
653 $this->setDefaults($defaults);
659 * Build Membership Block in Contribution Pages.
660 * @todo this was shared on CRM_Contribute_Form_ContributionBase but we are refactoring and simplifying for each
661 * step (main/confirm/thankyou)
664 * Contact checked for having a current membership for a particular membership.
665 * @param int|array $selectedMembershipTypeID
666 * Selected membership id.
667 * @param null $isTest
670 * Is this a separate membership payment
672 * @throws \CiviCRM_API3_Exception
673 * @throws \CRM_Core_Exception
675 private function buildMembershipBlock($cid, $selectedMembershipTypeID = NULL, $isTest = NULL) {
676 $separateMembershipPayment = FALSE;
677 if ($this->_membershipBlock
) {
678 $this->_currentMemberships
= [];
680 $membershipTypeIds = $membershipTypes = $radio = $radioOptAttrs = [];
681 $membershipPriceset = (!empty($this->_priceSetId
) && $this->_useForMember
);
683 $autoRenewMembershipTypeOptions = [];
685 $separateMembershipPayment = $this->_membershipBlock
['is_separate_payment'] ??
NULL;
687 if ($membershipPriceset) {
688 foreach ($this->_priceSet
['fields'] as $pField) {
689 if (empty($pField['options'])) {
692 foreach ($pField['options'] as $opId => $opValues) {
693 if (empty($opValues['membership_type_id'])) {
696 $membershipTypeIds[$opValues['membership_type_id']] = $opValues['membership_type_id'];
700 elseif (!empty($this->_membershipBlock
['membership_types'])) {
701 $membershipTypeIds = explode(',', $this->_membershipBlock
['membership_types']);
704 if (!empty($membershipTypeIds)) {
705 //set status message if wrong membershipType is included in membershipBlock
706 if (isset($this->_mid
) && !$membershipPriceset) {
707 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
711 if (!in_array($membershipTypeID, $membershipTypeIds)) {
712 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');
716 $membershipTypeValues = CRM_Member_BAO_Membership
::buildMembershipTypeValues($this, $membershipTypeIds);
717 $this->_membershipTypeValues
= $membershipTypeValues;
720 // Check if we support auto-renew on this contribution page
721 // FIXME: If any of the payment processors do NOT support recurring you cannot setup an
722 // auto-renew payment even if that processor is not selected.
723 $allowAutoRenewOpt = TRUE;
724 if (is_array($this->_paymentProcessors
)) {
725 foreach ($this->_paymentProcessors
as $id => $val) {
726 if ($id && !$val['is_recur']) {
727 $allowAutoRenewOpt = FALSE;
731 foreach ($membershipTypeIds as $value) {
732 $memType = $membershipTypeValues[$value];
733 if ($selectedMembershipTypeID != NULL) {
734 if ($memType['id'] == $selectedMembershipTypeID) {
735 $this->assign('minimum_fee', $memType['minimum_fee'] ??
NULL);
736 $this->assign('membership_name', $memType['name']);
738 $membership = new CRM_Member_DAO_Membership();
739 $membership->contact_id
= $cid;
740 $membership->membership_type_id
= $memType['id'];
741 if ($membership->find(TRUE)) {
742 $this->assign('renewal_mode', TRUE);
743 $memType['current_membership'] = $membership->end_date
;
744 $this->_currentMemberships
[$membership->membership_type_id
] = $membership->membership_type_id
;
747 $membershipTypes[] = $memType;
750 elseif ($memType['is_active']) {
752 if ($allowAutoRenewOpt) {
753 $javascriptMethod = ['onclick' => "return showHideAutoRenew( this.value );"];
754 $isAvailableAutoRenew = $this->_membershipBlock
['auto_renew'][$value] ??
1;
755 $autoRenewMembershipTypeOptions["autoRenewMembershipType_{$value}"] = (int) $memType['auto_renew'] * $isAvailableAutoRenew;
756 $allowAutoRenewMembership = TRUE;
759 $javascriptMethod = NULL;
760 $autoRenewMembershipTypeOptions["autoRenewMembershipType_{$value}"] = 0;
763 //add membership type.
764 $radio[$memType['id']] = NULL;
765 $radioOptAttrs[$memType['id']] = $javascriptMethod;
767 $membership = new CRM_Member_DAO_Membership();
768 $membership->contact_id
= $cid;
769 $membership->membership_type_id
= $memType['id'];
771 //show current membership, skip pending and cancelled membership records,
772 //because we take first membership record id for renewal
773 $membership->whereAdd('status_id != 5 AND status_id !=6');
775 if (!is_null($isTest)) {
776 $membership->is_test
= $isTest;
780 $membership->orderBy('end_date DESC');
782 if ($membership->find(TRUE)) {
783 if (!$membership->end_date
) {
784 unset($radio[$memType['id']]);
785 unset($radioOptAttrs[$memType['id']]);
786 $this->assign('islifetime', TRUE);
789 $this->assign('renewal_mode', TRUE);
790 $this->_currentMemberships
[$membership->membership_type_id
] = $membership->membership_type_id
;
791 $memType['current_membership'] = $membership->end_date
;
793 $endDate = $memType['current_membership'];
794 $this->_defaultMemTypeId
= $memType['id'];
796 if ($memType['current_membership'] < $endDate) {
797 $endDate = $memType['current_membership'];
798 $this->_defaultMemTypeId
= $memType['id'];
802 $membershipTypes[] = $memType;
807 $this->assign('membershipBlock', $this->_membershipBlock
);
808 $this->assign('showRadio', FALSE);
809 $this->assign('membershipTypes', $membershipTypes);
810 $this->assign('autoRenewMembershipTypeOptions', json_encode($autoRenewMembershipTypeOptions));
811 //give preference to user submitted auto_renew value.
812 $takeUserSubmittedAutoRenew = (!empty($_POST) ||
$this->isSubmitted());
813 $this->assign('takeUserSubmittedAutoRenew', $takeUserSubmittedAutoRenew);
815 // Assign autorenew option (0:hide,1:optional,2:required) so we can use it in confirmation etc.
816 $autoRenewOption = CRM_Price_BAO_PriceSet
::checkAutoRenewForPriceSet($this->_priceSetId
);
817 //$selectedMembershipTypeID is retrieved as an array for membership priceset if multiple
818 //options for different organisation is selected on the contribution page.
819 if (is_numeric($selectedMembershipTypeID) && isset($membershipTypeValues[$selectedMembershipTypeID]['auto_renew'])) {
820 $this->assign('autoRenewOption', $membershipTypeValues[$selectedMembershipTypeID]['auto_renew']);
823 $this->assign('autoRenewOption', $autoRenewOption);
827 return $separateMembershipPayment;
833 * Since we are only showing elements in frozen mode no help display needed.
837 public function getAction() {
838 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
839 return CRM_Core_Action
::VIEW | CRM_Core_Action
::PREVIEW
;
842 return CRM_Core_Action
::VIEW
;
847 * Set default values for the form.
849 * Note that in edit/view mode
850 * the default values are retrieved from the database
852 public function setDefaultValues() {
858 public function postProcess() {
859 $contactID = $this->getContactID();
861 $result = $this->processFormSubmission($contactID);
863 catch (CRM_Core_Exception
$e) {
864 $this->bounceOnError($e->getMessage());
867 if (is_array($result) && !empty($result['is_payment_failure'])) {
868 $this->bounceOnError($result['error']->getMessage());
870 // Presumably this is for hooks to access? Not quite clear & perhaps not required.
871 $this->set('params', $this->_params
);
875 * Wrangle financial type ID.
877 * This wrangling of the financialType ID was happening in a shared function rather than in the form it relates to & hence has been moved to that form
878 * Pledges are not relevant to the membership code so that portion will not go onto the membership form.
880 * Comments from previous refactor indicate doubt as to what was going on.
882 * @param int $financialTypeID
884 * @return null|string
886 public function wrangleFinancialTypeID($financialTypeID) {
887 if (empty($financialTypeID) && !empty($this->_values
['pledge_id'])) {
888 $financialTypeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_Pledge',
889 $this->_values
['pledge_id'],
893 return $financialTypeID;
899 * @param array $premiumParams
900 * @param CRM_Contribute_BAO_Contribution $contribution
902 protected function postProcessPremium($premiumParams, $contribution) {
903 $hour = $minute = $second = 0;
904 // assigning Premium information to receipt tpl
905 $selectProduct = $premiumParams['selectProduct'] ??
NULL;
906 if ($selectProduct &&
907 $selectProduct != 'no_thanks'
909 $startDate = $endDate = "";
910 $this->assign('selectPremium', TRUE);
911 $productDAO = new CRM_Contribute_DAO_Product();
912 $productDAO->id
= $selectProduct;
913 $productDAO->find(TRUE);
914 $this->assign('product_name', $productDAO->name
);
915 $this->assign('price', $productDAO->price
);
916 $this->assign('sku', $productDAO->sku
);
917 $this->assign('option', $premiumParams['options_' . $premiumParams['selectProduct']] ??
NULL);
919 $periodType = $productDAO->period_type
;
922 $fixed_period_start_day = $productDAO->fixed_period_start_day
;
923 $duration_unit = $productDAO->duration_unit
;
924 $duration_interval = $productDAO->duration_interval
;
925 if ($periodType === 'rolling') {
926 $startDate = date('Y-m-d');
928 elseif ($periodType === 'fixed') {
929 if ($fixed_period_start_day) {
930 $date = explode('-', date('Y-m-d'));
931 $month = substr($fixed_period_start_day, 0, strlen($fixed_period_start_day) - 2);
932 $day = substr($fixed_period_start_day, -2) . "<br/>";
934 $startDate = $year . '-' . $month . '-' . $day;
937 $startDate = date('Y-m-d');
941 $date = explode('-', $startDate);
946 switch ($duration_unit) {
948 $year +
= $duration_interval;
952 $month +
= $duration_interval;
956 $day +
= $duration_interval;
960 $day +
= ($duration_interval * 7);
962 $endDate = date('Y-m-d H:i:s', mktime($hour, $minute, $second, $month, $day, $year));
963 $this->assign('start_date', $startDate);
964 $this->assign('end_date', $endDate);
967 $dao = new CRM_Contribute_DAO_Premium();
968 $dao->entity_table
= 'civicrm_contribution_page';
969 $dao->entity_id
= $this->_id
;
971 $this->assign('contact_phone', $dao->premiums_contact_phone
);
972 $this->assign('contact_email', $dao->premiums_contact_email
);
974 //create Premium record
976 'product_id' => $premiumParams['selectProduct'],
977 'contribution_id' => $contribution->id
,
978 'product_option' => $premiumParams['options_' . $premiumParams['selectProduct']] ??
NULL,
980 'start_date' => CRM_Utils_Date
::customFormat($startDate, '%Y%m%d'),
981 'end_date' => CRM_Utils_Date
::customFormat($endDate, '%Y%m%d'),
983 if (!empty($premiumParams['selectProduct'])) {
984 $daoPremiumsProduct = new CRM_Contribute_DAO_PremiumsProduct();
985 $daoPremiumsProduct->product_id
= $premiumParams['selectProduct'];
986 $daoPremiumsProduct->premiums_id
= $dao->id
;
987 $daoPremiumsProduct->find(TRUE);
988 $params['financial_type_id'] = $daoPremiumsProduct->financial_type_id
;
991 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
992 $daoContrProd->contribution_id
= $contribution->id
;
993 if ($daoContrProd->find(TRUE)) {
994 $params['id'] = $daoContrProd->id
;
997 CRM_Contribute_BAO_Contribution
::addPremium($params);
998 if ($productDAO->cost
&& !empty($params['financial_type_id'])) {
1000 'cost' => $productDAO->cost
,
1001 'currency' => $productDAO->currency
,
1002 'financial_type_id' => $params['financial_type_id'],
1003 'contributionId' => $contribution->id
,
1005 CRM_Core_BAO_FinancialTrxn
::createPremiumTrxn($trxnParams);
1008 elseif ($selectProduct === 'no_thanks') {
1009 //Fixed For CRM-3901
1010 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
1011 $daoContrProd->contribution_id
= $contribution->id
;
1012 if ($daoContrProd->find(TRUE)) {
1013 $daoContrProd->delete();
1019 * Process the contribution.
1021 * @param array $params
1022 * @param array $result
1023 * @param array $contributionParams
1024 * Parameters to be passed to contribution create action.
1025 * This differs from params in that we are currently adding params to it and 1) ensuring they are being
1026 * passed consistently & 2) documenting them here.
1031 * - contribution_page_id
1034 * - thankyou_date (not all forms will set this)
1036 * @param CRM_Financial_DAO_FinancialType $financialType
1037 * @param int $billingLocationID
1038 * ID of billing location type.
1039 * @param bool $isRecur
1040 * Is this recurring?
1042 * @return \CRM_Contribute_DAO_Contribution
1044 * @throws \CRM_Core_Exception
1045 * @throws \CiviCRM_API3_Exception
1046 * @todo - this code was previously shared with the backoffice form - some parts of this
1047 * function may relate to that form, not this one.
1050 protected function processFormContribution(
1053 $contributionParams,
1059 $transaction = new CRM_Core_Transaction();
1060 $contactID = $contributionParams['contact_id'];
1062 $isEmailReceipt = !empty($form->_values
['is_email_receipt']);
1063 $isSeparateMembershipPayment = !empty($params['separate_membership_payment']);
1064 $pledgeID = !empty($params['pledge_id']) ?
$params['pledge_id'] : $form->_values
['pledge_id'] ??
NULL;
1065 if (!$isSeparateMembershipPayment && !empty($form->_values
['pledge_block_id']) &&
1066 (!empty($params['is_pledge']) ||
$pledgeID)) {
1073 // add these values for the recurringContrib function ,CRM-10188
1074 $params['financial_type_id'] = $financialType->id
;
1076 $contributionParams['address_id'] = CRM_Contribute_BAO_Contribution
::createAddress($params, $billingLocationID);
1078 //@todo - this is being set from the form to resolve CRM-10188 - an
1079 // eNotice caused by it not being set @ the front end
1080 // however, we then get it being over-written with null for backend contributions
1081 // a better fix would be to set the values in the respective forms rather than require
1082 // a function being shared by two forms to deal with their respective values
1083 // moving it to the BAO & not taking the $form as a param would make sense here.
1084 if (!isset($params['is_email_receipt']) && $isEmailReceipt) {
1085 $params['is_email_receipt'] = $isEmailReceipt;
1087 $params['is_recur'] = $isRecur;
1088 $params['payment_instrument_id'] = $contributionParams['payment_instrument_id'] ??
NULL;
1089 $recurringContributionID = self
::processRecurringContribution($form, $params, $contactID, $financialType);
1091 $now = date('YmdHis');
1092 $receiptDate = $params['receipt_date'] ??
NULL;
1093 if ($isEmailReceipt) {
1094 $receiptDate = $now;
1097 if (isset($params['amount'])) {
1098 $contributionParams = array_merge(self
::getContributionParams(
1099 $params, $financialType->id
,
1100 $result, $receiptDate,
1101 $recurringContributionID), $contributionParams
1103 $contributionParams['non_deductible_amount'] = self
::getNonDeductibleAmount($params, $financialType, TRUE, $form);
1104 $contributionParams['skipCleanMoney'] = TRUE;
1105 // @todo this is the wrong place for this - it should be done as close to form submission
1107 $contributionParams['total_amount'] = $params['amount'];
1109 $contribution = CRM_Contribute_BAO_Contribution
::add($contributionParams);
1111 if (Civi
::settings()->get('invoicing')) {
1113 // @todo - interrogate the line items passed in on the params array.
1114 // No reason to assume line items will be set on the form.
1115 foreach ($form->_lineItem
as $lineItemKey => $lineItemValue) {
1116 foreach ($lineItemValue as $key => $value) {
1117 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
1118 if (isset($dataArray[$value['tax_rate']])) {
1119 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] +
$value['tax_amount'];
1122 $dataArray[$value['tax_rate']] = $value['tax_amount'];
1127 $smarty = CRM_Core_Smarty
::singleton();
1128 $smarty->assign('dataArray', $dataArray);
1131 // lets store it in the form variable so postProcess hook can get to this and use it
1132 $form->_contributionID
= $contribution->id
;
1134 // @fixme: This is assigned to the smarty template for the receipt. It's value should be calculated and not taken from $params.
1135 $form->assign('totalTaxAmount', $params['tax_amount'] ??
NULL);
1137 // process soft credit / pcp params first
1138 CRM_Contribute_BAO_ContributionSoft
::formatSoftCreditParams($params, $form);
1140 //CRM-13981, processing honor contact into soft-credit contribution
1141 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
1144 $form = self
::handlePledge($form, $params, $contributionParams, $pledgeID, $contribution, $isEmailReceipt);
1147 if ($contribution) {
1148 CRM_Core_BAO_CustomValueTable
::postProcess($params,
1149 'civicrm_contribution',
1155 if ($contribution && !empty($params['contribution_note'])) {
1157 'entity_table' => 'civicrm_contribution',
1158 'note' => $params['contribution_note'],
1159 'entity_id' => $contribution->id
,
1160 'contact_id' => $contribution->contact_id
,
1163 CRM_Core_BAO_Note
::add($noteParams, []);
1166 //create contribution activity w/ individual and target
1167 //activity w/ organisation contact id when onbelf, CRM-4027
1169 $targetContactID = NULL;
1170 if (!empty($params['onbehalf_contact_id'])) {
1172 'source_contact_id' => $params['onbehalf_contact_id'],
1173 'on_behalf' => TRUE,
1175 $targetContactID = $contribution->contact_id
;
1178 // create an activity record
1179 if ($contribution) {
1180 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Contribution', $targetContactID, $actParams);
1183 $transaction->commit();
1184 return $contribution;
1188 * Create the recurring contribution record.
1190 * @param CRM_Core_Form $form
1191 * @param array $params
1192 * @param int $contactID
1193 * @param string $contributionType
1197 public static function processRecurringContribution($form, $params, $contactID, $contributionType) {
1199 if (empty($params['is_recur'])) {
1203 $recurParams = ['contact_id' => $contactID];
1204 $recurParams['amount'] = $params['amount'] ??
NULL;
1205 $recurParams['auto_renew'] = $params['auto_renew'] ??
NULL;
1206 $recurParams['frequency_unit'] = $params['frequency_unit'] ??
NULL;
1207 $recurParams['frequency_interval'] = $params['frequency_interval'] ??
NULL;
1208 $recurParams['installments'] = $params['installments'] ??
NULL;
1209 $recurParams['financial_type_id'] = $params['financial_type_id'] ??
NULL;
1210 $recurParams['currency'] = $params['currency'] ??
NULL;
1211 $recurParams['payment_instrument_id'] = $params['payment_instrument_id'];
1213 // CRM-14354: For an auto-renewing membership with an additional contribution,
1214 // if separate payments is not enabled, make sure only the membership fee recurs
1215 if (!empty($form->_membershipBlock
)
1216 && $form->_membershipBlock
['is_separate_payment'] === '0'
1217 && isset($params['selectMembership'])
1218 && $form->_values
['is_allow_other_amount'] == '1'
1220 && !empty($form->_membershipTypeValues
)
1221 && !empty($form->_membershipTypeValues
[$params['selectMembership']]['minimum_fee'])
1223 $recurParams['amount'] = $form->_membershipTypeValues
[$params['selectMembership']]['minimum_fee'];
1226 $recurParams['is_test'] = 0;
1227 if (($form->_action
& CRM_Core_Action
::PREVIEW
) ||
1228 (isset($form->_mode
) && ($form->_mode
== 'test'))
1230 $recurParams['is_test'] = 1;
1233 $recurParams['start_date'] = $recurParams['create_date'] = $recurParams['modified_date'] = date('YmdHis');
1234 if (!empty($params['receive_date'])) {
1235 $recurParams['start_date'] = date('YmdHis', strtotime($params['receive_date']));
1237 $recurParams['invoice_id'] = $params['invoiceID'] ??
NULL;
1238 $recurParams['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1239 $recurParams['payment_processor_id'] = $params['payment_processor_id'] ??
NULL;
1240 $recurParams['is_email_receipt'] = (bool) ($params['is_email_receipt'] ??
FALSE);
1241 // We set trxn_id=invoiceID specifically for paypal IPN. It is reset this when paypal sends us the real trxn id, CRM-2991
1242 $recurParams['processor_id'] = $recurParams['trxn_id'] = ($params['trxn_id'] ??
$params['invoiceID']);
1243 $recurParams['financial_type_id'] = $contributionType->id
;
1245 $campaignId = $params['campaign_id'] ??
$form->_values
['campaign_id'] ??
NULL;
1246 $recurParams['campaign_id'] = $campaignId;
1247 $recurring = CRM_Contribute_BAO_ContributionRecur
::add($recurParams);
1248 if (is_a($recurring, 'CRM_Core_Error')) {
1249 CRM_Core_Error
::displaySessionError($recurring);
1250 $urlString = 'civicrm/contribute/transact';
1251 $urlParams = '_qf_Main_display=true';
1252 if (get_class($form) == 'CRM_Contribute_Form_Contribution') {
1253 $urlString = 'civicrm/contact/view/contribution';
1254 $urlParams = "action=add&cid={$form->_contactID}";
1256 $urlParams .= "&mode={$form->_mode}";
1259 CRM_Utils_System
::redirect(CRM_Utils_System
::url($urlString, $urlParams));
1261 $form->_params
['contributionRecurID'] = $recurring->id
;
1263 return $recurring->id
;
1267 * Add on behalf of organization and it's location.
1269 * This situation occurs when on behalf of is enabled for the contribution page and the person
1270 * signing up does so on behalf of an organization.
1272 * @param array $behalfOrganization
1273 * array of organization info.
1274 * @param int $contactID
1275 * individual contact id. One.
1276 * who is doing the process of signup / contribution.
1278 * @param array $values
1279 * form values array.
1280 * @param array $params
1281 * @param array $fields
1282 * Array of fields from the onbehalf profile relevant to the organization.
1284 public static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params, $fields = NULL) {
1285 $isNotCurrentEmployer = FALSE;
1288 if (!empty($behalfOrganization['organization_id'])) {
1289 $orgID = $behalfOrganization['organization_id'];
1290 unset($behalfOrganization['organization_id']);
1292 // create employer relationship with $contactID only when new organization is there
1293 // else retain the existing relationship
1295 $isNotCurrentEmployer = TRUE;
1299 // check if matching organization contact exists
1300 $dupeIDs = CRM_Contact_BAO_Contact
::getDuplicateContacts($behalfOrganization, 'Organization', 'Unsupervised', [], FALSE);
1302 // CRM-6243 says to pick the first org even if more than one match
1303 if (count($dupeIDs) >= 1) {
1304 $behalfOrganization['contact_id'] = $orgID = $dupeIDs[0];
1305 // don't allow name edit
1306 unset($behalfOrganization['organization_name']);
1310 // if found permissioned related organization, allow location edit
1311 $behalfOrganization['contact_id'] = $orgID;
1312 // don't allow name edit
1313 unset($behalfOrganization['organization_name']);
1316 // handling for image url
1317 if (!empty($behalfOrganization['image_URL'])) {
1318 CRM_Contact_BAO_Contact
::processImageParams($behalfOrganization);
1321 // create organization, add location
1322 $behalfOrganization['contact_type'] = 'Organization';
1323 $orgID = CRM_Contact_BAO_Contact
::createProfileContact($behalfOrganization, $fields, $orgID,
1324 NULL, NULL, 'Organization'
1326 // create relationship
1327 if ($isNotCurrentEmployer) {
1329 \Civi\Api4\Relationship
::create(FALSE)
1330 ->addValue('contact_id_a', $contactID)
1331 ->addValue('contact_id_b', $orgID)
1332 ->addValue('relationship_type_id', CRM_Contact_BAO_RelationshipType
::getEmployeeRelationshipTypeID())
1333 ->addValue('is_permission_a_b:name', 'View and update')
1336 catch (CRM_Core_Exception
$e) {
1337 // Ignore if duplicate relationship.
1338 if ($e->getMessage() !== 'Duplicate Relationship') {
1344 // if multiple match - send a duplicate alert
1345 if ($dupeIDs && (count($dupeIDs) > 1)) {
1346 $values['onbehalf_dupe_alert'] = 1;
1348 $params['onbehalf_dupe_alert'] = 1;
1351 // make sure organization-contact-id is considered for recording
1352 // contribution/membership etc..
1353 if ($contactID != $orgID) {
1354 // take a note of contact-id, so we can send the
1355 // receipt to individual contact as well.
1357 // required for mailing/template display ..etc
1358 $values['related_contact'] = $contactID;
1360 //CRM-19172: Create CMS user for individual on whose behalf organization is doing contribution
1361 $params['onbehalf_contact_id'] = $contactID;
1363 //make this employee of relationship as current
1364 //employer / employee relationship, CRM-3532
1365 if ($isNotCurrentEmployer &&
1366 ($orgID != CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id'))
1368 $isNotCurrentEmployer = FALSE;
1371 if (!$isNotCurrentEmployer && $orgID) {
1372 //build current employer params
1373 $currentEmpParams[$contactID] = $orgID;
1374 CRM_Contact_BAO_Contact_Utils
::setCurrentEmployer($currentEmpParams);
1377 // contribution / signup will be done using this
1379 $contactID = $orgID;
1384 * Function used to se pcp related defaults / params.
1386 * This is used by contribution and also event PCPs
1388 * @param CRM_Core_Form $page
1390 * @param array $params
1394 public static function processPcp(&$page, $params): array {
1395 $params['pcp_made_through_id'] = $page->_pcpId
;
1397 $page->assign('pcpBlock', FALSE);
1398 // display honor roll data only if it's enabled for the PCP page
1399 if (!empty($page->_pcpInfo
['is_honor_roll'])) {
1400 $page->assign('pcpBlock', TRUE);
1401 if (!empty($params['pcp_display_in_roll']) && empty($params['pcp_roll_nickname'])) {
1402 $params['pcp_roll_nickname'] = ts('Anonymous');
1403 $params['pcp_is_anonymous'] = 1;
1406 $params['pcp_is_anonymous'] = 0;
1409 'pcp_display_in_roll',
1411 'pcp_roll_nickname',
1412 'pcp_personal_note',
1414 if (!empty($params[$val])) {
1415 $page->assign($val, $params[$val]);
1424 * Process membership.
1426 * @param array $membershipParams
1427 * @param int $contactID
1428 * @param array $customFieldsFormatted
1429 * @param array $premiumParams
1430 * @param array $membershipLineItems
1431 * Line items specifically relating to memberships.
1433 protected function processMembership($membershipParams, $contactID, $customFieldsFormatted, $premiumParams,
1434 $membershipLineItems): void
{
1436 $membershipTypeIDs = (array) $membershipParams['selectMembership'];
1437 $membershipTypes = CRM_Member_BAO_Membership
::buildMembershipTypeValues($this, $membershipTypeIDs);
1438 $membershipType = empty($membershipTypes) ?
[] : reset($membershipTypes);
1440 $this->assign('membership_name', $membershipType['name']);
1441 $this->_values
['membership_name'] = $membershipType['name'] ??
NULL;
1443 $isPaidMembership = FALSE;
1444 if ($this->_amount
>= 0.0 && isset($membershipParams['amount'])) {
1445 //amount must be greater than zero for
1446 //adding contribution record to contribution table.
1447 //this condition arises when separate membership payment is
1448 //enabled and contribution amount is not selected. fix for CRM-3010
1449 $isPaidMembership = TRUE;
1451 $isProcessSeparateMembershipTransaction = $this->isSeparateMembershipTransaction($this->_id
);
1453 if ($this->isFormSupportsNonMembershipContributions()) {
1454 $financialTypeID = $this->_values
['financial_type_id'];
1457 $financialTypeID = $membershipType['financial_type_id'] ??
$membershipParams['financial_type_id'] ??
NULL;
1460 if (!empty($this->_params
['membership_source'])) {
1461 $membershipParams['contribution_source'] = $this->_params
['membership_source'];
1464 $this->postProcessMembership($membershipParams, $contactID, $premiumParams, $customFieldsFormatted, $membershipType, $membershipTypeIDs, $isPaidMembership, $this->_membershipId
, $isProcessSeparateMembershipTransaction, $financialTypeID,
1465 $membershipLineItems);
1467 $this->assign('membership_assign', TRUE);
1468 $this->set('membershipTypeID', $membershipParams['selectMembership']);
1472 * Process the Memberships.
1474 * @param array $membershipParams
1475 * Array of membership fields.
1476 * @param int $contactID
1479 * @param array $premiumParams
1480 * @param null $customFieldsFormatted
1482 * @param array $membershipDetails
1484 * @param array $membershipTypeIDs
1486 * @param bool $isPaidMembership
1487 * @param array $membershipID
1489 * @param bool $isProcessSeparateMembershipTransaction
1491 * @param int $financialTypeID
1492 * @param array $unprocessedLineItems
1493 * Line items for payment options chosen on the form.
1495 * @throws \CRM_Core_Exception
1496 * @throws \CiviCRM_API3_Exception
1497 * @throws \Civi\Payment\Exception\PaymentProcessorException
1499 protected function postProcessMembership(
1500 $membershipParams, $contactID, $premiumParams,
1501 $customFieldsFormatted, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID,
1502 $isProcessSeparateMembershipTransaction, $financialTypeID, $unprocessedLineItems) {
1503 // Assign $this to $form while we eliminate it.
1505 $membershipContribution = NULL;
1506 $isTest = $membershipParams['is_test'] ??
FALSE;
1507 $errors = $paymentResults = [];
1508 $form->_values
['isMembership'] = TRUE;
1509 $isRecurForFirstTransaction = $form->_params
['is_recur'] ??
$membershipParams['is_recur'] ??
NULL;
1511 $totalAmount = $membershipParams['amount'];
1513 if ($isPaidMembership) {
1514 if ($isProcessSeparateMembershipTransaction) {
1515 // If we have 2 transactions only one can use the invoice id.
1516 $membershipParams['invoiceID'] .= '-2';
1517 if (!empty($membershipParams['auto_renew'])) {
1518 $isRecurForFirstTransaction = FALSE;
1522 if (!$isProcessSeparateMembershipTransaction) {
1523 // Skip line items in the contribution processing transaction.
1524 // We will create them with the membership for proper linking.
1525 $membershipParams['skipLineItem'] = 1;
1528 $membershipParams['total_amount'] = $totalAmount;
1529 $membershipParams['skipLineItem'] = 0;
1530 CRM_Price_BAO_LineItem
::getLineItemArray($membershipParams);
1533 $paymentResult = $this->processConfirm(
1538 $isRecurForFirstTransaction
1540 if (!empty($paymentResult['contribution'])) {
1541 $paymentResults[] = ['contribution_id' => $paymentResult['contribution']->id
, 'result' => $paymentResult];
1542 $this->postProcessPremium($premiumParams, $paymentResult['contribution']);
1543 //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
1544 $membershipContribution = $paymentResult['contribution'];
1545 // Save the contribution ID so that I can be used in email receipts
1546 // For example, if you need to generate a tax receipt for the donation only.
1547 $form->_values
['contribution_other_id'] = $membershipContribution->id
;
1551 if ($isProcessSeparateMembershipTransaction) {
1553 $form->_lineItem
= $unprocessedLineItems;
1554 if (empty($form->_params
['auto_renew']) && !empty($membershipParams['is_recur'])) {
1555 unset($membershipParams['is_recur']);
1557 [$membershipContribution, $secondPaymentResult] = $this->processSecondaryFinancialTransaction($contactID, array_merge($membershipParams, ['skipLineItem' => 1]),
1558 $isTest, $unprocessedLineItems, $membershipDetails['minimum_fee'] ??
0, $membershipDetails['financial_type_id'] ??
NULL);
1559 $paymentResults[] = ['contribution_id' => $membershipContribution->id
, 'result' => $secondPaymentResult];
1560 $totalAmount = $membershipContribution->total_amount
;
1562 catch (CRM_Core_Exception
$e) {
1563 $errors[2] = $e->getMessage();
1564 $membershipContribution = NULL;
1569 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1570 $membershipContributionID = $membershipContribution->id
;
1573 //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
1574 if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
1575 $form->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
1577 //@todo it should no longer be possible for it to get to this point & membership to not be an array
1578 if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
1579 $typesTerms = $membershipParams['types_terms'] ??
[];
1581 $membershipLines = $nonMembershipLines = [];
1582 foreach ($unprocessedLineItems as $priceSetID => $lines) {
1583 foreach ($lines as $line) {
1584 if (!empty($line['membership_type_id'])) {
1585 $membershipLines[$line['membership_type_id']] = $line['price_field_value_id'];
1591 $form->_params
['createdMembershipIDs'] = [];
1592 foreach ($membershipTypeIDs as $memType) {
1593 $membershipLineItems = [];
1594 if ($i < count($membershipTypeIDs)) {
1595 $membershipLineItems[$priceSetID][$membershipLines[$memType]] = $unprocessedLineItems[$priceSetID][$membershipLines[$memType]];
1596 unset($unprocessedLineItems[$priceSetID][$membershipLines[$memType]]);
1599 $membershipLineItems = $unprocessedLineItems;
1602 $numTerms = $typesTerms[$memType] ??
1;
1603 $contributionRecurID = $form->_params
['contributionRecurID'] ??
NULL;
1605 $membershipSource = NULL;
1606 if (!empty($form->_params
['membership_source'])) {
1607 $membershipSource = $form->_params
['membership_source'];
1609 elseif ((isset($form->_values
['title']) && !empty($form->_values
['title'])) ||
(isset($form->_values
['frontend_title']) && !empty($form->_values
['frontend_title']))) {
1610 $title = !empty($form->_values
['frontend_title']) ?
$form->_values
['frontend_title'] : $form->_values
['title'];
1611 $membershipSource = ts('Online Contribution:') . ' ' . $title;
1614 if (isset($form->_params
)) {
1615 $isPayLater = $form->_params
['is_pay_later'] ??
NULL;
1618 'campaign_id' => $form->_params
['campaign_id'] ??
($form->_values
['campaign_id'] ??
NULL),
1621 // @todo Move this into CRM_Member_BAO_Membership::processMembership
1622 if (!empty($membershipContribution)) {
1623 $pending = $membershipContribution->contribution_status_id
== CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1626 // The concept of contributeMode is deprecated.
1627 // the is_monetary concept probably should be too as it can be calculated from
1628 // the existence of 'amount' & seems fragile.
1629 if (((isset($this->_contributeMode
)) ||
!empty($this->_params
['is_pay_later'])
1631 (($this->_values
['is_monetary'] && $this->_amount
> 0.0))
1638 [$membership, $renewalMode, $dates] = self
::legacyProcessMembership(
1639 $contactID, $memType, $isTest,
1640 date('YmdHis'), $membershipParams['cms_contactID'] ??
NULL,
1641 $customFieldsFormatted,
1642 $numTerms, $membershipID, $pending,
1643 $contributionRecurID, $membershipSource, $isPayLater, $memParams, $membershipContribution,
1644 $membershipLineItems
1647 $form->set('renewal_mode', $renewalMode);
1648 if (!empty($dates)) {
1649 $form->assign('mem_start_date', CRM_Utils_Date
::customFormat($dates['start_date'], '%Y%m%d'));
1650 $form->assign('mem_end_date', CRM_Utils_Date
::customFormat($dates['end_date'], '%Y%m%d'));
1653 if (!empty($membershipContribution)) {
1654 // Next line is probably redundant. Checks prevent it happening twice.
1655 $membershipPaymentParams = [
1656 'membership_id' => $membership->id
,
1657 'membership_type_id' => $membership->membership_type_id
,
1658 'contribution_id' => $membershipContribution->id
,
1660 civicrm_api3('MembershipPayment', 'create', $membershipPaymentParams);
1663 CRM_Core_BAO_CustomValueTable
::postProcess($form->_params
, 'civicrm_membership', $membership->id
, 'Membership');
1664 $form->_params
['createdMembershipIDs'][] = $membership->id
;
1665 $form->_params
['membershipID'] = $membership->id
;
1667 //CRM-15232: Check if membership is created and on the basis of it use
1668 //membership receipt template to send payment receipt
1669 $form->_values
['isMembership'] = TRUE;
1672 if ($form->_priceSetId
&& !empty($form->_useForMember
) && !empty($form->_lineItem
)) {
1673 foreach ($form->_lineItem
[$form->_priceSetId
] as & $priceFieldOp) {
1674 if (!empty($priceFieldOp['membership_type_id']) && $membership->membership_type_id
== $priceFieldOp['membership_type_id']) {
1675 $membershipOb = $membership;
1676 $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date
::formatDateOnlyLong($membershipOb->start_date
) : '-';
1677 $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date
::formatDateOnlyLong($membershipOb->end_date
) : '-';
1680 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1683 $form->_values
['lineItem'] = $form->_lineItem
;
1684 $form->assign('lineItem', $form->_lineItem
);
1688 if (!empty($errors)) {
1689 $message = $this->compileErrorMessage($errors);
1690 throw new CRM_Core_Exception($message);
1693 if (isset($membershipContributionID)) {
1694 $form->_values
['contribution_id'] = $membershipContributionID;
1697 if (empty($form->_params
['is_pay_later']) && $form->_paymentProcessor
) {
1698 // the is_monetary concept probably should be deprecated as it can be calculated from
1699 // the existence of 'amount' & seems fragile.
1700 if ($form->_values
['is_monetary'] && $form->_amount
> 0.0 && !$form->_params
['is_pay_later']) {
1701 // call postProcess hook before leaving
1702 $form->postProcessHook();
1705 $payment = Civi\Payment\System
::singleton()->getByProcessor($form->_paymentProcessor
);
1706 // The contribution_other_id is effectively the ID for the only contribution or the non-membership contribution.
1707 // Since we have called the membership contribution (in a 2 contribution scenario) this is out
1708 // primary-contribution compared to that - but let's face it - it's all just too hard & confusing at the moment!
1709 $paymentParams = array_merge($form->_params
, ['contributionID' => $form->_values
['contribution_other_id']]);
1711 // CRM-19792 : set necessary fields for payment processor
1712 CRM_Core_Payment_Form
::mapParams($form->_bltID
, $paymentParams, $paymentParams, TRUE);
1714 // If this is a single membership-related contribution, it won't have
1715 // be performed yet, so do it now.
1716 if ($isPaidMembership && !$isProcessSeparateMembershipTransaction) {
1717 $paymentActionResult = $payment->doPayment($paymentParams);
1718 $paymentResults[] = ['contribution_id' => $paymentResult['contribution']->id
, 'result' => $paymentActionResult];
1720 // Do not send an email if Recurring transaction is done via Direct Mode
1721 // Email will we sent when the IPN is received.
1722 foreach ($paymentResults as $result) {
1723 //CRM-18211: Fix situation where second contribution doesn't exist because it is optional.
1724 if ($result['contribution_id']) {
1725 if (($result['result']['payment_status_id'] ??
NULL) == 1) {
1727 civicrm_api3('contribution', 'completetransaction', [
1728 'id' => $result['contribution_id'],
1729 'trxn_id' => $result['result']['trxn_id'] ??
NULL,
1730 'payment_processor_id' => $result['result']['payment_processor_id'] ??
$this->_paymentProcessor
['id'],
1731 'is_transactional' => FALSE,
1732 'fee_amount' => $result['result']['fee_amount'] ??
NULL,
1733 'receive_date' => $result['result']['receive_date'] ??
NULL,
1734 'card_type_id' => $result['result']['card_type_id'] ??
NULL,
1735 'pan_truncation' => $result['result']['pan_truncation'] ??
NULL,
1738 catch (CiviCRM_API3_Exception
$e) {
1739 if ($e->getErrorCode() != 'contribution_completed') {
1740 \Civi
::log()->error('CRM_Contribute_Form_Contribution_Confirm::completeTransaction CiviCRM_API3_Exception: ' . $e->getMessage());
1741 throw new CRM_Core_Exception('Failed to update contribution in database');
1750 $emailValues = array_merge($membershipParams, $form->_values
);
1751 $emailValues['membership_assign'] = 1;
1752 $emailValues['useForMember'] = !empty($form->_useForMember
);
1754 // Finally send an email receipt for pay-later scenario (although it might sometimes be caught above!)
1755 if ($totalAmount == 0) {
1756 // This feels like a bizarre hack as the variable name doesn't seem to be directly connected to it's use in the template.
1757 $emailValues['useForMember'] = 0;
1758 $emailValues['amount'] = 0;
1760 //CRM-18071, where on selecting $0 free membership payment section got hidden and
1761 // also it reset any payment processor selection result into pending free membership
1762 // so its a kind of hack to complete free membership at this point since there is no $form->_paymentProcessor info
1763 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1764 if (empty($form->_paymentProcessor
)) {
1765 // @todo this can maybe go now we are setting payment_processor_id = 0 more reliably.
1766 $paymentProcessorIDs = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_values
['payment_processor'] ??
NULL);
1767 $this->_paymentProcessor
['id'] = $paymentProcessorIDs[0];
1770 civicrm_api3('contribution', 'completetransaction', [
1771 'id' => $membershipContribution->id
,
1772 'payment_processor_id' => $this->_paymentProcessor
['id'],
1773 'is_transactional' => FALSE,
1776 catch (CiviCRM_API3_Exception
$e) {
1777 if ($e->getErrorCode() != 'contribution_completed') {
1778 \Civi
::log()->error('CRM_Contribute_Form_Contribution_Confirm::completeTransaction CiviCRM_API3_Exception: ' . $e->getMessage());
1779 throw new CRM_Core_Exception('Failed to update contribution in database');
1783 // return as completeTransaction() already sends the receipt mail.
1787 CRM_Contribute_BAO_ContributionPage
::sendMail($contactID,
1790 ['Contact', 'Organization', 'Membership']
1795 * Turn array of errors into message string.
1797 * @param array $errors
1801 protected function compileErrorMessage($errors) {
1802 foreach ($errors as $error) {
1803 if (is_string($error)) {
1804 $message[] = $error;
1807 return ts('Payment Processor Error message') . ': ' . implode('<br/>', $message);
1811 * Where a second separate financial transaction is supported we will process it here.
1813 * @param int $contactID
1814 * @param array $tempParams
1815 * @param bool $isTest
1816 * @param array $lineItems
1817 * @param $minimumFee
1818 * @param int $financialTypeID
1822 * @throws \CRM_Core_Exception
1823 * @throws \CiviCRM_API3_Exception
1824 * @throws \Civi\Payment\Exception\PaymentProcessorException
1826 private function processSecondaryFinancialTransaction($contactID, $tempParams, $isTest, $lineItems, $minimumFee,
1827 $financialTypeID): array {
1828 $financialType = new CRM_Financial_DAO_FinancialType();
1829 $financialType->id
= $financialTypeID;
1830 $financialType->find(TRUE);
1831 $tempParams['amount'] = $minimumFee;
1832 $tempParams['invoiceID'] = md5(uniqid(rand(), TRUE));
1833 $isRecur = $tempParams['is_recur'] ??
NULL;
1835 //assign receive date when separate membership payment
1836 //and contribution amount not selected.
1837 if ($this->_amount
== 0) {
1838 $now = date('YmdHis');
1839 $this->_params
['receive_date'] = $now;
1840 $receiveDate = CRM_Utils_Date
::mysqlToIso($now);
1841 $this->set('params', $this->_params
);
1842 $this->assign('receive_date', $receiveDate);
1845 $this->set('membership_amount', $minimumFee);
1846 $this->assign('membership_amount', $minimumFee);
1848 //set this variable as we are not creating pledge for
1849 //separate membership payment contribution.
1850 //so for differentiating membership contribution from
1851 //main contribution.
1852 $this->_params
['separate_membership_payment'] = 1;
1853 $contributionParams = [
1854 'contact_id' => $contactID,
1855 'line_item' => $lineItems,
1856 'is_test' => $isTest,
1857 'campaign_id' => $tempParams['campaign_id'] ??
$this->_values
['campaign_id'] ??
NULL,
1858 'contribution_page_id' => $this->_id
,
1859 'source' => $tempParams['source'] ??
$tempParams['description'] ??
NULL,
1861 $isMonetary = !empty($this->_values
['is_monetary']);
1863 if (empty($paymentParams['is_pay_later'])) {
1864 $contributionParams['payment_instrument_id'] = $this->_paymentProcessor
['payment_instrument_id'];
1868 // CRM-19792 : set necessary fields for payment processor
1869 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $tempParams, TRUE);
1871 $membershipContribution = $this->processFormContribution(
1874 $contributionParams,
1882 // We're not processing the line item here because we are processing a membership.
1883 // To ensure processing of the correct parameters, replace relevant parameters
1884 // in $tempParams with those in $membershipContribution.
1885 $tempParams['amount_level'] = $membershipContribution->amount_level
;
1886 $tempParams['total_amount'] = $membershipContribution->total_amount
;
1887 $tempParams['tax_amount'] = $membershipContribution->tax_amount
;
1888 $tempParams['contactID'] = $membershipContribution->contact_id
;
1889 $tempParams['financialTypeID'] = $membershipContribution->financial_type_id
;
1890 $tempParams['invoiceID'] = $membershipContribution->invoice_id
;
1891 $tempParams['trxn_id'] = $membershipContribution->trxn_id
;
1892 $tempParams['contributionID'] = $membershipContribution->id
;
1894 if ($this->_values
['is_monetary'] && !$this->_params
['is_pay_later'] && $minimumFee > 0.0) {
1895 // At the moment our tests are calling this form in a way that leaves 'object' empty. For
1896 // now we compensate here.
1897 if (empty($this->_paymentProcessor
['object'])) {
1898 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1901 $payment = $this->_paymentProcessor
['object'];
1903 $result = $payment->doPayment($tempParams);
1904 $this->set('membership_trx_id', $result['trxn_id']);
1905 $this->assign('membership_trx_id', $result['trxn_id']);
1908 return [$membershipContribution, $result];
1912 * Are we going to do 2 financial transactions.
1914 * Ie the membership block supports a separate transactions AND the contribution form has been configured for a
1916 * transaction AND a membership transaction AND the payment processor supports double financial transactions (ie. NOT doTransferCheckout style)
1918 * @param int $formID
1922 protected function isSeparateMembershipTransaction($formID): bool {
1923 $memBlockDetails = CRM_Member_BAO_Membership
::getMembershipBlock($formID);
1924 if (!empty($memBlockDetails['is_separate_payment']) && $this->isFormSupportsNonMembershipContributions()) {
1931 * This function sets the fields.
1933 * - $this->_params['amount_level']
1934 * - $this->_params['selectMembership']
1935 * And under certain circumstances sets
1936 * $this->_params['amount'] = null;
1938 * @param int $priceSetID
1940 public function setFormAmountFields($priceSetID) {
1941 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params
['priceSetId'], 'is_quick_config');
1942 $priceField = new CRM_Price_DAO_PriceField();
1943 $priceField->price_set_id
= $priceSetID;
1944 $priceField->orderBy('weight');
1945 $priceField->find();
1946 $paramWeDoNotUnderstand = NULL;
1948 while ($priceField->fetch()) {
1949 if ($priceField->name
== "contribution_amount") {
1950 $paramWeDoNotUnderstand = $priceField->id
;
1952 if ($isQuickConfig && !empty($this->_params
["price_{$priceField->id}"])) {
1953 if ($this->_values
['fee'][$priceField->id
]['html_type'] != 'Text') {
1954 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1955 // function to get correct amount level consistently. Remove setting of the amount level in
1956 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1957 // to cover all variants.
1958 $this->_params
['amount_level'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1959 $this->_params
["price_{$priceField->id}"], 'label');
1961 if ($priceField->name
== "membership_amount") {
1962 $this->_params
['selectMembership'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1963 $this->_params
["price_{$priceField->id}"], 'membership_type_id');
1966 // If separate payment we set contribution amount to be null, so that it will not show contribution amount same
1967 // as membership amount.
1968 // @todo - this needs more documentation - it appears the setting to null is tied up with separate membership payments
1969 // but the circumstances are very confusing. Many of these conditions are repeated in the next conditional
1970 // so we should merge them together
1971 // the quick config seems like a red-herring - if this is about a separate membership payment then there
1972 // are 2 types of line items - membership ones & non-membership ones - regardless of whether quick config is set
1974 !empty($this->_membershipBlock
['is_separate_payment'])
1975 && !empty($this->_values
['fee'][$priceField->id
])
1976 && ($this->_values
['fee'][$priceField->id
]['name'] == "other_amount")
1977 && ($this->_params
["price_{$paramWeDoNotUnderstand}"] ??
NULL) < 1
1978 && empty($this->_params
["price_{$priceField->id}"])
1980 $this->_params
['amount'] = NULL;
1983 // Fix for CRM-14375 - If we are using separate payments and "no
1984 // thank you" is selected for the additional contribution, set
1985 // contribution amount to be null, so that it will not show
1986 // contribution amount same as membership amount.
1987 //@todo - merge with section above
1988 if (!empty($this->_membershipBlock
['is_separate_payment'])
1989 && !empty($this->_values
['fee'][$priceField->id
])
1990 && ($this->_values
['fee'][$priceField->id
]['name'] ??
NULL) == 'contribution_amount'
1991 && ($this->_params
["price_{$priceField->id}"] ??
NULL) == '-1'
1993 $this->_params
['amount'] = NULL;
2001 * @param array $params
2003 * @throws \CRM_Core_Exception
2004 * @throws \CiviCRM_API3_Exception
2005 * @throws \Civi\API\Exception\UnauthorizedException
2007 public static function submit($params) {
2008 $form = new CRM_Contribute_Form_Contribution_Confirm();
2009 $form->_id
= $params['id'];
2011 CRM_Contribute_BAO_ContributionPage
::setValues($form->_id
, $form->_values
);
2012 $form->_separateMembershipPayment
= CRM_Contribute_BAO_ContributionPage
::getIsMembershipPayment($form->_id
);
2013 //this way the mocked up controller ignores the session stuff
2014 $_SERVER['REQUEST_METHOD'] = 'GET';
2015 $form->controller
= new CRM_Contribute_Controller_Contribution();
2016 $params['invoiceID'] = md5(uniqid(rand(), TRUE));
2018 $paramsProcessedForForm = $form->_params
= self
::getFormParams($params['id'], $params);
2020 $order = new CRM_Financial_BAO_Order();
2021 $order->setPriceSetIDByContributionPageID($params['id']);
2022 $order->setPriceSelectionFromUnfilteredInput($params);
2023 if (isset($params['amount']) && !CRM_Contribute_BAO_ContributionPage
::getIsMembershipPayment($form->_id
)) {
2024 // @todo deprecate receiving amount, calculate on the form.
2025 $order->setOverrideTotalAmount((float) $params['amount']);
2027 $amount = $order->getTotalAmount();
2028 if ($form->_separateMembershipPayment
) {
2029 $amount -= $order->getMembershipTotalAmount();
2031 $form->_amount
= $params['amount'] = $form->_params
['amount'] = $amount;
2032 // hack these in for test support.
2033 $form->_fields
['billing_first_name'] = 1;
2034 $form->_fields
['billing_last_name'] = 1;
2035 // CRM-18854 - Set form values to allow pledge to be created for api test.
2036 if (!empty($params['pledge_block_id'])) {
2037 $form->_values
['pledge_id'] = $params['pledge_id'] ??
NULL;
2038 $form->_values
['pledge_block_id'] = $params['pledge_block_id'];
2039 $pledgeBlock = CRM_Pledge_BAO_PledgeBlock
::getPledgeBlock($params['id']);
2040 $form->_values
['max_reminders'] = $pledgeBlock['max_reminders'];
2041 $form->_values
['initial_reminder_day'] = $pledgeBlock['initial_reminder_day'];
2042 $form->_values
['additional_reminder_day'] = $pledgeBlock['additional_reminder_day'];
2043 $form->_values
['is_email_receipt'] = FALSE;
2045 $priceSetID = $form->_params
['priceSetId'] = $paramsProcessedForForm['price_set_id'];
2046 $priceFields = CRM_Price_BAO_PriceSet
::getSetDetail($priceSetID);
2047 $priceSetFields = reset($priceFields);
2048 $form->_values
['fee'] = $priceSetFields['fields'];
2049 $form->_priceSetId
= $priceSetID;
2050 $form->setFormAmountFields($priceSetID);
2053 $capabilities[] = (ucfirst($form->_mode
) . 'Mode');
2055 $form->_paymentProcessors
= CRM_Financial_BAO_PaymentProcessor
::getPaymentProcessors($capabilities);
2056 $form->_params
['payment_processor_id'] = $params['payment_processor_id'] ??
0;
2057 if ($form->_params
['payment_processor_id'] !== '') {
2058 // It can be blank with a $0 transaction - then no processor needs to be selected
2059 $form->_paymentProcessor
= $form->_paymentProcessors
[$form->_params
['payment_processor_id']];
2061 if (!empty($params['payment_processor_id'])) {
2062 // The concept of contributeMode is deprecated as is the billing_mode concept.
2063 if ($form->_paymentProcessor
['billing_mode'] == 1) {
2064 $form->_contributeMode
= 'direct';
2067 $form->_contributeMode
= 'notify';
2071 if (!empty($params['useForMember'])) {
2072 $form->set('useForMember', 1);
2073 $form->_useForMember
= 1;
2075 $priceFields = $priceFields[$priceSetID]['fields'];
2077 $form->_lineItem
= [$priceSetID => $order->getLineItems()];
2078 $membershipPriceFieldIDs = [];
2079 foreach ($order->getLineItems() as $lineItem) {
2080 if (!empty($lineItem['membership_type_id'])) {
2081 $form->set('useForMember', 1);
2082 $form->_useForMember
= 1;
2083 $membershipPriceFieldIDs['id'] = $priceSetID;
2084 $membershipPriceFieldIDs[] = $lineItem['price_field_value_id'];
2087 $form->set('memberPriceFieldIDS', $membershipPriceFieldIDs);
2088 $form->setRecurringMembershipParams();
2089 $form->processFormSubmission($params['contact_id'] ??
NULL);
2093 * Helper function for static submit function.
2095 * Set relevant params - help us to build up an array that we can pass in.
2098 * @param array $params
2101 * @throws CiviCRM_API3_Exception
2103 public static function getFormParams($id, array $params) {
2104 if (!isset($params['is_pay_later'])) {
2105 if (!empty($params['payment_processor_id'])) {
2106 $params['is_pay_later'] = 0;
2108 elseif (($params['amount'] ??
0) !== 0) {
2109 $params['is_pay_later'] = civicrm_api3('contribution_page', 'getvalue', [
2111 'return' => 'is_pay_later',
2115 if (empty($params['price_set_id'])) {
2116 $params['price_set_id'] = CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution_page', $params['id']);
2122 * Post form submission handling.
2124 * This is also called from the test suite.
2126 * @param int $contactID
2130 * @throws \CRM_Core_Exception
2131 * @throws \CiviCRM_API3_Exception
2132 * @throws \Civi\API\Exception\UnauthorizedException
2134 protected function processFormSubmission($contactID) {
2135 if (!isset($this->_params
['payment_processor_id'])) {
2136 // If there is no processor we are using the pay-later manual pseudo-processor.
2137 // (note it might make sense to make this a row in the processor table in the db).
2138 $this->_params
['payment_processor_id'] = 0;
2140 if (isset($this->_params
['payment_processor_id']) && $this->_params
['payment_processor_id'] === 0) {
2141 $this->_params
['is_pay_later'] = $isPayLater = TRUE;
2144 if (!empty($this->_ccid
)) {
2145 $this->_params
['contribution_id'] = $this->_ccid
;
2147 //Set email-bltID if pre/post profile contains an email.
2148 if ($this->_emailExists
== TRUE) {
2149 foreach ($this->_params
as $key => $val) {
2150 if (substr($key, 0, 6) == 'email-' && empty($this->_params
["email-{$this->_bltID}"])) {
2151 $this->_params
["email-{$this->_bltID}"] = $this->_params
[$key];
2155 // add a description field at the very beginning
2156 $title = !empty($this->_values
['frontend_title']) ?
$this->_values
['frontend_title'] : $this->_values
['title'];
2157 $this->_params
['description'] = ts('Online Contribution') . ': ' . (!empty($this->_pcpInfo
['title']) ?
$this->_pcpInfo
['title'] : $title);
2159 $this->_params
['accountingCode'] = $this->_values
['accountingCode'] ??
NULL;
2162 $this->_params
['currencyID'] = CRM_Core_Config
::singleton()->defaultCurrency
;
2164 CRM_Contribute_Form_AbstractEditPayment
::formatCreditCardDetails($this->_params
);
2167 if (!empty($this->_params
['is_pledge']) && empty($this->_values
['pledge_id']) && !empty($this->_values
['adjust_recur_start_date'])) {
2168 $pledgeBlock = CRM_Pledge_BAO_PledgeBlock
::getPledgeBlock($this->_id
);
2169 if (!empty($this->_params
['start_date']) ||
empty($pledgeBlock['is_pledge_start_date_visible'])
2170 ||
empty($pledgeBlock['is_pledge_start_date_editable'])) {
2171 $pledgeStartDate = $this->_params
['start_date'] ??
NULL;
2172 $this->_params
['receive_date'] = CRM_Pledge_BAO_Pledge
::getPledgeStartDate($pledgeStartDate, $pledgeBlock);
2173 $recurParams = CRM_Pledge_BAO_Pledge
::buildRecurParams($this->_params
);
2174 $this->_params
= array_merge($this->_params
, $recurParams);
2178 //carry payment processor id.
2179 if (!empty($this->_paymentProcessor
['id'])) {
2180 $this->_params
['payment_processor_id'] = $this->_paymentProcessor
['id'];
2183 $premiumParams = $membershipParams = $params = $this->_params
;
2184 if (!empty($params['image_URL'])) {
2185 CRM_Contact_BAO_Contact
::processImageParams($params);
2188 $fields = ['email-Primary' => 1];
2190 // get the add to groups
2193 // now set the values for the billing location.
2194 foreach ($this->_fields
as $name => $value) {
2197 // get the add to groups for uf fields
2198 if (!empty($value['add_to_group_id'])) {
2199 $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id'];
2203 $fields = $this->formatParamsForPaymentProcessor($fields);
2205 // billing email address
2206 $fields["email-{$this->_bltID}"] = 1;
2208 // if onbehalf-of-organization contribution, take out
2209 // organization params in a separate variable, to make sure
2210 // normal behavior is continued. And use that variable to
2211 // process on-behalf-of functionality.
2212 if (!empty($this->_values
['onbehalf_profile_id']) && empty($this->_ccid
)) {
2213 $behalfOrganization = [];
2214 $orgFields = ['organization_name', 'organization_id', 'org_option'];
2215 foreach ($orgFields as $fld) {
2216 if (array_key_exists($fld, $params)) {
2217 $behalfOrganization[$fld] = $params[$fld];
2218 unset($params[$fld]);
2222 if (is_array($params['onbehalf']) && !empty($params['onbehalf'])) {
2223 foreach ($params['onbehalf'] as $fld => $values) {
2224 if (strstr($fld, 'custom_')) {
2225 $behalfOrganization[$fld] = $values;
2227 elseif (!(strstr($fld, '-'))) {
2228 if (in_array($fld, [
2229 'contribution_campaign_id',
2230 'member_campaign_id',
2232 $fld = 'campaign_id';
2235 $behalfOrganization[$fld] = $values;
2237 $this->_params
[$fld] = $values;
2242 if (array_key_exists('onbehalf_location', $params) && is_array($params['onbehalf_location'])) {
2243 foreach ($params['onbehalf_location'] as $block => $vals) {
2244 //fix for custom data (of type checkbox, multi-select)
2245 if (substr($block, 0, 7) == 'custom_') {
2248 // fix the index of block elements
2249 if (is_array($vals)) {
2250 foreach ($vals as $key => $val) {
2251 //dont adjust the index of address block as
2252 //it's index is WRT to location type
2253 $newKey = ($block == 'address') ?
$key : ++
$key;
2254 $behalfOrganization[$block][$newKey] = $val;
2258 unset($params['onbehalf_location']);
2260 if (!empty($params['onbehalf[image_URL]'])) {
2261 $behalfOrganization['image_URL'] = $params['onbehalf[image_URL]'];
2265 // check for profile double opt-in and get groups to be subscribed
2266 $subscribeGroupIds = CRM_Core_BAO_UFGroup
::getDoubleOptInGroupIds($params, $contactID);
2268 // since we are directly adding contact to group lets unset it from mailing
2269 if (!empty($addToGroups)) {
2270 foreach ($addToGroups as $groupId) {
2271 if (isset($subscribeGroupIds[$groupId])) {
2272 unset($subscribeGroupIds[$groupId]);
2277 foreach ($addToGroups as $k) {
2278 if (array_key_exists($k, $subscribeGroupIds)) {
2279 unset($addToGroups[$k]);
2283 if (empty($contactID)) {
2284 $dupeParams = $params;
2285 if (!empty($dupeParams['onbehalf'])) {
2286 unset($dupeParams['onbehalf']);
2288 if (!empty($dupeParams['honor'])) {
2289 unset($dupeParams['honor']);
2292 $contactID = CRM_Contact_BAO_Contact
::getFirstDuplicateContact($dupeParams, 'Individual', 'Unsupervised', [], FALSE);
2294 // Fetch default greeting id's if creating a contact
2296 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
2297 if (!isset($params[$greeting])) {
2298 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting('Individual', $greeting);
2302 $contactType = NULL;
2305 $contactType = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'contact_type');
2307 $contactID = CRM_Contact_BAO_Contact
::createProfileContact(
2317 // Make the contact ID associated with the contribution available at the Class level.
2318 // Also make available to the session.
2319 //@todo consider handling this in $this->getContactID();
2320 $this->set('contactID', $contactID);
2321 $this->_contactID
= $contactID;
2323 //get email primary first if exist
2324 $subscriptionEmail = ['email' => $params['email-Primary'] ??
NULL];
2325 if (!$subscriptionEmail['email']) {
2326 $subscriptionEmail['email'] = $params["email-{$this->_bltID}"] ??
NULL;
2328 // subscribing contact to groups
2329 if (!empty($subscribeGroupIds) && $subscriptionEmail['email']) {
2330 CRM_Mailing_Event_BAO_Subscribe
::commonSubscribe($subscribeGroupIds, $subscriptionEmail, $contactID);
2333 // If onbehalf-of-organization contribution / signup, add organization
2334 // and it's location.
2335 if (isset($this->_values
['onbehalf_profile_id']) &&
2336 isset($behalfOrganization['organization_name']) &&
2337 ($this->_values
['is_for_organization'] == 2 ||
2338 !empty($this->_params
['is_for_organization'])
2342 foreach ($this->_fields
['onbehalf'] as $name => $value) {
2343 $ufFields[$name] = 1;
2345 self
::processOnBehalfOrganization($behalfOrganization, $contactID, $this->_values
,
2346 $this->_params
, $ufFields
2349 elseif (!empty($this->_membershipContactID
) && $contactID != $this->_membershipContactID
) {
2350 // this is an onbehalf renew case for inherited membership. For e.g a permissioned member of household,
2351 // store current user id as related contact for later use for mailing / activity..
2352 $this->_values
['related_contact'] = $contactID;
2353 $this->_params
['related_contact'] = $contactID;
2354 // swap contact like we do for on-behalf-org case, so parent/primary membership is affected
2355 $contactID = $this->_membershipContactID
;
2358 // lets store the contactID in the session
2359 // for things like tell a friend
2360 $session = CRM_Core_Session
::singleton();
2361 if (!$session->get('userID')) {
2362 $session->set('transaction.userID', $contactID);
2365 $session->set('transaction.userID', NULL);
2368 $this->_useForMember
= $this->get('useForMember');
2370 // store the fact that this is a membership and membership type is selected
2371 if ($this->isMembershipSelected($membershipParams)) {
2372 $this->doMembershipProcessing($contactID, $membershipParams, $premiumParams, $this->_lineItem
);
2375 // at this point we've created a contact and stored its address etc
2376 // all the payment processors expect the name and address to be in the
2377 // so we copy stuff over to first_name etc.
2378 $paymentParams = $this->_params
;
2379 // Make it explict that we are letting the processConfirm function figure out the line items.
2380 $paymentParams['skipLineItem'] = 0;
2382 if (!isset($paymentParams['line_item'])) {
2383 $paymentParams['line_item'] = $this->_lineItem
;
2386 if (!empty($paymentParams['onbehalf']) &&
2387 is_array($paymentParams['onbehalf'])
2389 foreach ($paymentParams['onbehalf'] as $key => $value) {
2390 if (strstr($key, 'custom_')) {
2391 $this->_params
[$key] = $value;
2396 $result = $this->processConfirm($paymentParams,
2398 $this->wrangleFinancialTypeID($this->_values
['financial_type_id']),
2399 ($this->_mode
== 'test') ?
1 : 0,
2400 $paymentParams['is_recur'] ??
NULL
2403 if (empty($result['is_payment_failure'])) {
2404 // @todo move premium processing to complete transaction if it truly is an 'after' action.
2405 $this->postProcessPremium($premiumParams, $result['contribution']);
2407 if (!empty($result['contribution'])) {
2408 // It seems this line is hit when there is a zero dollar transaction & in tests, not sure when else.
2409 if (($result['payment_status_id'] ??
NULL) == 1) {
2411 civicrm_api3('contribution', 'completetransaction', [
2412 'id' => $result['contribution']->id
,
2413 'trxn_id' => $result['trxn_id'] ??
NULL,
2414 'payment_processor_id' => $result['payment_processor_id'] ??
$this->_paymentProcessor
['id'],
2415 'is_transactional' => FALSE,
2416 'fee_amount' => $result['fee_amount'] ??
NULL,
2417 'receive_date' => $result['receive_date'] ??
NULL,
2418 'card_type_id' => $result['card_type_id'] ??
NULL,
2419 'pan_truncation' => $result['pan_truncation'] ??
NULL,
2422 catch (CiviCRM_API3_Exception
$e) {
2423 if ($e->getErrorCode() != 'contribution_completed') {
2424 \Civi
::log()->error('CRM_Contribute_Form_Contribution_Confirm::completeTransaction CiviCRM_API3_Exception: ' . $e->getMessage());
2425 throw new CRM_Core_Exception('Failed to update contribution in database');
2435 * Return True/False if we have a membership selected on the contribution page
2436 * @param array $membershipParams
2440 private function isMembershipSelected($membershipParams) {
2441 $priceFieldIds = $this->get('memberPriceFieldIDS');
2442 if ((!empty($membershipParams['selectMembership']) && $membershipParams['selectMembership'] != 'no_thanks')
2443 && empty($priceFieldIds)) {
2447 $membershipParams = $this->getMembershipParamsFromPriceSet($membershipParams);
2449 return !empty($membershipParams['selectMembership']);
2453 * Extract the selected memberships from a priceSet
2455 * @param array $membershipParams
2459 private function getMembershipParamsFromPriceSet($membershipParams) {
2460 $priceFieldIds = $this->get('memberPriceFieldIDS');
2461 if (empty($priceFieldIds)) {
2462 return $membershipParams;
2464 $membershipParams['financial_type_id'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceFieldIds['id'], 'financial_type_id');
2465 unset($priceFieldIds['id']);
2466 $membershipTypeIds = [];
2467 $membershipTypeTerms = [];
2468 foreach ($priceFieldIds as $priceFieldId) {
2469 $membershipTypeId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id');
2470 if ($membershipTypeId) {
2471 $membershipTypeIds[] = $membershipTypeId;
2472 $term = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_num_terms') ?
: 1;
2473 $membershipTypeTerms[$membershipTypeId] = ($term > 1) ?
$term : 1;
2476 $membershipParams['selectMembership'] = $membershipTypeIds;
2477 $membershipParams['types_terms'] = $membershipTypeTerms;
2478 return $membershipParams;
2482 * Membership processing section.
2484 * This is in a separate function as part of a move towards refactoring.
2486 * @param int $contactID
2487 * @param array $membershipParams
2488 * @param array $premiumParams
2489 * @param array $formLineItems
2491 protected function doMembershipProcessing($contactID, $membershipParams, $premiumParams, $formLineItems) {
2492 if (!$this->_useForMember
) {
2493 $this->assign('membership_assign', TRUE);
2494 $this->set('membershipTypeID', $this->_params
['selectMembership']);
2497 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
2498 $membershipParams['is_test'] = 1;
2500 if ($this->_params
['is_pay_later']) {
2501 $membershipParams['is_pay_later'] = 1;
2504 if (isset($this->_params
['onbehalf_contact_id'])) {
2505 $membershipParams['onbehalf_contact_id'] = $this->_params
['onbehalf_contact_id'];
2507 //inherit campaign from contribution page.
2508 if (!array_key_exists('campaign_id', $membershipParams)) {
2509 $membershipParams['campaign_id'] = $this->_values
['campaign_id'] ??
NULL;
2512 $this->_params
= CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $membershipParams, TRUE);
2514 // This could be set by a hook.
2515 if (!empty($this->_params
['installments'])) {
2516 $membershipParams['installments'] = $this->_params
['installments'];
2518 // added new parameter for cms user contact id, needed to distinguish behaviour for on behalf of sign-ups
2519 if (isset($this->_params
['related_contact'])) {
2520 $membershipParams['cms_contactID'] = $this->_params
['related_contact'];
2523 $membershipParams['cms_contactID'] = $contactID;
2526 if (!empty($membershipParams['onbehalf']) &&
2527 is_array($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])
2529 $this->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
2532 $customFieldsFormatted = [];
2533 if (!empty($membershipParams['onbehalf']) &&
2534 is_array($membershipParams['onbehalf'])
2536 foreach ($membershipParams['onbehalf'] as $key => $value) {
2537 if (strstr($key, 'custom_')) {
2538 $customFieldId = explode('_', $key);
2539 CRM_Core_BAO_CustomField
::formatCustomField(
2541 $customFieldsFormatted,
2551 $membershipParams = $this->getMembershipParamsFromPriceSet($membershipParams);
2552 if (!empty($membershipParams['selectMembership'])) {
2554 $membershipLineItems = $formLineItems;
2555 if ($this->_separateMembershipPayment
&& $this->isFormSupportsNonMembershipContributions()) {
2556 $membershipLineItems = [];
2557 foreach ($this->_values
['fee'] as $key => $feeValues) {
2558 if ($feeValues['name'] == 'membership_amount') {
2559 $fieldId = $this->_params
['price_' . $key];
2560 $membershipLineItems[$this->_priceSetId
][$fieldId] = $this->_lineItem
[$this->_priceSetId
][$fieldId];
2561 unset($this->_lineItem
[$this->_priceSetId
][$fieldId]);
2567 $this->processMembership($membershipParams, $contactID, $customFieldsFormatted, $premiumParams, $membershipLineItems);
2569 catch (\Civi\Payment\Exception\PaymentProcessorException
$e) {
2570 CRM_Core_Session
::singleton()->setStatus($e->getMessage());
2571 if (!empty($this->_contributionID
)) {
2572 CRM_Contribute_BAO_Contribution
::failPayment($this->_contributionID
,
2573 $contactID, $e->getMessage());
2575 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
2577 catch (CRM_Core_Exception
$e) {
2578 CRM_Core_Session
::singleton()->setStatus($e->getMessage());
2579 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
2581 if (!$this->_amount
> 0.0 ||
!$membershipParams['amount']) {
2582 // we need to explicitly create a CMS user in case of free memberships
2583 // since it is done under processConfirm for paid memberships
2584 CRM_Contribute_BAO_Contribution_Utils
::createCMSUser($membershipParams,
2585 $membershipParams['cms_contactID'],
2586 'email-' . $this->_bltID
2593 * Complete transaction if payment has been processed.
2595 * Check the result for a success outcome & if paid then complete the transaction.
2597 * Completing will trigger update of related entities and emails.
2601 * @param array $result
2602 * @param int $contributionID
2604 * @throws \CiviCRM_API3_Exception
2605 * @throws \Exception
2607 protected function completeTransaction($result, $contributionID) {
2608 CRM_Core_Error
::deprecatedWarning('Use API3 Payment.create');
2609 if (($result['payment_status_id'] ??
NULL) == 1) {
2611 civicrm_api3('contribution', 'completetransaction', [
2612 'id' => $contributionID,
2613 'trxn_id' => $result['trxn_id'] ??
NULL,
2614 'payment_processor_id' => $result['payment_processor_id'] ??
$this->_paymentProcessor
['id'],
2615 'is_transactional' => FALSE,
2616 'fee_amount' => $result['fee_amount'] ??
NULL,
2617 'receive_date' => $result['receive_date'] ??
NULL,
2618 'card_type_id' => $result['card_type_id'] ??
NULL,
2619 'pan_truncation' => $result['pan_truncation'] ??
NULL,
2622 catch (CiviCRM_API3_Exception
$e) {
2623 if ($e->getErrorCode() != 'contribution_completed') {
2624 \Civi
::log()->error('CRM_Contribute_Form_Contribution_Confirm::completeTransaction CiviCRM_API3_Exception: ' . $e->getMessage());
2625 throw new CRM_Core_Exception('Failed to update contribution in database');
2632 * Bounce the user back to retry when an error occurs.
2634 * @param string $message
2636 protected function bounceOnError($message) {
2637 CRM_Core_Session
::singleton()
2638 ->setStatus(ts("Payment Processor Error message :") .
2640 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact',
2641 "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"
2646 * Is a payment being made.
2648 * Note that setting is_monetary on the form is somewhat legacy and the behaviour around this setting is confusing. It would be preferable
2649 * to look for the amount only (assuming this cannot refer to payment in goats or other non-monetary currency
2650 * @param CRM_Core_Form $form
2654 protected static function isPaymentTransaction($form) {
2655 return $form->_amount
>= 0.0;
2659 * Process payment after confirmation.
2661 * @param array $paymentParams
2662 * Array with payment related key.
2664 * @param int $contactID
2666 * @param int $financialTypeID
2667 * Financial type id.
2668 * @param bool $isTest
2669 * @param bool $isRecur
2671 * @throws CRM_Core_Exception
2676 public function processConfirm(
2684 CRM_Core_Payment_Form
::mapParams($form->_bltID
, $form->_params
, $paymentParams, TRUE);
2685 $isPaymentTransaction = self
::isPaymentTransaction($form);
2687 $financialType = new CRM_Financial_DAO_FinancialType();
2688 $financialType->id
= $financialTypeID;
2689 $financialType->find(TRUE);
2690 if ($financialType->is_deductible
) {
2691 $form->assign('is_deductible', TRUE);
2692 $form->set('is_deductible', TRUE);
2695 // add some financial type details to the params list
2696 // if folks need to use it
2697 $paymentParams['financial_type_id'] = $paymentParams['financialTypeID'] = $financialType->id
;
2698 //CRM-15297 - contributionType is obsolete - pass financial type as well so people can deprecate it
2699 $paymentParams['financialType_name'] = $paymentParams['contributionType_name'] = $form->_params
['contributionType_name'] = $financialType->name
;
2701 $paymentParams['financialType_accounting_code'] = $paymentParams['contributionType_accounting_code'] = $form->_params
['contributionType_accounting_code'] = CRM_Financial_BAO_FinancialAccount
::getAccountingCode($financialTypeID);
2702 $paymentParams['contributionPageID'] = $form->_params
['contributionPageID'] = $form->_values
['id'];
2703 $paymentParams['contactID'] = $form->_params
['contactID'] = $contactID;
2706 if (empty($form->_params
['receive_date'])) {
2707 $form->_params
['receive_date'] = date('YmdHis');
2709 if (!empty($form->_params
['start_date'])) {
2710 $form->_params
['start_date'] = date('YmdHis');
2712 $form->assign('receive_date',
2713 CRM_Utils_Date
::mysqlToIso($form->_params
['receive_date'])
2716 if (empty($form->_values
['amount'])) {
2717 // If the amount is not in _values[], set it
2718 $form->_values
['amount'] = $form->_params
['amount'];
2721 if (isset($paymentParams['contribution_source'])) {
2722 $paymentParams['source'] = $paymentParams['contribution_source'];
2724 if ($isPaymentTransaction) {
2725 $contributionParams = [
2726 'id' => $paymentParams['contribution_id'] ??
NULL,
2727 'contact_id' => $contactID,
2728 'is_test' => $isTest,
2729 'source' => CRM_Utils_Array
::value('source', $paymentParams, CRM_Utils_Array
::value('description', $paymentParams)),
2732 // CRM-21200: Don't overwrite contribution details during 'Pay now' payment
2733 if (empty($form->_params
['contribution_id'])) {
2734 $contributionParams['contribution_page_id'] = $form->_id
;
2735 $contributionParams['campaign_id'] = CRM_Utils_Array
::value('campaign_id', $paymentParams, CRM_Utils_Array
::value('campaign_id', $form->_values
));
2737 // In case of 'Pay now' payment, append the contribution source with new text 'Paid later via page ID: N.'
2739 // contribution.source only allows 255 characters so we are using ellipsify(...) to ensure it.
2740 $contributionParams['source'] = CRM_Utils_String
::ellipsify(
2741 ts('Paid later via page ID: %1. %2', [
2743 2 => $contributionParams['source'],
2745 // eventually activity.description append price information to source text so keep it 220 to ensure string length doesn't exceed 255 characters.
2750 if (isset($paymentParams['line_item'])) {
2751 // @todo make sure this is consisently set at this point.
2752 $contributionParams['line_item'] = $paymentParams['line_item'];
2754 if (!empty($form->_paymentProcessor
)) {
2755 $contributionParams['payment_instrument_id'] = $paymentParams['payment_instrument_id'] = $form->_paymentProcessor
['payment_instrument_id'];
2757 $contribution = $this->processFormContribution(
2760 $contributionParams,
2765 // CRM-13074 - create the CMSUser after the transaction is completed as it
2766 // is not appropriate to delete a valid contribution if a user create problem occurs
2767 if (isset($this->_params
['related_contact'])) {
2768 $contactID = $this->_params
['related_contact'];
2770 elseif (isset($this->_params
['cms_contactID'])) {
2771 $contactID = $this->_params
['cms_contactID'];
2773 CRM_Contribute_BAO_Contribution_Utils
::createCMSUser($this->_params
,
2775 'email-' . $form->_bltID
2778 $paymentParams['item_name'] = $form->_params
['description'];
2780 $paymentParams['qfKey'] = empty($paymentParams['qfKey']) ?
$form->controller
->_key
: $paymentParams['qfKey'];
2781 if ($paymentParams['skipLineItem']) {
2782 // We are not processing the line item here because we are processing a membership.
2783 // Do not continue with contribution processing in this function.
2784 return ['contribution' => $contribution];
2787 $paymentParams['contributionID'] = $contribution->id
;
2788 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
2790 if (!empty($form->_params
['is_recur']) && $contribution->contribution_recur_id
) {
2791 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
2793 if (isset($paymentParams['contribution_source'])) {
2794 $form->_params
['source'] = $paymentParams['contribution_source'];
2797 // get the price set values for receipt.
2798 if ($form->_priceSetId
&& $form->_lineItem
) {
2799 $form->_values
['lineItem'] = $form->_lineItem
;
2800 $form->_values
['priceSetID'] = $form->_priceSetId
;
2803 $form->_values
['contribution_id'] = $contribution->id
;
2804 $form->_values
['contribution_page_id'] = $contribution->contribution_page_id
;
2806 if (!empty($form->_paymentProcessor
)) {
2808 $payment = Civi\Payment\System
::singleton()->getByProcessor($form->_paymentProcessor
);
2809 if ($form->_contributeMode
== 'notify') {
2810 // We want to get rid of this & make it generic - eg. by making payment processing the last thing
2811 // and always calling it first.
2812 $form->postProcessHook();
2814 $result = $payment->doPayment($paymentParams);
2815 $form->_params
= array_merge($form->_params
, $result);
2816 $form->assign('trxn_id', $result['trxn_id'] ??
'');
2817 $contribution->trxn_id
= $result['trxn_id'] ??
$contribution->trxn_id ??
'';
2818 $contribution->payment_status_id
= $result['payment_status_id'];
2819 $result['contribution'] = $contribution;
2820 if ($result['payment_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending')
2821 && $payment->isSendReceiptForPending()) {
2822 CRM_Contribute_BAO_ContributionPage
::sendMail($contactID,
2824 $contribution->is_test
2829 catch (\Civi\Payment\Exception\PaymentProcessorException
$e) {
2830 // Clean up DB as appropriate.
2831 if (!empty($paymentParams['contributionID'])) {
2832 CRM_Contribute_BAO_Contribution
::failPayment($paymentParams['contributionID'],
2833 $paymentParams['contactID'], $e->getMessage());
2835 if (!empty($paymentParams['contributionRecurID'])) {
2836 CRM_Contribute_BAO_ContributionRecur
::deleteRecurContribution($paymentParams['contributionRecurID']);
2839 $result['is_payment_failure'] = TRUE;
2840 $result['error'] = $e;
2846 // Only pay later or unpaid should reach this point, although pay later likely does not & is handled via the
2847 // manual processor, so it's unclear what this set is for and whether the following send ever fires.
2848 $form->set('params', $form->_params
);
2850 if ($form->_params
['amount'] == 0) {
2851 // This is kind of a back-up for pay-later $0 transactions.
2852 // In other flows they pick up the manual processor & get dealt with above (I
2853 // think that might be better...).
2855 'payment_status_id' => 1,
2856 'contribution' => $contribution,
2857 'payment_processor_id' => 0,
2861 CRM_Contribute_BAO_ContributionPage
::sendMail($contactID,
2863 $contribution->is_test
2868 * Temporary function to allow unit tests to access function being refactored away.
2870 * @param int $contactID
2871 * @param int $membershipTypeID
2872 * @param int $membershipID
2875 * @throws \CRM_Core_Exception
2876 * @throws \CiviCRM_API3_Exception
2878 public static function unitTestAccessTolegacyProcessMembership($contactID, $membershipTypeID, $membershipID = NULL) {
2879 return self
::legacyProcessMembership(
2896 * Interim function for processing memberships - this is being refactored out of existence.
2898 * @param int $contactID
2899 * @param int $membershipTypeID
2900 * @param bool $is_test
2901 * @param string $changeToday
2902 * @param int $modifiedID
2903 * @param $customFieldsFormatted
2904 * @param $numRenewTerms
2905 * @param int $membershipID
2907 * @param int $contributionRecurID
2908 * @param $membershipSource
2909 * @param $isPayLater
2910 * @param array $memParams
2911 * @param null|CRM_Contribute_BAO_Contribution $contribution
2912 * @param array $lineItems
2915 * @throws \CRM_Core_Exception
2916 * @throws \CiviCRM_API3_Exception
2918 protected static function legacyProcessMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $contributionRecurID, $membershipSource, $isPayLater, $memParams = [], $contribution = NULL, $lineItems = []) {
2919 $renewalMode = $updateStatusId = FALSE;
2920 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2922 $statusFormat = '%Y-%m-%d';
2923 $membershipTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipType($membershipTypeID);
2927 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
2928 // is the same as the parent org of an existing membership of the contact
2929 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($contactID, $membershipTypeID,
2930 $is_test, $membershipID, TRUE
2932 if ($currentMembership) {
2933 $renewalMode = TRUE;
2935 // Do NOT do anything.
2936 //1. membership with status : PENDING/CANCELLED (CRM-2395)
2937 //2. Paylater/IPN renew. CRM-4556.
2938 if ($pending ||
in_array($currentMembership['status_id'], [
2939 array_search('Pending', $allStatus),
2941 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
2944 $memParams = array_merge([
2945 'id' => $currentMembership['id'],
2946 'contribution' => $contribution,
2947 'status_id' => $currentMembership['status_id'],
2948 'start_date' => $currentMembership['start_date'],
2949 'end_date' => $currentMembership['end_date'],
2950 'line_item' => $lineItems,
2951 'join_date' => $currentMembership['join_date'],
2952 'membership_type_id' => $membershipTypeID,
2953 'max_related' => !empty($membershipTypeDetails['max_related']) ?
$membershipTypeDetails['max_related'] : NULL,
2954 'membership_activity_status' => ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed',
2956 if ($contributionRecurID) {
2957 $memParams['contribution_recur_id'] = $contributionRecurID;
2960 $membership = CRM_Member_BAO_Membership
::create($memParams);
2961 return [$membership, $renewalMode, $dates];
2964 // Check and fix the membership if it is STALE
2965 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
2967 // Now Renew the membership
2968 if (!$currentMembership['is_current_member']) {
2969 // membership is not CURRENT
2971 // CRM-7297 Membership Upsell - calculate dates based on new membership type
2972 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($currentMembership['id'],
2978 $currentMembership['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
2979 foreach (['start_date', 'end_date'] as $dateType) {
2980 $currentMembership[$dateType] = $dates[$dateType] ??
NULL;
2982 $currentMembership['is_test'] = $is_test;
2984 if (!empty($membershipSource)) {
2985 $currentMembership['source'] = $membershipSource;
2988 if (!empty($currentMembership['id'])) {
2989 $ids['membership'] = $currentMembership['id'];
2991 $memParams = array_merge($currentMembership, $memParams);
2992 $memParams['membership_type_id'] = $membershipTypeID;
2994 //set the log start date.
2995 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
2999 // CURRENT Membership
3000 $membership = new CRM_Member_DAO_Membership();
3001 $membership->id
= $currentMembership['id'];
3002 $membership->find(TRUE);
3003 // CRM-7297 Membership Upsell - calculate dates based on new membership type
3004 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
3010 // Insert renewed dates for CURRENT membership
3011 $memParams['join_date'] = CRM_Utils_Date
::isoToMysql($membership->join_date
);
3012 $memParams['start_date'] = CRM_Utils_Date
::isoToMysql($membership->start_date
);
3013 $memParams['end_date'] = $dates['end_date'] ??
NULL;
3014 $memParams['membership_type_id'] = $membershipTypeID;
3016 //set the log start date.
3017 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
3020 if (!empty($membershipSource)) {
3021 $memParams['source'] = $membershipSource;
3023 elseif (empty($membership->source
)) {
3024 $memParams['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
3025 $currentMembership['id'],
3030 if (!empty($currentMembership['id'])) {
3031 $ids['membership'] = $currentMembership['id'];
3033 $memParams['membership_activity_status'] = ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed';
3038 $memParams = array_merge([
3039 'contact_id' => $contactID,
3040 'membership_type_id' => $membershipTypeID,
3044 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
3046 foreach (['join_date', 'start_date', 'end_date'] as $dateType) {
3047 $memParams[$dateType] = $dates[$dateType] ??
NULL;
3050 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(CRM_Utils_Date
::customFormat($dates['start_date'],
3053 CRM_Utils_Date
::customFormat($dates['end_date'],
3056 CRM_Utils_Date
::customFormat($dates['join_date'],
3064 $updateStatusId = $status['id'] ??
NULL;
3067 // if IPN/Pay-Later set status to: PENDING
3068 $updateStatusId = array_search('Pending', $allStatus);
3071 if (!empty($membershipSource)) {
3072 $memParams['source'] = $membershipSource;
3074 $memParams['is_test'] = $is_test;
3075 $memParams['is_pay_later'] = $isPayLater;
3077 // Putting this in an IF is precautionary as it seems likely that it would be ignored if empty, but
3078 // perhaps shouldn't be?
3079 if ($contributionRecurID) {
3080 $memParams['contribution_recur_id'] = $contributionRecurID;
3083 //if we decided status here and want to skip status
3084 //calculation in create( ); then need to pass 'skipStatusCal'.
3085 if ($updateStatusId) {
3086 $memParams['status_id'] = $updateStatusId;
3087 $memParams['skipStatusCal'] = TRUE;
3090 //since we are renewing,
3091 //make status override false.
3092 $memParams['is_override'] = FALSE;
3094 //CRM-4027, create log w/ individual contact.
3096 // @todo this param is likely unused now.
3097 $memParams['is_for_organization'] = TRUE;
3099 $params['modified_id'] = $modifiedID ??
$contactID;
3101 $memParams['contribution'] = $contribution;
3102 $memParams['custom'] = $customFieldsFormatted;
3103 // Load all line items & process all in membership. Don't do in contribution.
3104 // Relevant tests in api_v3_ContributionPageTest.
3105 $memParams['line_item'] = $lineItems;
3106 // @todo stop passing $ids (membership and userId may be set by this point)
3107 $membership = CRM_Member_BAO_Membership
::create($memParams, $ids);
3109 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
3110 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
3111 $membership->find(TRUE);
3113 return [$membership, $renewalMode, $dates];