3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * form to process actions on the group aspect of Custom Data
21 class CRM_Contribute_Form_Contribution_Confirm
extends CRM_Contribute_Form_ContributionBase
{
24 * The id of the contact associated with this contribution.
32 * The id of the contribution object that is created when the form is submitted.
36 public $_contributionID;
38 public $submitOnce = TRUE;
43 * @param $contributionParams
45 * @param $contribution
46 * @param $isEmailReceipt
49 public static function handlePledge(&$form, $params, $contributionParams, $pledgeID, $contribution, $isEmailReceipt) {
51 //when user doing pledge payments.
52 //update the schedule when payment(s) are made
53 $amount = $params['amount'];
54 $pledgePaymentParams = [];
55 foreach ($params['pledge_amount'] as $paymentId => $dontCare) {
56 $scheduledAmount = CRM_Core_DAO
::getFieldValue(
57 'CRM_Pledge_DAO_PledgePayment',
63 $pledgePayment = ($amount >= $scheduledAmount) ?
$scheduledAmount : $amount;
64 if ($pledgePayment > 0) {
65 $pledgePaymentParams[] = [
67 'contribution_id' => $contribution->id
,
68 'status_id' => $contribution->contribution_status_id
,
69 'actual_amount' => $pledgePayment,
71 $amount -= $pledgePayment;
74 if ($amount > 0 && count($pledgePaymentParams)) {
75 $pledgePaymentParams[count($pledgePaymentParams) - 1]['actual_amount'] +
= $amount;
77 foreach ($pledgePaymentParams as $p) {
78 CRM_Pledge_BAO_PledgePayment
::add($p);
81 //update pledge status according to the new payment statuses
82 CRM_Pledge_BAO_PledgePayment
::updatePledgePaymentStatus($pledgeID);
86 //when user creating pledge record.
88 $pledgeParams['contact_id'] = $contribution->contact_id
;
89 $pledgeParams['installment_amount'] = $pledgeParams['actual_amount'] = $contribution->total_amount
;
90 $pledgeParams['contribution_id'] = $contribution->id
;
91 $pledgeParams['contribution_page_id'] = $contribution->contribution_page_id
;
92 $pledgeParams['financial_type_id'] = $contribution->financial_type_id
;
93 $pledgeParams['frequency_interval'] = $params['pledge_frequency_interval'];
94 $pledgeParams['installments'] = $params['pledge_installments'];
95 $pledgeParams['frequency_unit'] = $params['pledge_frequency_unit'];
96 if ($pledgeParams['frequency_unit'] === 'month') {
97 $pledgeParams['frequency_day'] = intval(date("d"));
100 $pledgeParams['frequency_day'] = 1;
102 $pledgeParams['create_date'] = $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date("Ymd");
103 if (!empty($params['start_date'])) {
104 $pledgeParams['frequency_day'] = intval(date("d", strtotime($params['start_date'])));
105 $pledgeParams['start_date'] = $pledgeParams['scheduled_date'] = date('Ymd', strtotime($params['start_date']));
107 $pledgeParams['status_id'] = $contribution->contribution_status_id
;
108 $pledgeParams['max_reminders'] = $form->_values
['max_reminders'];
109 $pledgeParams['initial_reminder_day'] = $form->_values
['initial_reminder_day'];
110 $pledgeParams['additional_reminder_day'] = $form->_values
['additional_reminder_day'];
111 $pledgeParams['is_test'] = $contribution->is_test
;
112 $pledgeParams['acknowledge_date'] = date('Ymd');
113 $pledgeParams['original_installment_amount'] = $pledgeParams['installment_amount'];
115 //inherit campaign from contirb page.
116 $pledgeParams['campaign_id'] = $contributionParams['campaign_id'] ??
NULL;
118 $pledge = CRM_Pledge_BAO_Pledge
::create($pledgeParams);
120 $form->_params
['pledge_id'] = $pledge->id
;
122 //send acknowledgment email. only when pledge is created
123 if ($pledge->id
&& $isEmailReceipt) {
124 //build params to send acknowledgment.
125 $pledgeParams['id'] = $pledge->id
;
126 $pledgeParams['receipt_from_name'] = $form->_values
['receipt_from_name'];
127 $pledgeParams['receipt_from_email'] = $form->_values
['receipt_from_email'];
129 //scheduled amount will be same as installment_amount.
130 $pledgeParams['scheduled_amount'] = $pledgeParams['installment_amount'];
132 //get total pledge amount.
133 $pledgeParams['total_pledge_amount'] = $pledge->amount
;
135 CRM_Pledge_BAO_Pledge
::sendAcknowledgment($form, $pledgeParams);
143 * Set the parameters to be passed to contribution create function.
145 * @param array $params
146 * @param int $financialTypeID
147 * @param array $paymentProcessorOutcome
148 * @param string $receiptDate
149 * @param int $recurringContributionID
152 * @throws \CRM_Core_Exception
154 public static function getContributionParams(
155 $params, $financialTypeID,
156 $paymentProcessorOutcome, $receiptDate, $recurringContributionID) {
157 $contributionParams = [
158 'financial_type_id' => $financialTypeID,
159 'receive_date' => !empty($params['receive_date']) ? CRM_Utils_Date
::processDate($params['receive_date']) : date('YmdHis'),
160 'tax_amount' => $params['tax_amount'] ??
NULL,
161 'amount_level' => $params['amount_level'] ??
NULL,
162 'invoice_id' => $params['invoiceID'],
163 'currency' => $params['currencyID'],
164 'is_pay_later' => $params['is_pay_later'] ??
0,
165 //configure cancel reason, cancel date and thankyou date
166 //from 'contribution' type profile if included
167 'cancel_reason' => $params['cancel_reason'] ??
0,
168 'cancel_date' => isset($params['cancel_date']) ? CRM_Utils_Date
::format($params['cancel_date']) : NULL,
169 'thankyou_date' => isset($params['thankyou_date']) ? CRM_Utils_Date
::format($params['thankyou_date']) : NULL,
170 //setting to make available to hook - although seems wrong to set on form for BAO hook availability
171 'skipLineItem' => $params['skipLineItem'] ??
0,
174 if ($paymentProcessorOutcome) {
175 $contributionParams['payment_processor'] = $paymentProcessorOutcome['payment_processor'] ??
NULL;
177 if (!empty($params["is_email_receipt"])) {
178 $contributionParams +
= [
179 'receipt_date' => $receiptDate,
183 if ($recurringContributionID) {
184 $contributionParams['contribution_recur_id'] = $recurringContributionID;
187 $contributionParams['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
188 if (isset($contributionParams['invoice_id'])) {
189 $contributionParams['id'] = CRM_Core_DAO
::getFieldValue(
190 'CRM_Contribute_DAO_Contribution',
191 $contributionParams['invoice_id'],
197 return $contributionParams;
201 * Get non-deductible amount.
203 * This is a bit too much about wierd form interpretation to be this deep.
205 * @see https://issues.civicrm.org/jira/browse/CRM-11885
206 * if non_deductible_amount exists i.e. Additional Details fieldset was opened [and staff typed something] -> keep
209 * @param array $params
210 * @param CRM_Financial_BAO_FinancialType $financialType
211 * @param bool $online
212 * @param CRM_Contribute_Form_Contribution_Confirm $form
216 public static function getNonDeductibleAmount($params, $financialType, $online, $form) {
217 if (isset($params['non_deductible_amount']) && (!empty($params['non_deductible_amount']))) {
218 return $params['non_deductible_amount'];
220 $priceSetId = $params['priceSetId'] ??
NULL;
221 // return non-deductible amount if it is set at the price field option level
222 if ($priceSetId && !empty($form->_lineItem
)) {
223 $nonDeductibleAmount = CRM_Price_BAO_PriceSet
::getNonDeductibleAmountFromPriceSet($priceSetId, $form->_lineItem
);
226 if (!empty($nonDeductibleAmount)) {
227 return $nonDeductibleAmount;
230 if ($financialType->is_deductible
) {
231 if ($online && isset($params['selectProduct'])) {
232 $selectProduct = $params['selectProduct'] ??
NULL;
234 if (!$online && isset($params['product_name'][0])) {
235 $selectProduct = $params['product_name'][0];
237 // if there is a product - compare the value to the contribution amount
238 if (isset($selectProduct) &&
239 $selectProduct !== 'no_thanks'
241 $productDAO = new CRM_Contribute_DAO_Product();
242 $productDAO->id
= $selectProduct;
243 $productDAO->find(TRUE);
244 // product value exceeds contribution amount
245 if ($params['amount'] < $productDAO->price
) {
246 $nonDeductibleAmount = $params['amount'];
247 return $nonDeductibleAmount;
249 // product value does NOT exceed contribution amount
251 return $productDAO->price
;
254 // contribution is deductible - but there is no product
259 // contribution is NOT deductible
261 return $params['amount'];
267 * Set variables up before form is built.
269 public function preProcess() {
270 parent
::preProcess();
272 // lineItem isn't set until Register postProcess
273 $this->_lineItem
= $this->get('lineItem');
274 $this->_ccid
= $this->get('ccid');
276 $this->_params
= $this->controller
->exportValues('Main');
277 $this->_params
['ip_address'] = CRM_Utils_System
::ipAddress();
278 $this->_params
['amount'] = $this->get('amount');
279 if (isset($this->_params
['amount'])) {
280 $this->setFormAmountFields($this->_params
['priceSetId']);
283 $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 [$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 [$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 [$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 $this->assign('amount_block_is_active', $this->isFormSupportsNonMembershipContributions());
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 if (CRM_Core_Component
::isEnabled('CiviMember') && empty($this->_ccid
)) {
523 if (isset($params['selectMembership']) &&
524 $params['selectMembership'] !== 'no_thanks'
526 $this->buildMembershipBlock(
527 $this->_membershipContactID
,
528 $params['selectMembership']
530 if (!empty($params['auto_renew'])) {
531 $this->assign('auto_renew', TRUE);
535 $this->assign('membershipBlock', FALSE);
538 if (empty($this->_ccid
)) {
539 $this->buildCustom($this->_values
['custom_pre_id'], 'customPre', TRUE);
540 $this->buildCustom($this->_values
['custom_post_id'], 'customPost', TRUE);
543 if (!empty($this->_values
['onbehalf_profile_id']) &&
544 !empty($params['onbehalf']) &&
545 ($this->_values
['is_for_organization'] == 2 ||
546 !empty($params['is_for_organization'])
547 ) && empty($this->_ccid
)
549 $fieldTypes = ['Contact', 'Organization'];
550 $contactSubType = CRM_Contact_BAO_ContactType
::subTypes('Organization');
551 $fieldTypes = array_merge($fieldTypes, $contactSubType);
552 if (is_array($this->_membershipBlock
) && !empty($this->_membershipBlock
)) {
553 $fieldTypes = array_merge($fieldTypes, ['Membership']);
556 $fieldTypes = array_merge($fieldTypes, ['Contribution']);
559 $this->buildCustom($this->_values
['onbehalf_profile_id'], 'onbehalfProfile', TRUE, 'onbehalf', $fieldTypes);
562 $this->_separateMembershipPayment
= $this->get('separateMembershipPayment');
563 $this->assign('is_separate_payment', $this->_separateMembershipPayment
);
565 $this->assign('priceSetID', $this->_priceSetId
);
567 // The concept of contributeMode is deprecated.
568 // the is_monetary concept probably should be too as it can be calculated from
569 // the existence of 'amount' & seems fragile.
570 if ($this->_contributeMode
=== 'notify' ||
571 $this->_amount
<= 0.0 ||
$this->_params
['is_pay_later']
573 $contribButton = ts('Continue');
575 elseif (!empty($this->_ccid
)) {
576 $contribButton = ts('Make Payment');
579 $contribButton = ts('Make Contribution');
581 $this->assign('button', $contribButton);
583 $this->assign('continueText',
584 $this->getPaymentProcessorObject()->getText('contributionPageContinueText', [
585 'is_payment_to_existing' => !empty($this->_ccid
),
586 'amount' => $this->_amount
,
593 'name' => $contribButton,
594 'spacing' => ' ',
599 'name' => ts('Go Back'),
604 $fields = array_fill_keys(array_keys($this->_fields
), 1);
605 $fields["billing_state_province-{$this->_bltID}"] = $fields["billing_country-{$this->_bltID}"] = $fields["email-{$this->_bltID}"] = 1;
607 $contact = $this->_params
;
608 foreach ($fields as $name => $dontCare) {
609 // Recursively set defaults for nested fields
610 if (isset($contact[$name]) && is_array($contact[$name]) && ($name === 'onbehalf' ||
$name === 'honor')) {
611 foreach ($contact[$name] as $fieldName => $fieldValue) {
612 if (is_array($fieldValue) && $this->_fields
[$name][$fieldName]['html_type'] === 'CheckBox') {
613 foreach ($fieldValue as $key => $value) {
614 $defaults["{$name}[{$fieldName}][{$key}]"] = $value;
618 $defaults["{$name}[{$fieldName}]"] = $fieldValue;
622 elseif (isset($contact[$name])) {
623 $defaults[$name] = $contact[$name];
624 if (substr($name, 0, 7) === 'custom_') {
625 $timeField = "{$name}_time";
626 if (isset($contact[$timeField])) {
627 $defaults[$timeField] = $contact[$timeField];
629 if (isset($contact["{$name}_id"])) {
630 $defaults["{$name}_id"] = $contact["{$name}_id"];
633 elseif (in_array($name, [
637 ]) && !empty($contact[$name . '_custom'])
639 $defaults[$name . '_custom'] = $contact[$name . '_custom'];
644 $this->assign('useForMember', $this->get('useForMember'));
646 $this->setDefaults($defaults);
652 * Build Membership Block in Contribution Pages.
653 * @todo this was shared on CRM_Contribute_Form_ContributionBase but we are refactoring and simplifying for each
654 * step (main/confirm/thankyou)
657 * Contact checked for having a current membership for a particular membership.
658 * @param int|array $selectedMembershipTypeID
659 * Selected membership id.
660 * @param null $isTest
663 * Is this a separate membership payment
665 * @throws \CiviCRM_API3_Exception
666 * @throws \CRM_Core_Exception
668 private function buildMembershipBlock($cid, $selectedMembershipTypeID = NULL, $isTest = NULL) {
669 $separateMembershipPayment = FALSE;
670 if ($this->_membershipBlock
) {
671 $this->_currentMemberships
= [];
673 $membershipTypeIds = $membershipTypes = $radio = $radioOptAttrs = [];
674 $membershipPriceset = (!empty($this->_priceSetId
) && $this->_useForMember
);
676 $autoRenewMembershipTypeOptions = [];
678 $separateMembershipPayment = $this->_membershipBlock
['is_separate_payment'] ??
NULL;
680 if ($membershipPriceset) {
681 foreach ($this->_priceSet
['fields'] as $pField) {
682 if (empty($pField['options'])) {
685 foreach ($pField['options'] as $opId => $opValues) {
686 if (empty($opValues['membership_type_id'])) {
689 $membershipTypeIds[$opValues['membership_type_id']] = $opValues['membership_type_id'];
693 elseif (!empty($this->_membershipBlock
['membership_types'])) {
694 $membershipTypeIds = explode(',', $this->_membershipBlock
['membership_types']);
697 if (!empty($membershipTypeIds)) {
698 //set status message if wrong membershipType is included in membershipBlock
699 if (isset($this->_mid
) && !$membershipPriceset) {
700 $membershipTypeID = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
704 if (!in_array($membershipTypeID, $membershipTypeIds)) {
705 CRM_Core_Session
::setStatus(ts("Oops. The membership you're trying to renew appears to be invalid. Contact your site administrator if you need assistance. If you continue, you will be issued a new membership."), ts('Invalid Membership'), 'error');
709 $membershipTypeValues = CRM_Member_BAO_Membership
::buildMembershipTypeValues($this, $membershipTypeIds);
710 $this->_membershipTypeValues
= $membershipTypeValues;
713 // Check if we support auto-renew on this contribution page
714 // FIXME: If any of the payment processors do NOT support recurring you cannot setup an
715 // auto-renew payment even if that processor is not selected.
716 $allowAutoRenewOpt = TRUE;
717 if (is_array($this->_paymentProcessors
)) {
718 foreach ($this->_paymentProcessors
as $id => $val) {
719 if ($id && !$val['is_recur']) {
720 $allowAutoRenewOpt = FALSE;
724 foreach ($membershipTypeIds as $value) {
725 $memType = $membershipTypeValues[$value];
726 if ($selectedMembershipTypeID != NULL) {
727 if ($memType['id'] == $selectedMembershipTypeID) {
728 $this->assign('minimum_fee', $memType['minimum_fee'] ??
NULL);
729 $this->assign('membership_name', $memType['name']);
731 $membership = new CRM_Member_DAO_Membership();
732 $membership->contact_id
= $cid;
733 $membership->membership_type_id
= $memType['id'];
734 if ($membership->find(TRUE)) {
735 $this->assign('renewal_mode', TRUE);
736 $memType['current_membership'] = $membership->end_date
;
737 $this->_currentMemberships
[$membership->membership_type_id
] = $membership->membership_type_id
;
740 $membershipTypes[] = $memType;
743 elseif ($memType['is_active']) {
745 if ($allowAutoRenewOpt) {
746 $javascriptMethod = ['onclick' => "return showHideAutoRenew( this.value );"];
747 $isAvailableAutoRenew = $this->_membershipBlock
['auto_renew'][$value] ??
1;
748 $autoRenewMembershipTypeOptions["autoRenewMembershipType_{$value}"] = (int) $memType['auto_renew'] * $isAvailableAutoRenew;
749 $allowAutoRenewMembership = TRUE;
752 $javascriptMethod = NULL;
753 $autoRenewMembershipTypeOptions["autoRenewMembershipType_{$value}"] = 0;
756 //add membership type.
757 $radio[$memType['id']] = NULL;
758 $radioOptAttrs[$memType['id']] = $javascriptMethod;
760 $membership = new CRM_Member_DAO_Membership();
761 $membership->contact_id
= $cid;
762 $membership->membership_type_id
= $memType['id'];
764 //show current membership, skip pending and cancelled membership records,
765 //because we take first membership record id for renewal
766 $membership->whereAdd('status_id != 5 AND status_id !=6');
768 if (!is_null($isTest)) {
769 $membership->is_test
= $isTest;
773 $membership->orderBy('end_date DESC');
775 if ($membership->find(TRUE)) {
776 if (!$membership->end_date
) {
777 unset($radio[$memType['id']]);
778 unset($radioOptAttrs[$memType['id']]);
779 $this->assign('islifetime', TRUE);
782 $this->assign('renewal_mode', TRUE);
783 $this->_currentMemberships
[$membership->membership_type_id
] = $membership->membership_type_id
;
784 $memType['current_membership'] = $membership->end_date
;
786 $endDate = $memType['current_membership'];
787 $this->_defaultMemTypeId
= $memType['id'];
789 if ($memType['current_membership'] < $endDate) {
790 $endDate = $memType['current_membership'];
791 $this->_defaultMemTypeId
= $memType['id'];
795 $membershipTypes[] = $memType;
800 $this->assign('membershipBlock', $this->_membershipBlock
);
801 $this->assign('showRadio', FALSE);
802 $this->assign('membershipTypes', $membershipTypes);
803 $this->assign('autoRenewMembershipTypeOptions', json_encode($autoRenewMembershipTypeOptions));
804 //give preference to user submitted auto_renew value.
805 $takeUserSubmittedAutoRenew = (!empty($_POST) ||
$this->isSubmitted());
806 $this->assign('takeUserSubmittedAutoRenew', $takeUserSubmittedAutoRenew);
808 // Assign autorenew option (0:hide,1:optional,2:required) so we can use it in confirmation etc.
809 $autoRenewOption = CRM_Price_BAO_PriceSet
::checkAutoRenewForPriceSet($this->_priceSetId
);
810 //$selectedMembershipTypeID is retrieved as an array for membership priceset if multiple
811 //options for different organisation is selected on the contribution page.
812 if (is_numeric($selectedMembershipTypeID) && isset($membershipTypeValues[$selectedMembershipTypeID]['auto_renew'])) {
813 $this->assign('autoRenewOption', $membershipTypeValues[$selectedMembershipTypeID]['auto_renew']);
816 $this->assign('autoRenewOption', $autoRenewOption);
820 return $separateMembershipPayment;
826 * Since we are only showing elements in frozen mode no help display needed.
830 public function getAction() {
831 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
832 return CRM_Core_Action
::VIEW | CRM_Core_Action
::PREVIEW
;
835 return CRM_Core_Action
::VIEW
;
840 * Set default values for the form.
842 * Note that in edit/view mode
843 * the default values are retrieved from the database
845 public function setDefaultValues() {
851 public function postProcess() {
852 $contactID = $this->getContactID();
854 $result = $this->processFormSubmission($contactID);
856 catch (CRM_Core_Exception
$e) {
857 $this->bounceOnError($e->getMessage());
860 if (is_array($result) && !empty($result['is_payment_failure'])) {
861 $this->bounceOnError($result['error']->getMessage());
863 // Presumably this is for hooks to access? Not quite clear & perhaps not required.
864 $this->set('params', $this->_params
);
868 * Wrangle financial type ID.
870 * 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
871 * Pledges are not relevant to the membership code so that portion will not go onto the membership form.
873 * Comments from previous refactor indicate doubt as to what was going on.
875 * @param int $financialTypeID
877 * @return null|string
879 public function wrangleFinancialTypeID($financialTypeID) {
880 if (empty($financialTypeID) && !empty($this->_values
['pledge_id'])) {
881 $financialTypeID = CRM_Core_DAO
::getFieldValue('CRM_Pledge_DAO_Pledge',
882 $this->_values
['pledge_id'],
886 return $financialTypeID;
892 * @param array $premiumParams
893 * @param CRM_Contribute_BAO_Contribution $contribution
895 protected function postProcessPremium($premiumParams, $contribution) {
896 $hour = $minute = $second = 0;
897 // assigning Premium information to receipt tpl
898 $selectProduct = $premiumParams['selectProduct'] ??
NULL;
899 if ($selectProduct &&
900 $selectProduct != 'no_thanks'
902 $startDate = $endDate = "";
903 $this->assign('selectPremium', TRUE);
904 $productDAO = new CRM_Contribute_DAO_Product();
905 $productDAO->id
= $selectProduct;
906 $productDAO->find(TRUE);
907 $this->assign('product_name', $productDAO->name
);
908 $this->assign('price', $productDAO->price
);
909 $this->assign('sku', $productDAO->sku
);
910 $this->assign('option', $premiumParams['options_' . $premiumParams['selectProduct']] ??
NULL);
912 $periodType = $productDAO->period_type
;
915 $fixed_period_start_day = $productDAO->fixed_period_start_day
;
916 $duration_unit = $productDAO->duration_unit
;
917 $duration_interval = $productDAO->duration_interval
;
918 if ($periodType === 'rolling') {
919 $startDate = date('Y-m-d');
921 elseif ($periodType === 'fixed') {
922 if ($fixed_period_start_day) {
923 $date = explode('-', date('Y-m-d'));
924 $month = substr($fixed_period_start_day, 0, strlen($fixed_period_start_day) - 2);
925 $day = substr($fixed_period_start_day, -2) . "<br/>";
927 $startDate = $year . '-' . $month . '-' . $day;
930 $startDate = date('Y-m-d');
934 $date = explode('-', $startDate);
939 switch ($duration_unit) {
941 $year +
= $duration_interval;
945 $month +
= $duration_interval;
949 $day +
= $duration_interval;
953 $day +
= ($duration_interval * 7);
955 $endDate = date('Y-m-d H:i:s', mktime($hour, $minute, $second, $month, $day, $year));
956 $this->assign('start_date', $startDate);
957 $this->assign('end_date', $endDate);
960 $dao = new CRM_Contribute_DAO_Premium();
961 $dao->entity_table
= 'civicrm_contribution_page';
962 $dao->entity_id
= $this->_id
;
964 $this->assign('contact_phone', $dao->premiums_contact_phone
);
965 $this->assign('contact_email', $dao->premiums_contact_email
);
967 //create Premium record
969 'product_id' => $premiumParams['selectProduct'],
970 'contribution_id' => $contribution->id
,
971 'product_option' => $premiumParams['options_' . $premiumParams['selectProduct']] ??
NULL,
973 'start_date' => CRM_Utils_Date
::customFormat($startDate, '%Y%m%d'),
974 'end_date' => CRM_Utils_Date
::customFormat($endDate, '%Y%m%d'),
976 if (!empty($premiumParams['selectProduct'])) {
977 $daoPremiumsProduct = new CRM_Contribute_DAO_PremiumsProduct();
978 $daoPremiumsProduct->product_id
= $premiumParams['selectProduct'];
979 $daoPremiumsProduct->premiums_id
= $dao->id
;
980 $daoPremiumsProduct->find(TRUE);
981 $params['financial_type_id'] = $daoPremiumsProduct->financial_type_id
;
984 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
985 $daoContrProd->contribution_id
= $contribution->id
;
986 if ($daoContrProd->find(TRUE)) {
987 $params['id'] = $daoContrProd->id
;
990 CRM_Contribute_BAO_Contribution
::addPremium($params);
991 if ($productDAO->cost
&& !empty($params['financial_type_id'])) {
993 'cost' => $productDAO->cost
,
994 'currency' => $productDAO->currency
,
995 'financial_type_id' => $params['financial_type_id'],
996 'contributionId' => $contribution->id
,
998 CRM_Core_BAO_FinancialTrxn
::createPremiumTrxn($trxnParams);
1001 elseif ($selectProduct === 'no_thanks') {
1002 //Fixed For CRM-3901
1003 $daoContrProd = new CRM_Contribute_DAO_ContributionProduct();
1004 $daoContrProd->contribution_id
= $contribution->id
;
1005 if ($daoContrProd->find(TRUE)) {
1006 $daoContrProd->delete();
1012 * Process the contribution.
1014 * @param array $params
1015 * @param array $result
1016 * @param array $contributionParams
1017 * Parameters to be passed to contribution create action.
1018 * This differs from params in that we are currently adding params to it and 1) ensuring they are being
1019 * passed consistently & 2) documenting them here.
1024 * - contribution_page_id
1027 * - thankyou_date (not all forms will set this)
1029 * @param CRM_Financial_DAO_FinancialType $financialType
1030 * @param int $billingLocationID
1031 * ID of billing location type.
1032 * @param bool $isRecur
1033 * Is this recurring?
1035 * @return \CRM_Contribute_DAO_Contribution
1037 * @throws \CRM_Core_Exception
1038 * @throws \CiviCRM_API3_Exception
1039 * @todo - this code was previously shared with the backoffice form - some parts of this
1040 * function may relate to that form, not this one.
1043 protected function processFormContribution(
1046 $contributionParams,
1052 $transaction = new CRM_Core_Transaction();
1053 $contactID = $contributionParams['contact_id'];
1055 $isEmailReceipt = !empty($form->_values
['is_email_receipt']);
1056 $isSeparateMembershipPayment = !empty($params['separate_membership_payment']);
1057 $pledgeID = !empty($params['pledge_id']) ?
$params['pledge_id'] : $form->_values
['pledge_id'] ??
NULL;
1058 if (!$isSeparateMembershipPayment && !empty($form->_values
['pledge_block_id']) &&
1059 (!empty($params['is_pledge']) ||
$pledgeID)) {
1066 // add these values for the recurringContrib function ,CRM-10188
1067 $params['financial_type_id'] = $financialType->id
;
1069 $contributionParams['address_id'] = CRM_Contribute_BAO_Contribution
::createAddress($params, $billingLocationID);
1071 //@todo - this is being set from the form to resolve CRM-10188 - an
1072 // eNotice caused by it not being set @ the front end
1073 // however, we then get it being over-written with null for backend contributions
1074 // a better fix would be to set the values in the respective forms rather than require
1075 // a function being shared by two forms to deal with their respective values
1076 // moving it to the BAO & not taking the $form as a param would make sense here.
1077 if (!isset($params['is_email_receipt']) && $isEmailReceipt) {
1078 $params['is_email_receipt'] = $isEmailReceipt;
1080 $params['is_recur'] = $isRecur;
1081 $params['payment_instrument_id'] = $contributionParams['payment_instrument_id'] ??
NULL;
1082 $recurringContributionID = self
::processRecurringContribution($form, $params, $contactID, $financialType);
1084 $now = date('YmdHis');
1085 $receiptDate = $params['receipt_date'] ??
NULL;
1086 if ($isEmailReceipt) {
1087 $receiptDate = $now;
1090 if (isset($params['amount'])) {
1091 $contributionParams = array_merge(self
::getContributionParams(
1092 $params, $financialType->id
,
1093 $result, $receiptDate,
1094 $recurringContributionID), $contributionParams
1096 $contributionParams['non_deductible_amount'] = self
::getNonDeductibleAmount($params, $financialType, TRUE, $form);
1097 $contributionParams['skipCleanMoney'] = TRUE;
1098 // @todo this is the wrong place for this - it should be done as close to form submission
1100 $contributionParams['total_amount'] = $params['amount'];
1102 $contribution = CRM_Contribute_BAO_Contribution
::add($contributionParams);
1104 if (Civi
::settings()->get('invoicing')) {
1106 // @todo - interrogate the line items passed in on the params array.
1107 // No reason to assume line items will be set on the form.
1108 foreach ($form->_lineItem
as $lineItemKey => $lineItemValue) {
1109 foreach ($lineItemValue as $key => $value) {
1110 if (isset($value['tax_amount']) && isset($value['tax_rate'])) {
1111 if (isset($dataArray[$value['tax_rate']])) {
1112 $dataArray[$value['tax_rate']] = $dataArray[$value['tax_rate']] +
$value['tax_amount'];
1115 $dataArray[$value['tax_rate']] = $value['tax_amount'];
1120 $smarty = CRM_Core_Smarty
::singleton();
1121 $smarty->assign('dataArray', $dataArray);
1124 // lets store it in the form variable so postProcess hook can get to this and use it
1125 $form->_contributionID
= $contribution->id
;
1127 $form->assign('totalTaxAmount', $params['tax_amount'] ??
NULL);
1129 // process soft credit / pcp params first
1130 CRM_Contribute_BAO_ContributionSoft
::formatSoftCreditParams($params, $form);
1132 //CRM-13981, processing honor contact into soft-credit contribution
1133 CRM_Contribute_BAO_ContributionSoft
::processSoftContribution($params, $contribution);
1136 $form = self
::handlePledge($form, $params, $contributionParams, $pledgeID, $contribution, $isEmailReceipt);
1139 if ($contribution) {
1140 CRM_Core_BAO_CustomValueTable
::postProcess($params,
1141 'civicrm_contribution',
1147 if ($contribution && !empty($params['contribution_note'])) {
1149 'entity_table' => 'civicrm_contribution',
1150 'note' => $params['contribution_note'],
1151 'entity_id' => $contribution->id
,
1152 'contact_id' => $contribution->contact_id
,
1155 CRM_Core_BAO_Note
::add($noteParams, []);
1158 //create contribution activity w/ individual and target
1159 //activity w/ organisation contact id when onbelf, CRM-4027
1161 $targetContactID = NULL;
1162 if (!empty($params['onbehalf_contact_id'])) {
1164 'source_contact_id' => $params['onbehalf_contact_id'],
1165 'on_behalf' => TRUE,
1167 $targetContactID = $contribution->contact_id
;
1170 // create an activity record
1171 if ($contribution) {
1172 CRM_Activity_BAO_Activity
::addActivity($contribution, 'Contribution', $targetContactID, $actParams);
1175 $transaction->commit();
1176 return $contribution;
1180 * Create the recurring contribution record.
1182 * @param CRM_Core_Form $form
1183 * @param array $params
1184 * @param int $contactID
1185 * @param string $contributionType
1189 public static function processRecurringContribution($form, $params, $contactID, $contributionType) {
1191 if (empty($params['is_recur'])) {
1195 $recurParams = ['contact_id' => $contactID];
1196 $recurParams['amount'] = $params['amount'] ??
NULL;
1197 $recurParams['auto_renew'] = $params['auto_renew'] ??
NULL;
1198 $recurParams['frequency_unit'] = $params['frequency_unit'] ??
NULL;
1199 $recurParams['frequency_interval'] = $params['frequency_interval'] ??
NULL;
1200 $recurParams['installments'] = $params['installments'] ??
NULL;
1201 $recurParams['financial_type_id'] = $params['financial_type_id'] ??
NULL;
1202 $recurParams['currency'] = $params['currency'] ??
NULL;
1203 $recurParams['payment_instrument_id'] = $params['payment_instrument_id'];
1205 // CRM-14354: For an auto-renewing membership with an additional contribution,
1206 // if separate payments is not enabled, make sure only the membership fee recurs
1207 if (!empty($form->_membershipBlock
)
1208 && $form->_membershipBlock
['is_separate_payment'] === '0'
1209 && isset($params['selectMembership'])
1210 && $form->_values
['is_allow_other_amount'] == '1'
1212 && !empty($form->_membershipTypeValues
)
1213 && !empty($form->_membershipTypeValues
[$params['selectMembership']]['minimum_fee'])
1215 $recurParams['amount'] = $form->_membershipTypeValues
[$params['selectMembership']]['minimum_fee'];
1218 $recurParams['is_test'] = 0;
1219 if (($form->_action
& CRM_Core_Action
::PREVIEW
) ||
1220 (isset($form->_mode
) && ($form->_mode
== 'test'))
1222 $recurParams['is_test'] = 1;
1225 $recurParams['start_date'] = $recurParams['create_date'] = $recurParams['modified_date'] = date('YmdHis');
1226 if (!empty($params['receive_date'])) {
1227 $recurParams['start_date'] = date('YmdHis', strtotime($params['receive_date']));
1229 $recurParams['invoice_id'] = $params['invoiceID'] ??
NULL;
1230 $recurParams['contribution_status_id'] = CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1231 $recurParams['payment_processor_id'] = $params['payment_processor_id'] ??
NULL;
1232 $recurParams['is_email_receipt'] = (bool) ($params['is_email_receipt'] ??
FALSE);
1233 // We set trxn_id=invoiceID specifically for paypal IPN. It is reset this when paypal sends us the real trxn id, CRM-2991
1234 $recurParams['processor_id'] = $recurParams['trxn_id'] = ($params['trxn_id'] ??
$params['invoiceID']);
1235 $recurParams['financial_type_id'] = $contributionType->id
;
1237 $campaignId = $params['campaign_id'] ??
$form->_values
['campaign_id'] ??
NULL;
1238 $recurParams['campaign_id'] = $campaignId;
1239 $recurring = CRM_Contribute_BAO_ContributionRecur
::add($recurParams);
1240 if (is_a($recurring, 'CRM_Core_Error')) {
1241 CRM_Core_Error
::displaySessionError($recurring);
1242 $urlString = 'civicrm/contribute/transact';
1243 $urlParams = '_qf_Main_display=true';
1244 if (get_class($form) == 'CRM_Contribute_Form_Contribution') {
1245 $urlString = 'civicrm/contact/view/contribution';
1246 $urlParams = "action=add&cid={$form->_contactID}";
1248 $urlParams .= "&mode={$form->_mode}";
1251 CRM_Utils_System
::redirect(CRM_Utils_System
::url($urlString, $urlParams));
1253 $form->_params
['contributionRecurID'] = $recurring->id
;
1255 return $recurring->id
;
1259 * Add on behalf of organization and it's location.
1261 * This situation occurs when on behalf of is enabled for the contribution page and the person
1262 * signing up does so on behalf of an organization.
1264 * @param array $behalfOrganization
1265 * array of organization info.
1266 * @param int $contactID
1267 * individual contact id. One.
1268 * who is doing the process of signup / contribution.
1270 * @param array $values
1271 * form values array.
1272 * @param array $params
1273 * @param array $fields
1274 * Array of fields from the onbehalf profile relevant to the organization.
1276 public static function processOnBehalfOrganization(&$behalfOrganization, &$contactID, &$values, &$params, $fields = NULL) {
1277 $isNotCurrentEmployer = FALSE;
1280 if (!empty($behalfOrganization['organization_id'])) {
1281 $orgID = $behalfOrganization['organization_id'];
1282 unset($behalfOrganization['organization_id']);
1284 // create employer relationship with $contactID only when new organization is there
1285 // else retain the existing relationship
1287 $isNotCurrentEmployer = TRUE;
1291 // check if matching organization contact exists
1292 $dupeIDs = CRM_Contact_BAO_Contact
::getDuplicateContacts($behalfOrganization, 'Organization', 'Unsupervised', [], FALSE);
1294 // CRM-6243 says to pick the first org even if more than one match
1295 if (count($dupeIDs) >= 1) {
1296 $behalfOrganization['contact_id'] = $orgID = $dupeIDs[0];
1297 // don't allow name edit
1298 unset($behalfOrganization['organization_name']);
1302 // if found permissioned related organization, allow location edit
1303 $behalfOrganization['contact_id'] = $orgID;
1304 // don't allow name edit
1305 unset($behalfOrganization['organization_name']);
1308 // handling for image url
1309 if (!empty($behalfOrganization['image_URL'])) {
1310 CRM_Contact_BAO_Contact
::processImageParams($behalfOrganization);
1313 // create organization, add location
1314 $behalfOrganization['contact_type'] = 'Organization';
1315 $orgID = CRM_Contact_BAO_Contact
::createProfileContact($behalfOrganization, $fields, $orgID,
1316 NULL, NULL, 'Organization'
1318 // create relationship
1319 if ($isNotCurrentEmployer) {
1321 \Civi\Api4\Relationship
::create(FALSE)
1322 ->addValue('contact_id_a', $contactID)
1323 ->addValue('contact_id_b', $orgID)
1324 ->addValue('relationship_type_id', $relTypeId = CRM_Contact_BAO_RelationshipType
::getEmployeeRelationshipTypeID())
1325 ->addValue('is_permission_a_b:name', 'View and update')
1328 catch (CRM_Core_Exception
$e) {
1329 // Ignore if duplicate relationship.
1330 if ($e->getMessage() !== 'Duplicate Relationship') {
1336 // if multiple match - send a duplicate alert
1337 if ($dupeIDs && (count($dupeIDs) > 1)) {
1338 $values['onbehalf_dupe_alert'] = 1;
1340 $params['onbehalf_dupe_alert'] = 1;
1343 // make sure organization-contact-id is considered for recording
1344 // contribution/membership etc..
1345 if ($contactID != $orgID) {
1346 // take a note of contact-id, so we can send the
1347 // receipt to individual contact as well.
1349 // required for mailing/template display ..etc
1350 $values['related_contact'] = $contactID;
1352 //CRM-19172: Create CMS user for individual on whose behalf organization is doing contribution
1353 $params['onbehalf_contact_id'] = $contactID;
1355 //make this employee of relationship as current
1356 //employer / employee relationship, CRM-3532
1357 if ($isNotCurrentEmployer &&
1358 ($orgID != CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'employer_id'))
1360 $isNotCurrentEmployer = FALSE;
1363 if (!$isNotCurrentEmployer && $orgID) {
1364 //build current employer params
1365 $currentEmpParams[$contactID] = $orgID;
1366 CRM_Contact_BAO_Contact_Utils
::setCurrentEmployer($currentEmpParams);
1369 // contribution / signup will be done using this
1371 $contactID = $orgID;
1376 * Function used to se pcp related defaults / params.
1378 * This is used by contribution and also event PCPs
1380 * @param CRM_Core_Form $page
1382 * @param array $params
1386 public static function processPcp(&$page, $params): array {
1387 $params['pcp_made_through_id'] = $page->_pcpId
;
1388 $page->assign('pcpBlock', TRUE);
1389 if (!empty($params['pcp_display_in_roll']) && empty($params['pcp_roll_nickname'])) {
1390 $params['pcp_roll_nickname'] = ts('Anonymous');
1391 $params['pcp_is_anonymous'] = 1;
1394 $params['pcp_is_anonymous'] = 0;
1397 'pcp_display_in_roll',
1399 'pcp_roll_nickname',
1400 'pcp_personal_note',
1402 if (!empty($params[$val])) {
1403 $page->assign($val, $params[$val]);
1411 * Process membership.
1413 * @param array $membershipParams
1414 * @param int $contactID
1415 * @param array $customFieldsFormatted
1416 * @param array $fieldTypes
1417 * @param array $premiumParams
1418 * @param array $membershipLineItems
1419 * Line items specifically relating to memberships.
1421 protected function processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams,
1422 $membershipLineItems): void
{
1424 $membershipTypeIDs = (array) $membershipParams['selectMembership'];
1425 $membershipTypes = CRM_Member_BAO_Membership
::buildMembershipTypeValues($this, $membershipTypeIDs);
1426 $membershipType = empty($membershipTypes) ?
[] : reset($membershipTypes);
1428 $this->assign('membership_name', $membershipType['name']);
1429 $this->_values
['membership_name'] = $membershipType['name'] ??
NULL;
1431 $isPaidMembership = FALSE;
1432 if ($this->_amount
>= 0.0 && isset($membershipParams['amount'])) {
1433 //amount must be greater than zero for
1434 //adding contribution record to contribution table.
1435 //this condition arises when separate membership payment is
1436 //enabled and contribution amount is not selected. fix for CRM-3010
1437 $isPaidMembership = TRUE;
1439 $isProcessSeparateMembershipTransaction = $this->isSeparateMembershipTransaction($this->_id
);
1441 if ($this->isFormSupportsNonMembershipContributions()) {
1442 $financialTypeID = $this->_values
['financial_type_id'];
1445 $financialTypeID = $membershipType['financial_type_id'] ??
$membershipParams['financial_type_id'] ??
NULL;
1448 if (!empty($this->_params
['membership_source'])) {
1449 $membershipParams['contribution_source'] = $this->_params
['membership_source'];
1452 $this->postProcessMembership($membershipParams, $contactID, $premiumParams, $customFieldsFormatted, $fieldTypes, $membershipType, $membershipTypeIDs, $isPaidMembership, $this->_membershipId
, $isProcessSeparateMembershipTransaction, $financialTypeID,
1453 $membershipLineItems);
1455 $this->assign('membership_assign', TRUE);
1456 $this->set('membershipTypeID', $membershipParams['selectMembership']);
1460 * Process the Memberships.
1462 * @param array $membershipParams
1463 * Array of membership fields.
1464 * @param int $contactID
1467 * @param array $premiumParams
1468 * @param null $customFieldsFormatted
1469 * @param null $includeFieldTypes
1471 * @param array $membershipDetails
1473 * @param array $membershipTypeIDs
1475 * @param bool $isPaidMembership
1476 * @param array $membershipID
1478 * @param bool $isProcessSeparateMembershipTransaction
1480 * @param int $financialTypeID
1481 * @param array $unprocessedLineItems
1482 * Line items for payment options chosen on the form.
1484 * @throws \CRM_Core_Exception
1485 * @throws \CiviCRM_API3_Exception
1486 * @throws \Civi\Payment\Exception\PaymentProcessorException
1488 protected function postProcessMembership(
1489 $membershipParams, $contactID, $premiumParams,
1490 $customFieldsFormatted, $includeFieldTypes, $membershipDetails, $membershipTypeIDs, $isPaidMembership, $membershipID,
1491 $isProcessSeparateMembershipTransaction, $financialTypeID, $unprocessedLineItems) {
1492 // Assign $this to $form while we eliminate it.
1494 $membershipContribution = NULL;
1495 $isTest = $membershipParams['is_test'] ??
FALSE;
1496 $errors = $paymentResults = [];
1497 $form->_values
['isMembership'] = TRUE;
1498 $isRecurForFirstTransaction = $form->_params
['is_recur'] ??
$membershipParams['is_recur'] ??
NULL;
1500 $totalAmount = $membershipParams['amount'];
1502 if ($isPaidMembership) {
1503 if ($isProcessSeparateMembershipTransaction) {
1504 // If we have 2 transactions only one can use the invoice id.
1505 $membershipParams['invoiceID'] .= '-2';
1506 if (!empty($membershipParams['auto_renew'])) {
1507 $isRecurForFirstTransaction = FALSE;
1511 if (!$isProcessSeparateMembershipTransaction) {
1512 // Skip line items in the contribution processing transaction.
1513 // We will create them with the membership for proper linking.
1514 $membershipParams['skipLineItem'] = 1;
1517 $membershipParams['total_amount'] = $totalAmount;
1518 $membershipParams['skipLineItem'] = 0;
1519 CRM_Price_BAO_LineItem
::getLineItemArray($membershipParams);
1522 $paymentResult = $this->processConfirm(
1527 $isRecurForFirstTransaction
1529 if (!empty($paymentResult['contribution'])) {
1530 $paymentResults[] = ['contribution_id' => $paymentResult['contribution']->id
, 'result' => $paymentResult];
1531 $this->postProcessPremium($premiumParams, $paymentResult['contribution']);
1532 //note that this will be over-written if we are using a separate membership transaction. Otherwise there is only one
1533 $membershipContribution = $paymentResult['contribution'];
1534 // Save the contribution ID so that I can be used in email receipts
1535 // For example, if you need to generate a tax receipt for the donation only.
1536 $form->_values
['contribution_other_id'] = $membershipContribution->id
;
1540 if ($isProcessSeparateMembershipTransaction) {
1542 $form->_lineItem
= $unprocessedLineItems;
1543 if (empty($form->_params
['auto_renew']) && !empty($membershipParams['is_recur'])) {
1544 unset($membershipParams['is_recur']);
1546 [$membershipContribution, $secondPaymentResult] = $this->processSecondaryFinancialTransaction($contactID, array_merge($membershipParams, ['skipLineItem' => 1]),
1547 $isTest, $unprocessedLineItems, $membershipDetails['minimum_fee'] ??
0, $membershipDetails['financial_type_id'] ??
NULL);
1548 $paymentResults[] = ['contribution_id' => $membershipContribution->id
, 'result' => $secondPaymentResult];
1549 $totalAmount = $membershipContribution->total_amount
;
1551 catch (CRM_Core_Exception
$e) {
1552 $errors[2] = $e->getMessage();
1553 $membershipContribution = NULL;
1558 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1559 $membershipContributionID = $membershipContribution->id
;
1562 //@todo - why is this nested so deep? it seems like it could be just set on the calling function on the form layer
1563 if (isset($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])) {
1564 $form->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
1566 //@todo it should no longer be possible for it to get to this point & membership to not be an array
1567 if (is_array($membershipTypeIDs) && !empty($membershipContributionID)) {
1568 $typesTerms = $membershipParams['types_terms'] ??
[];
1570 $membershipLines = $nonMembershipLines = [];
1571 foreach ($unprocessedLineItems as $priceSetID => $lines) {
1572 foreach ($lines as $line) {
1573 if (!empty($line['membership_type_id'])) {
1574 $membershipLines[$line['membership_type_id']] = $line['price_field_value_id'];
1580 $form->_params
['createdMembershipIDs'] = [];
1581 foreach ($membershipTypeIDs as $memType) {
1582 $membershipLineItems = [];
1583 if ($i < count($membershipTypeIDs)) {
1584 $membershipLineItems[$priceSetID][$membershipLines[$memType]] = $unprocessedLineItems[$priceSetID][$membershipLines[$memType]];
1585 unset($unprocessedLineItems[$priceSetID][$membershipLines[$memType]]);
1588 $membershipLineItems = $unprocessedLineItems;
1591 $numTerms = $typesTerms[$memType] ??
1;
1592 $contributionRecurID = $form->_params
['contributionRecurID'] ??
NULL;
1594 $membershipSource = NULL;
1595 if (!empty($form->_params
['membership_source'])) {
1596 $membershipSource = $form->_params
['membership_source'];
1598 elseif ((isset($form->_values
['title']) && !empty($form->_values
['title'])) ||
(isset($form->_values
['frontend_title']) && !empty($form->_values
['frontend_title']))) {
1599 $title = !empty($form->_values
['frontend_title']) ?
$form->_values
['frontend_title'] : $form->_values
['title'];
1600 $membershipSource = ts('Online Contribution:') . ' ' . $title;
1603 if (isset($form->_params
)) {
1604 $isPayLater = $form->_params
['is_pay_later'] ??
NULL;
1607 'campaign_id' => $form->_params
['campaign_id'] ??
($form->_values
['campaign_id'] ??
NULL),
1610 // @todo Move this into CRM_Member_BAO_Membership::processMembership
1611 if (!empty($membershipContribution)) {
1612 $pending = $membershipContribution->contribution_status_id
== CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending');
1615 // The concept of contributeMode is deprecated.
1616 // the is_monetary concept probably should be too as it can be calculated from
1617 // the existence of 'amount' & seems fragile.
1618 if (((isset($this->_contributeMode
)) ||
!empty($this->_params
['is_pay_later'])
1620 (($this->_values
['is_monetary'] && $this->_amount
> 0.0))
1627 [$membership, $renewalMode, $dates] = self
::legacyProcessMembership(
1628 $contactID, $memType, $isTest,
1629 date('YmdHis'), $membershipParams['cms_contactID'] ??
NULL,
1630 $customFieldsFormatted,
1631 $numTerms, $membershipID, $pending,
1632 $contributionRecurID, $membershipSource, $isPayLater, $memParams, $membershipContribution,
1633 $membershipLineItems
1636 $form->set('renewal_mode', $renewalMode);
1637 if (!empty($dates)) {
1638 $form->assign('mem_start_date', CRM_Utils_Date
::customFormat($dates['start_date'], '%Y%m%d'));
1639 $form->assign('mem_end_date', CRM_Utils_Date
::customFormat($dates['end_date'], '%Y%m%d'));
1642 if (!empty($membershipContribution)) {
1643 // Next line is probably redundant. Checks prevent it happening twice.
1644 $membershipPaymentParams = [
1645 'membership_id' => $membership->id
,
1646 'membership_type_id' => $membership->membership_type_id
,
1647 'contribution_id' => $membershipContribution->id
,
1649 civicrm_api3('MembershipPayment', 'create', $membershipPaymentParams);
1652 CRM_Core_BAO_CustomValueTable
::postProcess($form->_params
, 'civicrm_membership', $membership->id
, 'Membership');
1653 $form->_params
['createdMembershipIDs'][] = $membership->id
;
1654 $form->_params
['membershipID'] = $membership->id
;
1656 //CRM-15232: Check if membership is created and on the basis of it use
1657 //membership receipt template to send payment receipt
1658 $form->_values
['isMembership'] = TRUE;
1661 if ($form->_priceSetId
&& !empty($form->_useForMember
) && !empty($form->_lineItem
)) {
1662 foreach ($form->_lineItem
[$form->_priceSetId
] as & $priceFieldOp) {
1663 if (!empty($priceFieldOp['membership_type_id']) && $membership->membership_type_id
== $priceFieldOp['membership_type_id']) {
1664 $membershipOb = $membership;
1665 $priceFieldOp['start_date'] = $membershipOb->start_date ? CRM_Utils_Date
::formatDateOnlyLong($membershipOb->start_date
) : '-';
1666 $priceFieldOp['end_date'] = $membershipOb->end_date ? CRM_Utils_Date
::formatDateOnlyLong($membershipOb->end_date
) : '-';
1669 $priceFieldOp['start_date'] = $priceFieldOp['end_date'] = 'N/A';
1672 $form->_values
['lineItem'] = $form->_lineItem
;
1673 $form->assign('lineItem', $form->_lineItem
);
1677 if (!empty($errors)) {
1678 $message = $this->compileErrorMessage($errors);
1679 throw new CRM_Core_Exception($message);
1682 if (isset($membershipContributionID)) {
1683 $form->_values
['contribution_id'] = $membershipContributionID;
1686 if (empty($form->_params
['is_pay_later']) && $form->_paymentProcessor
) {
1687 // the is_monetary concept probably should be deprecated as it can be calculated from
1688 // the existence of 'amount' & seems fragile.
1689 if ($form->_values
['is_monetary'] && $form->_amount
> 0.0 && !$form->_params
['is_pay_later']) {
1690 // call postProcess hook before leaving
1691 $form->postProcessHook();
1694 $payment = Civi\Payment\System
::singleton()->getByProcessor($form->_paymentProcessor
);
1695 // The contribution_other_id is effectively the ID for the only contribution or the non-membership contribution.
1696 // Since we have called the membership contribution (in a 2 contribution scenario) this is out
1697 // primary-contribution compared to that - but let's face it - it's all just too hard & confusing at the moment!
1698 $paymentParams = array_merge($form->_params
, ['contributionID' => $form->_values
['contribution_other_id']]);
1700 // CRM-19792 : set necessary fields for payment processor
1701 CRM_Core_Payment_Form
::mapParams($form->_bltID
, $paymentParams, $paymentParams, TRUE);
1703 // If this is a single membership-related contribution, it won't have
1704 // be performed yet, so do it now.
1705 if ($isPaidMembership && !$isProcessSeparateMembershipTransaction) {
1706 $paymentActionResult = $payment->doPayment($paymentParams, 'contribute');
1707 $paymentResults[] = ['contribution_id' => $paymentResult['contribution']->id
, 'result' => $paymentActionResult];
1709 // Do not send an email if Recurring transaction is done via Direct Mode
1710 // Email will we sent when the IPN is received.
1711 foreach ($paymentResults as $result) {
1712 //CRM-18211: Fix situation where second contribution doesn't exist because it is optional.
1713 if ($result['contribution_id']) {
1714 $this->completeTransaction($result['result'], $result['contribution_id']);
1720 $emailValues = array_merge($membershipParams, $form->_values
);
1721 $emailValues['membership_assign'] = 1;
1722 $emailValues['useForMember'] = !empty($form->_useForMember
);
1724 // Finally send an email receipt for pay-later scenario (although it might sometimes be caught above!)
1725 if ($totalAmount == 0) {
1726 // This feels like a bizarre hack as the variable name doesn't seem to be directly connected to it's use in the template.
1727 $emailValues['useForMember'] = 0;
1728 $emailValues['amount'] = 0;
1730 //CRM-18071, where on selecting $0 free membership payment section got hidden and
1731 // also it reset any payment processor selection result into pending free membership
1732 // so its a kind of hack to complete free membership at this point since there is no $form->_paymentProcessor info
1733 if (!empty($membershipContribution) && !is_a($membershipContribution, 'CRM_Core_Error')) {
1734 if (empty($form->_paymentProcessor
)) {
1735 // @todo this can maybe go now we are setting payment_processor_id = 0 more reliably.
1736 $paymentProcessorIDs = explode(CRM_Core_DAO
::VALUE_SEPARATOR
, $this->_values
['payment_processor'] ??
NULL);
1737 $this->_paymentProcessor
['id'] = $paymentProcessorIDs[0];
1739 $result = ['payment_status_id' => 1, 'contribution' => $membershipContribution];
1740 $this->completeTransaction($result, $result['contribution']->id
);
1742 // return as completeTransaction() already sends the receipt mail.
1746 CRM_Contribute_BAO_ContributionPage
::sendMail($contactID,
1754 * Turn array of errors into message string.
1756 * @param array $errors
1760 protected function compileErrorMessage($errors) {
1761 foreach ($errors as $error) {
1762 if (is_string($error)) {
1763 $message[] = $error;
1766 return ts('Payment Processor Error message') . ': ' . implode('<br/>', $message);
1770 * Where a second separate financial transaction is supported we will process it here.
1772 * @param int $contactID
1773 * @param array $tempParams
1774 * @param bool $isTest
1775 * @param array $lineItems
1776 * @param $minimumFee
1777 * @param int $financialTypeID
1781 * @throws \CRM_Core_Exception
1782 * @throws \CiviCRM_API3_Exception
1783 * @throws \Civi\Payment\Exception\PaymentProcessorException
1785 private function processSecondaryFinancialTransaction($contactID, $tempParams, $isTest, $lineItems, $minimumFee,
1786 $financialTypeID): array {
1787 $financialType = new CRM_Financial_DAO_FinancialType();
1788 $financialType->id
= $financialTypeID;
1789 $financialType->find(TRUE);
1790 $tempParams['amount'] = $minimumFee;
1791 $tempParams['invoiceID'] = md5(uniqid(rand(), TRUE));
1792 $isRecur = $tempParams['is_recur'] ??
NULL;
1794 //assign receive date when separate membership payment
1795 //and contribution amount not selected.
1796 if ($this->_amount
== 0) {
1797 $now = date('YmdHis');
1798 $this->_params
['receive_date'] = $now;
1799 $receiveDate = CRM_Utils_Date
::mysqlToIso($now);
1800 $this->set('params', $this->_params
);
1801 $this->assign('receive_date', $receiveDate);
1804 $this->set('membership_amount', $minimumFee);
1805 $this->assign('membership_amount', $minimumFee);
1807 //set this variable as we are not creating pledge for
1808 //separate membership payment contribution.
1809 //so for differentiating membership contribution from
1810 //main contribution.
1811 $this->_params
['separate_membership_payment'] = 1;
1812 $contributionParams = [
1813 'contact_id' => $contactID,
1814 'line_item' => $lineItems,
1815 'is_test' => $isTest,
1816 'campaign_id' => $tempParams['campaign_id'] ??
$this->_values
['campaign_id'] ??
NULL,
1817 'contribution_page_id' => $this->_id
,
1818 'source' => $tempParams['source'] ??
$tempParams['description'] ??
NULL,
1820 $isMonetary = !empty($this->_values
['is_monetary']);
1822 if (empty($paymentParams['is_pay_later'])) {
1823 $contributionParams['payment_instrument_id'] = $this->_paymentProcessor
['payment_instrument_id'];
1827 // CRM-19792 : set necessary fields for payment processor
1828 CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $tempParams, TRUE);
1830 $membershipContribution = $this->processFormContribution(
1833 $contributionParams,
1841 // We're not processing the line item here because we are processing a membership.
1842 // To ensure processing of the correct parameters, replace relevant parameters
1843 // in $tempParams with those in $membershipContribution.
1844 $tempParams['amount_level'] = $membershipContribution->amount_level
;
1845 $tempParams['total_amount'] = $membershipContribution->total_amount
;
1846 $tempParams['tax_amount'] = $membershipContribution->tax_amount
;
1847 $tempParams['contactID'] = $membershipContribution->contact_id
;
1848 $tempParams['financialTypeID'] = $membershipContribution->financial_type_id
;
1849 $tempParams['invoiceID'] = $membershipContribution->invoice_id
;
1850 $tempParams['trxn_id'] = $membershipContribution->trxn_id
;
1851 $tempParams['contributionID'] = $membershipContribution->id
;
1853 if ($this->_values
['is_monetary'] && !$this->_params
['is_pay_later'] && $minimumFee > 0.0) {
1854 // At the moment our tests are calling this form in a way that leaves 'object' empty. For
1855 // now we compensate here.
1856 if (empty($this->_paymentProcessor
['object'])) {
1857 $payment = Civi\Payment\System
::singleton()->getByProcessor($this->_paymentProcessor
);
1860 $payment = $this->_paymentProcessor
['object'];
1862 $result = $payment->doPayment($tempParams, 'contribute');
1863 $this->set('membership_trx_id', $result['trxn_id']);
1864 $this->assign('membership_trx_id', $result['trxn_id']);
1867 return [$membershipContribution, $result];
1871 * Are we going to do 2 financial transactions.
1873 * Ie the membership block supports a separate transactions AND the contribution form has been configured for a
1875 * transaction AND a membership transaction AND the payment processor supports double financial transactions (ie. NOT doTransferCheckout style)
1877 * @param int $formID
1881 protected function isSeparateMembershipTransaction($formID): bool {
1882 $memBlockDetails = CRM_Member_BAO_Membership
::getMembershipBlock($formID);
1883 if (!empty($memBlockDetails['is_separate_payment']) && $this->isFormSupportsNonMembershipContributions()) {
1890 * This function sets the fields.
1892 * - $this->_params['amount_level']
1893 * - $this->_params['selectMembership']
1894 * And under certain circumstances sets
1895 * $this->_params['amount'] = null;
1897 * @param int $priceSetID
1899 public function setFormAmountFields($priceSetID) {
1900 $isQuickConfig = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $this->_params
['priceSetId'], 'is_quick_config');
1901 $priceField = new CRM_Price_DAO_PriceField();
1902 $priceField->price_set_id
= $priceSetID;
1903 $priceField->orderBy('weight');
1904 $priceField->find();
1905 $paramWeDoNotUnderstand = NULL;
1907 while ($priceField->fetch()) {
1908 if ($priceField->name
== "contribution_amount") {
1909 $paramWeDoNotUnderstand = $priceField->id
;
1911 if ($isQuickConfig && !empty($this->_params
["price_{$priceField->id}"])) {
1912 if ($this->_values
['fee'][$priceField->id
]['html_type'] != 'Text') {
1913 // @todo - stop setting amount level in this function & call the CRM_Price_BAO_PriceSet::getAmountLevel
1914 // function to get correct amount level consistently. Remove setting of the amount level in
1915 // CRM_Price_BAO_PriceSet::processAmount. Extend the unit tests in CRM_Price_BAO_PriceSetTest
1916 // to cover all variants.
1917 $this->_params
['amount_level'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1918 $this->_params
["price_{$priceField->id}"], 'label');
1920 if ($priceField->name
== "membership_amount") {
1921 $this->_params
['selectMembership'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue',
1922 $this->_params
["price_{$priceField->id}"], 'membership_type_id');
1925 // If separate payment we set contribution amount to be null, so that it will not show contribution amount same
1926 // as membership amount.
1927 // @todo - this needs more documentation - it appears the setting to null is tied up with separate membership payments
1928 // but the circumstances are very confusing. Many of these conditions are repeated in the next conditional
1929 // so we should merge them together
1930 // the quick config seems like a red-herring - if this is about a separate membership payment then there
1931 // are 2 types of line items - membership ones & non-membership ones - regardless of whether quick config is set
1933 !empty($this->_membershipBlock
['is_separate_payment'])
1934 && !empty($this->_values
['fee'][$priceField->id
])
1935 && ($this->_values
['fee'][$priceField->id
]['name'] == "other_amount")
1936 && ($this->_params
["price_{$paramWeDoNotUnderstand}"] ??
NULL) < 1
1937 && empty($this->_params
["price_{$priceField->id}"])
1939 $this->_params
['amount'] = NULL;
1942 // Fix for CRM-14375 - If we are using separate payments and "no
1943 // thank you" is selected for the additional contribution, set
1944 // contribution amount to be null, so that it will not show
1945 // contribution amount same as membership amount.
1946 //@todo - merge with section above
1947 if (!empty($this->_membershipBlock
['is_separate_payment'])
1948 && !empty($this->_values
['fee'][$priceField->id
])
1949 && ($this->_values
['fee'][$priceField->id
]['name'] ??
NULL) == 'contribution_amount'
1950 && ($this->_params
["price_{$priceField->id}"] ??
NULL) == '-1'
1952 $this->_params
['amount'] = NULL;
1960 * @param array $params
1962 * @throws \CRM_Core_Exception
1963 * @throws \CiviCRM_API3_Exception
1964 * @throws \Civi\API\Exception\UnauthorizedException
1966 public static function submit($params) {
1967 $form = new CRM_Contribute_Form_Contribution_Confirm();
1968 $form->_id
= $params['id'];
1970 CRM_Contribute_BAO_ContributionPage
::setValues($form->_id
, $form->_values
);
1971 $form->_separateMembershipPayment
= CRM_Contribute_BAO_ContributionPage
::getIsMembershipPayment($form->_id
);
1972 //this way the mocked up controller ignores the session stuff
1973 $_SERVER['REQUEST_METHOD'] = 'GET';
1974 $form->controller
= new CRM_Contribute_Controller_Contribution();
1975 $params['invoiceID'] = md5(uniqid(rand(), TRUE));
1977 $paramsProcessedForForm = $form->_params
= self
::getFormParams($params['id'], $params);
1979 $order = new CRM_Financial_BAO_Order();
1980 $order->setPriceSetIDByContributionPageID($params['id']);
1981 $order->setPriceSelectionFromUnfilteredInput($params);
1982 if (isset($params['amount']) && !CRM_Contribute_BAO_ContributionPage
::getIsMembershipPayment($form->_id
)) {
1983 // @todo deprecate receiving amount, calculate on the form.
1984 $order->setOverrideTotalAmount((float) $params['amount']);
1986 $amount = $order->getTotalAmount();
1987 if ($form->_separateMembershipPayment
) {
1988 $amount -= $order->getMembershipTotalAmount();
1990 $form->_amount
= $params['amount'] = $form->_params
['amount'] = $amount;
1991 // hack these in for test support.
1992 $form->_fields
['billing_first_name'] = 1;
1993 $form->_fields
['billing_last_name'] = 1;
1994 // CRM-18854 - Set form values to allow pledge to be created for api test.
1995 if (!empty($params['pledge_block_id'])) {
1996 $form->_values
['pledge_id'] = $params['pledge_id'] ??
NULL;
1997 $form->_values
['pledge_block_id'] = $params['pledge_block_id'];
1998 $pledgeBlock = CRM_Pledge_BAO_PledgeBlock
::getPledgeBlock($params['id']);
1999 $form->_values
['max_reminders'] = $pledgeBlock['max_reminders'];
2000 $form->_values
['initial_reminder_day'] = $pledgeBlock['initial_reminder_day'];
2001 $form->_values
['additional_reminder_day'] = $pledgeBlock['additional_reminder_day'];
2002 $form->_values
['is_email_receipt'] = FALSE;
2004 $priceSetID = $form->_params
['priceSetId'] = $paramsProcessedForForm['price_set_id'];
2005 $priceFields = CRM_Price_BAO_PriceSet
::getSetDetail($priceSetID);
2006 $priceSetFields = reset($priceFields);
2007 $form->_values
['fee'] = $priceSetFields['fields'];
2008 $form->_priceSetId
= $priceSetID;
2009 $form->setFormAmountFields($priceSetID);
2012 $capabilities[] = (ucfirst($form->_mode
) . 'Mode');
2014 $form->_paymentProcessors
= CRM_Financial_BAO_PaymentProcessor
::getPaymentProcessors($capabilities);
2015 $form->_params
['payment_processor_id'] = $params['payment_processor_id'] ??
0;
2016 if ($form->_params
['payment_processor_id'] !== '') {
2017 // It can be blank with a $0 transaction - then no processor needs to be selected
2018 $form->_paymentProcessor
= $form->_paymentProcessors
[$form->_params
['payment_processor_id']];
2020 if (!empty($params['payment_processor_id'])) {
2021 // The concept of contributeMode is deprecated as is the billing_mode concept.
2022 if ($form->_paymentProcessor
['billing_mode'] == 1) {
2023 $form->_contributeMode
= 'direct';
2026 $form->_contributeMode
= 'notify';
2030 if (!empty($params['useForMember'])) {
2031 $form->set('useForMember', 1);
2032 $form->_useForMember
= 1;
2034 $priceFields = $priceFields[$priceSetID]['fields'];
2036 $form->_lineItem
= [$priceSetID => $order->getLineItems()];
2037 $membershipPriceFieldIDs = [];
2038 foreach ($order->getLineItems() as $lineItem) {
2039 if (!empty($lineItem['membership_type_id'])) {
2040 $form->set('useForMember', 1);
2041 $form->_useForMember
= 1;
2042 $membershipPriceFieldIDs['id'] = $priceSetID;
2043 $membershipPriceFieldIDs[] = $lineItem['price_field_value_id'];
2046 $form->set('memberPriceFieldIDS', $membershipPriceFieldIDs);
2047 $form->setRecurringMembershipParams();
2048 $form->processFormSubmission($params['contact_id'] ??
NULL);
2052 * Helper function for static submit function.
2054 * Set relevant params - help us to build up an array that we can pass in.
2057 * @param array $params
2060 * @throws CiviCRM_API3_Exception
2062 public static function getFormParams($id, array $params) {
2063 if (!isset($params['is_pay_later'])) {
2064 if (!empty($params['payment_processor_id'])) {
2065 $params['is_pay_later'] = 0;
2067 elseif (($params['amount'] ??
0) !== 0) {
2068 $params['is_pay_later'] = civicrm_api3('contribution_page', 'getvalue', [
2070 'return' => 'is_pay_later',
2074 if (empty($params['price_set_id'])) {
2075 $params['price_set_id'] = CRM_Price_BAO_PriceSet
::getFor('civicrm_contribution_page', $params['id']);
2081 * Post form submission handling.
2083 * This is also called from the test suite.
2085 * @param int $contactID
2089 * @throws \CRM_Core_Exception
2090 * @throws \CiviCRM_API3_Exception
2091 * @throws \Civi\API\Exception\UnauthorizedException
2093 protected function processFormSubmission($contactID) {
2094 if (!isset($this->_params
['payment_processor_id'])) {
2095 // If there is no processor we are using the pay-later manual pseudo-processor.
2096 // (note it might make sense to make this a row in the processor table in the db).
2097 $this->_params
['payment_processor_id'] = 0;
2099 if (isset($this->_params
['payment_processor_id']) && $this->_params
['payment_processor_id'] === 0) {
2100 $this->_params
['is_pay_later'] = $isPayLater = TRUE;
2103 if (!empty($this->_ccid
)) {
2104 $this->_params
['contribution_id'] = $this->_ccid
;
2106 //Set email-bltID if pre/post profile contains an email.
2107 if ($this->_emailExists
== TRUE) {
2108 foreach ($this->_params
as $key => $val) {
2109 if (substr($key, 0, 6) == 'email-' && empty($this->_params
["email-{$this->_bltID}"])) {
2110 $this->_params
["email-{$this->_bltID}"] = $this->_params
[$key];
2114 // add a description field at the very beginning
2115 $title = !empty($this->_values
['frontend_title']) ?
$this->_values
['frontend_title'] : $this->_values
['title'];
2116 $this->_params
['description'] = ts('Online Contribution') . ': ' . (!empty($this->_pcpInfo
['title']) ?
$this->_pcpInfo
['title'] : $title);
2118 $this->_params
['accountingCode'] = $this->_values
['accountingCode'] ??
NULL;
2121 $this->_params
['currencyID'] = CRM_Core_Config
::singleton()->defaultCurrency
;
2123 CRM_Contribute_Form_AbstractEditPayment
::formatCreditCardDetails($this->_params
);
2126 if (!empty($this->_params
['is_pledge']) && empty($this->_values
['pledge_id']) && !empty($this->_values
['adjust_recur_start_date'])) {
2127 $pledgeBlock = CRM_Pledge_BAO_PledgeBlock
::getPledgeBlock($this->_id
);
2128 if (!empty($this->_params
['start_date']) ||
empty($pledgeBlock['is_pledge_start_date_visible'])
2129 ||
empty($pledgeBlock['is_pledge_start_date_editable'])) {
2130 $pledgeStartDate = $this->_params
['start_date'] ??
NULL;
2131 $this->_params
['receive_date'] = CRM_Pledge_BAO_Pledge
::getPledgeStartDate($pledgeStartDate, $pledgeBlock);
2132 $recurParams = CRM_Pledge_BAO_Pledge
::buildRecurParams($this->_params
);
2133 $this->_params
= array_merge($this->_params
, $recurParams);
2137 //carry payment processor id.
2138 if (!empty($this->_paymentProcessor
['id'])) {
2139 $this->_params
['payment_processor_id'] = $this->_paymentProcessor
['id'];
2142 $premiumParams = $membershipParams = $params = $this->_params
;
2143 if (!empty($params['image_URL'])) {
2144 CRM_Contact_BAO_Contact
::processImageParams($params);
2147 $fields = ['email-Primary' => 1];
2149 // get the add to groups
2152 // now set the values for the billing location.
2153 foreach ($this->_fields
as $name => $value) {
2156 // get the add to groups for uf fields
2157 if (!empty($value['add_to_group_id'])) {
2158 $addToGroups[$value['add_to_group_id']] = $value['add_to_group_id'];
2162 $fields = $this->formatParamsForPaymentProcessor($fields);
2164 // billing email address
2165 $fields["email-{$this->_bltID}"] = 1;
2167 // if onbehalf-of-organization contribution, take out
2168 // organization params in a separate variable, to make sure
2169 // normal behavior is continued. And use that variable to
2170 // process on-behalf-of functionality.
2171 if (!empty($this->_values
['onbehalf_profile_id']) && empty($this->_ccid
)) {
2172 $behalfOrganization = [];
2173 $orgFields = ['organization_name', 'organization_id', 'org_option'];
2174 foreach ($orgFields as $fld) {
2175 if (array_key_exists($fld, $params)) {
2176 $behalfOrganization[$fld] = $params[$fld];
2177 unset($params[$fld]);
2181 if (is_array($params['onbehalf']) && !empty($params['onbehalf'])) {
2182 foreach ($params['onbehalf'] as $fld => $values) {
2183 if (strstr($fld, 'custom_')) {
2184 $behalfOrganization[$fld] = $values;
2186 elseif (!(strstr($fld, '-'))) {
2187 if (in_array($fld, [
2188 'contribution_campaign_id',
2189 'member_campaign_id',
2191 $fld = 'campaign_id';
2194 $behalfOrganization[$fld] = $values;
2196 $this->_params
[$fld] = $values;
2201 if (array_key_exists('onbehalf_location', $params) && is_array($params['onbehalf_location'])) {
2202 foreach ($params['onbehalf_location'] as $block => $vals) {
2203 //fix for custom data (of type checkbox, multi-select)
2204 if (substr($block, 0, 7) == 'custom_') {
2207 // fix the index of block elements
2208 if (is_array($vals)) {
2209 foreach ($vals as $key => $val) {
2210 //dont adjust the index of address block as
2211 //it's index is WRT to location type
2212 $newKey = ($block == 'address') ?
$key : ++
$key;
2213 $behalfOrganization[$block][$newKey] = $val;
2217 unset($params['onbehalf_location']);
2219 if (!empty($params['onbehalf[image_URL]'])) {
2220 $behalfOrganization['image_URL'] = $params['onbehalf[image_URL]'];
2224 // check for profile double opt-in and get groups to be subscribed
2225 $subscribeGroupIds = CRM_Core_BAO_UFGroup
::getDoubleOptInGroupIds($params, $contactID);
2227 // since we are directly adding contact to group lets unset it from mailing
2228 if (!empty($addToGroups)) {
2229 foreach ($addToGroups as $groupId) {
2230 if (isset($subscribeGroupIds[$groupId])) {
2231 unset($subscribeGroupIds[$groupId]);
2236 foreach ($addToGroups as $k) {
2237 if (array_key_exists($k, $subscribeGroupIds)) {
2238 unset($addToGroups[$k]);
2242 if (empty($contactID)) {
2243 $dupeParams = $params;
2244 if (!empty($dupeParams['onbehalf'])) {
2245 unset($dupeParams['onbehalf']);
2247 if (!empty($dupeParams['honor'])) {
2248 unset($dupeParams['honor']);
2251 $contactID = CRM_Contact_BAO_Contact
::getFirstDuplicateContact($dupeParams, 'Individual', 'Unsupervised', [], FALSE);
2253 // Fetch default greeting id's if creating a contact
2255 foreach (CRM_Contact_BAO_Contact
::$_greetingTypes as $greeting) {
2256 if (!isset($params[$greeting])) {
2257 $params[$greeting] = CRM_Contact_BAO_Contact_Utils
::defaultGreeting('Individual', $greeting);
2261 $contactType = NULL;
2264 $contactType = CRM_Core_DAO
::getFieldValue('CRM_Contact_DAO_Contact', $contactID, 'contact_type');
2266 $contactID = CRM_Contact_BAO_Contact
::createProfileContact(
2276 // Make the contact ID associated with the contribution available at the Class level.
2277 // Also make available to the session.
2278 //@todo consider handling this in $this->getContactID();
2279 $this->set('contactID', $contactID);
2280 $this->_contactID
= $contactID;
2282 //get email primary first if exist
2283 $subscriptionEmail = ['email' => $params['email-Primary'] ??
NULL];
2284 if (!$subscriptionEmail['email']) {
2285 $subscriptionEmail['email'] = $params["email-{$this->_bltID}"] ??
NULL;
2287 // subscribing contact to groups
2288 if (!empty($subscribeGroupIds) && $subscriptionEmail['email']) {
2289 CRM_Mailing_Event_BAO_Subscribe
::commonSubscribe($subscribeGroupIds, $subscriptionEmail, $contactID);
2292 // If onbehalf-of-organization contribution / signup, add organization
2293 // and it's location.
2294 if (isset($this->_values
['onbehalf_profile_id']) &&
2295 isset($behalfOrganization['organization_name']) &&
2296 ($this->_values
['is_for_organization'] == 2 ||
2297 !empty($this->_params
['is_for_organization'])
2301 foreach ($this->_fields
['onbehalf'] as $name => $value) {
2302 $ufFields[$name] = 1;
2304 self
::processOnBehalfOrganization($behalfOrganization, $contactID, $this->_values
,
2305 $this->_params
, $ufFields
2308 elseif (!empty($this->_membershipContactID
) && $contactID != $this->_membershipContactID
) {
2309 // this is an onbehalf renew case for inherited membership. For e.g a permissioned member of household,
2310 // store current user id as related contact for later use for mailing / activity..
2311 $this->_values
['related_contact'] = $contactID;
2312 $this->_params
['related_contact'] = $contactID;
2313 // swap contact like we do for on-behalf-org case, so parent/primary membership is affected
2314 $contactID = $this->_membershipContactID
;
2317 // lets store the contactID in the session
2318 // for things like tell a friend
2319 $session = CRM_Core_Session
::singleton();
2320 if (!$session->get('userID')) {
2321 $session->set('transaction.userID', $contactID);
2324 $session->set('transaction.userID', NULL);
2327 $this->_useForMember
= $this->get('useForMember');
2329 // store the fact that this is a membership and membership type is selected
2330 if ($this->isMembershipSelected($membershipParams)) {
2331 $this->doMembershipProcessing($contactID, $membershipParams, $premiumParams, $this->_lineItem
);
2334 // at this point we've created a contact and stored its address etc
2335 // all the payment processors expect the name and address to be in the
2336 // so we copy stuff over to first_name etc.
2337 $paymentParams = $this->_params
;
2338 // Make it explict that we are letting the processConfirm function figure out the line items.
2339 $paymentParams['skipLineItem'] = 0;
2341 if (!isset($paymentParams['line_item'])) {
2342 $paymentParams['line_item'] = $this->_lineItem
;
2345 if (!empty($paymentParams['onbehalf']) &&
2346 is_array($paymentParams['onbehalf'])
2348 foreach ($paymentParams['onbehalf'] as $key => $value) {
2349 if (strstr($key, 'custom_')) {
2350 $this->_params
[$key] = $value;
2355 $result = $this->processConfirm($paymentParams,
2357 $this->wrangleFinancialTypeID($this->_values
['financial_type_id']),
2358 ($this->_mode
== 'test') ?
1 : 0,
2359 $paymentParams['is_recur'] ??
NULL
2362 if (empty($result['is_payment_failure'])) {
2363 // @todo move premium processing to complete transaction if it truly is an 'after' action.
2364 $this->postProcessPremium($premiumParams, $result['contribution']);
2366 if (!empty($result['contribution'])) {
2367 // It seems this line is hit when there is a zero dollar transaction & in tests, not sure when else.
2368 $this->completeTransaction($result, $result['contribution']->id
);
2375 * Return True/False if we have a membership selected on the contribution page
2376 * @param array $membershipParams
2380 private function isMembershipSelected($membershipParams) {
2381 $priceFieldIds = $this->get('memberPriceFieldIDS');
2382 if ((!empty($membershipParams['selectMembership']) && $membershipParams['selectMembership'] != 'no_thanks')
2383 && empty($priceFieldIds)) {
2387 $membershipParams = $this->getMembershipParamsFromPriceSet($membershipParams);
2389 return !empty($membershipParams['selectMembership']);
2393 * Extract the selected memberships from a priceSet
2395 * @param array $membershipParams
2399 private function getMembershipParamsFromPriceSet($membershipParams) {
2400 $priceFieldIds = $this->get('memberPriceFieldIDS');
2401 if (empty($priceFieldIds)) {
2402 return $membershipParams;
2404 $membershipParams['financial_type_id'] = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceSet', $priceFieldIds['id'], 'financial_type_id');
2405 unset($priceFieldIds['id']);
2406 $membershipTypeIds = [];
2407 $membershipTypeTerms = [];
2408 foreach ($priceFieldIds as $priceFieldId) {
2409 $membershipTypeId = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_type_id');
2410 if ($membershipTypeId) {
2411 $membershipTypeIds[] = $membershipTypeId;
2412 $term = CRM_Core_DAO
::getFieldValue('CRM_Price_DAO_PriceFieldValue', $priceFieldId, 'membership_num_terms') ?
: 1;
2413 $membershipTypeTerms[$membershipTypeId] = ($term > 1) ?
$term : 1;
2416 $membershipParams['selectMembership'] = $membershipTypeIds;
2417 $membershipParams['types_terms'] = $membershipTypeTerms;
2418 return $membershipParams;
2422 * Membership processing section.
2424 * This is in a separate function as part of a move towards refactoring.
2426 * @param int $contactID
2427 * @param array $membershipParams
2428 * @param array $premiumParams
2429 * @param array $formLineItems
2431 protected function doMembershipProcessing($contactID, $membershipParams, $premiumParams, $formLineItems) {
2432 if (!$this->_useForMember
) {
2433 $this->assign('membership_assign', TRUE);
2434 $this->set('membershipTypeID', $this->_params
['selectMembership']);
2437 if ($this->_action
& CRM_Core_Action
::PREVIEW
) {
2438 $membershipParams['is_test'] = 1;
2440 if ($this->_params
['is_pay_later']) {
2441 $membershipParams['is_pay_later'] = 1;
2444 if (isset($this->_params
['onbehalf_contact_id'])) {
2445 $membershipParams['onbehalf_contact_id'] = $this->_params
['onbehalf_contact_id'];
2447 //inherit campaign from contribution page.
2448 if (!array_key_exists('campaign_id', $membershipParams)) {
2449 $membershipParams['campaign_id'] = $this->_values
['campaign_id'] ??
NULL;
2452 $this->_params
= CRM_Core_Payment_Form
::mapParams($this->_bltID
, $this->_params
, $membershipParams, TRUE);
2454 // This could be set by a hook.
2455 if (!empty($this->_params
['installments'])) {
2456 $membershipParams['installments'] = $this->_params
['installments'];
2458 // added new parameter for cms user contact id, needed to distinguish behaviour for on behalf of sign-ups
2459 if (isset($this->_params
['related_contact'])) {
2460 $membershipParams['cms_contactID'] = $this->_params
['related_contact'];
2463 $membershipParams['cms_contactID'] = $contactID;
2466 if (!empty($membershipParams['onbehalf']) &&
2467 is_array($membershipParams['onbehalf']) && !empty($membershipParams['onbehalf']['member_campaign_id'])
2469 $this->_params
['campaign_id'] = $membershipParams['onbehalf']['member_campaign_id'];
2472 $customFieldsFormatted = $fieldTypes = [];
2473 if (!empty($membershipParams['onbehalf']) &&
2474 is_array($membershipParams['onbehalf'])
2476 foreach ($membershipParams['onbehalf'] as $key => $value) {
2477 if (strstr($key, 'custom_')) {
2478 $customFieldId = explode('_', $key);
2479 CRM_Core_BAO_CustomField
::formatCustomField(
2481 $customFieldsFormatted,
2489 $fieldTypes = ['Contact', 'Organization', 'Membership'];
2492 $membershipParams = $this->getMembershipParamsFromPriceSet($membershipParams);
2493 if (!empty($membershipParams['selectMembership'])) {
2495 $membershipLineItems = $formLineItems;
2496 if ($this->_separateMembershipPayment
&& $this->isFormSupportsNonMembershipContributions()) {
2497 $membershipLineItems = [];
2498 foreach ($this->_values
['fee'] as $key => $feeValues) {
2499 if ($feeValues['name'] == 'membership_amount') {
2500 $fieldId = $this->_params
['price_' . $key];
2501 $membershipLineItems[$this->_priceSetId
][$fieldId] = $this->_lineItem
[$this->_priceSetId
][$fieldId];
2502 unset($this->_lineItem
[$this->_priceSetId
][$fieldId]);
2508 $this->processMembership($membershipParams, $contactID, $customFieldsFormatted, $fieldTypes, $premiumParams, $membershipLineItems);
2510 catch (\Civi\Payment\Exception\PaymentProcessorException
$e) {
2511 CRM_Core_Session
::singleton()->setStatus($e->getMessage());
2512 if (!empty($this->_contributionID
)) {
2513 CRM_Contribute_BAO_Contribution
::failPayment($this->_contributionID
,
2514 $contactID, $e->getMessage());
2516 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
2518 catch (CRM_Core_Exception
$e) {
2519 CRM_Core_Session
::singleton()->setStatus($e->getMessage());
2520 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact', "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"));
2522 if (!$this->_amount
> 0.0 ||
!$membershipParams['amount']) {
2523 // we need to explicitly create a CMS user in case of free memberships
2524 // since it is done under processConfirm for paid memberships
2525 CRM_Contribute_BAO_Contribution_Utils
::createCMSUser($membershipParams,
2526 $membershipParams['cms_contactID'],
2527 'email-' . $this->_bltID
2534 * Complete transaction if payment has been processed.
2536 * Check the result for a success outcome & if paid then complete the transaction.
2538 * Completing will trigger update of related entities and emails.
2540 * @param array $result
2541 * @param int $contributionID
2543 * @throws \CiviCRM_API3_Exception
2544 * @throws \Exception
2546 protected function completeTransaction($result, $contributionID) {
2547 if (($result['payment_status_id'] ??
NULL) == 1) {
2549 civicrm_api3('contribution', 'completetransaction', [
2550 'id' => $contributionID,
2551 'trxn_id' => $result['trxn_id'] ??
NULL,
2552 'payment_processor_id' => $result['payment_processor_id'] ??
$this->_paymentProcessor
['id'],
2553 'is_transactional' => FALSE,
2554 'fee_amount' => $result['fee_amount'] ??
NULL,
2555 'receive_date' => $result['receive_date'] ??
NULL,
2556 'card_type_id' => $result['card_type_id'] ??
NULL,
2557 'pan_truncation' => $result['pan_truncation'] ??
NULL,
2560 catch (CiviCRM_API3_Exception
$e) {
2561 if ($e->getErrorCode() != 'contribution_completed') {
2562 \Civi
::log()->error('CRM_Contribute_Form_Contribution_Confirm::completeTransaction CiviCRM_API3_Exception: ' . $e->getMessage());
2563 throw new CRM_Core_Exception('Failed to update contribution in database');
2570 * Bounce the user back to retry when an error occurs.
2572 * @param string $message
2574 protected function bounceOnError($message) {
2575 CRM_Core_Session
::singleton()
2576 ->setStatus(ts("Payment Processor Error message :") .
2578 CRM_Utils_System
::redirect(CRM_Utils_System
::url('civicrm/contribute/transact',
2579 "_qf_Main_display=true&qfKey={$this->_params['qfKey']}"
2584 * Is a payment being made.
2586 * Note that setting is_monetary on the form is somewhat legacy and the behaviour around this setting is confusing. It would be preferable
2587 * to look for the amount only (assuming this cannot refer to payment in goats or other non-monetary currency
2588 * @param CRM_Core_Form $form
2592 protected static function isPaymentTransaction($form) {
2593 return $form->_amount
>= 0.0;
2597 * Process payment after confirmation.
2599 * @param array $paymentParams
2600 * Array with payment related key.
2602 * @param int $contactID
2604 * @param int $financialTypeID
2605 * Financial type id.
2606 * @param bool $isTest
2607 * @param bool $isRecur
2609 * @throws CRM_Core_Exception
2614 public function processConfirm(
2622 CRM_Core_Payment_Form
::mapParams($form->_bltID
, $form->_params
, $paymentParams, TRUE);
2623 $isPaymentTransaction = self
::isPaymentTransaction($form);
2625 $financialType = new CRM_Financial_DAO_FinancialType();
2626 $financialType->id
= $financialTypeID;
2627 $financialType->find(TRUE);
2628 if ($financialType->is_deductible
) {
2629 $form->assign('is_deductible', TRUE);
2630 $form->set('is_deductible', TRUE);
2633 // add some financial type details to the params list
2634 // if folks need to use it
2635 $paymentParams['financial_type_id'] = $paymentParams['financialTypeID'] = $financialType->id
;
2636 //CRM-15297 - contributionType is obsolete - pass financial type as well so people can deprecate it
2637 $paymentParams['financialType_name'] = $paymentParams['contributionType_name'] = $form->_params
['contributionType_name'] = $financialType->name
;
2639 $paymentParams['financialType_accounting_code'] = $paymentParams['contributionType_accounting_code'] = $form->_params
['contributionType_accounting_code'] = CRM_Financial_BAO_FinancialAccount
::getAccountingCode($financialTypeID);
2640 $paymentParams['contributionPageID'] = $form->_params
['contributionPageID'] = $form->_values
['id'];
2641 $paymentParams['contactID'] = $form->_params
['contactID'] = $contactID;
2644 if (empty($form->_params
['receive_date'])) {
2645 $form->_params
['receive_date'] = date('YmdHis');
2647 if (!empty($form->_params
['start_date'])) {
2648 $form->_params
['start_date'] = date('YmdHis');
2650 $form->assign('receive_date',
2651 CRM_Utils_Date
::mysqlToIso($form->_params
['receive_date'])
2654 if (empty($form->_values
['amount'])) {
2655 // If the amount is not in _values[], set it
2656 $form->_values
['amount'] = $form->_params
['amount'];
2659 if (isset($paymentParams['contribution_source'])) {
2660 $paymentParams['source'] = $paymentParams['contribution_source'];
2662 if ($isPaymentTransaction) {
2663 $contributionParams = [
2664 'id' => $paymentParams['contribution_id'] ??
NULL,
2665 'contact_id' => $contactID,
2666 'is_test' => $isTest,
2667 'source' => CRM_Utils_Array
::value('source', $paymentParams, CRM_Utils_Array
::value('description', $paymentParams)),
2670 // CRM-21200: Don't overwrite contribution details during 'Pay now' payment
2671 if (empty($form->_params
['contribution_id'])) {
2672 $contributionParams['contribution_page_id'] = $form->_id
;
2673 $contributionParams['campaign_id'] = CRM_Utils_Array
::value('campaign_id', $paymentParams, CRM_Utils_Array
::value('campaign_id', $form->_values
));
2675 // In case of 'Pay now' payment, append the contribution source with new text 'Paid later via page ID: N.'
2677 // contribution.source only allows 255 characters so we are using ellipsify(...) to ensure it.
2678 $contributionParams['source'] = CRM_Utils_String
::ellipsify(
2679 ts('Paid later via page ID: %1. %2', [
2681 2 => $contributionParams['source'],
2683 // eventually activity.description append price information to source text so keep it 220 to ensure string length doesn't exceed 255 characters.
2688 if (isset($paymentParams['line_item'])) {
2689 // @todo make sure this is consisently set at this point.
2690 $contributionParams['line_item'] = $paymentParams['line_item'];
2692 if (!empty($form->_paymentProcessor
)) {
2693 $contributionParams['payment_instrument_id'] = $paymentParams['payment_instrument_id'] = $form->_paymentProcessor
['payment_instrument_id'];
2695 $contribution = $this->processFormContribution(
2698 $contributionParams,
2703 // CRM-13074 - create the CMSUser after the transaction is completed as it
2704 // is not appropriate to delete a valid contribution if a user create problem occurs
2705 if (isset($this->_params
['related_contact'])) {
2706 $contactID = $this->_params
['related_contact'];
2708 elseif (isset($this->_params
['cms_contactID'])) {
2709 $contactID = $this->_params
['cms_contactID'];
2711 CRM_Contribute_BAO_Contribution_Utils
::createCMSUser($this->_params
,
2713 'email-' . $form->_bltID
2716 $paymentParams['item_name'] = $form->_params
['description'];
2718 $paymentParams['qfKey'] = empty($paymentParams['qfKey']) ?
$form->controller
->_key
: $paymentParams['qfKey'];
2719 if ($paymentParams['skipLineItem']) {
2720 // We are not processing the line item here because we are processing a membership.
2721 // Do not continue with contribution processing in this function.
2722 return ['contribution' => $contribution];
2725 $paymentParams['contributionID'] = $contribution->id
;
2726 $paymentParams['contributionPageID'] = $contribution->contribution_page_id
;
2728 if (!empty($form->_params
['is_recur']) && $contribution->contribution_recur_id
) {
2729 $paymentParams['contributionRecurID'] = $contribution->contribution_recur_id
;
2731 if (isset($paymentParams['contribution_source'])) {
2732 $form->_params
['source'] = $paymentParams['contribution_source'];
2735 // get the price set values for receipt.
2736 if ($form->_priceSetId
&& $form->_lineItem
) {
2737 $form->_values
['lineItem'] = $form->_lineItem
;
2738 $form->_values
['priceSetID'] = $form->_priceSetId
;
2741 $form->_values
['contribution_id'] = $contribution->id
;
2742 $form->_values
['contribution_page_id'] = $contribution->contribution_page_id
;
2744 if (!empty($form->_paymentProcessor
)) {
2746 $payment = Civi\Payment\System
::singleton()->getByProcessor($form->_paymentProcessor
);
2747 if ($form->_contributeMode
== 'notify') {
2748 // We want to get rid of this & make it generic - eg. by making payment processing the last thing
2749 // and always calling it first.
2750 $form->postProcessHook();
2752 $result = $payment->doPayment($paymentParams);
2753 $form->_params
= array_merge($form->_params
, $result);
2754 $form->assign('trxn_id', $result['trxn_id'] ??
'');
2755 $contribution->trxn_id
= $result['trxn_id'] ??
$contribution->trxn_id ??
'';
2756 $contribution->payment_status_id
= $result['payment_status_id'];
2757 $result['contribution'] = $contribution;
2758 if ($result['payment_status_id'] == CRM_Core_PseudoConstant
::getKey('CRM_Contribute_BAO_Contribution', 'contribution_status_id', 'Pending')
2759 && $payment->isSendReceiptForPending()) {
2760 CRM_Contribute_BAO_ContributionPage
::sendMail($contactID,
2762 $contribution->is_test
2767 catch (\Civi\Payment\Exception\PaymentProcessorException
$e) {
2768 // Clean up DB as appropriate.
2769 if (!empty($paymentParams['contributionID'])) {
2770 CRM_Contribute_BAO_Contribution
::failPayment($paymentParams['contributionID'],
2771 $paymentParams['contactID'], $e->getMessage());
2773 if (!empty($paymentParams['contributionRecurID'])) {
2774 CRM_Contribute_BAO_ContributionRecur
::deleteRecurContribution($paymentParams['contributionRecurID']);
2777 $result['is_payment_failure'] = TRUE;
2778 $result['error'] = $e;
2784 // Only pay later or unpaid should reach this point, although pay later likely does not & is handled via the
2785 // manual processor, so it's unclear what this set is for and whether the following send ever fires.
2786 $form->set('params', $form->_params
);
2788 if ($form->_params
['amount'] == 0) {
2789 // This is kind of a back-up for pay-later $0 transactions.
2790 // In other flows they pick up the manual processor & get dealt with above (I
2791 // think that might be better...).
2793 'payment_status_id' => 1,
2794 'contribution' => $contribution,
2795 'payment_processor_id' => 0,
2799 CRM_Contribute_BAO_ContributionPage
::sendMail($contactID,
2801 $contribution->is_test
2806 * Temporary function to allow unit tests to access function being refactored away.
2808 * @param int $contactID
2809 * @param int $membershipTypeID
2810 * @param int $membershipID
2813 * @throws \CRM_Core_Exception
2814 * @throws \CiviCRM_API3_Exception
2816 public static function unitTestAccessTolegacyProcessMembership($contactID, $membershipTypeID, $membershipID = NULL) {
2817 return self
::legacyProcessMembership(
2834 * Interim function for processing memberships - this is being refactored out of existence.
2836 * @param int $contactID
2837 * @param int $membershipTypeID
2838 * @param bool $is_test
2839 * @param string $changeToday
2840 * @param int $modifiedID
2841 * @param $customFieldsFormatted
2842 * @param $numRenewTerms
2843 * @param int $membershipID
2845 * @param int $contributionRecurID
2846 * @param $membershipSource
2847 * @param $isPayLater
2848 * @param array $memParams
2849 * @param null|CRM_Contribute_BAO_Contribution $contribution
2850 * @param array $lineItems
2853 * @throws \CRM_Core_Exception
2854 * @throws \CiviCRM_API3_Exception
2856 protected static function legacyProcessMembership($contactID, $membershipTypeID, $is_test, $changeToday, $modifiedID, $customFieldsFormatted, $numRenewTerms, $membershipID, $pending, $contributionRecurID, $membershipSource, $isPayLater, $memParams = [], $contribution = NULL, $lineItems = []) {
2857 $renewalMode = $updateStatusId = FALSE;
2858 $allStatus = CRM_Member_PseudoConstant
::membershipStatus();
2860 $statusFormat = '%Y-%m-%d';
2861 $membershipTypeDetails = CRM_Member_BAO_MembershipType
::getMembershipType($membershipTypeID);
2865 // CRM-7297 - allow membership type to be be changed during renewal so long as the parent org of new membershipType
2866 // is the same as the parent org of an existing membership of the contact
2867 $currentMembership = CRM_Member_BAO_Membership
::getContactMembership($contactID, $membershipTypeID,
2868 $is_test, $membershipID, TRUE
2870 if ($currentMembership) {
2871 $renewalMode = TRUE;
2873 // Do NOT do anything.
2874 //1. membership with status : PENDING/CANCELLED (CRM-2395)
2875 //2. Paylater/IPN renew. CRM-4556.
2876 if ($pending ||
in_array($currentMembership['status_id'], [
2877 array_search('Pending', $allStatus),
2879 array_search('Cancelled', CRM_Member_PseudoConstant
::membershipStatus(NULL, " name = 'Cancelled' ", 'name', FALSE, TRUE)),
2882 $memParams = array_merge([
2883 'id' => $currentMembership['id'],
2884 'contribution' => $contribution,
2885 'status_id' => $currentMembership['status_id'],
2886 'start_date' => $currentMembership['start_date'],
2887 'end_date' => $currentMembership['end_date'],
2888 'line_item' => $lineItems,
2889 'join_date' => $currentMembership['join_date'],
2890 'membership_type_id' => $membershipTypeID,
2891 'max_related' => !empty($membershipTypeDetails['max_related']) ?
$membershipTypeDetails['max_related'] : NULL,
2892 'membership_activity_status' => ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed',
2894 if ($contributionRecurID) {
2895 $memParams['contribution_recur_id'] = $contributionRecurID;
2898 $membership = CRM_Member_BAO_Membership
::create($memParams);
2899 return [$membership, $renewalMode, $dates];
2902 // Check and fix the membership if it is STALE
2903 CRM_Member_BAO_Membership
::fixMembershipStatusBeforeRenew($currentMembership, $changeToday);
2905 // Now Renew the membership
2906 if (!$currentMembership['is_current_member']) {
2907 // membership is not CURRENT
2909 // CRM-7297 Membership Upsell - calculate dates based on new membership type
2910 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($currentMembership['id'],
2916 $currentMembership['join_date'] = CRM_Utils_Date
::customFormat($currentMembership['join_date'], $format);
2917 foreach (['start_date', 'end_date'] as $dateType) {
2918 $currentMembership[$dateType] = $dates[$dateType] ??
NULL;
2920 $currentMembership['is_test'] = $is_test;
2922 if (!empty($membershipSource)) {
2923 $currentMembership['source'] = $membershipSource;
2926 if (!empty($currentMembership['id'])) {
2927 $ids['membership'] = $currentMembership['id'];
2929 $memParams = array_merge($currentMembership, $memParams);
2930 $memParams['membership_type_id'] = $membershipTypeID;
2932 //set the log start date.
2933 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
2937 // CURRENT Membership
2938 $membership = new CRM_Member_DAO_Membership();
2939 $membership->id
= $currentMembership['id'];
2940 $membership->find(TRUE);
2941 // CRM-7297 Membership Upsell - calculate dates based on new membership type
2942 $dates = CRM_Member_BAO_MembershipType
::getRenewalDatesForMembershipType($membership->id
,
2948 // Insert renewed dates for CURRENT membership
2949 $memParams['join_date'] = CRM_Utils_Date
::isoToMysql($membership->join_date
);
2950 $memParams['start_date'] = CRM_Utils_Date
::isoToMysql($membership->start_date
);
2951 $memParams['end_date'] = $dates['end_date'] ??
NULL;
2952 $memParams['membership_type_id'] = $membershipTypeID;
2954 //set the log start date.
2955 $memParams['log_start_date'] = CRM_Utils_Date
::customFormat($dates['log_start_date'], $format);
2958 if (!empty($membershipSource)) {
2959 $memParams['source'] = $membershipSource;
2961 elseif (empty($membership->source
)) {
2962 $memParams['source'] = CRM_Core_DAO
::getFieldValue('CRM_Member_DAO_Membership',
2963 $currentMembership['id'],
2968 if (!empty($currentMembership['id'])) {
2969 $ids['membership'] = $currentMembership['id'];
2971 $memParams['membership_activity_status'] = ($pending ||
$isPayLater) ?
'Scheduled' : 'Completed';
2976 $memParams = array_merge([
2977 'contact_id' => $contactID,
2978 'membership_type_id' => $membershipTypeID,
2982 $dates = CRM_Member_BAO_MembershipType
::getDatesForMembershipType($membershipTypeID, NULL, NULL, NULL, $numRenewTerms);
2984 foreach (['join_date', 'start_date', 'end_date'] as $dateType) {
2985 $memParams[$dateType] = $dates[$dateType] ??
NULL;
2988 $status = CRM_Member_BAO_MembershipStatus
::getMembershipStatusByDate(CRM_Utils_Date
::customFormat($dates['start_date'],
2991 CRM_Utils_Date
::customFormat($dates['end_date'],
2994 CRM_Utils_Date
::customFormat($dates['join_date'],
3002 $updateStatusId = $status['id'] ??
NULL;
3005 // if IPN/Pay-Later set status to: PENDING
3006 $updateStatusId = array_search('Pending', $allStatus);
3009 if (!empty($membershipSource)) {
3010 $memParams['source'] = $membershipSource;
3012 $memParams['is_test'] = $is_test;
3013 $memParams['is_pay_later'] = $isPayLater;
3015 // Putting this in an IF is precautionary as it seems likely that it would be ignored if empty, but
3016 // perhaps shouldn't be?
3017 if ($contributionRecurID) {
3018 $memParams['contribution_recur_id'] = $contributionRecurID;
3021 //if we decided status here and want to skip status
3022 //calculation in create( ); then need to pass 'skipStatusCal'.
3023 if ($updateStatusId) {
3024 $memParams['status_id'] = $updateStatusId;
3025 $memParams['skipStatusCal'] = TRUE;
3028 //since we are renewing,
3029 //make status override false.
3030 $memParams['is_override'] = FALSE;
3032 //CRM-4027, create log w/ individual contact.
3034 // @todo this param is likely unused now.
3035 $memParams['is_for_organization'] = TRUE;
3037 $params['modified_id'] = $modifiedID ??
$contactID;
3039 $memParams['contribution'] = $contribution;
3040 $memParams['custom'] = $customFieldsFormatted;
3041 // Load all line items & process all in membership. Don't do in contribution.
3042 // Relevant tests in api_v3_ContributionPageTest.
3043 $memParams['line_item'] = $lineItems;
3044 // @todo stop passing $ids (membership and userId may be set by this point)
3045 $membership = CRM_Member_BAO_Membership
::create($memParams, $ids);
3047 // not sure why this statement is here, seems quite odd :( - Lobo: 12/26/2010
3048 // related to: http://forum.civicrm.org/index.php/topic,11416.msg49072.html#msg49072
3049 $membership->find(TRUE);
3051 return [$membership, $renewalMode, $dates];