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(CRM_Utils_Array
::value('start_date', $params)));
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
153 public static function getContributionParams(
154 $params, $financialTypeID,
155 $paymentProcessorOutcome, $receiptDate, $recurringContributionID) {
156 $contributionParams = [
157 'financial_type_id' => $financialTypeID,
158 'receive_date' => (CRM_Utils_Array
::value('receive_date', $params)) ? CRM_Utils_Date
::processDate($params['receive_date']) : date('YmdHis'),
159 'tax_amount' => $params['tax_amount'] ??
NULL,
160 'amount_level' => $params['amount_level'] ??
NULL,
161 'invoice_id' => $params['invoiceID'],
162 'currency' => $params['currencyID'],
163 'is_pay_later' => CRM_Utils_Array
::value('is_pay_later', $params, 0),
164 //configure cancel reason, cancel date and thankyou date
165 //from 'contribution' type profile if included
166 'cancel_reason' => CRM_Utils_Array
::value('cancel_reason', $params, 0),
167 'cancel_date' => isset($params['cancel_date']) ? CRM_Utils_Date
::format($params['cancel_date']) : NULL,
168 'thankyou_date' => isset($params['thankyou_date']) ? CRM_Utils_Date
::format($params['thankyou_date']) : NULL,
169 //setting to make available to hook - although seems wrong to set on form for BAO hook availability
170 'skipLineItem' => CRM_Utils_Array
::value('skipLineItem', $params, 0),
173 if ($paymentProcessorOutcome) {
174 $contributionParams['payment_processor'] = $paymentProcessorOutcome['payment_processor'] ??
NULL;
176 if (!empty($params["is_email_receipt"])) {
177 $contributionParams +
= [
178 'receipt_date' => $receiptDate,
182 if ($recurringContributionID) {
183 $contributionParams['contribution_recur_id'] = $recurringContributionID;
186 $contributionParams['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
187 if (isset($contributionParams['invoice_id'])) {
188 $contributionParams['id'] = CRM_Core_DAO
::getFieldValue(
189 'CRM_Contribute_DAO_Contribution',
190 $contributionParams['invoice_id'],
196 return $contributionParams;
200 * Get non-deductible amount.
202 * This is a bit too much about wierd form interpretation to be this deep.
204 * @see https://issues.civicrm.org/jira/browse/CRM-11885
205 * if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep
208 * @param array $params
209 * @param CRM_Financial_BAO_FinancialType $financialType
210 * @param bool $online
211 * @param CRM_Contribute_Form_Contribution_Confirm $form
215 protected static function getNonDeductibleAmount($params, $financialType, $online, $form) {
216 if (isset($params['non_deductible_amount']) && (!empty($params['non_deductible_amount']))) {
217 return $params['non_deductible_amount'];
219 $priceSetId = $params['priceSetId'] ??
NULL;
220 // return non-deductible amount if it is set at the price field option level
221 if ($priceSetId && !empty($form->_lineItem
)) {
222 $nonDeductibleAmount = CRM_Price_BAO_PriceSet
::getNonDeductibleAmountFromPriceSet($priceSetId, $form->_lineItem
);
225 if (!empty($nonDeductibleAmount)) {
226 return $nonDeductibleAmount;
229 if ($financialType->is_deductible
) {
230 if ($online && isset($params['selectProduct'])) {
231 $selectProduct = $params['selectProduct'] ??
NULL;
233 if (!$online && isset($params['product_name'][0])) {
234 $selectProduct = $params['product_name'][0];
236 // if there is a product - compare the value to the contribution amount
237 if (isset($selectProduct) &&
238 $selectProduct != 'no_thanks'
240 $productDAO = new CRM_Contribute_DAO_Product();
241 $productDAO->id
= $selectProduct;
242 $productDAO->find(TRUE);
243 // product value exceeds contribution amount
244 if ($params['amount'] < $productDAO->price
) {
245 $nonDeductibleAmount = $params['amount'];
246 return $nonDeductibleAmount;
248 // product value does NOT exceed contribution amount
250 return $productDAO->price
;
253 // contribution is deductible - but there is no product
258 // contribution is NOT deductible
260 return $params['amount'];
266 * Set variables up before form is built.
268 public function preProcess() {
269 parent
::preProcess();
271 // lineItem isn't set until Register postProcess
272 $this->_lineItem
= $this->get('lineItem');
273 $this->_ccid
= $this->get('ccid');
275 $this->_params
= $this->controller
->exportValues('Main');
276 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
277 $this->_params
['amount'] = $this->get('amount');
278 if (isset($this->_params
['amount'])) {
279 $this->setFormAmountFields($this->_params
['priceSetId']);
282 $this->_params
['tax_amount'] = $this->get('tax_amount');
283 $this->_useForMember
= $this->get('useForMember');
285 CRM_Contribute_Form_AbstractEditPayment
::formatCreditCardDetails($this->_params
);
287 $this->_params
['currencyID'] = CRM_Core_Config
::singleton()->defaultCurrency
;
289 if (!empty($this->_membershipBlock
)) {
290 $this->_params
['selectMembership'] = $this->get('selectMembership');
292 if (!empty($this->_paymentProcessor
) && $this->_paymentProcessor
['object']->supports('preApproval')) {
293 $preApprovalParams = $this->_paymentProcessor
['object']->getPreApprovalDetails($this->get('pre_approval_parameters'));
294 $this->_params
= array_merge($this->_params
, $preApprovalParams);
296 // We may have fetched some billing details from the getPreApprovalDetails function so we
297 // want to ensure we set this after that function has been called.
298 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $preApprovalParams, $this->_params
, FALSE);
301 $this->_params
['is_pay_later'] = $this->get('is_pay_later');
302 $this->assign('is_pay_later', $this->_params
['is_pay_later']);
303 if ($this->_params
['is_pay_later']) {
304 $this->assign('pay_later_receipt', CRM_Utils_Array
::value('pay_later_receipt', $this->_values
));
306 // if onbehalf-of-organization
307 if (!empty($this->_values
['onbehalf_profile_id']) && !empty($this->_params
['onbehalf']['organization_name'])) {
308 if (empty($this->_params
['org_option']) && empty($this->_params
['organization_id'])) {
309 $this->_params
['organization_id'] = $this->_params
['onbehalfof_id'] ??
NULL;
311 $this->_params
['organization_name'] = $this->_params
['onbehalf']['organization_name'];
318 'supplemental_address_1',
319 'supplemental_address_2',
320 'supplemental_address_3',
321 'postal_code_suffix',
327 $blocks = ['email', 'phone', 'im', 'url', 'openid'];
328 foreach ($this->_params
['onbehalf'] as $loc => $value) {
329 $field = $typeId = NULL;
330 if (strstr($loc, '-')) {
331 list($field, $locType) = explode('-', $loc);
334 if (in_array($field, $addressBlocks)) {
335 if ($locType == 'Primary') {
336 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
337 $locType = $defaultLocationType->id
;
340 if ($field == 'country') {
341 $value = CRM_Core_PseudoConstant
::countryIsoCode($value);
343 elseif ($field == 'state_province') {
344 $value = CRM_Core_PseudoConstant
::stateProvinceAbbreviation($value);
348 if (isset($this->_params
['onbehalf_location']['address'])
349 && count($this->_params
['onbehalf_location']['address']) > 0
354 $this->_params
['onbehalf_location']['address'][$locType][$field] = $value;
355 if (empty($this->_params
['onbehalf_location']['address'][$locType]['is_primary'])) {
356 $this->_params
['onbehalf_location']['address'][$locType]['is_primary'] = $isPrimary;
358 $this->_params
['onbehalf_location']['address'][$locType]['location_type_id'] = $locType;
360 elseif (in_array($field, $blocks)) {
361 if (!$typeId ||
is_numeric($typeId)) {
362 $blockName = $fieldName = $field;
363 $locationType = 'location_type_id';
364 if ($locType == 'Primary') {
365 $defaultLocationType = CRM_Core_BAO_LocationType
::getDefault();
366 $locationValue = $defaultLocationType->id
;
369 $locationValue = $locType;
374 if ($field == 'url') {
375 $blockName = 'website';
376 $locationType = 'website_type_id';
377 list($field, $locationValue) = explode('-', $loc);
379 elseif ($field == 'im') {
381 $locTypeId = 'provider_id';
382 $typeId = $this->_params
['onbehalf']["{$loc}-provider_id"];
384 elseif ($field == 'phone') {
385 list($field, $locType, $typeId) = explode('-', $loc);
386 $locTypeId = 'phone_type_id';
388 //check if extension field exists
389 $extField = str_replace('phone', 'phone_ext', $loc);
390 if (isset($this->_params
['onbehalf'][$extField])) {
391 $phoneExtField = ['phone_ext' => $this->_params
['onbehalf'][$extField]];
396 if (isset($this->_params
['onbehalf_location'][$blockName])
397 && count($this->_params
['onbehalf_location'][$blockName]) > 0
401 if ($locationValue) {
403 $fieldName => $value,
404 $locationType => $locationValue,
405 'is_primary' => $isPrimary,
409 $blockValues = array_merge($blockValues, [$locTypeId => $typeId]);
411 if (!empty($phoneExtField)) {
412 $blockValues = array_merge($blockValues, $phoneExtField);
415 $this->_params
['onbehalf_location'][$blockName][] = $blockValues;
419 elseif (strstr($loc, 'custom')) {
420 if ($value && isset($this->_params
['onbehalf']["{$loc}_id"])) {
421 $value = $this->_params
['onbehalf']["{$loc}_id"];
423 $this->_params
['onbehalf_location']["{$loc}"] = $value;
426 if ($loc == 'contact_sub_type') {
427 $this->_params
['onbehalf_location'][$loc] = $value;
430 $this->_params
['onbehalf_location'][$field] = $value;
435 elseif (!empty($this->_values
['is_for_organization'])) {
436 // no on behalf of an organization, CRM-5519
437 // so reset loc blocks from main params.
443 if (isset($this->_params
[$blk])) {
444 unset($this->_params
[$blk]);
448 $this->setRecurringMembershipParams();
451 $params = $this->processPcp($this, $this->_params
);
452 $this->_params
= $params;
454 $this->_params
['invoiceID'] = $this->get('invoiceID');
456 //carry campaign from profile.
457 if (array_key_exists('contribution_campaign_id', $this->_params
)) {
458 $this->_params
['campaign_id'] = $this->_params
['contribution_campaign_id'];
461 // assign contribution page id to the template so we can add css class for it
462 $this->assign('contributionPageID', $this->_id
);
463 $this->assign('is_for_organization', CRM_Utils_Array
::value('is_for_organization', $this->_params
));
465 $this->set('params', $this->_params
);
469 * Build the form object.
471 public function buildQuickForm() {
472 // FIXME: Some of this code is identical to Thankyou.php and should be broken out into a shared function
473 $this->assignToTemplate();
475 $params = $this->_params
;
476 // make sure we have values for it
477 if (!empty($this->_values
['honoree_profile_id']) && !empty($params['soft_credit_type_id']) && empty($this->_ccid
)) {
479 $softCreditTypes = CRM_Core_OptionGroup
::values("soft_credit_type", FALSE);
481 $this->assign('soft_credit_type', $softCreditTypes[$params['soft_credit_type_id']]);
482 CRM_Contribute_BAO_ContributionSoft
::formatHonoreeProfileFields($this, $params['honor']);
484 $fieldTypes = ['Contact'];
485 $fieldTypes[] = CRM_Core_BAO_UFGroup
::getContactType($this->_values
['honoree_profile_id']);
486 $this->buildCustom($this->_values
['honoree_profile_id'], 'honoreeProfileFields', TRUE, 'honor', $fieldTypes);
488 $this->assign('receiptFromEmail', CRM_Utils_Array
::value('receipt_from_email', $this->_values
));
489 $amount_block_is_active = $this->get('amount_block_is_active');
490 $this->assign('amount_block_is_active', $amount_block_is_active);
492 // Make a copy of line items array to use for display only
493 $tplLineItems = $this->_lineItem
;
494 if (CRM_Invoicing_Utils
::isInvoicingEnabled()) {
495 // @todo $params seems like exactly the wrong place to get totalTaxAmount from
496 // this is a calculated variable so we it should be transparent how we
497 // calculated it rather than coming from 'params'
498 $this->assign('totalTaxAmount', $params['tax_amount']);
500 $this->assignLineItemsToTemplate($tplLineItems);
502 $isDisplayLineItems = $this->_priceSetId
&& !CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_priceSetId
, 'is_quick_config');
504 $this->assign('isDisplayLineItems', $isDisplayLineItems);
506 if (!$isDisplayLineItems) {
507 // quickConfig is deprecated in favour of isDisplayLineItems. Lots of logic has been harnessed to quick config
508 // whereas isDisplayLineItems is specific & clear.
509 $this->assign('is_quick_config', 1);
510 $this->_params
['is_quick_config'] = 1;
513 if (!empty($params['selectProduct']) && $params['selectProduct'] != 'no_thanks') {
514 $option = $params['options_' . $params['selectProduct']] ??
NULL;
515 $productID = $params['selectProduct'];
516 CRM_Contribute_BAO_Premium
::buildPremiumBlock($this, $this->_id
, FALSE,
519 $this->set('productID', $productID);
520 $this->set('option', $option);
522 $config = CRM_Core_Config
::singleton();
523 if (in_array('CiviMember', $config->enableComponents
) && empty($this->_ccid
)) {
524 if (isset($params['selectMembership']) &&
525 $params['selectMembership'] != 'no_thanks'
527 $this->buildMembershipBlock(
528 $this->_membershipContactID
,
530 $params['selectMembership'],
533 if (!empty($params['auto_renew'])) {
534 $this->assign('auto_renew', TRUE);
538 $this->assign('membershipBlock', FALSE);
541 if (empty($this->_ccid
)) {
542 $this->buildCustom($this->_values
['custom_pre_id'], 'customPre', TRUE);
543 $this->buildCustom($this->_values
['custom_post_id'], 'customPost', TRUE);
546 if (!empty($this->_values
['onbehalf_profile_id']) &&
547 !empty($params['onbehalf']) &&
548 ($this->_values
['is_for_organization'] == 2 ||
549 !empty($params['is_for_organization'])
550 ) && empty($this->_ccid
)
552 $fieldTypes = ['Contact', 'Organization'];
553 $contactSubType = CRM_Contact_BAO_ContactType
::subTypes('Organization');
554 $fieldTypes = array_merge($fieldTypes, $contactSubType);
555 if (is_array($this->_membershipBlock
) && !empty($this->_membershipBlock
)) {
556 $fieldTypes = array_merge($fieldTypes, ['Membership']);
559 $fieldTypes = array_merge($fieldTypes, ['Contribution']);
562 $this->buildCustom($this->_values
['onbehalf_profile_id'], 'onbehalfProfile', TRUE, 'onbehalf', $fieldTypes);
565 $this->_separateMembershipPayment
= $this->get('separateMembershipPayment');
566 $this->assign('is_separate_payment', $this->_separateMembershipPayment
);
568 $this->assign('priceSetID', $this->_priceSetId
);
570 // The concept of contributeMode is deprecated.
571 // the is_monetary concept probably should be too as it can be calculated from
572 // the existence of 'amount' & seems fragile.
573 if ($this->_contributeMode
== 'notify' ||
574 $this->_amount
<= 0.0 ||
$this->_params
['is_pay_later']
576 $contribButton = ts('Continue');
578 elseif (!empty($this->_ccid
)) {
579 $contribButton = ts('Make Payment');
582 $contribButton = ts('Make Contribution');
584 $this->assign('button', $contribButton);
586 $this->assign('continueText',
587 $this->getPaymentProcessorObject()->getText('contributionPageContinueText', [
588 'is_payment_to_existing' => !empty($this->_ccid
),
589 'amount' => $this->_amount
,
596 'name' => $contribButton,
597 'spacing' => ' ',
602 'name' => ts('Go Back'),
607 $fields = array_fill_keys(array_keys($this->_fields
), 1);
608 $fields["billing_state_province-{$this->_bltID}"] = $fields["billing_country-{$this->_bltID}"] = $fields["email-{$this->_bltID}"] = 1;
610 $contact = $this->_params
;
611 foreach ($fields as $name => $dontCare) {
612 // Recursively set defaults for nested fields
613 if (isset($contact[$name]) && is_array($contact[$name]) && ($name == 'onbehalf' ||
$name == 'honor')) {
614 foreach ($contact[$name] as $fieldName => $fieldValue) {
615 if (is_array($fieldValue) && $this->_fields
[$name][$fieldName]['html_type'] == 'CheckBox') {
616 foreach ($fieldValue as $key => $value) {
617 $defaults["{$name}[{$fieldName}][{$key}]"] = $value;
621 $defaults["{$name}[{$fieldName}]"] = $fieldValue;
625 elseif (isset($contact[$name])) {
626 $defaults[$name] = $contact[$name];
627 if (substr($name, 0, 7) == 'custom_') {
628 $timeField = "{$name}_time";
629 if (isset($contact[$timeField])) {
630 $defaults[$timeField] = $contact[$timeField];
632 if (isset($contact["{$name}_id"])) {
633 $defaults["{$name}_id"] = $contact["{$name}_id"];
636 elseif (in_array($name, [
640 ]) && !empty($contact[$name . '_custom'])
642 $defaults[$name . '_custom'] = $contact[$name . '_custom'];
647 $this->assign('useForMember', $this->get('useForMember'));
649 $this->setDefaults($defaults);
657 * Since we are only showing elements in frozen mode no help display needed.
661 public function getAction() {
662 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
663 return CRM_Core_Action
::VIEW | CRM_Core_Action
::PREVIEW
;
666 return CRM_Core_Action
::VIEW
;
671 * Set default values for the form.
673 * Note that in edit/view mode
674 * the default values are retrieved from the database
676 public function setDefaultValues() {
682 public function postProcess() {
683 $contactID = $this->getContactID();
685 $result = $this->processFormSubmission($contactID);
687 catch (CRM_Core_Exception
$e) {
688 $this->bounceOnError($e->getMessage());
691 if (is_array($result) && !empty($result['is_payment_failure'])) {
692 $this->bounceOnError($result['error']->getMessage());
694 // Presumably this is for hooks to access? Not quite clear & perhaps not required.
695 $this->set('params', $this->_params
);
699 * Wrangle financial type ID.
701 * 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
702 * Pledges are not relevant to the membership code so that portion will not go onto the membership form.
704 * Comments from previous refactor indicate doubt as to what was going on.
706 * @param int $financialTypeID
708 * @return null|string
710 public function wrangleFinancialTypeID($financialTypeID) {
711 if (empty($financialTypeID) && !empty($this->_values
['pledge_id'])) {
712 $financialTypeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_Pledge',
713 $this->_values
['pledge_id'],
717 return $financialTypeID;
723 * @param array $premiumParams
724 * @param CRM_Contribute_BAO_Contribution $contribution
726 protected function postProcessPremium($premiumParams, $contribution) {
727 $hour = $minute = $second = 0;
728 // assigning Premium information to receipt tpl
729 $selectProduct = $premiumParams['selectProduct'] ??
NULL;
730 if ($selectProduct &&
731 $selectProduct != 'no_thanks'
733 $startDate = $endDate = "";
734 $this->assign('selectPremium', TRUE);
735 $productDAO = new CRM_Contribute_DAO_Product();
736 $productDAO->id
= $selectProduct;
737 $productDAO->find(TRUE);
738 $this->assign('product_name', $productDAO->name
);
739 $this->assign('price', $productDAO->price
);
740 $this->assign('sku', $productDAO->sku
);
741 $this->assign('option', CRM_Utils_Array
::value('options_' . $premiumParams['selectProduct'], $premiumParams));
743 $periodType = $productDAO->period_type
;
746 $fixed_period_start_day = $productDAO->fixed_period_start_day
;
747 $duration_unit = $productDAO->duration_unit
;
748 $duration_interval = $productDAO->duration_interval
;
749 if ($periodType == 'rolling') {
750 $startDate = date('Y-m-d');
752 elseif ($periodType == 'fixed') {
753 if ($fixed_period_start_day) {
754 $date = explode('-', date('Y-m-d'));
755 $month = substr($fixed_period_start_day, 0, strlen($fixed_period_start_day) - 2);
756 $day = substr($fixed_period_start_day, -2) . "<br/>";
758 $startDate = $year . '-' . $month . '-' . $day;
761 $startDate = date('Y-m-d');
765 $date = explode('-', $startDate);
770 switch ($duration_unit) {
772 $year = $year +
$duration_interval;
776 $month = $month +
$duration_interval;
780 $day = $day +
$duration_interval;
784 $day = $day +
($duration_interval * 7);
786 $endDate = date('Y-m-d H:i:s', mktime($hour, $minute, $second, $month, $day, $year));
787 $this->assign('start_date', $startDate);
788 $this->assign('end_date', $endDate);
791 $dao = new CRM_Contribute_DAO_Premium();
792 $dao->entity_table
= 'civicrm_contribution_page';
793 $dao->entity_id
= $this->_id
;
795 $this->assign('contact_phone', $dao->premiums_contact_phone
);
796 $this->assign('contact_email', $dao->premiums_contact_email
);
798 //create Premium record
800 'product_id' => $premiumParams['selectProduct'],
801 'contribution_id' => $contribution->id
,
802 'product_option' => $premiumParams['options_' . $premiumParams['selectProduct']] ??
NULL,
804 'start_date' => CRM_Utils_Date
::customFormat($startDate, '%Y%m%d'),
805 'end_date' => CRM_Utils_Date
::customFormat($endDate, '%Y%m%d'),
807 if (!empty($premiumParams['selectProduct'])) {
808 $daoPremiumsProduct = new CRM_Contribute_DAO_PremiumsProduct();
809 $daoPremiumsProduct->product_id
= $premiumParams['selectProduct'];
810 $daoPremiumsProduct->premiums_id
= $dao->id
;
811 $daoPremiumsProduct->find(TRUE);
812 $params['financial_type_id'] = $daoPremiumsProduct->financial_type_id
;
815 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
816 $daoContrProd->contribution_id
= $contribution->id
;
817 if ($daoContrProd->find(TRUE)) {
818 $params['id'] = $daoContrProd->id
;
821 CRM_Contribute_BAO_Contribution
::addPremium($params);
822 if ($productDAO->cost
&& !empty($params['financial_type_id'])) {
824 'cost' => $productDAO->cost
,
825 'currency' => $productDAO->currency
,
826 'financial_type_id' => $params['financial_type_id'],
827 'contributionId' => $contribution->id
,
829 CRM_Core_BAO_FinancialTrxn
::createPremiumTrxn($trxnParams);
832 elseif ($selectProduct == 'no_thanks') {
834 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
835 $daoContrProd->contribution_id
= $contribution->id
;
836 if ($daoContrProd->find(TRUE)) {
837 $daoContrProd->delete();
843 * Process the contribution.
845 * @param CRM_Core_Form $form
846 * @param array $params
847 * @param array $result
848 * @param array $contributionParams
849 * Parameters to be passed to contribution create action.
850 * This differs from params in that we are currently adding params to it and 1) ensuring they are being
851 * passed consistently & 2) documenting them here.
856 * - contribution_page_id
859 * - thankyou_date (not all forms will set this)
861 * @param CRM_Financial_DAO_FinancialType $financialType
862 * @param bool $online
863 * Is the form a front end form? If so set a bunch of unpredictable things that should be passed in from the form.
865 * @param int $billingLocationID
866 * ID of billing location type.
867 * @param bool $isRecur
870 * @return \CRM_Contribute_DAO_Contribution
872 * @throws \CRM_Core_Exception
873 * @throws \CiviCRM_API3_Exception
875 public static function processFormContribution(
885 $transaction = new CRM_Core_Transaction();
886 $contactID = $contributionParams['contact_id'];
888 $isEmailReceipt = !empty($form->_values
['is_email_receipt']);
889 $isSeparateMembershipPayment = !empty($params['separate_membership_payment']);
890 $pledgeID = !empty($params['pledge_id']) ?
$params['pledge_id'] : CRM_Utils_Array
::value('pledge_id', $form->_values
);
891 if (!$isSeparateMembershipPayment && !empty($form->_values
['pledge_block_id']) &&
892 (!empty($params['is_pledge']) ||
$pledgeID)) {
899 // add these values for the recurringContrib function ,CRM-10188
900 $params['financial_type_id'] = $financialType->id
;
902 $contributionParams['address_id'] = CRM_Contribute_BAO_Contribution
::createAddress($params, $billingLocationID);
904 //@todo - this is being set from the form to resolve CRM-10188 - an
905 // eNotice caused by it not being set @ the front end
906 // however, we then get it being over-written with null for backend contributions
907 // a better fix would be to set the values in the respective forms rather than require
908 // a function being shared by two forms to deal with their respective values
909 // moving it to the BAO & not taking the $form as a param would make sense here.
910 if (!isset($params['is_email_receipt']) && $isEmailReceipt) {
911 $params['is_email_receipt'] = $isEmailReceipt;
913 $params['is_recur'] = $isRecur;
914 $params['payment_instrument_id'] = $contributionParams['payment_instrument_id'] ??
NULL;
915 $recurringContributionID = self
::processRecurringContribution($form, $params, $contactID, $financialType);
917 $now = date('YmdHis');
918 $receiptDate = $params['receipt_date'] ??
NULL;
919 if ($isEmailReceipt) {
923 if (isset($params['amount'])) {
924 $contributionParams = array_merge(self
::getContributionParams(
925 $params, $financialType->id
,
926 $result, $receiptDate,
927 $recurringContributionID), $contributionParams
929 $contributionParams['non_deductible_amount'] = self
::getNonDeductibleAmount($params, $financialType, $online, $form);
930 $contributionParams['skipCleanMoney'] = TRUE;
931 // @todo this is the wrong place for this - it should be done as close to form submission
933 $contributionParams['total_amount'] = $params['amount'];
935 $contribution = CRM_Contribute_BAO_Contribution
::add($contributionParams);
937 $invoiceSettings = Civi
::settings()->get('contribution_invoice_settings');
938 $invoicing = $invoiceSettings['invoicing'] ??
NULL;
941 // @todo - interrogate the line items passed in on the params array.
942 // No reason to assume line items will be set on the form.
943 foreach ($form->_lineItem
as $lineItemKey => $lineItemValue) {
944 foreach ($lineItemValue as $key => $value) {
945 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
946 if (isset($dataArray[$value['tax_rate']])) {
947 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] +
$value['tax_amount'];
950 $dataArray[$value['tax_rate']] = $value['tax_amount'];
955 $smarty = CRM_Core_Smarty
::singleton();
956 $smarty->assign('dataArray', $dataArray);
957 $smarty->assign('totalTaxAmount', $params['tax_amount'] ??
NULL);
960 // lets store it in the form variable so postProcess hook can get to this and use it
961 $form->_contributionID
= $contribution->id
;
964 // process soft credit / pcp params first
965 CRM_Contribute_BAO_ContributionSoft
::formatSoftCreditParams($params, $form);
967 //CRM-13981, processing honor contact into soft-credit contribution
968 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
971 $form = self
::handlePledge($form, $params, $contributionParams, $pledgeID, $contribution, $isEmailReceipt);
974 if ($online && $contribution) {
975 CRM_Core_BAO_CustomValueTable
::postProcess($params,
976 'civicrm_contribution',
981 elseif ($contribution) {
982 //handle custom data.
983 $params['contribution_id'] = $contribution->id
;
984 if (!empty($params['custom']) &&
985 is_array($params['custom'])
987 CRM_Core_BAO_CustomValueTable
::store($params['custom'], 'civicrm_contribution', $contribution->id
);
991 if ($contribution && !empty($params['contribution_note'])) {
993 'entity_table' => 'civicrm_contribution',
994 'note' => $params['contribution_note'],
995 'entity_id' => $contribution->id
,
996 'contact_id' => $contribution->contact_id
,
999 CRM_Core_BAO_Note
::add($noteParams, []);
1002 if (isset($params['related_contact'])) {
1003 $contactID = $params['related_contact'];
1005 elseif (isset($params['cms_contactID'])) {
1006 $contactID = $params['cms_contactID'];
1009 //create contribution activity w/ individual and target
1010 //activity w/ organisation contact id when onbelf, CRM-4027
1012 $targetContactID = NULL;
1013 if (!empty($params['onbehalf_contact_id'])) {
1015 'source_contact_id' => $params['onbehalf_contact_id'],
1016 'on_behalf' => TRUE,
1018 $targetContactID = $contribution->contact_id
;
1021 // create an activity record
1022 if ($contribution) {
1023 CRM_Activity_BAO_Activity
::addActivity($contribution, NULL, $targetContactID, $actParams);
1026 $transaction->commit();
1027 // CRM-13074 - create the CMSUser after the transaction is completed as it
1028 // is not appropriate to delete a valid contribution if a user create problem occurs
1029 CRM_Contribute_BAO_Contribution_Utils
::createCMSUser($params,
1031 'email-' . $billingLocationID
1033 return $contribution;
1037 * Create the recurring contribution record.
1039 * @param CRM_Core_Form $form
1040 * @param array $params
1041 * @param int $contactID
1042 * @param string $contributionType
1046 public static function processRecurringContribution(&$form, &$params, $contactID, $contributionType) {
1048 if (empty($params['is_recur'])) {
1052 $recurParams = ['contact_id' => $contactID];
1053 $recurParams['amount'] = $params['amount'] ??
NULL;
1054 $recurParams['auto_renew'] = $params['auto_renew'] ??
NULL;
1055 $recurParams['frequency_unit'] = $params['frequency_unit'] ??
NULL;
1056 $recurParams['frequency_interval'] = $params['frequency_interval'] ??
NULL;
1057 $recurParams['installments'] = $params['installments'] ??
NULL;
1058 $recurParams['financial_type_id'] = $params['financial_type_id'] ??
NULL;
1059 $recurParams['currency'] = $params['currency'] ??
NULL;
1060 $recurParams['payment_instrument_id'] = $params['payment_instrument_id'];
1062 // CRM-14354: For an auto-renewing membership with an additional contribution,
1063 // if separate payments is not enabled, make sure only the membership fee recurs
1064 if (!empty($form->_membershipBlock
)
1065 && $form->_membershipBlock
['is_separate_payment'] === '0'
1066 && isset($params['selectMembership'])
1067 && $form->_values
['is_allow_other_amount'] == '1'
1069 && !empty($form->_membershipTypeValues
)
1070 && !empty($form->_membershipTypeValues
[$params['selectMembership']]['minimum_fee'])
1072 $recurParams['amount'] = $form->_membershipTypeValues
[$params['selectMembership']]['minimum_fee'];
1075 $recurParams['is_test'] = 0;
1076 if (($form->_action
& CRM_Core_Action
::PREVIEW
) ||
1077 (isset($form->_mode
) && ($form->_mode
== 'test'))
1079 $recurParams['is_test'] = 1;
1082 $recurParams['start_date'] = $recurParams['create_date'] = $recurParams['modified_date'] = date('YmdHis');
1083 if (!empty($params['receive_date'])) {
1084 $recurParams['start_date'] = date('YmdHis', strtotime($params['receive_date']));
1086 $recurParams['invoice_id'] = $params['invoiceID'] ??
NULL;
1087 $recurParams['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1088 $recurParams['payment_processor_id'] = $params['payment_processor_id'] ??
NULL;
1089 $recurParams['is_email_receipt'] = $params['is_email_receipt'] ??
NULL;
1090 // we need to add a unique trxn_id to avoid a unique key error
1091 // in paypal IPN we reset this when paypal sends us the real trxn id, CRM-2991
1092 $recurParams['trxn_id'] = CRM_Utils_Array
::value('trxn_id', $params, $params['invoiceID']);
1093 $recurParams['financial_type_id'] = $contributionType->id
;
1095 $campaignId = CRM_Utils_Array
::value('campaign_id', $params, CRM_Utils_Array
::value('campaign_id', $form->_values
));
1096 $recurParams['campaign_id'] = $campaignId;
1097 $recurring = CRM_Contribute_BAO_ContributionRecur
::add($recurParams);
1098 if (is_a($recurring, 'CRM_Core_Error')) {
1099 CRM_Core_Error
::displaySessionError($recurring);
1100 $urlString = 'civicrm/contribute/transact';
1101 $urlParams = '_qf_Main_display=true';
1102 if (get_class($form) == 'CRM_Contribute_Form_Contribution') {
1103 $urlString = 'civicrm/contact/view/contribution';
1104 $urlParams = "action=add&cid={$form->_contactID}";
1106 $urlParams .= "&mode={$form->_mode}";
1109 CRM_Utils_System
::redirect(CRM_Utils_System
::url($urlString, $urlParams));
1111 // Only set contribution recur ID for contributions since offline membership recur payments are handled somewhere else.
1112 if (!is_a($form, "CRM_Member_Form_Membership")) {
1113 $form->_params
['contributionRecurID'] = $recurring->id
;
1116 return $recurring->id
;
1120 * Add on behalf of organization and it's location.
1122 * This situation occurs when on behalf of is enabled for the contribution page and the person
1123 * signing up does so on behalf of an organization.
1125 * @param array $behalfOrganization
1126 * array of organization info.
1127 * @param int $contactID
1128 * individual contact id. One.
1129 * who is doing the process of signup / contribution.
1131 * @param array $values
1132 * form values array.
1133 * @param array $params
1134 * @param array $fields
1135 * Array of fields from the onbehalf profile relevant to the organization.
1137 public static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params, $fields = NULL) {
1138 $isNotCurrentEmployer = FALSE;
1141 if (!empty($behalfOrganization['organization_id'])) {
1142 $orgID = $behalfOrganization['organization_id'];
1143 unset($behalfOrganization['organization_id']);
1145 // create employer relationship with $contactID only when new organization is there
1146 // else retain the existing relationship
1148 // get the Employee relationship type id
1149 $relTypeId = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_RelationshipType', 'Employee of', 'id', 'name_a_b');
1151 // keep relationship params ready
1152 $relParams['relationship_type_id'] = $relTypeId . '_a_b';
1153 $relParams['is_permission_a_b'] = 1;
1154 $relParams['is_active'] = 1;
1155 $isNotCurrentEmployer = TRUE;
1158 // formalities for creating / editing organization.
1159 $behalfOrganization['contact_type'] = 'Organization';
1162 // check if matching organization contact exists
1163 $dupeIDs = CRM_Contact_BAO_Contact
::getDuplicateContacts($behalfOrganization, 'Organization', 'Unsupervised', [], FALSE);
1165 // CRM-6243 says to pick the first org even if more than one match
1166 if (count($dupeIDs) >= 1) {
1167 $behalfOrganization['contact_id'] = $orgID = $dupeIDs[0];
1168 // don't allow name edit
1169 unset($behalfOrganization['organization_name']);
1173 // if found permissioned related organization, allow location edit
1174 $behalfOrganization['contact_id'] = $orgID;
1175 // don't allow name edit
1176 unset($behalfOrganization['organization_name']);
1179 // handling for image url
1180 if (!empty($behalfOrganization['image_URL'])) {
1181 CRM_Contact_BAO_Contact
::processImageParams($behalfOrganization);
1184 // create organization, add location
1185 $orgID = CRM_Contact_BAO_Contact
::createProfileContact($behalfOrganization, $fields, $orgID,
1186 NULL, NULL, 'Organization'
1188 // create relationship
1189 if ($isNotCurrentEmployer) {
1190 $relParams['contact_check'][$orgID] = 1;
1191 $cid = ['contact' => $contactID];
1192 CRM_Contact_BAO_Relationship
::legacyCreateMultiple($relParams, $cid);
1195 // if multiple match - send a duplicate alert
1196 if ($dupeIDs && (count($dupeIDs) > 1)) {
1197 $values['onbehalf_dupe_alert'] = 1;
1199 $params['onbehalf_dupe_alert'] = 1;
1202 // make sure organization-contact-id is considered for recording
1203 // contribution/membership etc..
1204 if ($contactID != $orgID) {
1205 // take a note of contact-id, so we can send the
1206 // receipt to individual contact as well.
1208 // required for mailing/template display ..etc
1209 $values['related_contact'] = $contactID;
1211 //CRM-19172: Create CMS user for individual on whose behalf organization is doing contribution
1212 $params['onbehalf_contact_id'] = $contactID;
1214 //make this employee of relationship as current
1215 //employer / employee relationship, CRM-3532
1216 if ($isNotCurrentEmployer &&
1217 ($orgID != CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id'))
1219 $isNotCurrentEmployer = FALSE;
1222 if (!$isNotCurrentEmployer && $orgID) {
1223 //build current employer params
1224 $currentEmpParams[$contactID] = $orgID;
1225 CRM_Contact_BAO_Contact_Utils
::setCurrentEmployer($currentEmpParams);
1228 // contribution / signup will be done using this
1230 $contactID = $orgID;
1235 * Function used to send notification mail to pcp owner.
1237 * This is used by contribution and also event PCPs.
1239 * @param object $contribution
1240 * @param object $contributionSoft
1241 * Contribution object.
1243 public static function pcpNotifyOwner($contribution, $contributionSoft) {
1244 $params = ['id' => $contributionSoft->pcp_id
];
1245 CRM_Core_DAO
::commonRetrieve('CRM_PCP_DAO_PCP', $params, $pcpInfo);
1246 $ownerNotifyID = CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCPBlock', $pcpInfo['pcp_block_id'], 'owner_notify_id');
1247 $ownerNotifyOption = CRM_Core_PseudoConstant
::getName('CRM_PCP_DAO_PCPBlock', 'owner_notify_id', $ownerNotifyID);
1249 if ($ownerNotifyOption != 'no_notifications' &&
1250 (($ownerNotifyOption == 'owner_chooses' &&
1251 CRM_Core_DAO
::getFieldValue('CRM_PCP_DAO_PCP', $contributionSoft->pcp_id
, 'is_notify')) ||
1252 $ownerNotifyOption == 'all_owners')) {
1253 $pcpInfoURL = CRM_Utils_System
::url('civicrm/pcp/info',
1254 "reset=1&id={$contributionSoft->pcp_id}",
1255 TRUE, NULL, FALSE, TRUE
1257 // set email in the template here
1259 if (CRM_Core_BAO_LocationType
::getBilling()) {
1260 list($donorName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contribution->contact_id
,
1261 FALSE, CRM_Core_BAO_LocationType
::getBilling());
1263 // get primary location email if no email exist( for billing location).
1265 list($donorName, $email) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contribution->contact_id
);
1267 list($ownerName, $ownerEmail) = CRM_Contact_BAO_Contact_Location
::getEmailDetails($contributionSoft->contact_id
);
1269 'page_title' => $pcpInfo['title'],
1270 'receive_date' => $contribution->receive_date
,
1271 'total_amount' => $contributionSoft->amount
,
1272 'donors_display_name' => $donorName,
1273 'donors_email' => $email,
1274 'pcpInfoURL' => $pcpInfoURL,
1275 'is_honor_roll_enabled' => $contributionSoft->pcp_display_in_roll
,
1276 'currency' => $contributionSoft->currency
,
1278 $domainValues = CRM_Core_BAO_Domain
::getNameAndEmail();
1279 $sendTemplateParams = [
1280 'groupName' => 'msg_tpl_workflow_contribution',
1281 'valueName' => 'pcp_owner_notify',
1282 'contactId' => $contributionSoft->contact_id
,
1283 'toEmail' => $ownerEmail,
1284 'toName' => $ownerName,
1285 'from' => "$domainValues[0] <$domainValues[1]>",
1286 'tplParams' => $tplParams,
1287 'PDFFilename' => 'receipt.pdf',
1289 CRM_Core_BAO_MessageTemplate
::sendTemplate($sendTemplateParams);
1294 * Function used to se pcp related defaults / params.
1296 * This is used by contribution and also event PCPs
1298 * @param CRM_Core_Form $page
1300 * @param array $params
1304 public static function processPcp(&$page, $params) {
1305 $params['pcp_made_through_id'] = $page->_pcpId
;
1306 $page->assign('pcpBlock', TRUE);
1307 if (!empty($params['pcp_display_in_roll']) && empty($params['pcp_roll_nickname'])) {
1308 $params['pcp_roll_nickname'] = ts('Anonymous');
1309 $params['pcp_is_anonymous'] = 1;
1312 $params['pcp_is_anonymous'] = 0;
1315 'pcp_display_in_roll',
1317 'pcp_roll_nickname',
1318 'pcp_personal_note',
1320 if (!empty($params[$val])) {
1321 $page->assign($val, $params[$val]);
1329 * Process membership.
1331 * @param array $membershipParams
1332 * @param int $contactID
1333 * @param array $customFieldsFormatted
1334 * @param array $fieldTypes
1335 * @param array $premiumParams
1336 * @param array $membershipLineItems
1337 * Line items specifically relating to memberships.
1339 protected function processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams,
1340 $membershipLineItems) {
1342 $membershipTypeIDs = (array) $membershipParams['selectMembership'];
1343 $membershipTypes = CRM_Member_BAO_Membership
::buildMembershipTypeValues($this, $membershipTypeIDs);
1344 $membershipType = empty($membershipTypes) ?
[] : reset($membershipTypes);
1346 $this->assign('membership_name', CRM_Utils_Array
::value('name', $membershipType));
1347 $this->_values
['membership_name'] = $membershipType['name'] ??
NULL;
1349 $isPaidMembership = FALSE;
1350 if ($this->_amount
>= 0.0 && isset($membershipParams['amount'])) {
1351 //amount must be greater than zero for
1352 //adding contribution record to contribution table.
1353 //this condition arises when separate membership payment is
1354 //enabled and contribution amount is not selected. fix for CRM-3010
1355 $isPaidMembership = TRUE;
1357 $isProcessSeparateMembershipTransaction = $this->isSeparateMembershipTransaction($this->_id
, $this->_values
['amount_block_is_active']);
1359 if ($this->_values
['amount_block_is_active']) {
1360 $financialTypeID = $this->_values
['financial_type_id'];
1363 $financialTypeID = CRM_Utils_Array
::value('financial_type_id', $membershipType, CRM_Utils_Array
::value('financial_type_id', $membershipParams));
1366 if (!empty($this->_params
['membership_source'])) {
1367 $membershipParams['contribution_source'] = $this->_params
['membership_source'];
1370 $this->postProcessMembership($membershipParams, $contactID,
1371 $this, $premiumParams, $customFieldsFormatted, $fieldTypes, $membershipType, $membershipTypeIDs, $isPaidMembership, $this->_membershipId
, $isProcessSeparateMembershipTransaction, $financialTypeID,
1372 $membershipLineItems);
1374 $this->assign('membership_assign', TRUE);
1375 $this->set('membershipTypeID', $membershipParams['selectMembership']);
1379 * Process the Memberships.
1381 * @param array $membershipParams
1382 * Array of membership fields.
1383 * @param int $contactID
1385 * @param CRM_Contribute_Form_Contribution_Confirm $form
1386 * Confirmation form object.
1388 * @param array $premiumParams
1389 * @param null $customFieldsFormatted
1390 * @param null $includeFieldTypes
1392 * @param array $membershipDetails
1394 * @param array $membershipTypeIDs
1396 * @param bool $isPaidMembership
1397 * @param array $membershipID
1399 * @param bool $isProcessSeparateMembershipTransaction
1401 * @param int $financialTypeID
1402 * @param array $unprocessedLineItems
1403 * Line items for payment options chosen on the form.
1405 * @throws \CRM_Core_Exception
1406 * @throws \CiviCRM_API3_Exception
1407 * @throws \Civi\Payment\Exception\PaymentProcessorException
1409 protected function postProcessMembership(
1410 $membershipParams, $contactID, &$form, $premiumParams,
1411 $customFieldsFormatted = NULL, $includeFieldTypes = NULL, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID,
1412 $isProcessSeparateMembershipTransaction, $financialTypeID, $unprocessedLineItems) {
1414 $membershipContribution = NULL;
1415 $isTest = CRM_Utils_Array
::value('is_test', $membershipParams, FALSE);
1416 $errors = $paymentResults = [];
1417 $form->_values
['isMembership'] = TRUE;
1418 $isRecurForFirstTransaction = CRM_Utils_Array
::value('is_recur', $form->_params
, CRM_Utils_Array
::value('is_recur', $membershipParams));
1420 $totalAmount = $membershipParams['amount'];
1422 if ($isPaidMembership) {
1423 if ($isProcessSeparateMembershipTransaction) {
1424 // If we have 2 transactions only one can use the invoice id.
1425 $membershipParams['invoiceID'] .= '-2';
1426 if (!empty($membershipParams['auto_renew'])) {
1427 $isRecurForFirstTransaction = FALSE;
1431 if (!$isProcessSeparateMembershipTransaction) {
1432 // Skip line items in the contribution processing transaction.
1433 // We will create them with the membership for proper linking.
1434 $membershipParams['skipLineItem'] = 1;
1437 $membershipParams['total_amount'] = $totalAmount;
1438 $membershipParams['skipLineItem'] = 0;
1439 CRM_Price_BAO_LineItem
::getLineItemArray($membershipParams);
1442 $paymentResult = CRM_Contribute_BAO_Contribution_Utils
::processConfirm(
1448 $isRecurForFirstTransaction
1450 if (!empty($paymentResult['contribution'])) {
1451 $paymentResults[] = ['contribution_id' => $paymentResult['contribution']->id
, 'result' => $paymentResult];
1452 $this->postProcessPremium($premiumParams, $paymentResult['contribution']);
1453 //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
1454 $membershipContribution = $paymentResult['contribution'];
1455 // Save the contribution ID so that I can be used in email receipts
1456 // For example, if you need to generate a tax receipt for the donation only.
1457 $form->_values
['contribution_other_id'] = $membershipContribution->id
;
1461 if ($isProcessSeparateMembershipTransaction) {
1463 $form->_lineItem
= $unprocessedLineItems;
1464 if (empty($form->_params
['auto_renew']) && !empty($membershipParams['is_recur'])) {
1465 unset($membershipParams['is_recur']);
1467 list($membershipContribution, $secondPaymentResult) = $this->processSecondaryFinancialTransaction($contactID, $form, array_merge($membershipParams, ['skipLineItem' => 1]),
1468 $isTest, $unprocessedLineItems, CRM_Utils_Array
::value('minimum_fee', $membershipDetails, 0), CRM_Utils_Array
::value('financial_type_id', $membershipDetails));
1469 $paymentResults[] = ['contribution_id' => $membershipContribution->id
, 'result' => $secondPaymentResult];
1470 $totalAmount = $membershipContribution->total_amount
;
1472 catch (CRM_Core_Exception
$e) {
1473 $errors[2] = $e->getMessage();
1474 $membershipContribution = NULL;
1479 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1480 $membershipContributionID = $membershipContribution->id
;
1483 //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
1484 if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
1485 $form->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
1487 //@todo it should no longer be possible for it to get to this point & membership to not be an array
1488 if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
1489 $typesTerms = CRM_Utils_Array
::value('types_terms', $membershipParams, []);
1491 $membershipLines = $nonMembershipLines = [];
1492 foreach ($unprocessedLineItems as $priceSetID => $lines) {
1493 foreach ($lines as $line) {
1494 if (!empty($line['membership_type_id'])) {
1495 $membershipLines[$line['membership_type_id']] = $line['price_field_value_id'];
1501 $form->_params
['createdMembershipIDs'] = [];
1502 foreach ($membershipTypeIDs as $memType) {
1503 $membershipLineItems = [];
1504 if ($i < count($membershipTypeIDs)) {
1505 $membershipLineItems[$priceSetID][$membershipLines[$memType]] = $unprocessedLineItems[$priceSetID][$membershipLines[$memType]];
1506 unset($unprocessedLineItems[$priceSetID][$membershipLines[$memType]]);
1509 $membershipLineItems = $unprocessedLineItems;
1512 $numTerms = CRM_Utils_Array
::value($memType, $typesTerms, 1);
1513 $contributionRecurID = $form->_params
['contributionRecurID'] ??
NULL;
1515 $membershipSource = NULL;
1516 if (!empty($form->_params
['membership_source'])) {
1517 $membershipSource = $form->_params
['membership_source'];
1519 elseif ((isset($form->_values
['title']) && !empty($form->_values
['title'])) ||
(isset($form->_values
['frontend_title']) && !empty($form->_values
['frontend_title']))) {
1520 $title = !empty($form->_values
['frontend_title']) ?
$form->_values
['frontend_title'] : $form->_values
['title'];
1521 $membershipSource = ts('Online Contribution:') . ' ' . $title;
1524 if (isset($form->_params
)) {
1525 $isPayLater = $form->_params
['is_pay_later'] ??
NULL;
1528 if (isset($form->_values
) && is_array($form->_values
) && !empty($form->_values
)) {
1529 $campaignId = $form->_params
['campaign_id'] ??
NULL;
1530 if (!array_key_exists('campaign_id', $form->_params
)) {
1531 $campaignId = $form->_values
['campaign_id'] ??
NULL;
1535 // @todo Move this into CRM_Member_BAO_Membership::processMembership
1536 if (!empty($membershipContribution)) {
1537 $pending = $membershipContribution->contribution_status_id
== CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1540 $pending = $this->getIsPending();
1542 list($membership, $renewalMode, $dates) = CRM_Member_BAO_Membership
::processMembership(
1543 $contactID, $memType, $isTest,
1544 date('YmdHis'), CRM_Utils_Array
::value('cms_contactID', $membershipParams),
1545 $customFieldsFormatted,
1546 $numTerms, $membershipID, $pending,
1547 $contributionRecurID, $membershipSource, $isPayLater, $campaignId, [], $membershipContribution,
1548 $membershipLineItems
1551 $form->set('renewal_mode', $renewalMode);
1552 if (!empty($dates)) {
1553 $form->assign('mem_start_date', CRM_Utils_Date
::customFormat($dates['start_date'], '%Y%m%d'));
1554 $form->assign('mem_end_date', CRM_Utils_Date
::customFormat($dates['end_date'], '%Y%m%d'));
1557 if (!empty($membershipContribution)) {
1558 // Next line is probably redundant. Checks prevent it happening twice.
1559 $membershipPaymentParams = [
1560 'membership_id' => $membership->id
,
1561 'membership_type_id' => $membership->membership_type_id
,
1562 'contribution_id' => $membershipContribution->id
,
1564 civicrm_api3('MembershipPayment', 'create', $membershipPaymentParams);
1567 CRM_Core_BAO_CustomValueTable
::postProcess($form->_params
, 'civicrm_membership', $membership->id
, 'Membership');
1568 $form->_params
['createdMembershipIDs'][] = $membership->id
;
1569 $form->_params
['membershipID'] = $membership->id
;
1571 //CRM-15232: Check if membership is created and on the basis of it use
1572 //membership receipt template to send payment receipt
1573 $form->_values
['isMembership'] = TRUE;
1576 if ($form->_priceSetId
&& !empty($form->_useForMember
) && !empty($form->_lineItem
)) {
1577 foreach ($form->_lineItem
[$form->_priceSetId
] as & $priceFieldOp) {
1578 if (!empty($priceFieldOp['membership_type_id']) && $membership->membership_type_id
== $priceFieldOp['membership_type_id']) {
1579 $membershipOb = $membership;
1580 $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date
::customFormat($membershipOb->start_date
, '%B %E%f, %Y') : '-';
1581 $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date
::customFormat($membershipOb->end_date
, '%B %E%f, %Y') : '-';
1584 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1587 $form->_values
['lineItem'] = $form->_lineItem
;
1588 $form->assign('lineItem', $form->_lineItem
);
1592 if (!empty($errors)) {
1593 $message = $this->compileErrorMessage($errors);
1594 throw new CRM_Core_Exception($message);
1597 if (isset($membershipContributionID)) {
1598 $form->_values
['contribution_id'] = $membershipContributionID;
1601 if (empty($form->_params
['is_pay_later']) && $form->_paymentProcessor
) {
1602 // the is_monetary concept probably should be deprecated as it can be calculated from
1603 // the existence of 'amount' & seems fragile.
1604 if ($form->_values
['is_monetary'] && $form->_amount
> 0.0 && !$form->_params
['is_pay_later']) {
1605 // call postProcess hook before leaving
1606 $form->postProcessHook();
1609 $payment = Civi\Payment\System
::singleton()->getByProcessor($form->_paymentProcessor
);
1610 // The contribution_other_id is effectively the ID for the only contribution or the non-membership contribution.
1611 // Since we have called the membership contribution (in a 2 contribution scenario) this is out
1612 // primary-contribution compared to that - but let's face it - it's all just too hard & confusing at the moment!
1613 $paymentParams = array_merge($form->_params
, ['contributionID' => $form->_values
['contribution_other_id']]);
1615 // CRM-19792 : set necessary fields for payment processor
1616 CRM_Core_Payment_Form
::mapParams($form->_bltID
, $paymentParams, $paymentParams, TRUE);
1618 // If this is a single membership-related contribution, it won't have
1619 // be performed yet, so do it now.
1620 if ($isPaidMembership && !$isProcessSeparateMembershipTransaction) {
1621 $paymentActionResult = $payment->doPayment($paymentParams, 'contribute');
1622 $paymentResults[] = ['contribution_id' => $paymentResult['contribution']->id
, 'result' => $paymentActionResult];
1624 // Do not send an email if Recurring transaction is done via Direct Mode
1625 // Email will we sent when the IPN is received.
1626 foreach ($paymentResults as $result) {
1627 //CRM-18211: Fix situation where second contribution doesn't exist because it is optional.
1628 if ($result['contribution_id']) {
1629 $this->completeTransaction($result['result'], $result['contribution_id']);
1635 $emailValues = array_merge($membershipParams, $form->_values
);
1636 $emailValues['membership_assign'] = 1;
1637 $emailValues['useForMember'] = !empty($form->_useForMember
);
1639 // Finally send an email receipt for pay-later scenario (although it might sometimes be caught above!)
1640 if ($totalAmount == 0) {
1641 // This feels like a bizarre hack as the variable name doesn't seem to be directly connected to it's use in the template.
1642 $emailValues['useForMember'] = 0;
1643 $emailValues['amount'] = 0;
1645 //CRM-18071, where on selecting $0 free membership payment section got hidden and
1646 // also it reset any payment processor selection result into pending free membership
1647 // so its a kind of hack to complete free membership at this point since there is no $form->_paymentProcessor info
1648 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1649 if (empty($form->_paymentProcessor
)) {
1650 // @todo this can maybe go now we are setting payment_processor_id = 0 more reliably.
1651 $paymentProcessorIDs = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, CRM_Utils_Array
::value('payment_processor', $this->_values
));
1652 $this->_paymentProcessor
['id'] = $paymentProcessorIDs[0];
1654 $result = ['payment_status_id' => 1, 'contribution' => $membershipContribution];
1655 $this->completeTransaction($result, $result['contribution']->id
);
1657 // return as completeTransaction() already sends the receipt mail.
1661 CRM_Contribute_BAO_ContributionPage
::sendMail($contactID,
1669 * Turn array of errors into message string.
1671 * @param array $errors
1675 protected function compileErrorMessage($errors) {
1676 foreach ($errors as $error) {
1677 if (is_string($error)) {
1678 $message[] = $error;
1681 return ts('Payment Processor Error message') . ': ' . implode('<br/>', $message);
1685 * Where a second separate financial transaction is supported we will process it here.
1687 * @param int $contactID
1688 * @param CRM_Contribute_Form_Contribution_Confirm $form
1689 * @param array $tempParams
1690 * @param bool $isTest
1691 * @param array $lineItems
1692 * @param $minimumFee
1693 * @param int $financialTypeID
1695 * @throws CRM_Core_Exception
1697 * @return CRM_Contribute_BAO_Contribution
1699 protected function processSecondaryFinancialTransaction($contactID, &$form, $tempParams, $isTest, $lineItems, $minimumFee,
1701 $financialType = new CRM_Financial_DAO_FinancialType();
1702 $financialType->id
= $financialTypeID;
1703 $financialType->find(TRUE);
1704 $tempParams['amount'] = $minimumFee;
1705 $tempParams['invoiceID'] = md5(uniqid(rand(), TRUE));
1706 $isRecur = $tempParams['is_recur'] ??
NULL;
1708 //assign receive date when separate membership payment
1709 //and contribution amount not selected.
1710 if ($form->_amount
== 0) {
1711 $now = date('YmdHis');
1712 $form->_params
['receive_date'] = $now;
1713 $receiveDate = CRM_Utils_Date
::mysqlToIso($now);
1714 $form->set('params', $form->_params
);
1715 $form->assign('receive_date', $receiveDate);
1718 $form->set('membership_amount', $minimumFee);
1719 $form->assign('membership_amount', $minimumFee);
1721 // we don't need to create the user twice, so lets disable cms_create_account
1722 // irrespective of the value, CRM-2888
1723 $tempParams['cms_create_account'] = 0;
1725 //set this variable as we are not creating pledge for
1726 //separate membership payment contribution.
1727 //so for differentiating membership contribution from
1728 //main contribution.
1729 $form->_params
['separate_membership_payment'] = 1;
1730 $contributionParams = [
1731 'contact_id' => $contactID,
1732 'line_item' => $lineItems,
1733 'is_test' => $isTest,
1734 'campaign_id' => CRM_Utils_Array
::value('campaign_id', $tempParams, CRM_Utils_Array
::value('campaign_id',
1736 'contribution_page_id' => $form->_id
,
1737 'source' => CRM_Utils_Array
::value('source', $tempParams, CRM_Utils_Array
::value('description', $tempParams)),
1739 $isMonetary = !empty($form->_values
['is_monetary']);
1741 if (empty($paymentParams['is_pay_later'])) {
1742 $contributionParams['payment_instrument_id'] = $form->_paymentProcessor
['payment_instrument_id'];
1746 // CRM-19792 : set necessary fields for payment processor
1747 CRM_Core_Payment_Form
::mapParams($form->_bltID
, $form->_params
, $tempParams, TRUE);
1749 $membershipContribution = CRM_Contribute_Form_Contribution_Confirm
::processFormContribution($form,
1752 $contributionParams,
1761 // We're not processing the line item here because we are processing a membership.
1762 // To ensure processing of the correct parameters, replace relevant parameters
1763 // in $tempParams with those in $membershipContribution.
1764 $tempParams['amount_level'] = $membershipContribution->amount_level
;
1765 $tempParams['total_amount'] = $membershipContribution->total_amount
;
1766 $tempParams['tax_amount'] = $membershipContribution->tax_amount
;
1767 $tempParams['contactID'] = $membershipContribution->contact_id
;
1768 $tempParams['financialTypeID'] = $membershipContribution->financial_type_id
;
1769 $tempParams['invoiceID'] = $membershipContribution->invoice_id
;
1770 $tempParams['trxn_id'] = $membershipContribution->trxn_id
;
1771 $tempParams['contributionID'] = $membershipContribution->id
;
1773 if ($form->_values
['is_monetary'] && !$form->_params
['is_pay_later'] && $minimumFee > 0.0) {
1774 // At the moment our tests are calling this form in a way that leaves 'object' empty. For
1775 // now we compensate here.
1776 if (empty($form->_paymentProcessor
['object'])) {
1777 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1780 $payment = $form->_paymentProcessor
['object'];
1782 $result = $payment->doPayment($tempParams, 'contribute');
1783 $form->set('membership_trx_id', $result['trxn_id']);
1784 $form->assign('membership_trx_id', $result['trxn_id']);
1787 return [$membershipContribution, $result];
1791 * Is the payment a pending payment.
1793 * We are moving towards always creating as pending and updating at the end (based on payment), so this should be
1794 * an interim refactoring. It was shared with another unrelated form & some parameters may not apply to this form.
1798 protected function getIsPending() {
1799 // The concept of contributeMode is deprecated.
1800 // the is_monetary concept probably should be too as it can be calculated from
1801 // the existence of 'amount' & seems fragile.
1802 if (((isset($this->_contributeMode
)) ||
!empty($this->_params
['is_pay_later'])
1804 (($this->_values
['is_monetary'] && $this->_amount
> 0.0))
1812 * Are we going to do 2 financial transactions.
1814 * Ie the membership block supports a separate transactions AND the contribution form has been configured for a
1816 * transaction AND a membership transaction AND the payment processor supports double financial transactions (ie. NOT doTransferCheckout style)
1818 * @param int $formID
1819 * @param bool $amountBlockActiveOnForm
1823 public function isSeparateMembershipTransaction($formID, $amountBlockActiveOnForm) {
1824 $memBlockDetails = CRM_Member_BAO_Membership
::getMembershipBlock($formID);
1825 if (!empty($memBlockDetails['is_separate_payment']) && $amountBlockActiveOnForm) {
1832 * This function sets the fields.
1834 * - $this->_params['amount_level']
1835 * - $this->_params['selectMembership']
1836 * And under certain circumstances sets
1837 * $this->_params['amount'] = null;
1839 * @param int $priceSetID
1841 public function setFormAmountFields($priceSetID) {
1842 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params
['priceSetId'], 'is_quick_config');
1843 $priceField = new CRM_Price_DAO_PriceField();
1844 $priceField->price_set_id
= $priceSetID;
1845 $priceField->orderBy('weight');
1846 $priceField->find();
1847 $paramWeDoNotUnderstand = NULL;
1849 while ($priceField->fetch()) {
1850 if ($priceField->name
== "contribution_amount") {
1851 $paramWeDoNotUnderstand = $priceField->id
;
1853 if ($isQuickConfig && !empty($this->_params
["price_{$priceField->id}"])) {
1854 if ($this->_values
['fee'][$priceField->id
]['html_type'] != 'Text') {
1855 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1856 // function to get correct amount level consistently. Remove setting of the amount level in
1857 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1858 // to cover all variants.
1859 $this->_params
['amount_level'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1860 $this->_params
["price_{$priceField->id}"], 'label');
1862 if ($priceField->name
== "membership_amount") {
1863 $this->_params
['selectMembership'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1864 $this->_params
["price_{$priceField->id}"], 'membership_type_id');
1867 // If separate payment we set contribution amount to be null, so that it will not show contribution amount same
1868 // as membership amount.
1869 // @todo - this needs more documentation - it appears the setting to null is tied up with separate membership payments
1870 // but the circumstances are very confusing. Many of these conditions are repeated in the next conditional
1871 // so we should merge them together
1872 // the quick config seems like a red-herring - if this is about a separate membership payment then there
1873 // are 2 types of line items - membership ones & non-membership ones - regardless of whether quick config is set
1875 !empty($this->_membershipBlock
['is_separate_payment'])
1876 && !empty($this->_values
['fee'][$priceField->id
])
1877 && ($this->_values
['fee'][$priceField->id
]['name'] == "other_amount")
1878 && CRM_Utils_Array
::value("price_{$paramWeDoNotUnderstand}", $this->_params
) < 1
1879 && empty($this->_params
["price_{$priceField->id}"])
1881 $this->_params
['amount'] = NULL;
1884 // Fix for CRM-14375 - If we are using separate payments and "no
1885 // thank you" is selected for the additional contribution, set
1886 // contribution amount to be null, so that it will not show
1887 // contribution amount same as membership amount.
1888 //@todo - merge with section above
1889 if (!empty($this->_membershipBlock
['is_separate_payment'])
1890 && !empty($this->_values
['fee'][$priceField->id
])
1891 && CRM_Utils_Array
::value('name', $this->_values
['fee'][$priceField->id
]) == 'contribution_amount'
1892 && CRM_Utils_Array
::value("price_{$priceField->id}", $this->_params
) == '-1'
1894 $this->_params
['amount'] = NULL;
1902 * @param array $params
1904 * @throws CiviCRM_API3_Exception
1906 public static function submit($params) {
1907 $form = new CRM_Contribute_Form_Contribution_Confirm();
1908 $form->_id
= $params['id'];
1910 CRM_Contribute_BAO_ContributionPage
::setValues($form->_id
, $form->_values
);
1911 $form->_separateMembershipPayment
= CRM_Contribute_BAO_ContributionPage
::getIsMembershipPayment($form->_id
);
1912 //this way the mocked up controller ignores the session stuff
1913 $_SERVER['REQUEST_METHOD'] = 'GET';
1914 $form->controller
= new CRM_Contribute_Controller_Contribution();
1915 $params['invoiceID'] = md5(uniqid(rand(), TRUE));
1917 // We want to move away from passing in amount as it is calculated by the actually-submitted params.
1918 $params['amount'] = $params['amount'] ??
$form->getMainContributionAmount($params);
1919 $paramsProcessedForForm = $form->_params
= self
::getFormParams($params['id'], $params);
1920 $form->_amount
= $params['amount'];
1921 // hack these in for test support.
1922 $form->_fields
['billing_first_name'] = 1;
1923 $form->_fields
['billing_last_name'] = 1;
1924 // CRM-18854 - Set form values to allow pledge to be created for api test.
1925 if (!empty($params['pledge_block_id'])) {
1926 $form->_values
['pledge_id'] = $params['pledge_id'] ??
NULL;
1927 $form->_values
['pledge_block_id'] = $params['pledge_block_id'];
1928 $pledgeBlock = CRM_Pledge_BAO_PledgeBlock
::getPledgeBlock($params['id']);
1929 $form->_values
['max_reminders'] = $pledgeBlock['max_reminders'];
1930 $form->_values
['initial_reminder_day'] = $pledgeBlock['initial_reminder_day'];
1931 $form->_values
['additional_reminder_day'] = $pledgeBlock['additional_reminder_day'];
1932 $form->_values
['is_email_receipt'] = FALSE;
1934 $priceSetID = $form->_params
['priceSetId'] = $paramsProcessedForForm['price_set_id'];
1935 $priceFields = CRM_Price_BAO_PriceSet
::getSetDetail($priceSetID);
1936 $priceSetFields = reset($priceFields);
1937 $form->_values
['fee'] = $priceSetFields['fields'];
1938 $form->_priceSetId
= $priceSetID;
1939 $form->setFormAmountFields($priceSetID);
1942 $capabilities[] = (ucfirst($form->_mode
) . 'Mode');
1944 $form->_paymentProcessors
= CRM_Financial_BAO_PaymentProcessor
::getPaymentProcessors($capabilities);
1945 $form->_params
['payment_processor_id'] = $params['payment_processor_id'] ??
0;
1946 if ($form->_params
['payment_processor_id'] !== '') {
1947 // It can be blank with a $0 transaction - then no processor needs to be selected
1948 $form->_paymentProcessor
= $form->_paymentProcessors
[$form->_params
['payment_processor_id']];
1950 if (!empty($params['payment_processor_id'])) {
1951 // The concept of contributeMode is deprecated as is the billing_mode concept.
1952 if ($form->_paymentProcessor
['billing_mode'] == 1) {
1953 $form->_contributeMode
= 'direct';
1956 $form->_contributeMode
= 'notify';
1960 if (!empty($params['useForMember'])) {
1961 $form->set('useForMember', 1);
1962 $form->_useForMember
= 1;
1964 $priceFields = $priceFields[$priceSetID]['fields'];
1966 $form->processAmountAndGetAutoRenew($priceFields, $paramsProcessedForForm, $lineItems, $priceSetID);
1967 $form->_lineItem
= [$priceSetID => $lineItems];
1968 $membershipPriceFieldIDs = [];
1969 foreach ((array) $lineItems as $lineItem) {
1970 if (!empty($lineItem['membership_type_id'])) {
1971 $form->set('useForMember', 1);
1972 $form->_useForMember
= 1;
1973 $membershipPriceFieldIDs['id'] = $priceSetID;
1974 $membershipPriceFieldIDs[] = $lineItem['price_field_value_id'];
1977 $form->set('memberPriceFieldIDS', $membershipPriceFieldIDs);
1978 $form->setRecurringMembershipParams();
1979 $form->processFormSubmission(CRM_Utils_Array
::value('contact_id', $params));
1983 * Helper function for static submit function.
1985 * Set relevant params - help us to build up an array that we can pass in.
1988 * @param array $params
1991 * @throws CiviCRM_API3_Exception
1993 public static function getFormParams($id, array $params) {
1994 if (!isset($params['is_pay_later'])) {
1995 if (!empty($params['payment_processor_id'])) {
1996 $params['is_pay_later'] = 0;
1998 elseif ($params['amount'] !== 0) {
1999 $params['is_pay_later'] = civicrm_api3('contribution_page', 'getvalue', [
2001 'return' => 'is_pay_later',
2005 if (empty($params['price_set_id'])) {
2006 $params['price_set_id'] = CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution_page', $params['id']);
2012 * Post form submission handling.
2014 * This is also called from the test suite.
2016 * @param int $contactID
2019 * @throws \CRM_Core_Exception
2021 protected function processFormSubmission($contactID) {
2022 if (!isset($this->_params
['payment_processor_id'])) {
2023 // If there is no processor we are using the pay-later manual pseudo-processor.
2024 // (note it might make sense to make this a row in the processor table in the db).
2025 $this->_params
['payment_processor_id'] = 0;
2027 if (isset($this->_params
['payment_processor_id']) && $this->_params
['payment_processor_id'] === 0) {
2028 $this->_params
['is_pay_later'] = $isPayLater = TRUE;
2031 if (!empty($this->_ccid
)) {
2032 $this->_params
['contribution_id'] = $this->_ccid
;
2034 //Set email-bltID if pre/post profile contains an email.
2035 if ($this->_emailExists
== TRUE) {
2036 foreach ($this->_params
as $key => $val) {
2037 if (substr($key, 0, 6) == 'email-' && empty($this->_params
["email-{$this->_bltID}"])) {
2038 $this->_params
["email-{$this->_bltID}"] = $this->_params
[$key];
2042 // add a description field at the very beginning
2043 $title = !empty($this->_values
['frontend_title']) ?
$this->_values
['frontend_title'] : $this->_values
['title'];
2044 $this->_params
['description'] = ts('Online Contribution') . ': ' . (!empty($this->_pcpInfo
['title']) ?
$this->_pcpInfo
['title'] : $title);
2046 $this->_params
['accountingCode'] = $this->_values
['accountingCode'] ??
NULL;
2049 $this->_params
['currencyID'] = CRM_Core_Config
::singleton()->defaultCurrency
;
2051 CRM_Contribute_Form_AbstractEditPayment
::formatCreditCardDetails($this->_params
);
2054 if (!empty($this->_params
['is_pledge']) && empty($this->_values
['pledge_id']) && !empty($this->_values
['adjust_recur_start_date'])) {
2055 $pledgeBlock = CRM_Pledge_BAO_PledgeBlock
::getPledgeBlock($this->_id
);
2056 if (!empty($this->_params
['start_date']) ||
empty($pledgeBlock['is_pledge_start_date_visible'])
2057 ||
empty($pledgeBlock['is_pledge_start_date_editable'])) {
2058 $pledgeStartDate = $this->_params
['start_date'] ??
NULL;
2059 $this->_params
['receive_date'] = CRM_Pledge_BAO_Pledge
::getPledgeStartDate($pledgeStartDate, $pledgeBlock);
2060 $recurParams = CRM_Pledge_BAO_Pledge
::buildRecurParams($this->_params
);
2061 $this->_params
= array_merge($this->_params
, $recurParams);
2065 //carry payment processor id.
2066 if (!empty($this->_paymentProcessor
['id'])) {
2067 $this->_params
['payment_processor_id'] = $this->_paymentProcessor
['id'];
2070 $premiumParams = $membershipParams = $params = $this->_params
;
2071 if (!empty($params['image_URL'])) {
2072 CRM_Contact_BAO_Contact
::processImageParams($params);
2075 $fields = ['email-Primary' => 1];
2077 // get the add to groups
2080 // now set the values for the billing location.
2081 foreach ($this->_fields
as $name => $value) {
2084 // get the add to groups for uf fields
2085 if (!empty($value['add_to_group_id'])) {
2086 $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id'];
2090 $fields = $this->formatParamsForPaymentProcessor($fields);
2092 // billing email address
2093 $fields["email-{$this->_bltID}"] = 1;
2095 // if onbehalf-of-organization contribution, take out
2096 // organization params in a separate variable, to make sure
2097 // normal behavior is continued. And use that variable to
2098 // process on-behalf-of functionality.
2099 if (!empty($this->_values
['onbehalf_profile_id']) && empty($this->_ccid
)) {
2100 $behalfOrganization = [];
2101 $orgFields = ['organization_name', 'organization_id', 'org_option'];
2102 foreach ($orgFields as $fld) {
2103 if (array_key_exists($fld, $params)) {
2104 $behalfOrganization[$fld] = $params[$fld];
2105 unset($params[$fld]);
2109 if (is_array($params['onbehalf']) && !empty($params['onbehalf'])) {
2110 foreach ($params['onbehalf'] as $fld => $values) {
2111 if (strstr($fld, 'custom_')) {
2112 $behalfOrganization[$fld] = $values;
2114 elseif (!(strstr($fld, '-'))) {
2115 if (in_array($fld, [
2116 'contribution_campaign_id',
2117 'member_campaign_id',
2119 $fld = 'campaign_id';
2122 $behalfOrganization[$fld] = $values;
2124 $this->_params
[$fld] = $values;
2129 if (array_key_exists('onbehalf_location', $params) && is_array($params['onbehalf_location'])) {
2130 foreach ($params['onbehalf_location'] as $block => $vals) {
2131 //fix for custom data (of type checkbox, multi-select)
2132 if (substr($block, 0, 7) == 'custom_') {
2135 // fix the index of block elements
2136 if (is_array($vals)) {
2137 foreach ($vals as $key => $val) {
2138 //dont adjust the index of address block as
2139 //it's index is WRT to location type
2140 $newKey = ($block == 'address') ?
$key : ++
$key;
2141 $behalfOrganization[$block][$newKey] = $val;
2145 unset($params['onbehalf_location']);
2147 if (!empty($params['onbehalf[image_URL]'])) {
2148 $behalfOrganization['image_URL'] = $params['onbehalf[image_URL]'];
2152 // check for profile double opt-in and get groups to be subscribed
2153 $subscribeGroupIds = CRM_Core_BAO_UFGroup
::getDoubleOptInGroupIds($params, $contactID);
2155 // since we are directly adding contact to group lets unset it from mailing
2156 if (!empty($addToGroups)) {
2157 foreach ($addToGroups as $groupId) {
2158 if (isset($subscribeGroupIds[$groupId])) {
2159 unset($subscribeGroupIds[$groupId]);
2164 foreach ($addToGroups as $k) {
2165 if (array_key_exists($k, $subscribeGroupIds)) {
2166 unset($addToGroups[$k]);
2170 if (empty($contactID)) {
2171 $dupeParams = $params;
2172 if (!empty($dupeParams['onbehalf'])) {
2173 unset($dupeParams['onbehalf']);
2175 if (!empty($dupeParams['honor'])) {
2176 unset($dupeParams['honor']);
2179 $contactID = CRM_Contact_BAO_Contact
::getFirstDuplicateContact($dupeParams, 'Individual', 'Unsupervised', [], FALSE);
2181 // Fetch default greeting id's if creating a contact
2183 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
2184 if (!isset($params[$greeting])) {
2185 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting('Individual', $greeting);
2189 $contactType = NULL;
2192 $contactType = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'contact_type');
2194 $contactID = CRM_Contact_BAO_Contact
::createProfileContact(
2204 // Make the contact ID associated with the contribution available at the Class level.
2205 // Also make available to the session.
2206 //@todo consider handling this in $this->getContactID();
2207 $this->set('contactID', $contactID);
2208 $this->_contactID
= $contactID;
2210 //get email primary first if exist
2211 $subscriptionEmail = ['email' => CRM_Utils_Array
::value('email-Primary', $params)];
2212 if (!$subscriptionEmail['email']) {
2213 $subscriptionEmail['email'] = $params["email-{$this->_bltID}"] ??
NULL;
2215 // subscribing contact to groups
2216 if (!empty($subscribeGroupIds) && $subscriptionEmail['email']) {
2217 CRM_Mailing_Event_BAO_Subscribe
::commonSubscribe($subscribeGroupIds, $subscriptionEmail, $contactID);
2220 // If onbehalf-of-organization contribution / signup, add organization
2221 // and it's location.
2222 if (isset($this->_values
['onbehalf_profile_id']) &&
2223 isset($behalfOrganization['organization_name']) &&
2224 ($this->_values
['is_for_organization'] == 2 ||
2225 !empty($this->_params
['is_for_organization'])
2229 foreach ($this->_fields
['onbehalf'] as $name => $value) {
2230 $ufFields[$name] = 1;
2232 self
::processOnBehalfOrganization($behalfOrganization, $contactID, $this->_values
,
2233 $this->_params
, $ufFields
2236 elseif (!empty($this->_membershipContactID
) && $contactID != $this->_membershipContactID
) {
2237 // this is an onbehalf renew case for inherited membership. For e.g a permissioned member of household,
2238 // store current user id as related contact for later use for mailing / activity..
2239 $this->_values
['related_contact'] = $contactID;
2240 $this->_params
['related_contact'] = $contactID;
2241 // swap contact like we do for on-behalf-org case, so parent/primary membership is affected
2242 $contactID = $this->_membershipContactID
;
2245 // lets store the contactID in the session
2246 // for things like tell a friend
2247 $session = CRM_Core_Session
::singleton();
2248 if (!$session->get('userID')) {
2249 $session->set('transaction.userID', $contactID);
2252 $session->set('transaction.userID', NULL);
2255 $this->_useForMember
= $this->get('useForMember');
2257 // store the fact that this is a membership and membership type is selected
2258 if ($this->isMembershipSelected($membershipParams)) {
2259 if (!$this->_useForMember
) {
2260 $this->assign('membership_assign', TRUE);
2261 $this->set('membershipTypeID', $this->_params
['selectMembership']);
2264 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
2265 $membershipParams['is_test'] = 1;
2267 if ($this->_params
['is_pay_later']) {
2268 $membershipParams['is_pay_later'] = 1;
2271 if (isset($this->_params
['onbehalf_contact_id'])) {
2272 $membershipParams['onbehalf_contact_id'] = $this->_params
['onbehalf_contact_id'];
2274 //inherit campaign from contribution page.
2275 if (!array_key_exists('campaign_id', $membershipParams)) {
2276 $membershipParams['campaign_id'] = $this->_values
['campaign_id'] ??
NULL;
2279 $this->_params
= CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $membershipParams, TRUE);
2280 $this->doMembershipProcessing($contactID, $membershipParams, $premiumParams, $this->_lineItem
);
2283 // at this point we've created a contact and stored its address etc
2284 // all the payment processors expect the name and address to be in the
2285 // so we copy stuff over to first_name etc.
2286 $paymentParams = $this->_params
;
2287 // Make it explict that we are letting the processConfirm function figure out the line items.
2288 $paymentParams['skipLineItem'] = 0;
2290 if (!isset($paymentParams['line_item'])) {
2291 $paymentParams['line_item'] = $this->_lineItem
;
2294 if (!empty($paymentParams['onbehalf']) &&
2295 is_array($paymentParams['onbehalf'])
2297 foreach ($paymentParams['onbehalf'] as $key => $value) {
2298 if (strstr($key, 'custom_')) {
2299 $this->_params
[$key] = $value;
2304 $result = CRM_Contribute_BAO_Contribution_Utils
::processConfirm($this, $paymentParams,
2306 $this->wrangleFinancialTypeID($this->_values
['financial_type_id']),
2307 ($this->_mode
== 'test') ?
1 : 0,
2308 CRM_Utils_Array
::value('is_recur', $paymentParams)
2311 if (empty($result['is_payment_failure'])) {
2312 // @todo move premium processing to complete transaction if it truly is an 'after' action.
2313 $this->postProcessPremium($premiumParams, $result['contribution']);
2315 if (!empty($result['contribution'])) {
2316 // It seems this line is hit when there is a zero dollar transaction & in tests, not sure when else.
2317 $this->completeTransaction($result, $result['contribution']->id
);
2324 * Return True/False if we have a membership selected on the contribution page
2325 * @param array $membershipParams
2329 private function isMembershipSelected($membershipParams) {
2330 $priceFieldIds = $this->get('memberPriceFieldIDS');
2331 if ((!empty($membershipParams['selectMembership']) && $membershipParams['selectMembership'] != 'no_thanks')
2332 && empty($priceFieldIds)) {
2336 $membershipParams = $this->getMembershipParamsFromPriceSet($membershipParams);
2338 return !empty($membershipParams['selectMembership']);
2342 * Extract the selected memberships from a priceSet
2344 * @param array $membershipParams
2348 private function getMembershipParamsFromPriceSet($membershipParams) {
2349 $priceFieldIds = $this->get('memberPriceFieldIDS');
2350 if (empty($priceFieldIds)) {
2351 return $membershipParams;
2353 $membershipParams['financial_type_id'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceFieldIds['id'], 'financial_type_id');
2354 unset($priceFieldIds['id']);
2355 $membershipTypeIds = [];
2356 $membershipTypeTerms = [];
2357 foreach ($priceFieldIds as $priceFieldId) {
2358 $membershipTypeId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id');
2359 if ($membershipTypeId) {
2360 $membershipTypeIds[] = $membershipTypeId;
2361 $term = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_num_terms') ?
: 1;
2362 $membershipTypeTerms[$membershipTypeId] = ($term > 1) ?
$term : 1;
2365 $membershipParams['selectMembership'] = $membershipTypeIds;
2366 $membershipParams['types_terms'] = $membershipTypeTerms;
2367 return $membershipParams;
2371 * Membership processing section.
2373 * This is in a separate function as part of a move towards refactoring.
2375 * @param int $contactID
2376 * @param array $membershipParams
2377 * @param array $premiumParams
2378 * @param array $formLineItems
2380 protected function doMembershipProcessing($contactID, $membershipParams, $premiumParams, $formLineItems) {
2381 // This could be set by a hook.
2382 if (!empty($this->_params
['installments'])) {
2383 $membershipParams['installments'] = $this->_params
['installments'];
2385 // added new parameter for cms user contact id, needed to distinguish behaviour for on behalf of sign-ups
2386 if (isset($this->_params
['related_contact'])) {
2387 $membershipParams['cms_contactID'] = $this->_params
['related_contact'];
2390 $membershipParams['cms_contactID'] = $contactID;
2393 if (!empty($membershipParams['onbehalf']) &&
2394 is_array($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])
2396 $this->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
2399 $customFieldsFormatted = $fieldTypes = [];
2400 if (!empty($membershipParams['onbehalf']) &&
2401 is_array($membershipParams['onbehalf'])
2403 foreach ($membershipParams['onbehalf'] as $key => $value) {
2404 if (strstr($key, 'custom_')) {
2405 $customFieldId = explode('_', $key);
2406 CRM_Core_BAO_CustomField
::formatCustomField(
2408 $customFieldsFormatted,
2416 $fieldTypes = ['Contact', 'Organization', 'Membership'];
2419 $membershipParams = $this->getMembershipParamsFromPriceSet($membershipParams);
2420 if (!empty($membershipParams['selectMembership'])) {
2422 $membershipLineItems = $formLineItems;
2423 if ($this->_separateMembershipPayment
&& $this->_values
['amount_block_is_active']) {
2424 $membershipLineItems = [];
2425 foreach ($this->_values
['fee'] as $key => $feeValues) {
2426 if ($feeValues['name'] == 'membership_amount') {
2427 $fieldId = $this->_params
['price_' . $key];
2428 $membershipLineItems[$this->_priceSetId
][$fieldId] = $this->_lineItem
[$this->_priceSetId
][$fieldId];
2429 unset($this->_lineItem
[$this->_priceSetId
][$fieldId]);
2435 $this->processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems);
2437 catch (\Civi\Payment\Exception\PaymentProcessorException
$e) {
2438 CRM_Core_Session
::singleton()->setStatus($e->getMessage());
2439 if (!empty($this->_contributionID
)) {
2440 CRM_Contribute_BAO_Contribution
::failPayment($this->_contributionID
,
2441 $contactID, $e->getMessage());
2443 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
2445 catch (CRM_Core_Exception
$e) {
2446 CRM_Core_Session
::singleton()->setStatus($e->getMessage());
2447 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
2449 if (!$this->_amount
> 0.0 ||
!$membershipParams['amount']) {
2450 // we need to explicitly create a CMS user in case of free memberships
2451 // since it is done under processConfirm for paid memberships
2452 CRM_Contribute_BAO_Contribution_Utils
::createCMSUser($membershipParams,
2453 $membershipParams['cms_contactID'],
2454 'email-' . $this->_bltID
2461 * Complete transaction if payment has been processed.
2463 * Check the result for a success outcome & if paid then complete the transaction.
2465 * Completing will trigger update of related entities and emails.
2467 * @param array $result
2468 * @param int $contributionID
2470 * @throws \CiviCRM_API3_Exception
2471 * @throws \Exception
2473 protected function completeTransaction($result, $contributionID) {
2474 if (CRM_Utils_Array
::value('payment_status_id', $result) == 1) {
2476 civicrm_api3('contribution', 'completetransaction', [
2477 'id' => $contributionID,
2478 'trxn_id' => $result['trxn_id'] ??
NULL,
2479 'payment_processor_id' => CRM_Utils_Array
::value('payment_processor_id', $result, $this->_paymentProcessor
['id']),
2480 'is_transactional' => FALSE,
2481 'fee_amount' => $result['fee_amount'] ??
NULL,
2482 'receive_date' => $result['receive_date'] ??
NULL,
2483 'card_type_id' => $result['card_type_id'] ??
NULL,
2484 'pan_truncation' => $result['pan_truncation'] ??
NULL,
2487 catch (CiviCRM_API3_Exception
$e) {
2488 if ($e->getErrorCode() != 'contribution_completed') {
2489 throw new CRM_Core_Exception('Failed to update contribution in database');
2496 * Bounce the user back to retry when an error occurs.
2498 * @param string $message
2500 protected function bounceOnError($message) {
2501 CRM_Core_Session
::singleton()
2502 ->setStatus(ts("Payment Processor Error message :") .
2504 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact',
2505 "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"