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 protected 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 $this->_params
['tax_amount'] = $this->get('tax_amount');
284 $this->_useForMember
= $this->get('useForMember');
286 CRM_Contribute_Form_AbstractEditPayment
::formatCreditCardDetails($this->_params
);
288 $this->_params
['currencyID'] = CRM_Core_Config
::singleton()->defaultCurrency
;
290 if (!empty($this->_membershipBlock
)) {
291 $this->_params
['selectMembership'] = $this->get('selectMembership');
293 if (!empty($this->_paymentProcessor
) && $this->_paymentProcessor
['object']->supports('preApproval')) {
294 $preApprovalParams = $this->_paymentProcessor
['object']->getPreApprovalDetails($this->get('pre_approval_parameters'));
295 $this->_params
= array_merge($this->_params
, $preApprovalParams);
297 // We may have fetched some billing details from the getPreApprovalDetails function so we
298 // want to ensure we set this after that function has been called.
299 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $preApprovalParams, $this->_params
, FALSE);
302 $this->_params
['is_pay_later'] = $this->get('is_pay_later');
303 $this->assign('is_pay_later', $this->_params
['is_pay_later']);
304 if ($this->_params
['is_pay_later']) {
305 $this->assign('pay_later_receipt', $this->_values
['pay_later_receipt'] ??
NULL);
307 // if onbehalf-of-organization
308 if (!empty($this->_values
['onbehalf_profile_id']) && !empty($this->_params
['onbehalf']['organization_name'])) {
309 if (empty($this->_params
['org_option']) && empty($this->_params
['organization_id'])) {
310 $this->_params
['organization_id'] = $this->_params
['onbehalfof_id'] ??
NULL;
312 $this->_params
['organization_name'] = $this->_params
['onbehalf']['organization_name'];
319 'supplemental_address_1',
320 'supplemental_address_2',
321 'supplemental_address_3',
322 'postal_code_suffix',
328 $blocks = ['email', 'phone', 'im', 'url', 'openid'];
329 foreach ($this->_params
['onbehalf'] as $loc => $value) {
330 $field = $typeId = NULL;
331 if (strstr($loc, '-')) {
332 list($field, $locType) = explode('-', $loc);
335 if (in_array($field, $addressBlocks)) {
336 if ($locType === 'Primary') {
337 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
338 $locType = $defaultLocationType->id
;
341 if ($field === 'country') {
342 $value = CRM_Core_PseudoConstant
::countryIsoCode($value);
344 elseif ($field === 'state_province') {
345 $value = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($value);
349 if (isset($this->_params
['onbehalf_location']['address'])
350 && count($this->_params
['onbehalf_location']['address']) > 0
355 $this->_params
['onbehalf_location']['address'][$locType][$field] = $value;
356 if (empty($this->_params
['onbehalf_location']['address'][$locType]['is_primary'])) {
357 $this->_params
['onbehalf_location']['address'][$locType]['is_primary'] = $isPrimary;
359 $this->_params
['onbehalf_location']['address'][$locType]['location_type_id'] = $locType;
361 elseif (in_array($field, $blocks)) {
362 if (!$typeId ||
is_numeric($typeId)) {
363 $blockName = $fieldName = $field;
364 $locationType = 'location_type_id';
365 if ($locType === 'Primary') {
366 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
367 $locationValue = $defaultLocationType->id
;
370 $locationValue = $locType;
375 if ($field == 'url') {
376 $blockName = 'website';
377 $locationType = 'website_type_id';
378 list($field, $locationValue) = explode('-', $loc);
380 elseif ($field == 'im') {
382 $locTypeId = 'provider_id';
383 $typeId = $this->_params
['onbehalf']["{$loc}-provider_id"];
385 elseif ($field == 'phone') {
386 list($field, $locType, $typeId) = explode('-', $loc);
387 $locTypeId = 'phone_type_id';
389 //check if extension field exists
390 $extField = str_replace('phone', 'phone_ext', $loc);
391 if (isset($this->_params
['onbehalf'][$extField])) {
392 $phoneExtField = ['phone_ext' => $this->_params
['onbehalf'][$extField]];
397 if (isset($this->_params
['onbehalf_location'][$blockName])
398 && count($this->_params
['onbehalf_location'][$blockName]) > 0
402 if ($locationValue) {
404 $fieldName => $value,
405 $locationType => $locationValue,
406 'is_primary' => $isPrimary,
410 $blockValues = array_merge($blockValues, [$locTypeId => $typeId]);
412 if (!empty($phoneExtField)) {
413 $blockValues = array_merge($blockValues, $phoneExtField);
416 $this->_params
['onbehalf_location'][$blockName][] = $blockValues;
420 elseif (strstr($loc, 'custom')) {
421 if ($value && isset($this->_params
['onbehalf']["{$loc}_id"])) {
422 $value = $this->_params
['onbehalf']["{$loc}_id"];
424 $this->_params
['onbehalf_location']["{$loc}"] = $value;
427 if ($loc === 'contact_sub_type') {
428 $this->_params
['onbehalf_location'][$loc] = $value;
431 $this->_params
['onbehalf_location'][$field] = $value;
436 elseif (!empty($this->_values
['is_for_organization'])) {
437 // no on behalf of an organization, CRM-5519
438 // so reset loc blocks from main params.
444 if (isset($this->_params
[$blk])) {
445 unset($this->_params
[$blk]);
449 $this->setRecurringMembershipParams();
452 $params = $this->processPcp($this, $this->_params
);
453 $this->_params
= $params;
455 $this->_params
['invoiceID'] = $this->get('invoiceID');
457 //carry campaign from profile.
458 if (array_key_exists('contribution_campaign_id', $this->_params
)) {
459 $this->_params
['campaign_id'] = $this->_params
['contribution_campaign_id'];
462 // assign contribution page id to the template so we can add css class for it
463 $this->assign('contributionPageID', $this->_id
);
464 $this->assign('is_for_organization', $this->_params
['is_for_organization'] ??
NULL);
466 $this->set('params', $this->_params
);
470 * Build the form object.
472 public function buildQuickForm() {
473 // FIXME: Some of this code is identical to Thankyou.php and should be broken out into a shared function
474 $this->assignToTemplate();
476 $params = $this->_params
;
477 // make sure we have values for it
478 if (!empty($this->_values
['honoree_profile_id']) && !empty($params['soft_credit_type_id']) && empty($this->_ccid
)) {
480 $softCreditTypes = CRM_Core_OptionGroup
::values("soft_credit_type", FALSE);
482 $this->assign('soft_credit_type', $softCreditTypes[$params['soft_credit_type_id']]);
483 CRM_Contribute_BAO_ContributionSoft
::formatHonoreeProfileFields($this, $params['honor']);
485 $fieldTypes = ['Contact'];
486 $fieldTypes[] = CRM_Core_BAO_UFGroup
::getContactType($this->_values
['honoree_profile_id']);
487 $this->buildCustom($this->_values
['honoree_profile_id'], 'honoreeProfileFields', TRUE, 'honor', $fieldTypes);
489 $this->assign('receiptFromEmail', $this->_values
['receipt_from_email'] ??
NULL);
490 $amount_block_is_active = $this->get('amount_block_is_active');
491 $this->assign('amount_block_is_active', $amount_block_is_active);
493 // Make a copy of line items array to use for display only
494 $tplLineItems = $this->_lineItem
;
495 if (CRM_Invoicing_Utils
::isInvoicingEnabled()) {
496 // @todo $params seems like exactly the wrong place to get totalTaxAmount from
497 // this is a calculated variable so we it should be transparent how we
498 // calculated it rather than coming from 'params'
499 $this->assign('totalTaxAmount', $params['tax_amount']);
501 $this->assignLineItemsToTemplate($tplLineItems);
503 $isDisplayLineItems = $this->_priceSetId
&& !CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config');
505 $this->assign('isDisplayLineItems', $isDisplayLineItems);
507 if (!$isDisplayLineItems) {
508 // quickConfig is deprecated in favour of isDisplayLineItems. Lots of logic has been harnessed to quick config
509 // whereas isDisplayLineItems is specific & clear.
510 $this->assign('is_quick_config', 1);
511 $this->_params
['is_quick_config'] = 1;
514 if (!empty($params['selectProduct']) && $params['selectProduct'] !== 'no_thanks') {
515 $option = $params['options_' . $params['selectProduct']] ??
NULL;
516 $productID = $params['selectProduct'];
517 CRM_Contribute_BAO_Premium
::buildPremiumBlock($this, $this->_id
, FALSE,
520 $this->set('productID', $productID);
521 $this->set('option', $option);
523 $config = CRM_Core_Config
::singleton();
524 if (in_array('CiviMember', $config->enableComponents
) && empty($this->_ccid
)) {
525 if (isset($params['selectMembership']) &&
526 $params['selectMembership'] !== 'no_thanks'
528 $this->buildMembershipBlock(
529 $this->_membershipContactID
,
531 $params['selectMembership'],
534 if (!empty($params['auto_renew'])) {
535 $this->assign('auto_renew', TRUE);
539 $this->assign('membershipBlock', FALSE);
542 if (empty($this->_ccid
)) {
543 $this->buildCustom($this->_values
['custom_pre_id'], 'customPre', TRUE);
544 $this->buildCustom($this->_values
['custom_post_id'], 'customPost', TRUE);
547 if (!empty($this->_values
['onbehalf_profile_id']) &&
548 !empty($params['onbehalf']) &&
549 ($this->_values
['is_for_organization'] == 2 ||
550 !empty($params['is_for_organization'])
551 ) && empty($this->_ccid
)
553 $fieldTypes = ['Contact', 'Organization'];
554 $contactSubType = CRM_Contact_BAO_ContactType
::subTypes('Organization');
555 $fieldTypes = array_merge($fieldTypes, $contactSubType);
556 if (is_array($this->_membershipBlock
) && !empty($this->_membershipBlock
)) {
557 $fieldTypes = array_merge($fieldTypes, ['Membership']);
560 $fieldTypes = array_merge($fieldTypes, ['Contribution']);
563 $this->buildCustom($this->_values
['onbehalf_profile_id'], 'onbehalfProfile', TRUE, 'onbehalf', $fieldTypes);
566 $this->_separateMembershipPayment
= $this->get('separateMembershipPayment');
567 $this->assign('is_separate_payment', $this->_separateMembershipPayment
);
569 $this->assign('priceSetID', $this->_priceSetId
);
571 // The concept of contributeMode is deprecated.
572 // the is_monetary concept probably should be too as it can be calculated from
573 // the existence of 'amount' & seems fragile.
574 if ($this->_contributeMode
== 'notify' ||
575 $this->_amount
<= 0.0 ||
$this->_params
['is_pay_later']
577 $contribButton = ts('Continue');
579 elseif (!empty($this->_ccid
)) {
580 $contribButton = ts('Make Payment');
583 $contribButton = ts('Make Contribution');
585 $this->assign('button', $contribButton);
587 $this->assign('continueText',
588 $this->getPaymentProcessorObject()->getText('contributionPageContinueText', [
589 'is_payment_to_existing' => !empty($this->_ccid
),
590 'amount' => $this->_amount
,
597 'name' => $contribButton,
598 'spacing' => ' ',
603 'name' => ts('Go Back'),
608 $fields = array_fill_keys(array_keys($this->_fields
), 1);
609 $fields["billing_state_province-{$this->_bltID}"] = $fields["billing_country-{$this->_bltID}"] = $fields["email-{$this->_bltID}"] = 1;
611 $contact = $this->_params
;
612 foreach ($fields as $name => $dontCare) {
613 // Recursively set defaults for nested fields
614 if (isset($contact[$name]) && is_array($contact[$name]) && ($name == 'onbehalf' ||
$name == 'honor')) {
615 foreach ($contact[$name] as $fieldName => $fieldValue) {
616 if (is_array($fieldValue) && $this->_fields
[$name][$fieldName]['html_type'] == 'CheckBox') {
617 foreach ($fieldValue as $key => $value) {
618 $defaults["{$name}[{$fieldName}][{$key}]"] = $value;
622 $defaults["{$name}[{$fieldName}]"] = $fieldValue;
626 elseif (isset($contact[$name])) {
627 $defaults[$name] = $contact[$name];
628 if (substr($name, 0, 7) == 'custom_') {
629 $timeField = "{$name}_time";
630 if (isset($contact[$timeField])) {
631 $defaults[$timeField] = $contact[$timeField];
633 if (isset($contact["{$name}_id"])) {
634 $defaults["{$name}_id"] = $contact["{$name}_id"];
637 elseif (in_array($name, [
641 ]) && !empty($contact[$name . '_custom'])
643 $defaults[$name . '_custom'] = $contact[$name . '_custom'];
648 $this->assign('useForMember', $this->get('useForMember'));
650 $this->setDefaults($defaults);
658 * Since we are only showing elements in frozen mode no help display needed.
662 public function getAction() {
663 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
664 return CRM_Core_Action
::VIEW | CRM_Core_Action
::PREVIEW
;
667 return CRM_Core_Action
::VIEW
;
672 * Set default values for the form.
674 * Note that in edit/view mode
675 * the default values are retrieved from the database
677 public function setDefaultValues() {
683 public function postProcess() {
684 $contactID = $this->getContactID();
686 $result = $this->processFormSubmission($contactID);
688 catch (CRM_Core_Exception
$e) {
689 $this->bounceOnError($e->getMessage());
692 if (is_array($result) && !empty($result['is_payment_failure'])) {
693 $this->bounceOnError($result['error']->getMessage());
695 // Presumably this is for hooks to access? Not quite clear & perhaps not required.
696 $this->set('params', $this->_params
);
700 * Wrangle financial type ID.
702 * 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
703 * Pledges are not relevant to the membership code so that portion will not go onto the membership form.
705 * Comments from previous refactor indicate doubt as to what was going on.
707 * @param int $financialTypeID
709 * @return null|string
711 public function wrangleFinancialTypeID($financialTypeID) {
712 if (empty($financialTypeID) && !empty($this->_values
['pledge_id'])) {
713 $financialTypeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_Pledge',
714 $this->_values
['pledge_id'],
718 return $financialTypeID;
724 * @param array $premiumParams
725 * @param CRM_Contribute_BAO_Contribution $contribution
727 protected function postProcessPremium($premiumParams, $contribution) {
728 $hour = $minute = $second = 0;
729 // assigning Premium information to receipt tpl
730 $selectProduct = $premiumParams['selectProduct'] ??
NULL;
731 if ($selectProduct &&
732 $selectProduct != 'no_thanks'
734 $startDate = $endDate = "";
735 $this->assign('selectPremium', TRUE);
736 $productDAO = new CRM_Contribute_DAO_Product();
737 $productDAO->id
= $selectProduct;
738 $productDAO->find(TRUE);
739 $this->assign('product_name', $productDAO->name
);
740 $this->assign('price', $productDAO->price
);
741 $this->assign('sku', $productDAO->sku
);
742 $this->assign('option', $premiumParams['options_' . $premiumParams['selectProduct']] ??
NULL);
744 $periodType = $productDAO->period_type
;
747 $fixed_period_start_day = $productDAO->fixed_period_start_day
;
748 $duration_unit = $productDAO->duration_unit
;
749 $duration_interval = $productDAO->duration_interval
;
750 if ($periodType == 'rolling') {
751 $startDate = date('Y-m-d');
753 elseif ($periodType == 'fixed') {
754 if ($fixed_period_start_day) {
755 $date = explode('-', date('Y-m-d'));
756 $month = substr($fixed_period_start_day, 0, strlen($fixed_period_start_day) - 2);
757 $day = substr($fixed_period_start_day, -2) . "<br/>";
759 $startDate = $year . '-' . $month . '-' . $day;
762 $startDate = date('Y-m-d');
766 $date = explode('-', $startDate);
771 switch ($duration_unit) {
773 $year = $year +
$duration_interval;
777 $month = $month +
$duration_interval;
781 $day = $day +
$duration_interval;
785 $day = $day +
($duration_interval * 7);
787 $endDate = date('Y-m-d H:i:s', mktime($hour, $minute, $second, $month, $day, $year));
788 $this->assign('start_date', $startDate);
789 $this->assign('end_date', $endDate);
792 $dao = new CRM_Contribute_DAO_Premium();
793 $dao->entity_table
= 'civicrm_contribution_page';
794 $dao->entity_id
= $this->_id
;
796 $this->assign('contact_phone', $dao->premiums_contact_phone
);
797 $this->assign('contact_email', $dao->premiums_contact_email
);
799 //create Premium record
801 'product_id' => $premiumParams['selectProduct'],
802 'contribution_id' => $contribution->id
,
803 'product_option' => $premiumParams['options_' . $premiumParams['selectProduct']] ??
NULL,
805 'start_date' => CRM_Utils_Date
::customFormat($startDate, '%Y%m%d'),
806 'end_date' => CRM_Utils_Date
::customFormat($endDate, '%Y%m%d'),
808 if (!empty($premiumParams['selectProduct'])) {
809 $daoPremiumsProduct = new CRM_Contribute_DAO_PremiumsProduct();
810 $daoPremiumsProduct->product_id
= $premiumParams['selectProduct'];
811 $daoPremiumsProduct->premiums_id
= $dao->id
;
812 $daoPremiumsProduct->find(TRUE);
813 $params['financial_type_id'] = $daoPremiumsProduct->financial_type_id
;
816 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
817 $daoContrProd->contribution_id
= $contribution->id
;
818 if ($daoContrProd->find(TRUE)) {
819 $params['id'] = $daoContrProd->id
;
822 CRM_Contribute_BAO_Contribution
::addPremium($params);
823 if ($productDAO->cost
&& !empty($params['financial_type_id'])) {
825 'cost' => $productDAO->cost
,
826 'currency' => $productDAO->currency
,
827 'financial_type_id' => $params['financial_type_id'],
828 'contributionId' => $contribution->id
,
830 CRM_Core_BAO_FinancialTrxn
::createPremiumTrxn($trxnParams);
833 elseif ($selectProduct == 'no_thanks') {
835 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
836 $daoContrProd->contribution_id
= $contribution->id
;
837 if ($daoContrProd->find(TRUE)) {
838 $daoContrProd->delete();
844 * Process the contribution.
846 * @param CRM_Core_Form $form
847 * @param array $params
848 * @param array $result
849 * @param array $contributionParams
850 * Parameters to be passed to contribution create action.
851 * This differs from params in that we are currently adding params to it and 1) ensuring they are being
852 * passed consistently & 2) documenting them here.
857 * - contribution_page_id
860 * - thankyou_date (not all forms will set this)
862 * @param CRM_Financial_DAO_FinancialType $financialType
863 * @param bool $online
864 * Is the form a front end form? If so set a bunch of unpredictable things that should be passed in from the form.
866 * @param int $billingLocationID
867 * ID of billing location type.
868 * @param bool $isRecur
871 * @return \CRM_Contribute_DAO_Contribution
873 * @throws \CRM_Core_Exception
874 * @throws \CiviCRM_API3_Exception
876 public static function processFormContribution(
886 $transaction = new CRM_Core_Transaction();
887 $contactID = $contributionParams['contact_id'];
889 $isEmailReceipt = !empty($form->_values
['is_email_receipt']);
890 $isSeparateMembershipPayment = !empty($params['separate_membership_payment']);
891 $pledgeID = !empty($params['pledge_id']) ?
$params['pledge_id'] : $form->_values
['pledge_id'] ??
NULL;
892 if (!$isSeparateMembershipPayment && !empty($form->_values
['pledge_block_id']) &&
893 (!empty($params['is_pledge']) ||
$pledgeID)) {
900 // add these values for the recurringContrib function ,CRM-10188
901 $params['financial_type_id'] = $financialType->id
;
903 $contributionParams['address_id'] = CRM_Contribute_BAO_Contribution
::createAddress($params, $billingLocationID);
905 //@todo - this is being set from the form to resolve CRM-10188 - an
906 // eNotice caused by it not being set @ the front end
907 // however, we then get it being over-written with null for backend contributions
908 // a better fix would be to set the values in the respective forms rather than require
909 // a function being shared by two forms to deal with their respective values
910 // moving it to the BAO & not taking the $form as a param would make sense here.
911 if (!isset($params['is_email_receipt']) && $isEmailReceipt) {
912 $params['is_email_receipt'] = $isEmailReceipt;
914 $params['is_recur'] = $isRecur;
915 $params['payment_instrument_id'] = $contributionParams['payment_instrument_id'] ??
NULL;
916 $recurringContributionID = self
::processRecurringContribution($form, $params, $contactID, $financialType);
918 $now = date('YmdHis');
919 $receiptDate = $params['receipt_date'] ??
NULL;
920 if ($isEmailReceipt) {
924 if (isset($params['amount'])) {
925 $contributionParams = array_merge(self
::getContributionParams(
926 $params, $financialType->id
,
927 $result, $receiptDate,
928 $recurringContributionID), $contributionParams
930 $contributionParams['non_deductible_amount'] = self
::getNonDeductibleAmount($params, $financialType, $online, $form);
931 $contributionParams['skipCleanMoney'] = TRUE;
932 // @todo this is the wrong place for this - it should be done as close to form submission
934 $contributionParams['total_amount'] = $params['amount'];
936 $contribution = CRM_Contribute_BAO_Contribution
::add($contributionParams);
938 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
939 $invoicing = $invoiceSettings['invoicing'] ??
NULL;
942 // @todo - interrogate the line items passed in on the params array.
943 // No reason to assume line items will be set on the form.
944 foreach ($form->_lineItem
as $lineItemKey => $lineItemValue) {
945 foreach ($lineItemValue as $key => $value) {
946 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
947 if (isset($dataArray[$value['tax_rate']])) {
948 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] +
$value['tax_amount'];
951 $dataArray[$value['tax_rate']] = $value['tax_amount'];
956 $smarty = CRM_Core_Smarty
::singleton();
957 $smarty->assign('dataArray', $dataArray);
958 $smarty->assign('totalTaxAmount', $params['tax_amount'] ??
NULL);
961 // lets store it in the form variable so postProcess hook can get to this and use it
962 $form->_contributionID
= $contribution->id
;
965 // process soft credit / pcp params first
966 CRM_Contribute_BAO_ContributionSoft
::formatSoftCreditParams($params, $form);
968 //CRM-13981, processing honor contact into soft-credit contribution
969 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
972 $form = self
::handlePledge($form, $params, $contributionParams, $pledgeID, $contribution, $isEmailReceipt);
975 if ($online && $contribution) {
976 CRM_Core_BAO_CustomValueTable
::postProcess($params,
977 'civicrm_contribution',
982 elseif ($contribution) {
983 //handle custom data.
984 $params['contribution_id'] = $contribution->id
;
985 if (!empty($params['custom']) &&
986 is_array($params['custom'])
988 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
992 if ($contribution && !empty($params['contribution_note'])) {
994 'entity_table' => 'civicrm_contribution',
995 'note' => $params['contribution_note'],
996 'entity_id' => $contribution->id
,
997 'contact_id' => $contribution->contact_id
,
1000 CRM_Core_BAO_Note
::add($noteParams, []);
1003 if (isset($params['related_contact'])) {
1004 $contactID = $params['related_contact'];
1006 elseif (isset($params['cms_contactID'])) {
1007 $contactID = $params['cms_contactID'];
1010 //create contribution activity w/ individual and target
1011 //activity w/ organisation contact id when onbelf, CRM-4027
1013 $targetContactID = NULL;
1014 if (!empty($params['onbehalf_contact_id'])) {
1016 'source_contact_id' => $params['onbehalf_contact_id'],
1017 'on_behalf' => TRUE,
1019 $targetContactID = $contribution->contact_id
;
1022 // create an activity record
1023 if ($contribution) {
1024 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Contribution', $targetContactID, $actParams);
1027 $transaction->commit();
1028 // CRM-13074 - create the CMSUser after the transaction is completed as it
1029 // is not appropriate to delete a valid contribution if a user create problem occurs
1030 CRM_Contribute_BAO_Contribution_Utils
::createCMSUser($params,
1032 'email-' . $billingLocationID
1034 return $contribution;
1038 * Create the recurring contribution record.
1040 * @param CRM_Core_Form $form
1041 * @param array $params
1042 * @param int $contactID
1043 * @param string $contributionType
1047 public static function processRecurringContribution(&$form, &$params, $contactID, $contributionType) {
1049 if (empty($params['is_recur'])) {
1053 $recurParams = ['contact_id' => $contactID];
1054 $recurParams['amount'] = $params['amount'] ??
NULL;
1055 $recurParams['auto_renew'] = $params['auto_renew'] ??
NULL;
1056 $recurParams['frequency_unit'] = $params['frequency_unit'] ??
NULL;
1057 $recurParams['frequency_interval'] = $params['frequency_interval'] ??
NULL;
1058 $recurParams['installments'] = $params['installments'] ??
NULL;
1059 $recurParams['financial_type_id'] = $params['financial_type_id'] ??
NULL;
1060 $recurParams['currency'] = $params['currency'] ??
NULL;
1061 $recurParams['payment_instrument_id'] = $params['payment_instrument_id'];
1063 // CRM-14354: For an auto-renewing membership with an additional contribution,
1064 // if separate payments is not enabled, make sure only the membership fee recurs
1065 if (!empty($form->_membershipBlock
)
1066 && $form->_membershipBlock
['is_separate_payment'] === '0'
1067 && isset($params['selectMembership'])
1068 && $form->_values
['is_allow_other_amount'] == '1'
1070 && !empty($form->_membershipTypeValues
)
1071 && !empty($form->_membershipTypeValues
[$params['selectMembership']]['minimum_fee'])
1073 $recurParams['amount'] = $form->_membershipTypeValues
[$params['selectMembership']]['minimum_fee'];
1076 $recurParams['is_test'] = 0;
1077 if (($form->_action
& CRM_Core_Action
::PREVIEW
) ||
1078 (isset($form->_mode
) && ($form->_mode
== 'test'))
1080 $recurParams['is_test'] = 1;
1083 $recurParams['start_date'] = $recurParams['create_date'] = $recurParams['modified_date'] = date('YmdHis');
1084 if (!empty($params['receive_date'])) {
1085 $recurParams['start_date'] = date('YmdHis', strtotime($params['receive_date']));
1087 $recurParams['invoice_id'] = $params['invoiceID'] ??
NULL;
1088 $recurParams['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1089 $recurParams['payment_processor_id'] = $params['payment_processor_id'] ??
NULL;
1090 $recurParams['is_email_receipt'] = $params['is_email_receipt'] ??
NULL;
1091 // we need to add a unique trxn_id to avoid a unique key error
1092 // in paypal IPN we reset this when paypal sends us the real trxn id, CRM-2991
1093 $recurParams['trxn_id'] = $params['trxn_id'] ??
$params['invoiceID'];
1094 $recurParams['financial_type_id'] = $contributionType->id
;
1096 $campaignId = $params['campaign_id'] ??
$form->_values
['campaign_id'] ??
NULL;
1097 $recurParams['campaign_id'] = $campaignId;
1098 $recurring = CRM_Contribute_BAO_ContributionRecur
::add($recurParams);
1099 if (is_a($recurring, 'CRM_Core_Error')) {
1100 CRM_Core_Error
::displaySessionError($recurring);
1101 $urlString = 'civicrm/contribute/transact';
1102 $urlParams = '_qf_Main_display=true';
1103 if (get_class($form) == 'CRM_Contribute_Form_Contribution') {
1104 $urlString = 'civicrm/contact/view/contribution';
1105 $urlParams = "action=add&cid={$form->_contactID}";
1107 $urlParams .= "&mode={$form->_mode}";
1110 CRM_Utils_System
::redirect(CRM_Utils_System
::url($urlString, $urlParams));
1112 // Only set contribution recur ID for contributions since offline membership recur payments are handled somewhere else.
1113 if (!is_a($form, "CRM_Member_Form_Membership")) {
1114 $form->_params
['contributionRecurID'] = $recurring->id
;
1117 return $recurring->id
;
1121 * Add on behalf of organization and it's location.
1123 * This situation occurs when on behalf of is enabled for the contribution page and the person
1124 * signing up does so on behalf of an organization.
1126 * @param array $behalfOrganization
1127 * array of organization info.
1128 * @param int $contactID
1129 * individual contact id. One.
1130 * who is doing the process of signup / contribution.
1132 * @param array $values
1133 * form values array.
1134 * @param array $params
1135 * @param array $fields
1136 * Array of fields from the onbehalf profile relevant to the organization.
1138 public static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params, $fields = NULL) {
1139 $isNotCurrentEmployer = FALSE;
1142 if (!empty($behalfOrganization['organization_id'])) {
1143 $orgID = $behalfOrganization['organization_id'];
1144 unset($behalfOrganization['organization_id']);
1146 // create employer relationship with $contactID only when new organization is there
1147 // else retain the existing relationship
1149 $isNotCurrentEmployer = TRUE;
1153 // check if matching organization contact exists
1154 $dupeIDs = CRM_Contact_BAO_Contact
::getDuplicateContacts($behalfOrganization, 'Organization', 'Unsupervised', [], FALSE);
1156 // CRM-6243 says to pick the first org even if more than one match
1157 if (count($dupeIDs) >= 1) {
1158 $behalfOrganization['contact_id'] = $orgID = $dupeIDs[0];
1159 // don't allow name edit
1160 unset($behalfOrganization['organization_name']);
1164 // if found permissioned related organization, allow location edit
1165 $behalfOrganization['contact_id'] = $orgID;
1166 // don't allow name edit
1167 unset($behalfOrganization['organization_name']);
1170 // handling for image url
1171 if (!empty($behalfOrganization['image_URL'])) {
1172 CRM_Contact_BAO_Contact
::processImageParams($behalfOrganization);
1175 // create organization, add location
1176 $behalfOrganization['contact_type'] = 'Organization';
1177 $orgID = CRM_Contact_BAO_Contact
::createProfileContact($behalfOrganization, $fields, $orgID,
1178 NULL, NULL, 'Organization'
1180 // create relationship
1181 if ($isNotCurrentEmployer) {
1183 \Civi\Api4\Relationship
::create(FALSE)
1184 ->addValue('contact_id_a', $contactID)
1185 ->addValue('contact_id_b', $orgID)
1186 ->addValue('relationship_type_id', CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b'))
1187 ->addValue('is_permission_a_b:name', 'View and update')
1190 catch (CRM_Core_Exception
$e) {
1191 // Ignore if duplicate relationship.
1192 if ($e->getMessage() !== 'Duplicate Relationship') {
1198 // if multiple match - send a duplicate alert
1199 if ($dupeIDs && (count($dupeIDs) > 1)) {
1200 $values['onbehalf_dupe_alert'] = 1;
1202 $params['onbehalf_dupe_alert'] = 1;
1205 // make sure organization-contact-id is considered for recording
1206 // contribution/membership etc..
1207 if ($contactID != $orgID) {
1208 // take a note of contact-id, so we can send the
1209 // receipt to individual contact as well.
1211 // required for mailing/template display ..etc
1212 $values['related_contact'] = $contactID;
1214 //CRM-19172: Create CMS user for individual on whose behalf organization is doing contribution
1215 $params['onbehalf_contact_id'] = $contactID;
1217 //make this employee of relationship as current
1218 //employer / employee relationship, CRM-3532
1219 if ($isNotCurrentEmployer &&
1220 ($orgID != CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id'))
1222 $isNotCurrentEmployer = FALSE;
1225 if (!$isNotCurrentEmployer && $orgID) {
1226 //build current employer params
1227 $currentEmpParams[$contactID] = $orgID;
1228 CRM_Contact_BAO_Contact_Utils
::setCurrentEmployer($currentEmpParams);
1231 // contribution / signup will be done using this
1233 $contactID = $orgID;
1238 * Function used to send notification mail to pcp owner.
1240 * This is used by contribution and also event PCPs.
1242 * @param object $contribution
1243 * @param object $contributionSoft
1244 * Contribution object.
1246 public static function pcpNotifyOwner($contribution, $contributionSoft) {
1247 $params = ['id' => $contributionSoft->pcp_id
];
1248 CRM_Core_DAO
::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo);
1249 $ownerNotifyID = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCPBlock', $pcpInfo['pcp_block_id'], 'owner_notify_id');
1250 $ownerNotifyOption = CRM_Core_PseudoConstant
::getName('CRM_PCP_DAO_PCPBlock', 'owner_notify_id', $ownerNotifyID);
1252 if ($ownerNotifyOption != 'no_notifications' &&
1253 (($ownerNotifyOption == 'owner_chooses' &&
1254 CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP', $contributionSoft->pcp_id
, 'is_notify')) ||
1255 $ownerNotifyOption == 'all_owners')) {
1256 $pcpInfoURL = CRM_Utils_System
::url('civicrm/pcp/info',
1257 "reset=1&id={$contributionSoft->pcp_id}",
1258 TRUE, NULL, FALSE, TRUE
1260 // set email in the template here
1262 if (CRM_Core_BAO_LocationType
::getBilling()) {
1263 list($donorName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contribution->contact_id
,
1264 FALSE, CRM_Core_BAO_LocationType
::getBilling());
1266 // get primary location email if no email exist( for billing location).
1268 list($donorName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contribution->contact_id
);
1270 list($ownerName, $ownerEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contributionSoft->contact_id
);
1272 'page_title' => $pcpInfo['title'],
1273 'receive_date' => $contribution->receive_date
,
1274 'total_amount' => $contributionSoft->amount
,
1275 'donors_display_name' => $donorName,
1276 'donors_email' => $email,
1277 'pcpInfoURL' => $pcpInfoURL,
1278 'is_honor_roll_enabled' => $contributionSoft->pcp_display_in_roll
,
1279 'currency' => $contributionSoft->currency
,
1281 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
1282 $sendTemplateParams = [
1283 'groupName' => 'msg_tpl_workflow_contribution',
1284 'valueName' => 'pcp_owner_notify',
1285 'contactId' => $contributionSoft->contact_id
,
1286 'toEmail' => $ownerEmail,
1287 'toName' => $ownerName,
1288 'from' => "$domainValues[0] <$domainValues[1]>",
1289 'tplParams' => $tplParams,
1290 'PDFFilename' => 'receipt.pdf',
1292 CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
1297 * Function used to se pcp related defaults / params.
1299 * This is used by contribution and also event PCPs
1301 * @param CRM_Core_Form $page
1303 * @param array $params
1307 public static function processPcp(&$page, $params) {
1308 $params['pcp_made_through_id'] = $page->_pcpId
;
1309 $page->assign('pcpBlock', TRUE);
1310 if (!empty($params['pcp_display_in_roll']) && empty($params['pcp_roll_nickname'])) {
1311 $params['pcp_roll_nickname'] = ts('Anonymous');
1312 $params['pcp_is_anonymous'] = 1;
1315 $params['pcp_is_anonymous'] = 0;
1318 'pcp_display_in_roll',
1320 'pcp_roll_nickname',
1321 'pcp_personal_note',
1323 if (!empty($params[$val])) {
1324 $page->assign($val, $params[$val]);
1332 * Process membership.
1334 * @param array $membershipParams
1335 * @param int $contactID
1336 * @param array $customFieldsFormatted
1337 * @param array $fieldTypes
1338 * @param array $premiumParams
1339 * @param array $membershipLineItems
1340 * Line items specifically relating to memberships.
1342 protected function processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams,
1343 $membershipLineItems) {
1345 $membershipTypeIDs = (array) $membershipParams['selectMembership'];
1346 $membershipTypes = CRM_Member_BAO_Membership
::buildMembershipTypeValues($this, $membershipTypeIDs);
1347 $membershipType = empty($membershipTypes) ?
[] : reset($membershipTypes);
1349 $this->assign('membership_name', $membershipType['name']);
1350 $this->_values
['membership_name'] = $membershipType['name'] ??
NULL;
1352 $isPaidMembership = FALSE;
1353 if ($this->_amount
>= 0.0 && isset($membershipParams['amount'])) {
1354 //amount must be greater than zero for
1355 //adding contribution record to contribution table.
1356 //this condition arises when separate membership payment is
1357 //enabled and contribution amount is not selected. fix for CRM-3010
1358 $isPaidMembership = TRUE;
1360 $isProcessSeparateMembershipTransaction = $this->isSeparateMembershipTransaction($this->_id
, $this->_values
['amount_block_is_active']);
1362 if ($this->_values
['amount_block_is_active']) {
1363 $financialTypeID = $this->_values
['financial_type_id'];
1366 $financialTypeID = $membershipType['financial_type_id'] ??
$membershipParams['financial_type_id'] ??
NULL;
1369 if (!empty($this->_params
['membership_source'])) {
1370 $membershipParams['contribution_source'] = $this->_params
['membership_source'];
1373 $this->postProcessMembership($membershipParams, $contactID,
1374 $this, $premiumParams, $customFieldsFormatted, $fieldTypes, $membershipType, $membershipTypeIDs, $isPaidMembership, $this->_membershipId
, $isProcessSeparateMembershipTransaction, $financialTypeID,
1375 $membershipLineItems);
1377 $this->assign('membership_assign', TRUE);
1378 $this->set('membershipTypeID', $membershipParams['selectMembership']);
1382 * Process the Memberships.
1384 * @param array $membershipParams
1385 * Array of membership fields.
1386 * @param int $contactID
1388 * @param CRM_Contribute_Form_Contribution_Confirm $form
1389 * Confirmation form object.
1391 * @param array $premiumParams
1392 * @param null $customFieldsFormatted
1393 * @param null $includeFieldTypes
1395 * @param array $membershipDetails
1397 * @param array $membershipTypeIDs
1399 * @param bool $isPaidMembership
1400 * @param array $membershipID
1402 * @param bool $isProcessSeparateMembershipTransaction
1404 * @param int $financialTypeID
1405 * @param array $unprocessedLineItems
1406 * Line items for payment options chosen on the form.
1408 * @throws \CRM_Core_Exception
1409 * @throws \CiviCRM_API3_Exception
1410 * @throws \Civi\Payment\Exception\PaymentProcessorException
1412 protected function postProcessMembership(
1413 $membershipParams, $contactID, &$form, $premiumParams,
1414 $customFieldsFormatted = NULL, $includeFieldTypes = NULL, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID,
1415 $isProcessSeparateMembershipTransaction, $financialTypeID, $unprocessedLineItems) {
1417 $membershipContribution = NULL;
1418 $isTest = $membershipParams['is_test'] ??
FALSE;
1419 $errors = $paymentResults = [];
1420 $form->_values
['isMembership'] = TRUE;
1421 $isRecurForFirstTransaction = $form->_params
['is_recur'] ??
$membershipParams['is_recur'] ??
NULL;
1423 $totalAmount = $membershipParams['amount'];
1425 if ($isPaidMembership) {
1426 if ($isProcessSeparateMembershipTransaction) {
1427 // If we have 2 transactions only one can use the invoice id.
1428 $membershipParams['invoiceID'] .= '-2';
1429 if (!empty($membershipParams['auto_renew'])) {
1430 $isRecurForFirstTransaction = FALSE;
1434 if (!$isProcessSeparateMembershipTransaction) {
1435 // Skip line items in the contribution processing transaction.
1436 // We will create them with the membership for proper linking.
1437 $membershipParams['skipLineItem'] = 1;
1440 $membershipParams['total_amount'] = $totalAmount;
1441 $membershipParams['skipLineItem'] = 0;
1442 CRM_Price_BAO_LineItem
::getLineItemArray($membershipParams);
1445 $paymentResult = CRM_Contribute_BAO_Contribution_Utils
::processConfirm(
1451 $isRecurForFirstTransaction
1453 if (!empty($paymentResult['contribution'])) {
1454 $paymentResults[] = ['contribution_id' => $paymentResult['contribution']->id
, 'result' => $paymentResult];
1455 $this->postProcessPremium($premiumParams, $paymentResult['contribution']);
1456 //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
1457 $membershipContribution = $paymentResult['contribution'];
1458 // Save the contribution ID so that I can be used in email receipts
1459 // For example, if you need to generate a tax receipt for the donation only.
1460 $form->_values
['contribution_other_id'] = $membershipContribution->id
;
1464 if ($isProcessSeparateMembershipTransaction) {
1466 $form->_lineItem
= $unprocessedLineItems;
1467 if (empty($form->_params
['auto_renew']) && !empty($membershipParams['is_recur'])) {
1468 unset($membershipParams['is_recur']);
1470 list($membershipContribution, $secondPaymentResult) = $this->processSecondaryFinancialTransaction($contactID, $form, array_merge($membershipParams, ['skipLineItem' => 1]),
1471 $isTest, $unprocessedLineItems, $membershipDetails['minimum_fee'] ??
0, $membershipDetails['financial_type_id'] ??
NULL);
1472 $paymentResults[] = ['contribution_id' => $membershipContribution->id
, 'result' => $secondPaymentResult];
1473 $totalAmount = $membershipContribution->total_amount
;
1475 catch (CRM_Core_Exception
$e) {
1476 $errors[2] = $e->getMessage();
1477 $membershipContribution = NULL;
1482 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1483 $membershipContributionID = $membershipContribution->id
;
1486 //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
1487 if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
1488 $form->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
1490 //@todo it should no longer be possible for it to get to this point & membership to not be an array
1491 if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
1492 $typesTerms = $membershipParams['types_terms'] ??
[];
1494 $membershipLines = $nonMembershipLines = [];
1495 foreach ($unprocessedLineItems as $priceSetID => $lines) {
1496 foreach ($lines as $line) {
1497 if (!empty($line['membership_type_id'])) {
1498 $membershipLines[$line['membership_type_id']] = $line['price_field_value_id'];
1504 $form->_params
['createdMembershipIDs'] = [];
1505 foreach ($membershipTypeIDs as $memType) {
1506 $membershipLineItems = [];
1507 if ($i < count($membershipTypeIDs)) {
1508 $membershipLineItems[$priceSetID][$membershipLines[$memType]] = $unprocessedLineItems[$priceSetID][$membershipLines[$memType]];
1509 unset($unprocessedLineItems[$priceSetID][$membershipLines[$memType]]);
1512 $membershipLineItems = $unprocessedLineItems;
1515 $numTerms = $typesTerms[$memType] ??
1;
1516 $contributionRecurID = $form->_params
['contributionRecurID'] ??
NULL;
1518 $membershipSource = NULL;
1519 if (!empty($form->_params
['membership_source'])) {
1520 $membershipSource = $form->_params
['membership_source'];
1522 elseif ((isset($form->_values
['title']) && !empty($form->_values
['title'])) ||
(isset($form->_values
['frontend_title']) && !empty($form->_values
['frontend_title']))) {
1523 $title = !empty($form->_values
['frontend_title']) ?
$form->_values
['frontend_title'] : $form->_values
['title'];
1524 $membershipSource = ts('Online Contribution:') . ' ' . $title;
1527 if (isset($form->_params
)) {
1528 $isPayLater = $form->_params
['is_pay_later'] ??
NULL;
1531 'campaign_id' => $form->_params
['campaign_id'] ??
($form->_values
['campaign_id'] ??
NULL),
1534 // @todo Move this into CRM_Member_BAO_Membership::processMembership
1535 if (!empty($membershipContribution)) {
1536 $pending = $membershipContribution->contribution_status_id
== CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1539 // The concept of contributeMode is deprecated.
1540 // the is_monetary concept probably should be too as it can be calculated from
1541 // the existence of 'amount' & seems fragile.
1542 if (((isset($this->_contributeMode
)) ||
!empty($this->_params
['is_pay_later'])
1544 (($this->_values
['is_monetary'] && $this->_amount
> 0.0))
1551 list($membership, $renewalMode, $dates) = CRM_Member_BAO_Membership
::processMembership(
1552 $contactID, $memType, $isTest,
1553 date('YmdHis'), $membershipParams['cms_contactID'] ??
NULL,
1554 $customFieldsFormatted,
1555 $numTerms, $membershipID, $pending,
1556 $contributionRecurID, $membershipSource, $isPayLater, $memParams, [], $membershipContribution,
1557 $membershipLineItems
1560 $form->set('renewal_mode', $renewalMode);
1561 if (!empty($dates)) {
1562 $form->assign('mem_start_date', CRM_Utils_Date
::customFormat($dates['start_date'], '%Y%m%d'));
1563 $form->assign('mem_end_date', CRM_Utils_Date
::customFormat($dates['end_date'], '%Y%m%d'));
1566 if (!empty($membershipContribution)) {
1567 // Next line is probably redundant. Checks prevent it happening twice.
1568 $membershipPaymentParams = [
1569 'membership_id' => $membership->id
,
1570 'membership_type_id' => $membership->membership_type_id
,
1571 'contribution_id' => $membershipContribution->id
,
1573 civicrm_api3('MembershipPayment', 'create', $membershipPaymentParams);
1576 CRM_Core_BAO_CustomValueTable
::postProcess($form->_params
, 'civicrm_membership', $membership->id
, 'Membership');
1577 $form->_params
['createdMembershipIDs'][] = $membership->id
;
1578 $form->_params
['membershipID'] = $membership->id
;
1580 //CRM-15232: Check if membership is created and on the basis of it use
1581 //membership receipt template to send payment receipt
1582 $form->_values
['isMembership'] = TRUE;
1585 if ($form->_priceSetId
&& !empty($form->_useForMember
) && !empty($form->_lineItem
)) {
1586 foreach ($form->_lineItem
[$form->_priceSetId
] as & $priceFieldOp) {
1587 if (!empty($priceFieldOp['membership_type_id']) && $membership->membership_type_id
== $priceFieldOp['membership_type_id']) {
1588 $membershipOb = $membership;
1589 $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date
::formatDateOnlyLong($membershipOb->start_date
) : '-';
1590 $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date
::formatDateOnlyLong($membershipOb->end_date
) : '-';
1593 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1596 $form->_values
['lineItem'] = $form->_lineItem
;
1597 $form->assign('lineItem', $form->_lineItem
);
1601 if (!empty($errors)) {
1602 $message = $this->compileErrorMessage($errors);
1603 throw new CRM_Core_Exception($message);
1606 if (isset($membershipContributionID)) {
1607 $form->_values
['contribution_id'] = $membershipContributionID;
1610 if (empty($form->_params
['is_pay_later']) && $form->_paymentProcessor
) {
1611 // the is_monetary concept probably should be deprecated as it can be calculated from
1612 // the existence of 'amount' & seems fragile.
1613 if ($form->_values
['is_monetary'] && $form->_amount
> 0.0 && !$form->_params
['is_pay_later']) {
1614 // call postProcess hook before leaving
1615 $form->postProcessHook();
1618 $payment = Civi\Payment\System
::singleton()->getByProcessor($form->_paymentProcessor
);
1619 // The contribution_other_id is effectively the ID for the only contribution or the non-membership contribution.
1620 // Since we have called the membership contribution (in a 2 contribution scenario) this is out
1621 // primary-contribution compared to that - but let's face it - it's all just too hard & confusing at the moment!
1622 $paymentParams = array_merge($form->_params
, ['contributionID' => $form->_values
['contribution_other_id']]);
1624 // CRM-19792 : set necessary fields for payment processor
1625 CRM_Core_Payment_Form
::mapParams($form->_bltID
, $paymentParams, $paymentParams, TRUE);
1627 // If this is a single membership-related contribution, it won't have
1628 // be performed yet, so do it now.
1629 if ($isPaidMembership && !$isProcessSeparateMembershipTransaction) {
1630 $paymentActionResult = $payment->doPayment($paymentParams, 'contribute');
1631 $paymentResults[] = ['contribution_id' => $paymentResult['contribution']->id
, 'result' => $paymentActionResult];
1633 // Do not send an email if Recurring transaction is done via Direct Mode
1634 // Email will we sent when the IPN is received.
1635 foreach ($paymentResults as $result) {
1636 //CRM-18211: Fix situation where second contribution doesn't exist because it is optional.
1637 if ($result['contribution_id']) {
1638 $this->completeTransaction($result['result'], $result['contribution_id']);
1644 $emailValues = array_merge($membershipParams, $form->_values
);
1645 $emailValues['membership_assign'] = 1;
1646 $emailValues['useForMember'] = !empty($form->_useForMember
);
1648 // Finally send an email receipt for pay-later scenario (although it might sometimes be caught above!)
1649 if ($totalAmount == 0) {
1650 // This feels like a bizarre hack as the variable name doesn't seem to be directly connected to it's use in the template.
1651 $emailValues['useForMember'] = 0;
1652 $emailValues['amount'] = 0;
1654 //CRM-18071, where on selecting $0 free membership payment section got hidden and
1655 // also it reset any payment processor selection result into pending free membership
1656 // so its a kind of hack to complete free membership at this point since there is no $form->_paymentProcessor info
1657 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1658 if (empty($form->_paymentProcessor
)) {
1659 // @todo this can maybe go now we are setting payment_processor_id = 0 more reliably.
1660 $paymentProcessorIDs = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_values
['payment_processor'] ??
NULL);
1661 $this->_paymentProcessor
['id'] = $paymentProcessorIDs[0];
1663 $result = ['payment_status_id' => 1, 'contribution' => $membershipContribution];
1664 $this->completeTransaction($result, $result['contribution']->id
);
1666 // return as completeTransaction() already sends the receipt mail.
1670 CRM_Contribute_BAO_ContributionPage
::sendMail($contactID,
1678 * Turn array of errors into message string.
1680 * @param array $errors
1684 protected function compileErrorMessage($errors) {
1685 foreach ($errors as $error) {
1686 if (is_string($error)) {
1687 $message[] = $error;
1690 return ts('Payment Processor Error message') . ': ' . implode('<br/>', $message);
1694 * Where a second separate financial transaction is supported we will process it here.
1696 * @param int $contactID
1697 * @param CRM_Contribute_Form_Contribution_Confirm $form
1698 * @param array $tempParams
1699 * @param bool $isTest
1700 * @param array $lineItems
1701 * @param $minimumFee
1702 * @param int $financialTypeID
1704 * @throws CRM_Core_Exception
1706 * @return CRM_Contribute_BAO_Contribution
1708 protected function processSecondaryFinancialTransaction($contactID, &$form, $tempParams, $isTest, $lineItems, $minimumFee,
1710 $financialType = new CRM_Financial_DAO_FinancialType();
1711 $financialType->id
= $financialTypeID;
1712 $financialType->find(TRUE);
1713 $tempParams['amount'] = $minimumFee;
1714 $tempParams['invoiceID'] = md5(uniqid(rand(), TRUE));
1715 $isRecur = $tempParams['is_recur'] ??
NULL;
1717 //assign receive date when separate membership payment
1718 //and contribution amount not selected.
1719 if ($form->_amount
== 0) {
1720 $now = date('YmdHis');
1721 $form->_params
['receive_date'] = $now;
1722 $receiveDate = CRM_Utils_Date
::mysqlToIso($now);
1723 $form->set('params', $form->_params
);
1724 $form->assign('receive_date', $receiveDate);
1727 $form->set('membership_amount', $minimumFee);
1728 $form->assign('membership_amount', $minimumFee);
1730 // we don't need to create the user twice, so lets disable cms_create_account
1731 // irrespective of the value, CRM-2888
1732 $tempParams['cms_create_account'] = 0;
1734 //set this variable as we are not creating pledge for
1735 //separate membership payment contribution.
1736 //so for differentiating membership contribution from
1737 //main contribution.
1738 $form->_params
['separate_membership_payment'] = 1;
1739 $contributionParams = [
1740 'contact_id' => $contactID,
1741 'line_item' => $lineItems,
1742 'is_test' => $isTest,
1743 'campaign_id' => $tempParams['campaign_id'] ??
$form->_values
['campaign_id'] ??
NULL,
1744 'contribution_page_id' => $form->_id
,
1745 'source' => $tempParams['source'] ??
$tempParams['description'] ??
NULL,
1747 $isMonetary = !empty($form->_values
['is_monetary']);
1749 if (empty($paymentParams['is_pay_later'])) {
1750 $contributionParams['payment_instrument_id'] = $form->_paymentProcessor
['payment_instrument_id'];
1754 // CRM-19792 : set necessary fields for payment processor
1755 CRM_Core_Payment_Form
::mapParams($form->_bltID
, $form->_params
, $tempParams, TRUE);
1757 $membershipContribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($form,
1760 $contributionParams,
1769 // We're not processing the line item here because we are processing a membership.
1770 // To ensure processing of the correct parameters, replace relevant parameters
1771 // in $tempParams with those in $membershipContribution.
1772 $tempParams['amount_level'] = $membershipContribution->amount_level
;
1773 $tempParams['total_amount'] = $membershipContribution->total_amount
;
1774 $tempParams['tax_amount'] = $membershipContribution->tax_amount
;
1775 $tempParams['contactID'] = $membershipContribution->contact_id
;
1776 $tempParams['financialTypeID'] = $membershipContribution->financial_type_id
;
1777 $tempParams['invoiceID'] = $membershipContribution->invoice_id
;
1778 $tempParams['trxn_id'] = $membershipContribution->trxn_id
;
1779 $tempParams['contributionID'] = $membershipContribution->id
;
1781 if ($form->_values
['is_monetary'] && !$form->_params
['is_pay_later'] && $minimumFee > 0.0) {
1782 // At the moment our tests are calling this form in a way that leaves 'object' empty. For
1783 // now we compensate here.
1784 if (empty($form->_paymentProcessor
['object'])) {
1785 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1788 $payment = $form->_paymentProcessor
['object'];
1790 $result = $payment->doPayment($tempParams, 'contribute');
1791 $form->set('membership_trx_id', $result['trxn_id']);
1792 $form->assign('membership_trx_id', $result['trxn_id']);
1795 return [$membershipContribution, $result];
1799 * Are we going to do 2 financial transactions.
1801 * Ie the membership block supports a separate transactions AND the contribution form has been configured for a
1803 * transaction AND a membership transaction AND the payment processor supports double financial transactions (ie. NOT doTransferCheckout style)
1805 * @param int $formID
1806 * @param bool $amountBlockActiveOnForm
1810 public function isSeparateMembershipTransaction($formID, $amountBlockActiveOnForm) {
1811 $memBlockDetails = CRM_Member_BAO_Membership
::getMembershipBlock($formID);
1812 if (!empty($memBlockDetails['is_separate_payment']) && $amountBlockActiveOnForm) {
1819 * This function sets the fields.
1821 * - $this->_params['amount_level']
1822 * - $this->_params['selectMembership']
1823 * And under certain circumstances sets
1824 * $this->_params['amount'] = null;
1826 * @param int $priceSetID
1828 public function setFormAmountFields($priceSetID) {
1829 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params
['priceSetId'], 'is_quick_config');
1830 $priceField = new CRM_Price_DAO_PriceField();
1831 $priceField->price_set_id
= $priceSetID;
1832 $priceField->orderBy('weight');
1833 $priceField->find();
1834 $paramWeDoNotUnderstand = NULL;
1836 while ($priceField->fetch()) {
1837 if ($priceField->name
== "contribution_amount") {
1838 $paramWeDoNotUnderstand = $priceField->id
;
1840 if ($isQuickConfig && !empty($this->_params
["price_{$priceField->id}"])) {
1841 if ($this->_values
['fee'][$priceField->id
]['html_type'] != 'Text') {
1842 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1843 // function to get correct amount level consistently. Remove setting of the amount level in
1844 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1845 // to cover all variants.
1846 $this->_params
['amount_level'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1847 $this->_params
["price_{$priceField->id}"], 'label');
1849 if ($priceField->name
== "membership_amount") {
1850 $this->_params
['selectMembership'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1851 $this->_params
["price_{$priceField->id}"], 'membership_type_id');
1854 // If separate payment we set contribution amount to be null, so that it will not show contribution amount same
1855 // as membership amount.
1856 // @todo - this needs more documentation - it appears the setting to null is tied up with separate membership payments
1857 // but the circumstances are very confusing. Many of these conditions are repeated in the next conditional
1858 // so we should merge them together
1859 // the quick config seems like a red-herring - if this is about a separate membership payment then there
1860 // are 2 types of line items - membership ones & non-membership ones - regardless of whether quick config is set
1862 !empty($this->_membershipBlock
['is_separate_payment'])
1863 && !empty($this->_values
['fee'][$priceField->id
])
1864 && ($this->_values
['fee'][$priceField->id
]['name'] == "other_amount")
1865 && ($this->_params
["price_{$paramWeDoNotUnderstand}"] ??
NULL) < 1
1866 && empty($this->_params
["price_{$priceField->id}"])
1868 $this->_params
['amount'] = NULL;
1871 // Fix for CRM-14375 - If we are using separate payments and "no
1872 // thank you" is selected for the additional contribution, set
1873 // contribution amount to be null, so that it will not show
1874 // contribution amount same as membership amount.
1875 //@todo - merge with section above
1876 if (!empty($this->_membershipBlock
['is_separate_payment'])
1877 && !empty($this->_values
['fee'][$priceField->id
])
1878 && ($this->_values
['fee'][$priceField->id
]['name'] ??
NULL) == 'contribution_amount'
1879 && ($this->_params
["price_{$priceField->id}"] ??
NULL) == '-1'
1881 $this->_params
['amount'] = NULL;
1889 * @param array $params
1891 * @throws CiviCRM_API3_Exception
1893 public static function submit($params) {
1894 $form = new CRM_Contribute_Form_Contribution_Confirm();
1895 $form->_id
= $params['id'];
1897 CRM_Contribute_BAO_ContributionPage
::setValues($form->_id
, $form->_values
);
1898 $form->_separateMembershipPayment
= CRM_Contribute_BAO_ContributionPage
::getIsMembershipPayment($form->_id
);
1899 //this way the mocked up controller ignores the session stuff
1900 $_SERVER['REQUEST_METHOD'] = 'GET';
1901 $form->controller
= new CRM_Contribute_Controller_Contribution();
1902 $params['invoiceID'] = md5(uniqid(rand(), TRUE));
1904 // We want to move away from passing in amount as it is calculated by the actually-submitted params.
1905 if ($form->getMainContributionAmount($params)) {
1906 $params['amount'] = $form->getMainContributionAmount($params);
1908 $paramsProcessedForForm = $form->_params
= self
::getFormParams($params['id'], $params);
1910 $order = new CRM_Financial_BAO_Order();
1911 $order->setPriceSelectionFromUnfilteredInput($params);
1912 if (isset($params['amount'])) {
1913 // @todo deprecate receiving amount, calculate on the form.
1914 $order->setOverrideTotalAmount($params['amount']);
1916 $amount = $order->getTotalAmount();
1917 $form->_amount
= $params['amount'] = $form->_params
['amount'] = $params['amount'] ??
$amount;
1918 // hack these in for test support.
1919 $form->_fields
['billing_first_name'] = 1;
1920 $form->_fields
['billing_last_name'] = 1;
1921 // CRM-18854 - Set form values to allow pledge to be created for api test.
1922 if (!empty($params['pledge_block_id'])) {
1923 $form->_values
['pledge_id'] = $params['pledge_id'] ??
NULL;
1924 $form->_values
['pledge_block_id'] = $params['pledge_block_id'];
1925 $pledgeBlock = CRM_Pledge_BAO_PledgeBlock
::getPledgeBlock($params['id']);
1926 $form->_values
['max_reminders'] = $pledgeBlock['max_reminders'];
1927 $form->_values
['initial_reminder_day'] = $pledgeBlock['initial_reminder_day'];
1928 $form->_values
['additional_reminder_day'] = $pledgeBlock['additional_reminder_day'];
1929 $form->_values
['is_email_receipt'] = FALSE;
1931 $priceSetID = $form->_params
['priceSetId'] = $paramsProcessedForForm['price_set_id'];
1932 $priceFields = CRM_Price_BAO_PriceSet
::getSetDetail($priceSetID);
1933 $priceSetFields = reset($priceFields);
1934 $form->_values
['fee'] = $priceSetFields['fields'];
1935 $form->_priceSetId
= $priceSetID;
1936 $form->setFormAmountFields($priceSetID);
1939 $capabilities[] = (ucfirst($form->_mode
) . 'Mode');
1941 $form->_paymentProcessors
= CRM_Financial_BAO_PaymentProcessor
::getPaymentProcessors($capabilities);
1942 $form->_params
['payment_processor_id'] = $params['payment_processor_id'] ??
0;
1943 if ($form->_params
['payment_processor_id'] !== '') {
1944 // It can be blank with a $0 transaction - then no processor needs to be selected
1945 $form->_paymentProcessor
= $form->_paymentProcessors
[$form->_params
['payment_processor_id']];
1947 if (!empty($params['payment_processor_id'])) {
1948 // The concept of contributeMode is deprecated as is the billing_mode concept.
1949 if ($form->_paymentProcessor
['billing_mode'] == 1) {
1950 $form->_contributeMode
= 'direct';
1953 $form->_contributeMode
= 'notify';
1957 if (!empty($params['useForMember'])) {
1958 $form->set('useForMember', 1);
1959 $form->_useForMember
= 1;
1961 $priceFields = $priceFields[$priceSetID]['fields'];
1963 $form->processAmountAndGetAutoRenew($priceFields, $paramsProcessedForForm, $lineItems, $priceSetID);
1964 $form->_lineItem
= [$priceSetID => $lineItems];
1965 $membershipPriceFieldIDs = [];
1966 foreach ((array) $lineItems as $lineItem) {
1967 if (!empty($lineItem['membership_type_id'])) {
1968 $form->set('useForMember', 1);
1969 $form->_useForMember
= 1;
1970 $membershipPriceFieldIDs['id'] = $priceSetID;
1971 $membershipPriceFieldIDs[] = $lineItem['price_field_value_id'];
1974 $form->set('memberPriceFieldIDS', $membershipPriceFieldIDs);
1975 $form->setRecurringMembershipParams();
1976 $form->processFormSubmission($params['contact_id'] ??
NULL);
1980 * Helper function for static submit function.
1982 * Set relevant params - help us to build up an array that we can pass in.
1985 * @param array $params
1988 * @throws CiviCRM_API3_Exception
1990 public static function getFormParams($id, array $params) {
1991 if (!isset($params['is_pay_later'])) {
1992 if (!empty($params['payment_processor_id'])) {
1993 $params['is_pay_later'] = 0;
1995 elseif (($params['amount'] ??
0) !== 0) {
1996 $params['is_pay_later'] = civicrm_api3('contribution_page', 'getvalue', [
1998 'return' => 'is_pay_later',
2002 if (empty($params['price_set_id'])) {
2003 $params['price_set_id'] = CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution_page', $params['id']);
2009 * Post form submission handling.
2011 * This is also called from the test suite.
2013 * @param int $contactID
2016 * @throws \CRM_Core_Exception
2018 protected function processFormSubmission($contactID) {
2019 if (!isset($this->_params
['payment_processor_id'])) {
2020 // If there is no processor we are using the pay-later manual pseudo-processor.
2021 // (note it might make sense to make this a row in the processor table in the db).
2022 $this->_params
['payment_processor_id'] = 0;
2024 if (isset($this->_params
['payment_processor_id']) && $this->_params
['payment_processor_id'] === 0) {
2025 $this->_params
['is_pay_later'] = $isPayLater = TRUE;
2028 if (!empty($this->_ccid
)) {
2029 $this->_params
['contribution_id'] = $this->_ccid
;
2031 //Set email-bltID if pre/post profile contains an email.
2032 if ($this->_emailExists
== TRUE) {
2033 foreach ($this->_params
as $key => $val) {
2034 if (substr($key, 0, 6) == 'email-' && empty($this->_params
["email-{$this->_bltID}"])) {
2035 $this->_params
["email-{$this->_bltID}"] = $this->_params
[$key];
2039 // add a description field at the very beginning
2040 $title = !empty($this->_values
['frontend_title']) ?
$this->_values
['frontend_title'] : $this->_values
['title'];
2041 $this->_params
['description'] = ts('Online Contribution') . ': ' . (!empty($this->_pcpInfo
['title']) ?
$this->_pcpInfo
['title'] : $title);
2043 $this->_params
['accountingCode'] = $this->_values
['accountingCode'] ??
NULL;
2046 $this->_params
['currencyID'] = CRM_Core_Config
::singleton()->defaultCurrency
;
2048 CRM_Contribute_Form_AbstractEditPayment
::formatCreditCardDetails($this->_params
);
2051 if (!empty($this->_params
['is_pledge']) && empty($this->_values
['pledge_id']) && !empty($this->_values
['adjust_recur_start_date'])) {
2052 $pledgeBlock = CRM_Pledge_BAO_PledgeBlock
::getPledgeBlock($this->_id
);
2053 if (!empty($this->_params
['start_date']) ||
empty($pledgeBlock['is_pledge_start_date_visible'])
2054 ||
empty($pledgeBlock['is_pledge_start_date_editable'])) {
2055 $pledgeStartDate = $this->_params
['start_date'] ??
NULL;
2056 $this->_params
['receive_date'] = CRM_Pledge_BAO_Pledge
::getPledgeStartDate($pledgeStartDate, $pledgeBlock);
2057 $recurParams = CRM_Pledge_BAO_Pledge
::buildRecurParams($this->_params
);
2058 $this->_params
= array_merge($this->_params
, $recurParams);
2062 //carry payment processor id.
2063 if (!empty($this->_paymentProcessor
['id'])) {
2064 $this->_params
['payment_processor_id'] = $this->_paymentProcessor
['id'];
2067 $premiumParams = $membershipParams = $params = $this->_params
;
2068 if (!empty($params['image_URL'])) {
2069 CRM_Contact_BAO_Contact
::processImageParams($params);
2072 $fields = ['email-Primary' => 1];
2074 // get the add to groups
2077 // now set the values for the billing location.
2078 foreach ($this->_fields
as $name => $value) {
2081 // get the add to groups for uf fields
2082 if (!empty($value['add_to_group_id'])) {
2083 $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id'];
2087 $fields = $this->formatParamsForPaymentProcessor($fields);
2089 // billing email address
2090 $fields["email-{$this->_bltID}"] = 1;
2092 // if onbehalf-of-organization contribution, take out
2093 // organization params in a separate variable, to make sure
2094 // normal behavior is continued. And use that variable to
2095 // process on-behalf-of functionality.
2096 if (!empty($this->_values
['onbehalf_profile_id']) && empty($this->_ccid
)) {
2097 $behalfOrganization = [];
2098 $orgFields = ['organization_name', 'organization_id', 'org_option'];
2099 foreach ($orgFields as $fld) {
2100 if (array_key_exists($fld, $params)) {
2101 $behalfOrganization[$fld] = $params[$fld];
2102 unset($params[$fld]);
2106 if (is_array($params['onbehalf']) && !empty($params['onbehalf'])) {
2107 foreach ($params['onbehalf'] as $fld => $values) {
2108 if (strstr($fld, 'custom_')) {
2109 $behalfOrganization[$fld] = $values;
2111 elseif (!(strstr($fld, '-'))) {
2112 if (in_array($fld, [
2113 'contribution_campaign_id',
2114 'member_campaign_id',
2116 $fld = 'campaign_id';
2119 $behalfOrganization[$fld] = $values;
2121 $this->_params
[$fld] = $values;
2126 if (array_key_exists('onbehalf_location', $params) && is_array($params['onbehalf_location'])) {
2127 foreach ($params['onbehalf_location'] as $block => $vals) {
2128 //fix for custom data (of type checkbox, multi-select)
2129 if (substr($block, 0, 7) == 'custom_') {
2132 // fix the index of block elements
2133 if (is_array($vals)) {
2134 foreach ($vals as $key => $val) {
2135 //dont adjust the index of address block as
2136 //it's index is WRT to location type
2137 $newKey = ($block == 'address') ?
$key : ++
$key;
2138 $behalfOrganization[$block][$newKey] = $val;
2142 unset($params['onbehalf_location']);
2144 if (!empty($params['onbehalf[image_URL]'])) {
2145 $behalfOrganization['image_URL'] = $params['onbehalf[image_URL]'];
2149 // check for profile double opt-in and get groups to be subscribed
2150 $subscribeGroupIds = CRM_Core_BAO_UFGroup
::getDoubleOptInGroupIds($params, $contactID);
2152 // since we are directly adding contact to group lets unset it from mailing
2153 if (!empty($addToGroups)) {
2154 foreach ($addToGroups as $groupId) {
2155 if (isset($subscribeGroupIds[$groupId])) {
2156 unset($subscribeGroupIds[$groupId]);
2161 foreach ($addToGroups as $k) {
2162 if (array_key_exists($k, $subscribeGroupIds)) {
2163 unset($addToGroups[$k]);
2167 if (empty($contactID)) {
2168 $dupeParams = $params;
2169 if (!empty($dupeParams['onbehalf'])) {
2170 unset($dupeParams['onbehalf']);
2172 if (!empty($dupeParams['honor'])) {
2173 unset($dupeParams['honor']);
2176 $contactID = CRM_Contact_BAO_Contact
::getFirstDuplicateContact($dupeParams, 'Individual', 'Unsupervised', [], FALSE);
2178 // Fetch default greeting id's if creating a contact
2180 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
2181 if (!isset($params[$greeting])) {
2182 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting('Individual', $greeting);
2186 $contactType = NULL;
2189 $contactType = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'contact_type');
2191 $contactID = CRM_Contact_BAO_Contact
::createProfileContact(
2201 // Make the contact ID associated with the contribution available at the Class level.
2202 // Also make available to the session.
2203 //@todo consider handling this in $this->getContactID();
2204 $this->set('contactID', $contactID);
2205 $this->_contactID
= $contactID;
2207 //get email primary first if exist
2208 $subscriptionEmail = ['email' => $params['email-Primary'] ??
NULL];
2209 if (!$subscriptionEmail['email']) {
2210 $subscriptionEmail['email'] = $params["email-{$this->_bltID}"] ??
NULL;
2212 // subscribing contact to groups
2213 if (!empty($subscribeGroupIds) && $subscriptionEmail['email']) {
2214 CRM_Mailing_Event_BAO_Subscribe
::commonSubscribe($subscribeGroupIds, $subscriptionEmail, $contactID);
2217 // If onbehalf-of-organization contribution / signup, add organization
2218 // and it's location.
2219 if (isset($this->_values
['onbehalf_profile_id']) &&
2220 isset($behalfOrganization['organization_name']) &&
2221 ($this->_values
['is_for_organization'] == 2 ||
2222 !empty($this->_params
['is_for_organization'])
2226 foreach ($this->_fields
['onbehalf'] as $name => $value) {
2227 $ufFields[$name] = 1;
2229 self
::processOnBehalfOrganization($behalfOrganization, $contactID, $this->_values
,
2230 $this->_params
, $ufFields
2233 elseif (!empty($this->_membershipContactID
) && $contactID != $this->_membershipContactID
) {
2234 // this is an onbehalf renew case for inherited membership. For e.g a permissioned member of household,
2235 // store current user id as related contact for later use for mailing / activity..
2236 $this->_values
['related_contact'] = $contactID;
2237 $this->_params
['related_contact'] = $contactID;
2238 // swap contact like we do for on-behalf-org case, so parent/primary membership is affected
2239 $contactID = $this->_membershipContactID
;
2242 // lets store the contactID in the session
2243 // for things like tell a friend
2244 $session = CRM_Core_Session
::singleton();
2245 if (!$session->get('userID')) {
2246 $session->set('transaction.userID', $contactID);
2249 $session->set('transaction.userID', NULL);
2252 $this->_useForMember
= $this->get('useForMember');
2254 // store the fact that this is a membership and membership type is selected
2255 if ($this->isMembershipSelected($membershipParams)) {
2256 if (!$this->_useForMember
) {
2257 $this->assign('membership_assign', TRUE);
2258 $this->set('membershipTypeID', $this->_params
['selectMembership']);
2261 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
2262 $membershipParams['is_test'] = 1;
2264 if ($this->_params
['is_pay_later']) {
2265 $membershipParams['is_pay_later'] = 1;
2268 if (isset($this->_params
['onbehalf_contact_id'])) {
2269 $membershipParams['onbehalf_contact_id'] = $this->_params
['onbehalf_contact_id'];
2271 //inherit campaign from contribution page.
2272 if (!array_key_exists('campaign_id', $membershipParams)) {
2273 $membershipParams['campaign_id'] = $this->_values
['campaign_id'] ??
NULL;
2276 $this->_params
= CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $membershipParams, TRUE);
2277 $this->doMembershipProcessing($contactID, $membershipParams, $premiumParams, $this->_lineItem
);
2280 // at this point we've created a contact and stored its address etc
2281 // all the payment processors expect the name and address to be in the
2282 // so we copy stuff over to first_name etc.
2283 $paymentParams = $this->_params
;
2284 // Make it explict that we are letting the processConfirm function figure out the line items.
2285 $paymentParams['skipLineItem'] = 0;
2287 if (!isset($paymentParams['line_item'])) {
2288 $paymentParams['line_item'] = $this->_lineItem
;
2291 if (!empty($paymentParams['onbehalf']) &&
2292 is_array($paymentParams['onbehalf'])
2294 foreach ($paymentParams['onbehalf'] as $key => $value) {
2295 if (strstr($key, 'custom_')) {
2296 $this->_params
[$key] = $value;
2301 $result = CRM_Contribute_BAO_Contribution_Utils
::processConfirm($this, $paymentParams,
2303 $this->wrangleFinancialTypeID($this->_values
['financial_type_id']),
2304 ($this->_mode
== 'test') ?
1 : 0,
2305 $paymentParams['is_recur'] ??
NULL
2308 if (empty($result['is_payment_failure'])) {
2309 // @todo move premium processing to complete transaction if it truly is an 'after' action.
2310 $this->postProcessPremium($premiumParams, $result['contribution']);
2312 if (!empty($result['contribution'])) {
2313 // It seems this line is hit when there is a zero dollar transaction & in tests, not sure when else.
2314 $this->completeTransaction($result, $result['contribution']->id
);
2321 * Return True/False if we have a membership selected on the contribution page
2322 * @param array $membershipParams
2326 private function isMembershipSelected($membershipParams) {
2327 $priceFieldIds = $this->get('memberPriceFieldIDS');
2328 if ((!empty($membershipParams['selectMembership']) && $membershipParams['selectMembership'] != 'no_thanks')
2329 && empty($priceFieldIds)) {
2333 $membershipParams = $this->getMembershipParamsFromPriceSet($membershipParams);
2335 return !empty($membershipParams['selectMembership']);
2339 * Extract the selected memberships from a priceSet
2341 * @param array $membershipParams
2345 private function getMembershipParamsFromPriceSet($membershipParams) {
2346 $priceFieldIds = $this->get('memberPriceFieldIDS');
2347 if (empty($priceFieldIds)) {
2348 return $membershipParams;
2350 $membershipParams['financial_type_id'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceFieldIds['id'], 'financial_type_id');
2351 unset($priceFieldIds['id']);
2352 $membershipTypeIds = [];
2353 $membershipTypeTerms = [];
2354 foreach ($priceFieldIds as $priceFieldId) {
2355 $membershipTypeId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id');
2356 if ($membershipTypeId) {
2357 $membershipTypeIds[] = $membershipTypeId;
2358 $term = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_num_terms') ?
: 1;
2359 $membershipTypeTerms[$membershipTypeId] = ($term > 1) ?
$term : 1;
2362 $membershipParams['selectMembership'] = $membershipTypeIds;
2363 $membershipParams['types_terms'] = $membershipTypeTerms;
2364 return $membershipParams;
2368 * Membership processing section.
2370 * This is in a separate function as part of a move towards refactoring.
2372 * @param int $contactID
2373 * @param array $membershipParams
2374 * @param array $premiumParams
2375 * @param array $formLineItems
2377 protected function doMembershipProcessing($contactID, $membershipParams, $premiumParams, $formLineItems) {
2378 // This could be set by a hook.
2379 if (!empty($this->_params
['installments'])) {
2380 $membershipParams['installments'] = $this->_params
['installments'];
2382 // added new parameter for cms user contact id, needed to distinguish behaviour for on behalf of sign-ups
2383 if (isset($this->_params
['related_contact'])) {
2384 $membershipParams['cms_contactID'] = $this->_params
['related_contact'];
2387 $membershipParams['cms_contactID'] = $contactID;
2390 if (!empty($membershipParams['onbehalf']) &&
2391 is_array($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])
2393 $this->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
2396 $customFieldsFormatted = $fieldTypes = [];
2397 if (!empty($membershipParams['onbehalf']) &&
2398 is_array($membershipParams['onbehalf'])
2400 foreach ($membershipParams['onbehalf'] as $key => $value) {
2401 if (strstr($key, 'custom_')) {
2402 $customFieldId = explode('_', $key);
2403 CRM_Core_BAO_CustomField
::formatCustomField(
2405 $customFieldsFormatted,
2413 $fieldTypes = ['Contact', 'Organization', 'Membership'];
2416 $membershipParams = $this->getMembershipParamsFromPriceSet($membershipParams);
2417 if (!empty($membershipParams['selectMembership'])) {
2419 $membershipLineItems = $formLineItems;
2420 if ($this->_separateMembershipPayment
&& $this->_values
['amount_block_is_active']) {
2421 $membershipLineItems = [];
2422 foreach ($this->_values
['fee'] as $key => $feeValues) {
2423 if ($feeValues['name'] == 'membership_amount') {
2424 $fieldId = $this->_params
['price_' . $key];
2425 $membershipLineItems[$this->_priceSetId
][$fieldId] = $this->_lineItem
[$this->_priceSetId
][$fieldId];
2426 unset($this->_lineItem
[$this->_priceSetId
][$fieldId]);
2432 $this->processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems);
2434 catch (\Civi\Payment\Exception\PaymentProcessorException
$e) {
2435 CRM_Core_Session
::singleton()->setStatus($e->getMessage());
2436 if (!empty($this->_contributionID
)) {
2437 CRM_Contribute_BAO_Contribution
::failPayment($this->_contributionID
,
2438 $contactID, $e->getMessage());
2440 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
2442 catch (CRM_Core_Exception
$e) {
2443 CRM_Core_Session
::singleton()->setStatus($e->getMessage());
2444 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
2446 if (!$this->_amount
> 0.0 ||
!$membershipParams['amount']) {
2447 // we need to explicitly create a CMS user in case of free memberships
2448 // since it is done under processConfirm for paid memberships
2449 CRM_Contribute_BAO_Contribution_Utils
::createCMSUser($membershipParams,
2450 $membershipParams['cms_contactID'],
2451 'email-' . $this->_bltID
2458 * Complete transaction if payment has been processed.
2460 * Check the result for a success outcome & if paid then complete the transaction.
2462 * Completing will trigger update of related entities and emails.
2464 * @param array $result
2465 * @param int $contributionID
2467 * @throws \CiviCRM_API3_Exception
2468 * @throws \Exception
2470 protected function completeTransaction($result, $contributionID) {
2471 if (($result['payment_status_id'] ??
NULL) == 1) {
2473 civicrm_api3('contribution', 'completetransaction', [
2474 'id' => $contributionID,
2475 'trxn_id' => $result['trxn_id'] ??
NULL,
2476 'payment_processor_id' => $result['payment_processor_id'] ??
$this->_paymentProcessor
['id'],
2477 'is_transactional' => FALSE,
2478 'fee_amount' => $result['fee_amount'] ??
NULL,
2479 'receive_date' => $result['receive_date'] ??
NULL,
2480 'card_type_id' => $result['card_type_id'] ??
NULL,
2481 'pan_truncation' => $result['pan_truncation'] ??
NULL,
2484 catch (CiviCRM_API3_Exception
$e) {
2485 if ($e->getErrorCode() != 'contribution_completed') {
2486 throw new CRM_Core_Exception('Failed to update contribution in database');
2493 * Bounce the user back to retry when an error occurs.
2495 * @param string $message
2497 protected function bounceOnError($message) {
2498 CRM_Core_Session
::singleton()
2499 ->setStatus(ts("Payment Processor Error message :") .
2501 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact',
2502 "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"